hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
eca12c6871facfbbe846d5589551191e08ca6d20
diff --git a/aws/resource_aws_vpc_endpoint_subnet_association.go b/aws/resource_aws_vpc_endpoint_subnet_association.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_vpc_endpoint_subnet_association.go +++ b/aws/resource_aws_vpc_endpoint_subnet_association.go @@ -9,6 +9,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/terraform/helper/hashcode" + "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/helper/schema" ) @@ -52,10 +53,25 @@ func resourceAwsVpcEndpointSubnetAssociationCreate(d *schema.ResourceData, meta return err } - _, err = conn.ModifyVpcEndpoint(&ec2.ModifyVpcEndpointInput{ - VpcEndpointId: aws.String(endpointId), - AddSubnetIds: aws.StringSlice([]string{snId}), - }) + // See https://github.com/terraform-providers/terraform-provider-aws/issues/3382. + // Prevent concurrent subnet association requests and delay between requests. + mk := "vpc_endpoint_subnet_association_" + endpointId + awsMutexKV.Lock(mk) + defer awsMutexKV.Unlock(mk) + + c := &resource.StateChangeConf{ + Delay: 1 * time.Minute, + Timeout: 3 * time.Minute, + Target: []string{"ok"}, + Refresh: func() (interface{}, string, error) { + res, err := conn.ModifyVpcEndpoint(&ec2.ModifyVpcEndpointInput{ + VpcEndpointId: aws.String(endpointId), + AddSubnetIds: aws.StringSlice([]string{snId}), + }) + return res, "ok", err + }, + } + _, err = c.WaitForState() if err != nil { return fmt.Errorf("Error creating Vpc Endpoint/Subnet association: %s", err) }
Add back mutex and delay for concurrent modifications.
terraform-providers_terraform-provider-aws
train
267755dae581e39d6d425970a0a28dcc40e1e809
diff --git a/packages/@vue/cli/lib/Creator.js b/packages/@vue/cli/lib/Creator.js index <HASH>..<HASH> 100644 --- a/packages/@vue/cli/lib/Creator.js +++ b/packages/@vue/cli/lib/Creator.js @@ -83,7 +83,7 @@ module.exports = class Creator { // write base package.json to disk clearConsole() logWithSpinner('✨', `Creating project in ${chalk.yellow(context)}.`) - writeFileTree(context, { + await writeFileTree(context, { 'package.json': JSON.stringify({ name, version: '0.1.0',
make sure to await writeFileTree
vuejs_vue-cli
train
d6e9f7778ede7e91f5af9f5f5740a9b6d9c6abb7
diff --git a/showcases/de/versicherungsneuantrag/process-application/src/main/java/com/camunda/demo/versicherungsneuantrag/adapter/DeactivateFollowUpDateAdapter.java b/showcases/de/versicherungsneuantrag/process-application/src/main/java/com/camunda/demo/versicherungsneuantrag/adapter/DeactivateFollowUpDateAdapter.java index <HASH>..<HASH> 100644 --- a/showcases/de/versicherungsneuantrag/process-application/src/main/java/com/camunda/demo/versicherungsneuantrag/adapter/DeactivateFollowUpDateAdapter.java +++ b/showcases/de/versicherungsneuantrag/process-application/src/main/java/com/camunda/demo/versicherungsneuantrag/adapter/DeactivateFollowUpDateAdapter.java @@ -1,29 +1,40 @@ package com.camunda.demo.versicherungsneuantrag.adapter; +import java.util.logging.Level; +import java.util.logging.Logger; + import org.camunda.bpm.engine.delegate.CaseExecutionListener; import org.camunda.bpm.engine.delegate.DelegateCaseExecution; import org.camunda.bpm.engine.runtime.CaseExecution; import org.camunda.bpm.engine.task.Task; public class DeactivateFollowUpDateAdapter implements CaseExecutionListener { + + private Logger LOG = Logger.getLogger(DeactivateFollowUpDateAdapter.class.getName()); @Override public void notify(DelegateCaseExecution caseExecution) throws Exception { - // find case execution doing the humanTask AntragEntscheiden - CaseExecution decisionCaseExecution = caseExecution.getProcessEngineServices().getCaseService().createCaseExecutionQuery() // - .caseInstanceId(caseExecution.getCaseInstanceId()) - // TODO: make more generic - .activityId("PI_humanTaskAntragEntscheiden") - .singleResult(); - - // find the according task - Task task = caseExecution.getProcessEngineServices().getTaskService().createTaskQuery() // - .caseExecutionId(decisionCaseExecution.getId()) - .singleResult(); - - // Remove a follow-up date - task.setFollowUpDate(null); - caseExecution.getProcessEngineServices().getTaskService().saveTask(task); + try { + // find case execution doing the humanTask AntragEntscheiden + CaseExecution decisionCaseExecution = caseExecution.getProcessEngineServices().getCaseService().createCaseExecutionQuery() // + .caseInstanceId(caseExecution.getCaseInstanceId()) + // TODO: make more generic + .activityId("PI_humanTaskAntragEntscheiden") + .singleResult(); + + // find the according task + Task task = caseExecution.getProcessEngineServices().getTaskService().createTaskQuery() // + .caseExecutionId(decisionCaseExecution.getId()) + .singleResult(); + + // Remove a follow-up date + task.setFollowUpDate(null); + caseExecution.getProcessEngineServices().getTaskService().saveTask(task); + } + catch (Exception ex) { + // ignore exception to avoid problems because of canceled tasks or the like + LOG.log(Level.INFO, "Could not deactivate follow-up date of decision task, maybe already ended?", ex); + } } }
make DeactivateFollowUpDateAdapter more robust (now works with finished decision task)
camunda-consulting_code
train
efeae5e7ee7785ddc5cd740c5b071c3b08b1e06f
diff --git a/libnetwork/ipvs/ipvs_test.go b/libnetwork/ipvs/ipvs_test.go index <HASH>..<HASH> 100644 --- a/libnetwork/ipvs/ipvs_test.go +++ b/libnetwork/ipvs/ipvs_test.go @@ -363,4 +363,13 @@ func TestTimeouts(t *testing.T) { c2, err := i.GetConfig() assert.NilError(t, err) assert.DeepEqual(t, cfg, *c2) + + // A timeout value 0 means that the current timeout value of the corresponding entry is preserved + cfg = Config{77 * time.Second, 0 * time.Second, 77 * time.Second} + err = i.SetConfig(&cfg) + assert.NilError(t, err) + + c3, err := i.GetConfig() + assert.NilError(t, err) + assert.DeepEqual(t, *c3, Config{77 * time.Second, 66 * time.Second, 77 * time.Second}) }
[ipvs] Add SetConfig test with timeout=0
moby_moby
train
683dc19fe36afc0f653bdd1d10a08918d48be335
diff --git a/airflow/hooks/dbapi_hook.py b/airflow/hooks/dbapi_hook.py index <HASH>..<HASH> 100644 --- a/airflow/hooks/dbapi_hook.py +++ b/airflow/hooks/dbapi_hook.py @@ -163,10 +163,11 @@ class DbApiHook(BaseHook): for s in sql: if sys.version_info[0] < 3: s = s.encode('utf-8') - self.log.info(s) if parameters is not None: + self.log.info("{} with parameters {}".format(s, parameters)) cur.execute(s, parameters) else: + self.log.info(s) cur.execute(s) # If autocommit was set to False for db that supports autocommit,
[AIRFLOW-<I>] include parameters into log.info in SQL operators, if any (#<I>) For all SQL-operators based on DbApiHook, sql command itself is printed into log.info. But if parameters are used for the sql command, the parameters would not be included in the printing. This makes the log less useful. This commit ensures that the parameters are also printed into the log.info, if any.
apache_airflow
train
a2f4d8fa9b37f58ef36518097063e4d2b348127a
diff --git a/src/instrumentTest/java/com/couchbase/lite/LiteTestCase.java b/src/instrumentTest/java/com/couchbase/lite/LiteTestCase.java index <HASH>..<HASH> 100644 --- a/src/instrumentTest/java/com/couchbase/lite/LiteTestCase.java +++ b/src/instrumentTest/java/com/couchbase/lite/LiteTestCase.java @@ -416,13 +416,15 @@ public abstract class LiteTestCase extends TestCase { Replication replicator = event.getSource(); Log.d(TAG, replicator + " changed. " + replicator.getCompletedChangesCount() + " / " + replicator.getChangesCount()); + /* this assertion is failing, so comment it out for now. see https://github.com/couchbase/couchbase-lite-java-core/issues/100 if (!replicator.isRunning()) { if (replicator.getCompletedChangesCount() > replicator.getChangesCount()) { String msg = String.format("replicator.getCompletedChangesCount() - %d > replicator.getChangesCount() - %d", replicator.getCompletedChangesCount(), replicator.getChangesCount()); Log.d(TAG, msg); throw new RuntimeException(msg); } - } + }*/ + if (!replicator.isRunning()) { replicationFinished = true;
Issue #<I> - assertion is failing (sporadically) so comment it out for now. <URL>
couchbase_couchbase-lite-android
train
f71ecc1a05793cf33c3f1c46194f4b917b899adb
diff --git a/lib/podoff.rb b/lib/podoff.rb index <HASH>..<HASH> 100644 --- a/lib/podoff.rb +++ b/lib/podoff.rb @@ -224,7 +224,7 @@ module Podoff add(obj) end - def write(path) + def write(path=:string) f = case path
make Document#write default to path=:string
jmettraux_podoff
train
a494118dc730afcb6aba8e59f1f3d09a7d4f9302
diff --git a/packages/cli/src/download-npm-package.js b/packages/cli/src/download-npm-package.js index <HASH>..<HASH> 100644 --- a/packages/cli/src/download-npm-package.js +++ b/packages/cli/src/download-npm-package.js @@ -15,7 +15,7 @@ export default async (pkg, dest) => { const tmpObj = tmp.dirSync({ unsafeCleanup: true }); // step 2: download package from npm - const result = await spawn.sync("npm", ["pack", pkg], { + const result = spawn.sync("npm", ["pack", pkg], { stdio: "ignore", cwd: tmpObj.name, });
fix: cli await on spawn bug
36node_sketch
train
ccd9c1c3632aa22cdcc4e064f17e07803b1d27ba
diff --git a/ifstools/ifs.py b/ifstools/ifs.py index <HASH>..<HASH> 100644 --- a/ifstools/ifs.py +++ b/ifstools/ifs.py @@ -253,6 +253,9 @@ class IFS: if progress: tqdm.write(f) + p.close() + p.terminate() + # restore stuff from before for folder in folders: if isinstance(folder, MD5Folder):
Fix issue with IFS class not terminating Pool after creating new archive (#<I>)
mon_ifstools
train
4fb34e937020b9ab1c625023a17538421351b34b
diff --git a/nodeconductor/core/admin.py b/nodeconductor/core/admin.py index <HASH>..<HASH> 100644 --- a/nodeconductor/core/admin.py +++ b/nodeconductor/core/admin.py @@ -15,6 +15,7 @@ from rest_framework import permissions as rf_permissions from reversion.admin import VersionAdmin from nodeconductor.core import models +from nodeconductor.core.authentication import can_access_admin_site def get_admin_url(obj): @@ -110,7 +111,7 @@ class CustomAdminAuthenticationForm(admin_forms.AdminAuthenticationForm): } def confirm_login_allowed(self, user): - if not user.is_active or not user.is_support: + if not can_access_admin_site(user): return super(CustomAdminAuthenticationForm, self).confirm_login_allowed(user) @@ -121,10 +122,8 @@ class CustomAdminSite(admin.AdminSite): login_form = CustomAdminAuthenticationForm def has_permission(self, request): - if request.method in rf_permissions.SAFE_METHODS: - return request.user.is_active and (request.user.is_staff or request.user.is_support) - - return request.user.is_active and request.user.is_staff + is_safe = request.method in rf_permissions.SAFE_METHODS + return can_access_admin_site(request.user) and (is_safe or request.user.is_staff) @classmethod def clone_default(cls): diff --git a/nodeconductor/core/authentication.py b/nodeconductor/core/authentication.py index <HASH>..<HASH> 100644 --- a/nodeconductor/core/authentication.py +++ b/nodeconductor/core/authentication.py @@ -12,9 +12,13 @@ import nodeconductor.logging.middleware TOKEN_KEY = settings.NODECONDUCTOR.get('TOKEN_KEY', 'x-auth-token') +def can_access_admin_site(user): + return user.is_active and (user.is_staff or user.is_support) + + class AuthenticationBackend(object): """ - Enables only active superuser and staff to execute any action via admin site. + Enables only support and staff to access admin site. """ def authenticate(self, username, password): @@ -24,14 +28,10 @@ class AuthenticationBackend(object): return None def has_perm(self, user_obj, perm, obj=None): - if not user_obj.is_active: - return False - return user_obj.is_superuser or user_obj.is_staff + return can_access_admin_site(user_obj) def has_module_perms(self, user_obj, app_label): - if not user_obj.is_active: - return False - return user_obj.is_superuser or user_obj.is_staff + return can_access_admin_site(user_obj) class TokenAuthentication(rest_framework.authentication.TokenAuthentication):
Extract permission logic to function [WAL-<I>]
opennode_waldur-core
train
10ba14f3f9bd0c416ea771298c85bebfd65b9165
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -284,7 +284,7 @@ setup(name='concurrent-log-handler', data_files=[ ('tests', ["stresstest.py"]), ('docs', [ - 'README', + 'README.md', 'LICENSE', ]), ],
Fix rename of readme.
Preston-Landers_concurrent-log-handler
train
c169bdcdce7a659548780418b5f11fa912b8b10e
diff --git a/spyder/widgets/ipython.py b/spyder/widgets/ipython.py index <HASH>..<HASH> 100644 --- a/spyder/widgets/ipython.py +++ b/spyder/widgets/ipython.py @@ -208,8 +208,9 @@ class IPythonShellWidget(RichJupyterWidget): # --- Keyboard shortcuts --- self.shortcuts = self.create_shortcuts() - # --- To communicate with Spyder --- - self._commands = {} + # --- To save the replies of kernel method executions + # (except getting values of variables) + self._kernel_methods = {} #---- Public API ---------------------------------------------------------- def set_ipyclient(self, ipyclient): @@ -361,9 +362,9 @@ These commands were executed: def refresh_namespacebrowser(self): """Refresh namespace browser""" if self.namespacebrowser: - self.silent_exec_command( + self.silent_exec_method( 'get_ipython().kernel.get_namespace_view()') - self.silent_exec_command( + self.silent_exec_method( 'get_ipython().kernel.get_var_properties()') def set_namespace_view_settings(self): @@ -376,39 +377,44 @@ These commands were executed: """Execute code in the kernel without increasing the prompt""" self.kernel_client.execute(to_text_string(code), silent=True) - def silent_exec_command(self, code): - """Silently execute code in the kernel + def silent_exec_method(self, code): + """Silently execute a kernel method and save its reply + + The methods passed here **don't** involve getting a value + of a variable but instead replies that can be handled by + ast.literal_eval. + + To get a value see `get_value` Parameters ---------- code : string - Valid string to be executed by the kernel. + Code that contains the kernel method as part of its + string See Also -------- - handle_exec_command : Private method that deals with the reply + handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD """ - # Generate uuid, which would be used as an indication of whether or # not the unique request originated from here local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:code }) - command = code.split('.')[-1] - self._commands[local_uuid] = command + method = code.split('.')[-1] + self._kernel_methods[local_uuid] = method self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, - 'silent_exec_command') + 'silent_exec_method') - def handle_exec_command(self, msg): + def handle_exec_method(self, msg): """ - Handle data returned by silent executions with commands - on the kernel. + Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. @@ -417,14 +423,14 @@ These commands were executed: if not user_exp: return for expression in user_exp: - if expression in self._commands: - command = self._commands[expression] + if expression in self._kernel_methods: + method = self._kernel_methods[expression] reply = user_exp[expression] data = reply.get('data') - if command == 'get_namespace_view()': + if method == 'get_namespace_view()': view = ast.literal_eval(data['text/plain']) self.sig_namespace_view.emit(view) - elif command == 'get_var_properties()': + elif method == 'get_var_properties()': properties = ast.literal_eval(data['text/plain']) self.sig_var_properties.emit(properties) @@ -433,7 +439,12 @@ These commands were executed: self.silent_execute("get_ipython().kernel.get_value('%s')" % name) def _handle_data_message(self, msg): - """Handle raw (serialized) data sent by the kernel""" + """ + Handle raw (serialized) data sent by the kernel + + We only handle data asked by Spyder, in case people uses + publish_data for other purposes. + """ # Deserialize data data = deserialize_object(msg['buffers'])[0] @@ -487,8 +498,8 @@ These commands were executed: # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False - if info and info.kind == 'silent_exec_command' and not self._hidden: - self.handle_exec_command(msg) + if info and info.kind == 'silent_exec_method' and not self._hidden: + self.handle_exec_method(msg) self._request_info['execute'].pop(msg_id) else: super(IPythonShellWidget, self)._handle_execute_reply(msg)
IPython Console: Refactoring to better explain how we communicate with the kernel
spyder-ide_spyder
train
029ec1edfe89c4088e3bf8cf48a51b49825694a3
diff --git a/auth/ldap/auth.php b/auth/ldap/auth.php index <HASH>..<HASH> 100644 --- a/auth/ldap/auth.php +++ b/auth/ldap/auth.php @@ -1083,7 +1083,9 @@ class auth_plugin_ldap extends auth_plugin_base { * */ function user_update($olduser, $newuser) { - global $USER; + global $CFG; + + require_once($CFG->dirroot . '/user/profile/lib.php'); if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) { error_log($this->errorlogtag.get_string('renamingnotallowed', 'auth_ldap'));
MDL-<I> auth_ldap: require /user/profile/lib.php file
moodle_moodle
train
b9d0c3d95cd191810de0efb351492a3cb38e720b
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -145,6 +145,8 @@ var torrentStream = function(link, opts) { return; } + if (!torrent.announce || !torrent.announce.length) return; + var tr = new tracker.Client(new Buffer(opts.id), engine.port || DEFAULT_PORT, torrent); tr.on('peer', function(addr) {
create tracker only when announce list is not empty
mafintosh_torrent-stream
train
cae7a3b8078f30695dfbdd3784c236544e370542
diff --git a/core-bundle/src/EventListener/SessionListener.php b/core-bundle/src/EventListener/SessionListener.php index <HASH>..<HASH> 100644 --- a/core-bundle/src/EventListener/SessionListener.php +++ b/core-bundle/src/EventListener/SessionListener.php @@ -38,7 +38,7 @@ class SessionListener /** * Registers the Contao front end and back end session bags. */ - public function onKernelRequest() + public function registerContaoAttributeBags() { $beBag = new AttributeBag('_contao_be_attributes'); $beBag->setName('contao_backend'); diff --git a/core-bundle/src/Resources/config/services.yml b/core-bundle/src/Resources/config/services.yml index <HASH>..<HASH> 100644 --- a/core-bundle/src/Resources/config/services.yml +++ b/core-bundle/src/Resources/config/services.yml @@ -42,7 +42,8 @@ services: arguments: - "@session" tags: - - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 64 } + - { name: kernel.event_listener, event: kernel.request, method: registerContaoAttributeBags, priority: 64 } + - { name: kernel.event_listener, event: console.command, method: registerContaoAttributeBags, priority: 64 } contao.listener.toggle_view: class: Contao\CoreBundle\EventListener\ToggleViewListener diff --git a/core-bundle/tests/EventListener/SessionListenerTest.php b/core-bundle/tests/EventListener/SessionListenerTest.php index <HASH>..<HASH> 100644 --- a/core-bundle/tests/EventListener/SessionListenerTest.php +++ b/core-bundle/tests/EventListener/SessionListenerTest.php @@ -41,7 +41,7 @@ class SessionListenerTest extends TestCase $session = $this->getSession(); $listener = new SessionListener($session); - $listener->onKernelRequest(); + $listener->registerContaoAttributeBags(); $this->assertInstanceOf( 'Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag',
[Core] Fixed Session bags were not registered on console
contao_contao
train
68692abaf623d20a5bc3372d94e4c4341f24315a
diff --git a/uncompyle6/__init__.py b/uncompyle6/__init__.py index <HASH>..<HASH> 100644 --- a/uncompyle6/__init__.py +++ b/uncompyle6/__init__.py @@ -55,7 +55,10 @@ from uncompyle6.main import decompile_file uncompyle_file = decompile_file # Conventience functions so you can say: -# from uncompyle6 import (deparse_code, deparse_code2str) +# from uncompyle6 import (code_deparse, deparse_code2str) -deparse_code = uncompyle6.semantics.pysource.deparse_code +code_deparse = uncompyle6.semantics.pysource.code_deparse deparse_code2str = uncompyle6.semantics.pysource.deparse_code2str + +# This is deprecated: +deparse_code = uncompyle6.semantics.pysource.deparse_code diff --git a/uncompyle6/semantics/fragments.py b/uncompyle6/semantics/fragments.py index <HASH>..<HASH> 100644 --- a/uncompyle6/semantics/fragments.py +++ b/uncompyle6/semantics/fragments.py @@ -1,4 +1,17 @@ # Copyright (c) 2015-2018 by Rocky Bernstein +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. """ Creates Python source code from an uncompyle6 parse tree, diff --git a/uncompyle6/semantics/pysource.py b/uncompyle6/semantics/pysource.py index <HASH>..<HASH> 100644 --- a/uncompyle6/semantics/pysource.py +++ b/uncompyle6/semantics/pysource.py @@ -2630,9 +2630,27 @@ class SourceWalker(GenericASTTraversal, object): return MAP.get(node, MAP_DIRECT) +# +DEFAULT_DEBUG_OPTS = { + 'asm': False, + 'tree': False, + 'grammar': False +} + +# This interface is deprecated. Use simpler code_deparse. def deparse_code(version, co, out=sys.stdout, showasm=None, showast=False, showgrammar=False, code_objects={}, compile_mode='exec', is_pypy=False, walker=SourceWalker): + debug_opts = { + 'asm': showasm, + 'ast': showast, + 'grammar': showgrammar + } + return code_deparse(co, out, version, debug_opts, code_objects, compile_mode, + is_pypy, walker) + +def code_deparse(co, out=sys.stdout, version=None, debug_opts=DEFAULT_DEBUG_OPTS, + code_objects={}, compile_mode='exec', is_pypy=False, walker=SourceWalker): """ ingests and deparses a given code block 'co'. If version is None, we will use the current Python interpreter version. @@ -2647,16 +2665,16 @@ def deparse_code(version, co, out=sys.stdout, showasm=None, showast=False, scanner = get_scanner(version, is_pypy=is_pypy) tokens, customize = scanner.ingest(co, code_objects=code_objects, - show_asm=showasm) + show_asm=debug_opts['asm']) debug_parser = dict(PARSER_DEFAULT_DEBUG) - if showgrammar: - debug_parser['reduce'] = showgrammar + if debug_opts.get('grammar', None): + debug_parser['reduce'] = debug_opts['grammar'] debug_parser['errorstack'] = 'full' # Build Syntax Tree from disassembly. linestarts = dict(scanner.opc.findlinestarts(co)) - deparsed = walker(version, out, scanner, showast=showast, + deparsed = walker(version, out, scanner, showast=debug_opts['ast'], debug_parser=debug_parser, compile_mode=compile_mode, is_pypy=is_pypy, linestarts=linestarts) @@ -2705,12 +2723,6 @@ def deparse_code(version, co, out=sys.stdout, showasm=None, showast=False, raise SourceWalkerError("Deparsing stopped due to parse error") return deparsed -# -DEFAULT_DEBUG_OPTS = { - 'asm': False, - 'tree': False, - 'grammar': False -} def deparse_code2str(code, out=sys.stdout, version=None, debug_opts=DEFAULT_DEBUG_OPTS, code_objects={}, compile_mode='exec',
Start changing API to make version optional... and use debug option dictionary
rocky_python-uncompyle6
train
54f766d240f8e8c01bcde6061c877cf6e65e7f3d
diff --git a/cli/command/cli.go b/cli/command/cli.go index <HASH>..<HASH> 100644 --- a/cli/command/cli.go +++ b/cli/command/cli.go @@ -9,7 +9,6 @@ import ( "runtime" "strconv" "strings" - "sync" "time" "github.com/docker/cli/cli/config" @@ -136,12 +135,9 @@ func (cli *DockerCli) loadConfigFile() { cli.configFile = cliconfig.LoadDefaultConfigFile(cli.err) } -var fetchServerInfo sync.Once - // ServerInfo returns the server version details for the host this client is // connected to func (cli *DockerCli) ServerInfo() ServerInfo { - fetchServerInfo.Do(cli.initializeFromClient) return cli.serverInfo } @@ -276,6 +272,7 @@ func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...Initialize return err } } + cli.initializeFromClient() return nil }
Partially revert cf<I>b<I>a<I>f3e<I>e6e<I>c<I>aa<I> as it breaks the version negotiation with an older docker engine.
docker_cli
train
2740f2b319f29e99ef90736ae1b776b4c84dc22f
diff --git a/python_modules/dagster/dagster/core/definitions/config_mappable.py b/python_modules/dagster/dagster/core/definitions/config_mappable.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster/dagster/core/definitions/config_mappable.py +++ b/python_modules/dagster/dagster/core/definitions/config_mappable.py @@ -12,11 +12,10 @@ from dagster.core.errors import ( class ConfiguredMixin(ABC): - def __init__(self, _configured_config_mapping_fn, *args, is_nameless=False, **kwargs): + def __init__(self, _configured_config_mapping_fn, *args, **kwargs): self._configured_config_mapping_fn = check.opt_callable_param( _configured_config_mapping_fn, "config_mapping_fn" ) - self._is_nameless = is_nameless super(ConfiguredMixin, self).__init__(*args, **kwargs) @abstractproperty diff --git a/python_modules/dagster/dagster/core/definitions/logger.py b/python_modules/dagster/dagster/core/definitions/logger.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster/dagster/core/definitions/logger.py +++ b/python_modules/dagster/dagster/core/definitions/logger.py @@ -30,7 +30,7 @@ class LoggerDefinition(ConfiguredMixin): self.__configured_config_mapping_fn = check.opt_callable_param( _configured_config_mapping_fn, "config_mapping_fn" ) - super(LoggerDefinition, self).__init__(_configured_config_mapping_fn, is_nameless=True) + super(LoggerDefinition, self).__init__(_configured_config_mapping_fn) @property def logger_fn(self):
[easy] eliminate is_nameless in ConfiguredMixin Summary: This should have never been checked in at all. Test Plan: BK Reviewers: sandyryza Reviewed By: sandyryza Differential Revision: <URL>
dagster-io_dagster
train
ab6c6862ec2e5bb328fd0bb3e4061b10ff2caf42
diff --git a/src/directives/formBuilderDnd.js b/src/directives/formBuilderDnd.js index <HASH>..<HASH> 100644 --- a/src/directives/formBuilderDnd.js +++ b/src/directives/formBuilderDnd.js @@ -142,6 +142,10 @@ module.exports = [ } } + if (index === undefined) { + index = $scope.component.components.length + } + // Add the component to the components array. $scope.component.components.splice(index, 0, component); $timeout($scope.$apply.bind($scope));
If index is undefined when adding a component in PDF builder, add it to the end of the components list
formio_ngFormBuilder
train
023a5ef5905ca728b6fc048fa8735f179ec257b3
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -9,9 +9,6 @@ assert sys.version_info >= (3, 2), 'Python 3.2+ required.' with open(os.path.join('atlassian', 'VERSION')) as file: version = file.read().strip() -with open('requirements.txt') as file: - requirements = file.readlines() - with open('README.rst') as file: long_description = file.read() @@ -33,7 +30,9 @@ setup( include_package_data=True, zip_safe=False, - install_requires=requirements, + install_requires=[ + 'requests' + ], platforms='Platform Independent', classifiers=[
Fix issue with requiremetns.txt on installing pip package
atlassian-api_atlassian-python-api
train
31826be25cf7a8b49458808bc915a68b641badfa
diff --git a/wayback-core/src/main/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandler.java b/wayback-core/src/main/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandler.java index <HASH>..<HASH> 100644 --- a/wayback-core/src/main/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandler.java +++ b/wayback-core/src/main/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandler.java @@ -296,6 +296,7 @@ public class FastArchivalUrlReplayParseEventHandler implements // it would trigger bodyInsert. We may want to revise this behavior // based on real-world examples. context.putData(STATE_IN_NOSCRIPT, ""); + inNoScript = true; } else if (tagName.equals(BODY_TAG) && inHead) { context.putData(FERRET_IN_HEAD, null); inHead = false; @@ -545,6 +546,7 @@ public class FastArchivalUrlReplayParseEventHandler implements protected void emitHeadInsert(ReplayParseContext context, Node node, boolean postInsert) throws IOException { String headInsert = null; + context.putData(FERRET_HEAD_INSERTED, FERRET_HEAD_INSERTED); if (headInsertJsp == null) { this.emit(context, null, node, null); @@ -553,7 +555,6 @@ public class FastArchivalUrlReplayParseEventHandler implements try { headInsert = context.getJspExec().jspToString(headInsertJsp); - context.putData(FERRET_HEAD_INSERTED, FERRET_HEAD_INSERTED); } catch (ServletException e) { e.printStackTrace(); } diff --git a/wayback-core/src/test/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandlerTest.java b/wayback-core/src/test/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandlerTest.java index <HASH>..<HASH> 100644 --- a/wayback-core/src/test/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandlerTest.java +++ b/wayback-core/src/test/java/org/archive/wayback/archivalurl/FastArchivalUrlReplayParseEventHandlerTest.java @@ -1088,6 +1088,39 @@ public class FastArchivalUrlReplayParseEventHandlerTest extends TestCase { assertEquals(expected, out); } + /** + * There may not be a JSP to insert into HEAD, but we still want to + * avoid putting the JSP body insert into NOSCRIPT. + * @throws Exception + */ + public void testNOSCRIPT_noHeadInsertJsp() throws Exception { + delegator.setJspInsertPath("body-insert.jsp"); + jspExec = new TestJSPExecutor(); + + final String input = "<!DOCTYPE html>\n" + + "<head>\n" + + " <noscript>\n" + + " <img height=\"1\" width=\"1\" style=\"display:none\" src=\"ping.gif\">\n" + + " </noscript>\n" + + "</head>\n" + + "<body>\n" + + " body body\n" + + "</body>\n" + + "</html>\n"; + final String expected = "<!DOCTYPE html>\n" + + "<head>\n" + + " <noscript>\n" + + " <img height=\"1\" width=\"1\" style=\"display:none\" src=\"ping.gif\">\n" + + " </noscript>\n" + + "</head>\n" + + "<body>[[[JSP-INSERT:body-insert.jsp]]]\n" + + " body body\n" + + "</body>\n" + + "</html>\n";; + String out = doEndToEnd(input); + assertEquals(expected, out); + } + /** * pathological case of missing {@code </NOSCRIPT>}. * {@code </HEAD>} shall close </NOSCRIPT> as well.
Avoid inserting toolbar in NOSCRIPT tag. This is to fix #<I> by storing that HEAD has been inserted when there was no `headInsertJsp`.
iipc_openwayback
train
950d082b00d2d22da6fbe5a20d05881948aef9b5
diff --git a/actstream/managers.py b/actstream/managers.py index <HASH>..<HASH> 100644 --- a/actstream/managers.py +++ b/actstream/managers.py @@ -71,7 +71,7 @@ class ActionManager(GFKManager): 'content_type_id', 'object_id') if not follow_gfks: - return EmptyGFKQuerySet() + return qs.none() for content_type_id, object_id in follow_gfks.iterator(): actors_by_content_type[content_type_id].append(object_id)
Return qs.none() instead of new EmptyGFKQuerySet() This fixes downstream errors in code that assumes QuerySets have a model wiht a _meta attribute, ie Class Based Views.
justquick_django-activity-stream
train
7691070d587b85842e2829e4a82a03ef1c68b98a
diff --git a/hearthstone/hslog/parser.py b/hearthstone/hslog/parser.py index <HASH>..<HASH> 100644 --- a/hearthstone/hslog/parser.py +++ b/hearthstone/hslog/parser.py @@ -301,9 +301,9 @@ class LogWatcher(LogBroadcastMixin): entity = Card(id, cardid) self.current_game.register_entity(entity) self._entity_node = entity - packet = FullEntity(entity, cardid) - packet.ts = ts - self.current_node.packets.append(packet) + self._entity_packet = FullEntity(entity, cardid) + self._entity_packet.ts = ts + self.current_node.packets.append(self._entity_packet) # The first packet in a game is always FULL_ENTITY so # broadcast game_ready if we haven't yet for this game
hslog: Mark FullEntity as an _entity_packet
HearthSim_python-hearthstone
train
70e519e286993471571d10f1ac4a738e1e070647
diff --git a/consistency-checker/src/main/java/com/redhat/lightblue/migrator/consistency/ConsistencyChecker.java b/consistency-checker/src/main/java/com/redhat/lightblue/migrator/consistency/ConsistencyChecker.java index <HASH>..<HASH> 100644 --- a/consistency-checker/src/main/java/com/redhat/lightblue/migrator/consistency/ConsistencyChecker.java +++ b/consistency-checker/src/main/java/com/redhat/lightblue/migrator/consistency/ConsistencyChecker.java @@ -331,7 +331,10 @@ public class ConsistencyChecker implements Runnable { findRequest.select(includeFieldRecursively("*")); LOGGER.debug("Get next job: {}", findRequest.getBody()); - job = client.data(findRequest, MigrationJob.class); + MigrationJob[] jobs = client.data(findRequest, MigrationJob[].class); + if (jobs != null && jobs.length > 0) { + job = jobs[0]; + } } catch (IOException e) { LOGGER.error("Problem getting migrationJob", e); } diff --git a/consistency-checker/src/test/java/com/redhat/lightblue/migrator/consistency/ConsistencyCheckerTest.java b/consistency-checker/src/test/java/com/redhat/lightblue/migrator/consistency/ConsistencyCheckerTest.java index <HASH>..<HASH> 100644 --- a/consistency-checker/src/test/java/com/redhat/lightblue/migrator/consistency/ConsistencyCheckerTest.java +++ b/consistency-checker/src/test/java/com/redhat/lightblue/migrator/consistency/ConsistencyCheckerTest.java @@ -13,6 +13,9 @@ import org.slf4j.LoggerFactory; import com.redhat.lightblue.client.LightblueClient; import com.redhat.lightblue.client.http.LightblueHttpClient; +import com.redhat.lightblue.client.request.LightblueRequest; +import com.redhat.lightblue.client.response.LightblueResponse; +import java.io.IOException; public class ConsistencyCheckerTest { @@ -157,7 +160,7 @@ public class ConsistencyCheckerTest { checker.run(); } - + @Test public void isJobExecutable_NoExecutions() { MigrationJob job = new MigrationJob(); @@ -191,4 +194,33 @@ public class ConsistencyCheckerTest { Assert.assertFalse(ConsistencyChecker.isJobExecutable(job)); } + @Test + public void getNextAvailableJob() { + final String pid = "jewzaam was here"; + + checker.setClient(new LightblueClient() { + @Override + public LightblueResponse metadata(LightblueRequest lr) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public LightblueResponse data(LightblueRequest lr) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public <T> T data(LightblueRequest lr, Class<T> type) throws IOException { + MigrationJob[] jobs = new MigrationJob[1]; + jobs[0] = new MigrationJob(); + jobs[0].setPid(pid); + return (T)jobs; + } + }); + + MigrationJob job = checker.getNextAvailableJob(); + + Assert.assertNotNull(job); + Assert.assertEquals(pid, job.getPid()); + } }
Fixes #<I>: getNextAvailableJob handles array of one job returned
lightblue-platform_lightblue-migrator
train
d985697d8f8e00a5dd3ad216f5c5f9572c195b82
diff --git a/src/ecdsa.js b/src/ecdsa.js index <HASH>..<HASH> 100644 --- a/src/ecdsa.js +++ b/src/ecdsa.js @@ -18,6 +18,8 @@ ECPointFp.prototype.getEncoded = function (compressed) { var x = this.getX().toBigInteger(); var y = this.getY().toBigInteger(); + // Get value as a 32-byte Buffer + // Fixed length based on a patch by bitaddress.org and Casascius var enc = integerToBytes(x, 32); if (compressed) {
Added credit on encoding fix. See #1.
BitGo_bitgo-utxo-lib
train
ab1a23526ddca49b824d2abc0431109d08f8a552
diff --git a/zipline/finance/trading.py b/zipline/finance/trading.py index <HASH>..<HASH> 100644 --- a/zipline/finance/trading.py +++ b/zipline/finance/trading.py @@ -176,7 +176,7 @@ class TradingEnvironment(object): if next_open is None: raise Exception( "Attempt to backtest beyond available history. \ -Last successful date: %s" % self.market_open) +Last successful date: %s" % self.last_trading_day) return self.get_open_and_close(next_open)
BUG: Use last trading day for last successful date message. market_open member does not exist on TradingEnvironment.
quantopian_zipline
train
9c614f5a7a4c719f4a2fa67290dccf2f6e245920
diff --git a/doc/providers/security.rst b/doc/providers/security.rst index <HASH>..<HASH> 100644 --- a/doc/providers/security.rst +++ b/doc/providers/security.rst @@ -7,7 +7,8 @@ your applications. Parameters ---------- -n/a +* **security.hide_user_not_found** (optional): Defines whether to hide user not + found exception or not. Defaults to ``true``. Services -------- diff --git a/src/Silex/Provider/SecurityServiceProvider.php b/src/Silex/Provider/SecurityServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Silex/Provider/SecurityServiceProvider.php +++ b/src/Silex/Provider/SecurityServiceProvider.php @@ -71,6 +71,7 @@ class SecurityServiceProvider implements ServiceProviderInterface $app['security.role_hierarchy'] = array(); $app['security.access_rules'] = array(); + $app['security.hide_user_not_found'] = true; $app['security'] = $app->share(function ($app) { return new SecurityContext($app['security.authentication_manager'], $app['security.access_manager']); @@ -510,7 +511,8 @@ class SecurityServiceProvider implements ServiceProviderInterface $app['security.user_provider.'.$name], $app['security.user_checker'], $name, - $app['security.encoder_factory'] + $app['security.encoder_factory'], + $app['security.hide_user_not_found'] ); }); }); diff --git a/tests/Silex/Tests/Provider/SecurityServiceProviderTest.php b/tests/Silex/Tests/Provider/SecurityServiceProviderTest.php index <HASH>..<HASH> 100644 --- a/tests/Silex/Tests/Provider/SecurityServiceProviderTest.php +++ b/tests/Silex/Tests/Provider/SecurityServiceProviderTest.php @@ -145,6 +145,25 @@ class SecurityServiceProviderTest extends WebTestCase $this->assertInstanceOf('Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator', $app['security.validator.user_password_validator']); } + public function testExposedExceptions() + { + $app = $this->createApplication('form'); + $app['security.hide_user_not_found'] = false; + + $client = new Client($app); + + $client->request('get', '/'); + $this->assertEquals('ANONYMOUS', $client->getResponse()->getContent()); + + $client->request('post', '/login_check', array('_username' => 'fabien', '_password' => 'bar')); + $this->assertEquals('The presented password is invalid.', $app['security.last_error']($client->getRequest())); + $client->getRequest()->getSession()->save(); + + $client->request('post', '/login_check', array('_username' => 'unknown', '_password' => 'bar')); + $this->assertEquals('Username "unknown" does not exist.', $app['security.last_error']($client->getRequest())); + $client->getRequest()->getSession()->save(); + } + public function createApplication($authenticationMethod = 'form') { $app = new Application();
Added "security.hide_user_not_found" support in SecurityServiceProvider
silexphp_Silex
train
c2a2d0867b975a0891bf077f8a5e1ac579867407
diff --git a/provider/maas/environ_whitebox_test.go b/provider/maas/environ_whitebox_test.go index <HASH>..<HASH> 100644 --- a/provider/maas/environ_whitebox_test.go +++ b/provider/maas/environ_whitebox_test.go @@ -998,6 +998,33 @@ func (suite *environSuite) createSubnets(c *gc.C) instance.Instance { // needed for getNodeGroups to work suite.testMAASObject.TestServer.AddBootImage("uuid-0", `{"architecture": "amd64", "release": "precise"}`) + + jsonText1 := `{ + "ip_range_high": "192.168.2.255", + "ip_range_low": "192.168.2.128", + "broadcast_ip": "192.168.2.255", + "static_ip_range_low": "192.168.2.0", + "name": "eth0", + "ip": "192.168.2.1", + "subnet_mask": "255.255.255.0", + "management": 2, + "static_ip_range_high": "192.168.2.127", + "interface": "eth0" + }` + jsonText2 := `{ + "ip_range_high": "172.16.0.128", + "ip_range_low": "172.16.0.2", + "broadcast_ip": "172.16.0.255", + "static_ip_range_low": "172.16.0.129", + "name": "eth0", + "ip": "172.16.0.2", + "subnet_mask": "255.255.255.0", + "management": 2, + "static_ip_range_high": "172.16.0.255", + "interface": "eth0" + }` + suite.testMAASObject.TestServer.NewNodegroupInterface("uuid-0", jsonText1) + suite.testMAASObject.TestServer.NewNodegroupInterface("uuid-0", jsonText2) return test_instance }
Add nodegroup interface definitions to Subnets tests
juju_juju
train
28ccced8e9754c66830cf55c4bf615158790eaa9
diff --git a/classes/Pods.php b/classes/Pods.php index <HASH>..<HASH> 100644 --- a/classes/Pods.php +++ b/classes/Pods.php @@ -1350,7 +1350,11 @@ class Pods { $fields = array_merge( $object_fields, $this->fields ); } else { - foreach ( $fields as $k => $field ) { + $form_fields = $fields; // Temporary + + $fields = array(); + + foreach ( $form_fields as $k => $field ) { $name = $k; if ( !is_array( $field ) ) { @@ -1361,14 +1365,14 @@ class Pods { $name = $field[ 'name' ]; if ( pods_var_raw( 'hidden', $field, false, null, true ) ) - unset( $fields[ $k ] ); + continue; elseif ( isset( $object_fields[ $name ] ) ) - $fields[ $k ] = array_merge( $object_fields[ $name ], $field ); + $fields[ $name ] = array_merge( $object_fields[ $name ], $field ); elseif ( isset( $this->fields[ $name ] ) ) - $fields[ $k ] = array_merge( $this->fields[ $name ], $field ); - else - unset( $fields[ $k ] ); + $fields[ $name ] = array_merge( $this->fields[ $name ], $field ); } + + unset( $form_fields ); // Cleanup } $label = $params[ 'label' ]; diff --git a/deprecated/classes/Pods.php b/deprecated/classes/Pods.php index <HASH>..<HASH> 100644 --- a/deprecated/classes/Pods.php +++ b/deprecated/classes/Pods.php @@ -347,6 +347,7 @@ class Pods_Deprecated pods_deprecated( 'Pods::publicForm', '2.0.0', 'Pods::form' ); if ( !empty( $fields ) ) { + // Just update field name here, form() will handle the rest foreach ( $fields as $k => $field ) { $name = $k;
Fixes #<I> for good!
pods-framework_pods
train
c95f8be0ae11a21863ea4f641a51159e4b8b4435
diff --git a/salt/modules/random_org.py b/salt/modules/random_org.py index <HASH>..<HASH> 100644 --- a/salt/modules/random_org.py +++ b/salt/modules/random_org.py @@ -65,8 +65,6 @@ def __virtual__(): :return: The virtual name of the module. ''' - if not ENABLED: - return False return __virtualname__ diff --git a/tests/unit/modules/random_org_test.py b/tests/unit/modules/random_org_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/random_org_test.py +++ b/tests/unit/modules/random_org_test.py @@ -20,6 +20,8 @@ ensure_in_syspath('../../') # Import Salt Libs from salt.modules import random_org +random_org.__opts__ = {} + @skipIf(NO_MOCK, NO_MOCK_REASON) class RandomOrgTestCase(TestCase):
Updating unit tests based on changes to module.
saltstack_salt
train
2632f33ef42a6532352430904f51620111fcf2bf
diff --git a/lib/sprinkle/installers/apt.rb b/lib/sprinkle/installers/apt.rb index <HASH>..<HASH> 100644 --- a/lib/sprinkle/installers/apt.rb +++ b/lib/sprinkle/installers/apt.rb @@ -1,18 +1,23 @@ module Sprinkle module Installers class Apt < Installer - attr_accessor :packages + attr_accessor :packages, :command - def initialize(parent, packages, &block) + def initialize(parent, *packages, &block) super parent, &block - packages = [packages] unless packages.is_a? Array + packages.flatten! + @command = 'install' + if packages.first == :build_dep + packages.shift + @command = 'build-dep' + end @packages = packages end protected def install_commands - "DEBCONF_TERSE='yes' DEBIAN_PRIORITY='critical' DEBIAN_FRONTEND=noninteractive apt-get -qyu install #{@packages.join(' ')}" + "DEBCONF_TERSE='yes' DEBIAN_PRIORITY='critical' DEBIAN_FRONTEND=noninteractive apt-get -qyu #{command} #{@packages.join(' ')}" end end diff --git a/spec/sprinkle/installers/apt_spec.rb b/spec/sprinkle/installers/apt_spec.rb index <HASH>..<HASH> 100644 --- a/spec/sprinkle/installers/apt_spec.rb +++ b/spec/sprinkle/installers/apt_spec.rb @@ -6,8 +6,8 @@ describe Sprinkle::Installers::Apt do @package = mock(Sprinkle::Package, :name => 'package') end - def create_apt(debs, &block) - Sprinkle::Installers::Apt.new(@package, debs, &block) + def create_apt(*debs, &block) + Sprinkle::Installers::Apt.new(@package, *debs, &block) end describe 'when created' do @@ -24,6 +24,15 @@ describe Sprinkle::Installers::Apt do end + describe 'when created for :build_dep install' do + + it 'should remove :build_dep from packages list' do + @installer = create_apt :build_dep, 'ruby' + @installer.packages.should == [ 'ruby' ] + end + + end + describe 'during installation' do before do @@ -49,5 +58,17 @@ describe Sprinkle::Installers::Apt do it 'should install a specific version if defined' end + + describe 'during :build_dep installation' do + before do + @installer = create_apt :build_dep, 'ruby' + @install_commands = @installer.send :install_commands + end + + it 'should invoke the apt installer with build-dep command for all specified packages' do + @install_commands.should =~ /apt-get -qyu build-dep ruby/ + end + + end end
added :build_dep option for apt installer to run apt-get build-dep command for installing dependencies only
sprinkle-tool_sprinkle
train
02ef5bad9e2284916e7ccbf30d957bb86eb068f3
diff --git a/views/auth.php b/views/auth.php index <HASH>..<HASH> 100644 --- a/views/auth.php +++ b/views/auth.php @@ -4,7 +4,7 @@ foreach ($services as $name => $service) { echo '<li class="auth-service '.$service->id.'">'; $html = '<span class="auth-icon '.$service->id.'"><i></i></span>'; - $html .= '<span class="auth-title">'.Yii::t('eauth', $service->title).'</span>'; + $html .= '<span class="auth-title">'.$service->title.'</span>'; $html = CHtml::link($html, array($action, 'service' => $name), array( 'class' => 'auth-link '.$service->id, )); @@ -13,4 +13,4 @@ } ?> </ul> -</div> \ No newline at end of file +</div>
Update views/auth.php Removed title translation in `views/auth.php`
Nodge_yii-eauth
train
e08fdbc955dcc6c08f586307c7bfb32972c61bf2
diff --git a/docs/testdox.txt b/docs/testdox.txt index <HASH>..<HASH> 100644 --- a/docs/testdox.txt +++ b/docs/testdox.txt @@ -693,6 +693,7 @@ s9e\TextFormatter\Tests\Configurator\Helpers\TemplateHelper [x] loadTemplate() can load '<ul><li>one<li>two</ul>' [x] loadTemplate() accepts unescaped ampersands [x] loadTemplate() converts HTML entities + [x] loadTemplate() does not break numeric character references [x] saveTemplate() correctly handles '<ul><li>one<li>two</ul>' [x] loadTemplate() throws an exception on malformed XSL [x] asXPath('foo') returns 'foo' diff --git a/src/Configurator/Helpers/TemplateHelper.php b/src/Configurator/Helpers/TemplateHelper.php index <HASH>..<HASH> 100644 --- a/src/Configurator/Helpers/TemplateHelper.php +++ b/src/Configurator/Helpers/TemplateHelper.php @@ -51,9 +51,9 @@ abstract class TemplateHelper } // Try fixing unescaped ampersands and replacing HTML entities - $tmp = preg_replace('(&(?![A-Za-z0-9]+;|#x?\\d+;))', '&amp;', $template); + $tmp = preg_replace('(&(?![A-Za-z0-9]+;|#\\d+;|#x[A-Fa-f0-9]+;))', '&amp;', $template); $tmp = preg_replace_callback( - '(&(?!quot|amp|apos|lt|gt)\\w+;)', + '(&(?!quot;|amp;|apos;|lt;|gt;)\\w+;)', function ($m) { return html_entity_decode($m[0]); diff --git a/tests/Configurator/Helpers/TemplateHelperTest.php b/tests/Configurator/Helpers/TemplateHelperTest.php index <HASH>..<HASH> 100644 --- a/tests/Configurator/Helpers/TemplateHelperTest.php +++ b/tests/Configurator/Helpers/TemplateHelperTest.php @@ -119,8 +119,22 @@ class TemplateHelperTest extends Test */ public function testLoadTemplateEntities() { - $template = '<b title="&eacute;"><xsl:apply-templates/></b>'; - $xml = '<b title="é"><xsl:apply-templates/></b>'; + $template = '<b title="&&eacute;;"><xsl:apply-templates/></b>'; + $xml = '<b title="&amp;é;"><xsl:apply-templates/></b>'; + + $dom = TemplateHelper::loadTemplate($template); + $this->assertInstanceOf('DOMDocument', $dom); + + $this->assertSame($xml, $dom->saveXML($dom->documentElement->firstChild)); + } + + /** + * @testdox loadTemplate() does not break numeric character references + */ + public function testLoadTemplateNumericCharacterReferences() + { + $template = '<b title="&&#x4C;&#x4f;&#76;;"><xsl:apply-templates/></b>'; + $xml = '<b title="&amp;LOL;"><xsl:apply-templates/></b>'; $dom = TemplateHelper::loadTemplate($template); $this->assertInstanceOf('DOMDocument', $dom);
TemplateHelper: don't break numeric character references when fixing a template
s9e_TextFormatter
train
91e0c5ae8a533d98827eff5eea0b46d365991b9a
diff --git a/framework/db/Command.php b/framework/db/Command.php index <HASH>..<HASH> 100644 --- a/framework/db/Command.php +++ b/framework/db/Command.php @@ -69,7 +69,7 @@ class Command extends \yii\base\Component /** * @var array the parameters (name => value) that are bound to the current PDO statement. * This property is maintained by methods such as [[bindValue()]]. It is mainly provided for logging purpose - * and is used to generated [[rawSql]]. Do not modify it directly. + * and is used to generate [[rawSql]]. Do not modify it directly. */ public $params = []; /** diff --git a/framework/db/Connection.php b/framework/db/Connection.php index <HASH>..<HASH> 100644 --- a/framework/db/Connection.php +++ b/framework/db/Connection.php @@ -700,6 +700,31 @@ class Connection extends Component } /** + * Executes the provided callback by using the master connection. + * + * This method is provided so that you can temporarily force using the master connection to perform + * DB operations. For example, + * + * ```php + * $result = $db->useMaster(function ($db) { + * return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne(); + * }); + * ``` + * + * @param callable $callback a PHP callable to be executed by this method. Its signature is + * `function ($db)`. Its return value will be returned by this method. + * @return mixed the return value of the callback + */ + public function useMaster(callable $callback) + { + $enableSlave = $this->enableSlave; + $this->enableSlave = false; + $result = call_user_func($callback, $this); + $this->enableSlave = $enableSlave; + return $result; + } + + /** * Selects a slave and opens the connection. * @param array $slaves the list of candidate slave configurations * @return Connection the opened slave connection, or null if no slave is available diff --git a/framework/db/oci/QueryBuilder.php b/framework/db/oci/QueryBuilder.php index <HASH>..<HASH> 100644 --- a/framework/db/oci/QueryBuilder.php +++ b/framework/db/oci/QueryBuilder.php @@ -8,6 +8,7 @@ namespace yii\db\oci; use yii\base\InvalidParamException; +use yii\db\Connection; /** * QueryBuilder is the query builder for Oracle databases. @@ -133,11 +134,9 @@ EOD; $value = (int) $value; } else { // use master connection to get the biggest PK value - $enableSlave = $this->db->enableSlave; - $this->db->enableSlave = false; - $value = (int) $this->db->createCommand("SELECT MAX(\"{$tableSchema->primaryKey}\") FROM \"{$tableSchema->name}\"")->queryScalar(); - $this->db->enableSlave = $enableSlave; - $value++; + $value = $this->db->useMaster(function (Connection $db) use ($tableSchema) { + return $db->createCommand("SELECT MAX(\"{$tableSchema->primaryKey}\") FROM \"{$tableSchema->name}\"")->queryScalar(); + }) + 1; } return "DROP SEQUENCE \"{$tableSchema->name}_SEQ\";" diff --git a/framework/db/oci/Schema.php b/framework/db/oci/Schema.php index <HASH>..<HASH> 100644 --- a/framework/db/oci/Schema.php +++ b/framework/db/oci/Schema.php @@ -8,6 +8,7 @@ namespace yii\db\oci; use yii\base\InvalidCallException; +use yii\db\Connection; use yii\db\TableSchema; use yii\db\ColumnSchema; @@ -196,11 +197,9 @@ EOD; { if ($this->db->isActive) { // get the last insert id from the master connection - $enableSlave = $this->db->enableSlave; - $this->db->enableSlave = false; - $id = $this->db->createCommand("SELECT {$sequenceName}.CURRVAL FROM DUAL")->queryScalar(); - $this->db->enableSlave = $enableSlave; - return $id; + return $this->db->useMaster(function (Connection $db) use ($sequenceName) { + return $db->createCommand("SELECT {$sequenceName}.CURRVAL FROM DUAL")->queryScalar(); + }); } else { throw new InvalidCallException('DB Connection is not active.'); } diff --git a/framework/db/sqlite/QueryBuilder.php b/framework/db/sqlite/QueryBuilder.php index <HASH>..<HASH> 100644 --- a/framework/db/sqlite/QueryBuilder.php +++ b/framework/db/sqlite/QueryBuilder.php @@ -7,6 +7,7 @@ namespace yii\db\sqlite; +use yii\db\Connection; use yii\db\Exception; use yii\base\InvalidParamException; use yii\base\NotSupportedException; @@ -120,10 +121,9 @@ class QueryBuilder extends \yii\db\QueryBuilder if ($value === null) { $key = reset($table->primaryKey); $tableName = $db->quoteTableName($tableName); - $enableSlave = $this->db->enableSlave; - $this->db->enableSlave = false; - $value = $db->createCommand("SELECT MAX('$key') FROM $tableName")->queryScalar(); - $this->db->enableSlave = $enableSlave; + $value = $this->db->useMaster(function (Connection $db) use ($key, $tableName) { + return $db->createCommand("SELECT MAX('$key') FROM $tableName")->queryScalar(); + }); } else { $value = (int) $value - 1; }
Added Connection::useMaster() and refactored code.
yiisoft_yii2
train
6cdd808dfc7e35cf84c2455a79b44e8ce1f83670
diff --git a/modules/cxf-client-ws/src/main/java/io/oasp/module/cxf/common/impl/client/ws/CxfWsClientAutoConfiguration.java b/modules/cxf-client-ws/src/main/java/io/oasp/module/cxf/common/impl/client/ws/CxfWsClientAutoConfiguration.java index <HASH>..<HASH> 100644 --- a/modules/cxf-client-ws/src/main/java/io/oasp/module/cxf/common/impl/client/ws/CxfWsClientAutoConfiguration.java +++ b/modules/cxf-client-ws/src/main/java/io/oasp/module/cxf/common/impl/client/ws/CxfWsClientAutoConfiguration.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration; import io.oasp.module.service.common.api.sync.SyncServiceClientFactory; /** - * {@link Configuration} for REST (JAX-RS) clients using Apache CXF. + * {@link Configuration} for SOAP (JAX-WS) clients using Apache CXF. * * @since 3.0.0 */ @@ -14,10 +14,10 @@ import io.oasp.module.service.common.api.sync.SyncServiceClientFactory; public class CxfWsClientAutoConfiguration { /** - * @return an implemenation of {@link SyncServiceClientFactory} based on CXF for REST (JAX-RS). + * @return an implemenation of {@link SyncServiceClientFactory} based on CXF for SAOP (JAX-WS). */ @Bean - public SyncServiceClientFactory syncServiceClientFactoryCxfRest() { + public SyncServiceClientFactory syncServiceClientFactoryCxfWs() { return new SyncServiceClientFactoryCxfWs(); }
oasp/oasp4j#<I>: fixed damn stupid copy-paste bug
oasp_oasp4j
train
aac2b6154332f3ac1a6f971e3908a1d1887fd2d7
diff --git a/lib/inject.js b/lib/inject.js index <HASH>..<HASH> 100644 --- a/lib/inject.js +++ b/lib/inject.js @@ -2,6 +2,7 @@ var vstamp = require('vigour-stamp') var subscribe = require('./subscribe') +// make this into a util super handy function keyToNumber (key) { var hash = 0 for (let i = 0, len = key.length; i < len; i++) { @@ -13,13 +14,13 @@ function keyToNumber (key) { module.exports = { properties: { - _lstamp: true, + stamp: true, _sid: true, _subscriptions: true, cachedSyncPath: true }, // make it easy to create different stamps when using a hub (source ids etc) - _lstamp: 0, + stamp: 0, define: { isState: { value: true }, keysCheck (val, key) { @@ -44,16 +45,16 @@ module.exports = { }, on: { data: { - lstamp: function lstamp (val, stamp) { + stamp: function lstamp (val, stamp) { var parent = this.cParent() - this._lstamp = stamp + this.stamp = stamp if (this._subscriptions) { let l = this vstamp.on(stamp, function () { l.emit('subscription', val, stamp) }) } else { - while (parent && parent._lstamp !== stamp) { + while (parent && parent.stamp !== stamp) { lstampInner(parent, val, stamp) parent = parent.cParent() } @@ -64,7 +65,7 @@ module.exports = { } function lstampInner (parent, val, stamp) { - parent._lstamp = stamp + parent.stamp = stamp if (parent._subscriptions) { let l = parent vstamp.on(stamp, function () { diff --git a/lib/subscribe/item.js b/lib/subscribe/item.js index <HASH>..<HASH> 100644 --- a/lib/subscribe/item.js +++ b/lib/subscribe/item.js @@ -12,7 +12,14 @@ module.exports = function item (key, target, subs, update, tree, stamp) { } else if (key === '$condition') { return condition(target, subs, update, tree, stamp) } else { - return struct(key, target && target[key], subs, update, tree, tree[key], stamp) + return struct( + key, + target && key in target && target[key], + subs, update, + tree, + key in tree && tree[key], + stamp + ) } } diff --git a/lib/subscribe/struct.js b/lib/subscribe/struct.js index <HASH>..<HASH> 100644 --- a/lib/subscribe/struct.js +++ b/lib/subscribe/struct.js @@ -9,7 +9,7 @@ const composite = require('./composite') module.exports = function struct (key, target, subs, update, tree, treeKey, stamp) { var changed if (target && target.val !== null) { - let leafStamp = target._lstamp + (target._sid || target.sid()) + let leafStamp = target.stamp + (target._sid || target.sid()) let traveltarget if (target.val && target.val._base_version) { traveltarget = target.origin()
rename _lstamp to stamp
vigour-io_state
train
82cf14a035a07defacea04ae67029d5942a8311d
diff --git a/command/v7/set_label_command.go b/command/v7/set_label_command.go index <HASH>..<HASH> 100644 --- a/command/v7/set_label_command.go +++ b/command/v7/set_label_command.go @@ -46,6 +46,17 @@ func (cmd *SetLabelCommand) Setup(config command.Config, ui command.UI) error { return nil } +func (cmd SetLabelCommand) ValidateFlags() error { + if cmd.BuildpackStack != "" && ResourceType(cmd.RequiredArgs.ResourceType) != Buildpack { + return translatableerror.ArgumentCombinationError{ + Args: []string{ + cmd.RequiredArgs.ResourceType, "--stack, -s", + }, + } + } + return nil +} + func (cmd SetLabelCommand) Execute(args []string) error { labels := make(map[string]types.NullString) @@ -62,6 +73,11 @@ func (cmd SetLabelCommand) Execute(args []string) error { return err } + err = cmd.ValidateFlags() + if err != nil { + return err + } + err = cmd.validateFlags() if err != nil { return err
v7: App operator can use `cf set-label` on buildpacks [#<I>](<URL>)
cloudfoundry_cli
train
e5f929453fb141e035aeb1b867aeb06ca516409a
diff --git a/Resources/scripts/Clastic.js b/Resources/scripts/Clastic.js index <HASH>..<HASH> 100644 --- a/Resources/scripts/Clastic.js +++ b/Resources/scripts/Clastic.js @@ -11,12 +11,11 @@ module.exports = function() { global.Clastic.Clastic.prototype.resolvePaths = function(paths, rootDir) { var fs = require('fs'); - require(rootDir + '/src/Clastic/CoreBundle/Resources/scripts/GulpScript.js')(); + require('./GulpScript.js')(); - var sourceDir = 'src/Clastic'; var extraScripts = []; - fs.readdirSync(sourceDir).forEach(function (file) { - var pathDefinitions = rootDir + '/' + sourceDir + '/' + file + '/clastic.js'; + fs.readdirSync(rootDir).forEach(function (file) { + var pathDefinitions = rootDir + '/' + file + '/clastic.js'; if (fs.existsSync(pathDefinitions) && !fs.statSync(pathDefinitions).isDirectory()) { extraScripts = extraScripts.concat(require(pathDefinitions)(paths)); }
[Core] Make assets work for implementors.
Clastic_CoreBundle
train
62ab04e35245143d936a06dcd83064fdc7339965
diff --git a/examples/example_game.py b/examples/example_game.py index <HASH>..<HASH> 100644 --- a/examples/example_game.py +++ b/examples/example_game.py @@ -14,3 +14,5 @@ bsa = game.BoxscoreAdvanced('0041400122') print(bsa.sql_team_advanced()) bsf = game.BoxscoreFourFactors('0041400122') print(bsf.sql_team_four_factors()) +pt = game.PlayerTracking('0041400122') +print(pt.info()) \ No newline at end of file
Added example of PlayerTracking.
seemethere_nba_py
train
17d0ec69770943598e6ee5b2f751990f80b469f8
diff --git a/lib/geometry/transformation.rb b/lib/geometry/transformation.rb index <HASH>..<HASH> 100644 --- a/lib/geometry/transformation.rb +++ b/lib/geometry/transformation.rb @@ -8,12 +8,12 @@ To create a pure translation relationship: translate = Geometry::Transformation.new(:translate => Point[4, 2]) -To create a transformation with an origin and an X-axis aligned with the parent +To create a transformation with an origin and an X-axis aligned with the parent coordinate system's Y-axis (the Y and Z axes will be chosen arbitrarily): translate = Geometry::Transformation.new(:origin => [4, 2], :x => [0,1,0]) -To create a transformation with an origin, an X-axis aligned with the parent +To create a transformation with an origin, an X-axis aligned with the parent coordinate system's Y-axis, and a Y-axis aligned with the parent coordinate system's X-axis: @@ -76,5 +76,34 @@ system's X-axis: def identity? !(@rotation || @scale || @translation) end + + # Compose the current {Transformation} with another one + def +(other) + if other.is_a?(Array) or other.is_a?(Vector) + options = {} + options[:x] = @x_axis if @x_axis + options[:y] = @y_axis if @y_axis + options[:z] = @z_axis if @z_axis + if @translation + Transformation.new(@translation+other, @rotation, @scale, options) + else + Transformation.new(other, @rotation, @scale, options) + end + end + end + + def -(other) + if other.is_a?(Array) or other.is_a?(Vector) + options = {} + options[:x] = @x_axis if @x_axis + options[:y] = @y_axis if @y_axis + options[:z] = @z_axis if @z_axis + if @translation + Transformation.new(@translation-other, @rotation, @scale, options) + else + Transformation.new(other.map {|e| -e}, @rotation, @scale, options) + end + end + end end end diff --git a/test/geometry/transformation.rb b/test/geometry/transformation.rb index <HASH>..<HASH> 100644 --- a/test/geometry/transformation.rb +++ b/test/geometry/transformation.rb @@ -6,13 +6,15 @@ describe Geometry::Transformation do Point = Geometry::Point Transformation = Geometry::Transformation - let(:transformation) { Geometry::Transformation.new } - describe "when constructed" do - it "must accept nothing and become and identity transformation" do + it "must accept nothing and become an identity transformation" do Transformation.new.identity?.must_equal true end + it "must accept a translate parameter" do + Transformation.new([4,2]).translation.must_equal Point[4,2] + end + it "must accept a translate Array" do translate = Transformation.new(:translate => [4,2]) translate.translation.must_equal Point[4,2] @@ -46,7 +48,7 @@ describe Geometry::Transformation do it "must raise an exception when given too many rotation options" do lambda { Transformation.new :rotate => [1,2], :x => [1,0] }.must_raise ArgumentError end - + it "must accept an x axis option" do t = Transformation.new :x => [0,1] t.x_axis.must_equal [0,1] @@ -58,4 +60,20 @@ describe Geometry::Transformation do end end end + + describe "composition" do + let(:transformation) { Geometry::Transformation.new :x => [0,1,0] } + + it "array addition" do + (transformation + [1,2]).translation.must_equal Point[1,2] + ((transformation + [1,2]) + [2,3]).translation.must_equal Point[3,5] + (transformation + [1,2]).x_axis.must_equal [0,1,0] + end + + it "must update the translation when an array is subtracted" do + (transformation - [1,2]).translation.must_equal Point[-1,-2] + ((transformation - [1,2]) - [2,3]).translation.must_equal Point[-3,-5] + (transformation - [1,2,3]).x_axis.must_equal [0,1,0] + end + end end
Added basic Transformation composition Only supports translation for now
bfoz_geometry
train
dd0ff3eeb59c0e92b10ea712be77066326084207
diff --git a/src/http-api.js b/src/http-api.js index <HASH>..<HASH> 100644 --- a/src/http-api.js +++ b/src/http-api.js @@ -385,8 +385,8 @@ module.exports.MatrixHttpApi.prototype = { if (!queryParams) { queryParams = {}; } - if (this.authorization_header_supported === undefined || - this.authorization_header_supported) { + if (this.authorizationHeaderSupported === undefined || + this.authorizationHeaderSupported) { if (isFinite(opts)) { // opts used to be localTimeoutMs opts = { @@ -422,18 +422,44 @@ module.exports.MatrixHttpApi.prototype = { const self = this; + if (this.authorizationHeaderSupported === undefined) { + const defer = q.defer(); + const returnPromise = defer.promise; + returnPromise.abort = requestPromise.abort; + + requestPromise.then((resp) => { + self.authorizationHeaderSupported = true; + defer.resolve(resp); + }, (err) => { + if (err.errcode == 'M_MISSING_TOKEN' || + err.toString().indexOf("Error: CORS request rejected") != -1) { + self.authorizationHeaderSupported = false; + queryParams.access_token = opts.headers.Authorization.substr(7); + delete opts.headers.Authorization; + const secondPromise = self.request( + callback, method, path, queryParams, data, opts, + ); + returnPromise.abort = secondPromise.abort; + secondPromise.then((resp) => { + defer.resolve(resp); + }, (err) => { + if (err.errcode == 'M_UNKNOWN_TOKEN') { + self.event_emitter.emit("Session.logged_out"); + } + defer.reject(err); + }); + } else if (err.errcode == 'M_UNKNOWN_TOKEN') { + self.event_emitter.emit("Session.logged_out"); + defer.reject(err); + } else { + defer.reject(err); + } + }); + + return returnPromise; + } + requestPromise.catch(function(err) { - if (err.errcode == 'M_MISSING_TOKEN' || - err.toString().indexOf("Error: CORS request rejected") != -1) { - self.authorization_header_supported = false; - queryParams.access_token = opts.headers.Authorization.substr(7); - delete opts.headers.Authorization; - const secondPromise = self.request( - callback, method, path, queryParams, data, opts, - ); - requestPromise.abort = secondPromise.abort; - return secondPromise; - } if (err.errcode == 'M_UNKNOWN_TOKEN') { self.event_emitter.emit("Session.logged_out"); }
intercept first authedRequest to determine if accessToken can be send by header (clearer structure)
matrix-org_matrix-js-sdk
train
277d6805ca506b3ade38d092d52d030479b243f5
diff --git a/centinel/command.py b/centinel/command.py index <HASH>..<HASH> 100644 --- a/centinel/command.py +++ b/centinel/command.py @@ -37,6 +37,7 @@ class Command(): self.timeout = timeout self.started = False self.stopped = False + self.exception = None self.error = False self.notifications = "" @@ -73,10 +74,19 @@ class Command(): return False def _invoke_cmd(self): - self.process = subprocess.Popen(self.command, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) + # if the command execution throws an exception, + # it should be caught and stored in a variable. + try: + self.process = subprocess.Popen(self.command, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + except Exception as e: + self.exception = e + self.started = False + self.error = False + return + self.kill_switch = self.process.terminate self.starting = True while True: @@ -84,4 +94,4 @@ class Command(): if not line: break self.output_callback(self, line, self.process.terminate) - self.notifications += line + self.notifications += line + "\n"
added new line after each output line, added exception handling
iclab_centinel
train
9093a3f64fdf21bd029558300f60f85e4722805f
diff --git a/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/OpenApiFormat.java b/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/OpenApiFormat.java index <HASH>..<HASH> 100644 --- a/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/OpenApiFormat.java +++ b/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/OpenApiFormat.java @@ -15,7 +15,9 @@ package com.liferay.commerce.openapi.util; import com.liferay.commerce.openapi.util.exception.OpenApiException; +import com.liferay.commerce.openapi.util.util.DTOProvider; import com.liferay.commerce.openapi.util.util.OpenApiComponentUtil; +import com.liferay.commerce.openapi.util.util.Provider; import java.util.Set; @@ -24,17 +26,27 @@ import java.util.Set; */ public enum OpenApiFormat { - BIGDECIMAL("bigdecimal", OpenApiType.NUMBER, "java.math.BigDecimal"), - BINARY("binary", OpenApiType.STRING, "byte[]"), - BOOLEAN("boolean", OpenApiType.BOOLEAN, "boolean", true), - BYTE("byte", OpenApiType.STRING, "byte"), - DATE("date", OpenApiType.STRING, "java.util.Date"), - DATE_TIME("date-time", OpenApiType.STRING, "java.util.Date"), - DOUBLE("double", OpenApiType.NUMBER, "double"), - FLOAT("float", OpenApiType.NUMBER, "float", true), - INT32("int32", OpenApiType.INTEGER, "int", true), - INT64("int64", OpenApiType.INTEGER, "long"), - STRING(null, OpenApiType.STRING, "String", true); + BIGDECIMAL( + "bigdecimal", OpenApiType.NUMBER, + new Provider("BigDecimal", "java.math.BigDecimal"), true), + BINARY("binary", OpenApiType.STRING, new Provider("Byte[]", null), false), + BOOLEAN( + "boolean", OpenApiType.BOOLEAN, new Provider("Boolean", null), true), + BYTE("byte", OpenApiType.STRING, new Provider("Byte", null), false), + DATE( + "date", OpenApiType.STRING, new Provider("Date", "java.util.Date"), + false), + DATE_TIME( + "date-time", OpenApiType.STRING, new Provider("Date", "java.util.Date"), + false), + DICTIONARY( + null, OpenApiType.DICTIONARY, new Provider("Map", "java.util.Map"), + true), + DOUBLE("double", OpenApiType.NUMBER, new Provider("Double", null), false), + FLOAT("float", OpenApiType.NUMBER, new Provider("Float", null), true), + INT32("int32", OpenApiType.INTEGER, new Provider("Integer", null), true), + INT64("int64", OpenApiType.INTEGER, new Provider("Long", null), false), + STRING(null, OpenApiType.STRING, new Provider("String", null), true); public static OpenApiFormat fromOpenApiTypeAndFormat( OpenApiType openApiType, String openApiFormatDefinition) { @@ -65,7 +77,7 @@ public enum OpenApiFormat { return defaultOpenApiFormat; } - public static String getJavaType( + public static Provider getJavaTypeProvider( OpenApiProperty openApiProperty, Set<OpenApiComponent> openApiComponents) { @@ -77,17 +89,17 @@ public enum OpenApiFormat { openApiComponents); if (openApiComponent.isDictionary()) { - return "Map<String, String>"; + return DICTIONARY.getProvider(); } else if (openApiComponent.isObject()) { - return openApiComponent.getName() + "DTO"; + return new DTOProvider(openApiComponent.getName()); } throw new OpenApiException( "Unable to resolve java type for " + openApiComponent); } - return openApiProperty.getJavaType(); + return openApiProperty.getJavaTypeProvider(); } public String getGetterSyntax() { @@ -98,8 +110,8 @@ public enum OpenApiFormat { return "get"; } - public String getJavaType() { - return _javaType; + public Provider getProvider() { + return _provider; } public String getSetterSyntax() { @@ -108,25 +120,17 @@ public enum OpenApiFormat { private OpenApiFormat( String openApiFormatExpression, OpenApiType openApiType, - String javaType) { + Provider javaTypeProvider, boolean defaultFormat) { + _default = defaultFormat; _openApiFormatExpression = openApiFormatExpression; _openApiType = openApiType; - _javaType = javaType; - } - - private OpenApiFormat( - String openApiFormatExpression, OpenApiType openApiType, - String javaType, boolean defaultFormat) { - - this(openApiFormatExpression, openApiType, javaType); - - _default = defaultFormat; + _provider = javaTypeProvider; } - private boolean _default; - private String _javaType; - private String _openApiFormatExpression; - private OpenApiType _openApiType; + private final boolean _default; + private final String _openApiFormatExpression; + private final OpenApiType _openApiType; + private final Provider _provider; } \ No newline at end of file
COMMERCE-<I> commerce-openapi-util - Reorganize - instead of fixed representation of FQCN use Provider which has both. as format is widely used to obtain javaType for caller, this way we reach couple goals: primitive types as objects (Integer, Long, etc), avoid using FQCN in variable declaration and proper Map import in DTOs
liferay_com-liferay-commerce
train
3b03a4ae6f7ee8f8379c31ee04add2e6f7474d28
diff --git a/pymata_aio/pymata_core.py b/pymata_aio/pymata_core.py index <HASH>..<HASH> 100644 --- a/pymata_aio/pymata_core.py +++ b/pymata_aio/pymata_core.py @@ -1380,7 +1380,7 @@ class PymataCore: self.analog_pins[pin].current_value = value # append pin number to return value and return as a list - value = [pin, value] + value = [pin, value, Constants.ANALOG] if self.analog_pins[pin].cb: if self.analog_pins[pin].cb_type: @@ -1419,7 +1419,7 @@ class PymataCore: pin = port * 8 for pin in range(pin, min(pin + 8, len(self.digital_pins))): self.digital_pins[pin].current_value = port_data & 0x01 - data = [pin, self.digital_pins[pin].current_value] + data = [pin, self.digital_pins[pin].current_value, Constants.INPUT] if self.digital_pins[pin].cb: if self.digital_pins[pin].cb_type: await self.digital_pins[pin].cb(data)
Add pin state/type in reporting msgs
MrYsLab_pymata-aio
train
5b5c820dc7e0567aba64de3ab638f34eab0d2961
diff --git a/src/android/Sync.java b/src/android/Sync.java index <HASH>..<HASH> 100644 --- a/src/android/Sync.java +++ b/src/android/Sync.java @@ -435,8 +435,9 @@ public class Sync extends CordovaPlugin { String type = args.optString(2, TYPE_REPLACE); Log.d(LOG_TAG, "type = " + type); File dir = new File(outputDirectory); + Log.d(LOG_TAG, "dir = " + dir.exists()); - if (type.equals(TYPE_LOCAL)) { + if (type.equals(TYPE_LOCAL) && !dir.exists()) { if ("null".equals(src) && (copyRootApp || copyCordovaAssets)) { if (copyRootApp) { copyRootApp(outputDirectory); @@ -445,11 +446,15 @@ public class Sync extends CordovaPlugin { copyCordovaAssets(outputDirectory); } - } else if (!dir.exists()) { + } else { type = TYPE_REPLACE; } } + if (!dir.exists()) { + dir.mkdirs(); + } + if (!type.equals(TYPE_LOCAL)) { // download file if (download(src, createDownloadFileLocation(id), headers, progress, callbackContext)) { @@ -521,11 +526,6 @@ public class Sync extends CordovaPlugin { outputDirectory += id; Log.d(LOG_TAG, "output dir = " + outputDirectory); - File fd = new File(outputDirectory); - if (!fd.exists()) { - fd.mkdirs(); - } - return outputDirectory; }
Issue #<I>: Feat: copyRootApp if it hasn't been done before
phonegap_phonegap-plugin-contentsync
train
1ff1c8bb7159855095f7dbb0a39ef44cc6fb2815
diff --git a/src/Search/Request/BucketInterface.php b/src/Search/Request/BucketInterface.php index <HASH>..<HASH> 100644 --- a/src/Search/Request/BucketInterface.php +++ b/src/Search/Request/BucketInterface.php @@ -26,8 +26,13 @@ namespace Smile\ElasticSuiteCore\Search\Request; */ interface BucketInterface extends \Magento\Framework\Search\Request\BucketInterface { - const TYPE_HISTOGRAM = 'histogramBucket'; - const TYPE_DATE_HISTOGRAM = 'dateHistogramBucket'; + const TYPE_HISTOGRAM = 'histogramBucket'; + const TYPE_DATE_HISTOGRAM = 'dateHistogramBucket'; + + const SORT_ORDER_COUNT = '_count'; + const SORT_ORDER_TERM = '_term'; + const SORT_ORDER_RELEVANCE = "_score"; + const SORT_ORDER_MANUAL = "_manual"; /** * Indicates if the aggregation is nested.
Append facet sort orders to BucketInterface
Smile-SA_elasticsuite
train
9469c175e36f59499526374b56d2a79dda670604
diff --git a/includes/class-module.php b/includes/class-module.php index <HASH>..<HASH> 100644 --- a/includes/class-module.php +++ b/includes/class-module.php @@ -237,6 +237,12 @@ abstract class Module { return ''; } + $template = apply_filters( 'hogan/module/' . $this->name . '/template', $this->template, $this ); + + if ( ! file_exists( $template ) || 0 !== validate_file( $template ) ) { + return ''; + } + if ( false === $echo ) { ob_start(); } @@ -245,7 +251,7 @@ abstract class Module { $this->render_opening_template_wrappers( $counter ); // Include module template. - include apply_filters( 'hogan/module/' . $this->name . '/template', $this->template, $this ); + include $template; // Echo closing wrappers. $this->render_closing_template_wrappers();
Check if file exists and prevent directory traversal includes
DekodeInteraktiv_hogan-core
train
9eb216ead6d28ffe7514c91cb0d6bc80ab314b90
diff --git a/gridsome/lib/app/createRoutes.js b/gridsome/lib/app/createRoutes.js index <HASH>..<HASH> 100644 --- a/gridsome/lib/app/createRoutes.js +++ b/gridsome/lib/app/createRoutes.js @@ -44,6 +44,13 @@ module.exports = store => { templates.forEach(page => { const typeName = page.pageQuery.type + + if (!store.types.hasOwnProperty(typeName)) { + return console.info( + `No content type was found for ${page.internal.origin}` + ) + } + const contentType = store.types[typeName] const collection = store.collections[typeName] const { component, pageQuery } = page
fix: don’t create routes for missing content types
gridsome_gridsome
train
3e7fe481771ab797f5a92de32082986b7dcba121
diff --git a/modules/org.opencms.workplace/resources/system/workplace/resources/components/js_calendar/calendar.js b/modules/org.opencms.workplace/resources/system/workplace/resources/components/js_calendar/calendar.js index <HASH>..<HASH> 100644 --- a/modules/org.opencms.workplace/resources/system/workplace/resources/components/js_calendar/calendar.js +++ b/modules/org.opencms.workplace/resources/system/workplace/resources/components/js_calendar/calendar.js @@ -12,7 +12,7 @@ * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html */ -// $Id: calendar.js,v 1.51 2005/03/07 16:44:31 mishoo Exp $ +// $Id: calendar.js,v 1.3 2010/01/14 14:29:15 andreas Exp $ /** The Calendar object constructor. */ Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) { @@ -88,6 +88,7 @@ Calendar.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) ); Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) ); +Calendar.is_ie7up = ( Calendar.is_ie && parseFloat(navigator.userAgent.replace(/.*msie ([0-9]+).*/i, "$1" )) >= 7 ); /// detect Opera browser Calendar.is_opera = /opera/i.test(navigator.userAgent); @@ -1389,7 +1390,7 @@ Calendar.prototype.showAtElement = function (el, opts) { document.body.appendChild(cp); var br = Calendar.getAbsolutePos(cp); document.body.removeChild(cp); - if (Calendar.is_ie) { + if (Calendar.is_ie && !Calendar.is_ie7up) { br.y += document.body.scrollTop; br.x += document.body.scrollLeft; } else { @@ -1801,6 +1802,5 @@ Date.prototype.setFullYear = function(y) { // END: DATE OBJECT PATCHES - // global object that remembers the calendar -window._dynarch_popupCalendar = null; +window._dynarch_popupCalendar = null;
fixed calendar positioning issues in IE 7+
alkacon_opencms-core
train
db9610383a3ac64b82f6bdca91612130e6874691
diff --git a/test/integration/cors.js b/test/integration/cors.js index <HASH>..<HASH> 100644 --- a/test/integration/cors.js +++ b/test/integration/cors.js @@ -14,10 +14,13 @@ describe('setting CORS headers', function () { port: config.www_port, method: 'options', path: '/_api/_session/', - agent: false + agent: false, + headers: { + 'transfer-encoding': 'chunked' + } }, function (res) { expect(res.headers['access-control-allow-origin']).to.be('*'); - expect(res.headers['access-control-allow-headers']).to.be('authorization, content-length, content-type, if-match, if-none-match, origin, x-requested-with, host, connection, transfer-encoding'); + expect(res.headers['access-control-allow-headers']).to.be('authorization, content-length, content-type, if-match, if-none-match, origin, x-requested-with, transfer-encoding, host, connection'); expect(res.headers['access-control-expose-headers']).to.be('content-type, content-length, etag'); expect(res.headers['access-control-allow-methods']).to.be('GET, PUT, POST, DELETE'); expect(res.headers['access-control-allow-credentials']).to.be('true'); @@ -34,12 +37,13 @@ describe('setting CORS headers', function () { method: 'get', path: '/_api/_session/', headers: { - origin: 'http://some.app.com/' + origin: 'http://some.app.com/', + 'transfer-encoding': 'chunked' }, agent: false }, function (res) { expect(res.headers['access-control-allow-origin']).to.be('http://some.app.com/'); - expect(res.headers['access-control-allow-headers']).to.be('authorization, content-length, content-type, if-match, if-none-match, origin, x-requested-with, host, connection'); + expect(res.headers['access-control-allow-headers']).to.be('authorization, content-length, content-type, if-match, if-none-match, origin, x-requested-with, transfer-encoding, host, connection'); expect(res.headers['access-control-expose-headers']).to.be('content-type, content-length, etag'); expect(res.headers['access-control-allow-methods']).to.be('GET, PUT, POST, DELETE'); expect(res.headers['access-control-allow-credentials']).to.be('true');
fix(test): fix http headers for Node.js <I> and io.js * * * This commit was sponsored by The Hoodie Firm. You can hire The Hoodie Firm: <URL>
hoodiehq_hoodie
train
31c11444e28ca9bb7a1eeb5984f4b7e6b6710eac
diff --git a/themes/colors/templates/personbox_template.php b/themes/colors/templates/personbox_template.php index <HASH>..<HASH> 100644 --- a/themes/colors/templates/personbox_template.php +++ b/themes/colors/templates/personbox_template.php @@ -34,7 +34,7 @@ if (!defined('WT_WEBTREES')) { echo '<div id="out-',$boxID,'" ',$outBoxAdd,'> <div class="noprint" id="icons-',$boxID,'" style="',$iconsStyleAdd,' width: 25px; height: 50px">', $icons, '</div>', - '<div id="tbox-',$boxID,'" style="height:auto; max-height:80px; overflow: hidden; ">', + '<div id="tbox-',$boxID,'" style="height:auto; max-height:', $bheight,'px; overflow: hidden; ">', $thumbnail, '<a onclick="event.cancelBubble=true;" href="individual.php?pid=', $pid, '&amp;ged=', rawurlencode($GEDCOM), '">
Change max-width from static value to theme setting for block height
fisharebest_webtrees
train
48c068f67e3651ea09dd3fa7aaea7d02fe6eea92
diff --git a/src/Workflow/Activity/Task.php b/src/Workflow/Activity/Task.php index <HASH>..<HASH> 100644 --- a/src/Workflow/Activity/Task.php +++ b/src/Workflow/Activity/Task.php @@ -15,7 +15,6 @@ namespace PHPMentors\Workflower\Workflow\Activity; use PHPMentors\DomainKata\Entity\EntityInterface; use PHPMentors\Workflower\Workflow\Participant\ParticipantInterface; use PHPMentors\Workflower\Workflow\Participant\Role; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; class Task implements ActivityInterface, \Serializable { @@ -40,11 +39,6 @@ class Task implements ActivityInterface, \Serializable private $workItems = array(); /** - * @var EventDispatcherInterface - */ - private $eventDispatcher; - - /** * @var int|string */ private $defaultSequenceFlowId;
remove `$eventDispatcher` from `Task`
phpmentors-jp_workflower
train
1c78da85d371dc330512e992dc6d15fdcfad15b1
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -26,7 +26,7 @@ module.exports = function(grunt) { jshint: { all: [ 'Gruntfile.js', - 'lib/*.js', + 'tasks/*.js', '<%= nodeunit.tests %>' ], options: {
Fixes jshint tasks dir
DSSWG_DSS
train
fa9f5ca416f71bcdb1f86079c0480443cf46144e
diff --git a/src/Database.php b/src/Database.php index <HASH>..<HASH> 100644 --- a/src/Database.php +++ b/src/Database.php @@ -994,6 +994,7 @@ FOOT; /** @lang PhpRegExp */ '#int\(\d+\)#' => 'int', /** @lang PhpRegExp */ '#CHARACTER\sSET\s\w+#' => '', /** @lang PhpRegExp */ '#COLLATE\s\w+#' => '', + /** @lang PhpRegExp */ '#\sON\sDELETE\sNO\sACTION#' => '', /** @lang PhpRegExp */ '#AUTO_INCREMENT=\d+#' => '', /** @lang PhpRegExp */ '#COLLATE=\w+#' => '', /** @lang PhpRegExp */ '#DEFAULT CHARSET=\w+#' => '', // todo - I feel like this makes sense to flag but Actions
default on on 8 ON DELETE NO ACTION,
RichardTMiles_CarbonPHP
train
d2518e8794aa577255687b020366b1ece6b370d8
diff --git a/lib/configure.js b/lib/configure.js index <HASH>..<HASH> 100644 --- a/lib/configure.js +++ b/lib/configure.js @@ -5,7 +5,9 @@ module.exports = exports = configure * Module dependencies. */ -var path = require('path') +var fs = require('fs') + , path = require('path') + , glob = require('glob') , win = process.platform == 'win32' exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module' @@ -63,12 +65,37 @@ function configure (gyp, argv, callback) { argv.unshift('-f') } + var hasArch = argv.some(function (arg) { + return arg.indexOf('-Dtarget_arch') === 0 + }) + // was --arch specified? + if (!hasArch && gyp.opts.arch) { + gyp.verbose('using the architecture specified by --arch', gyp.opts.arch) + argv.push('-Dtarget_arch=' + gyp.opts.arch) + hasArch = true + } + + // this may need to be tweaked for windows and stuff, we'll see... + if (!hasArch) { + // on < 0.8 the target_arch variable is set to ia32 by default unless + // overridden, so we have to explicitly specify the arch here + gyp.verbose('target arch not specified, using the current host architecture', process.arch) + argv.push('-Dtarget_arch=' + process.arch) + gyp.opts.arch = process.arch + hasArch = true + } + + // execute `gyp_addon` from the current target node version argv.unshift(gyp_addon) var cp = gyp.spawn(python, argv) cp.on('exit', function (code, signal) { if (code !== 0) { callback(new Error('`gyp_addon` failed with exit code: ' + code)) + } else if (process.platform == 'darwin' && gyp.opts.arch != 'ia32') { + // XXX: Add a version check here when node upgrades gyp to a version that + // fixes this + remove_i386() } else { callback() } @@ -76,4 +103,70 @@ function configure (gyp, argv, callback) { } + /** + * Removes the lines that contain '-arch i386' from any generated + * *.target.gyp.mk files. This works around a nasty gyp bug where they + * hard-code these flags in for some reason. + */ + + function remove_i386 () { + glob('*.target.gyp.mk', function (err, files) { + if (err) return callback(err) + var count = files.length + if (count === 0) return callback() + files.forEach(function (filename) { + remove_i386single(filename, function (err) { + if (err) return callback(err) + --count || callback() + }) + }) + }) + } + + function remove_i386single (filename, done) { + gyp.verbose('removing "-arch i386" flag from', filename) + var rs = fs.createReadStream(filename) + , lines = [] + rs.setEncoding('utf8') + emitLines(rs) + rs.on('line', function (line) { + // ignore lines containing the bad flag + if (!~line.indexOf('-arch i386')) { + lines.push(line) + } + }) + rs.on('end', function () { + // now save the file back with the offending lines removed + fs.writeFile(filename, lines.join('\n'), function (err) { + if (err) return done(err) + done() + }) + }) + } + +} + + +/** + * A quick little thingy that takes a Stream instance and makes it emit 'line' + * events when a newline is encountered. + */ + +function emitLines (stream) { + var backlog = '' + stream.on('data', function (data) { + backlog += data + var n = backlog.indexOf('\n') + // got a \n? emit one or more 'line' events + while (~n) { + stream.emit('line', backlog.substring(0, n)) + backlog = backlog.substring(n + 1) + n = backlog.indexOf('\n') + } + }) + stream.on('end', function () { + if (backlog) { + stream.emit('line', backlog) + } + }) } diff --git a/lib/node-gyp.js b/lib/node-gyp.js index <HASH>..<HASH> 100644 --- a/lib/node-gyp.js +++ b/lib/node-gyp.js @@ -60,6 +60,7 @@ proto.package = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'packag proto.configDefs = { help: Boolean // everywhere + , arch: String // 'configure' , debug: Boolean // 'build' , ensure: Boolean // 'install' , verbose: Boolean // everywhere
Add an --arch flag, and properly default to the current arch when not defined. Closes #<I>.
janeasystems_nodejs-mobile-gyp
train
086c1c3b9e99fb7b1d04b1ef5c7f3e89543c1259
diff --git a/ng-FitText.js b/ng-FitText.js index <HASH>..<HASH> 100644 --- a/ng-FitText.js +++ b/ng-FitText.js @@ -1,4 +1,4 @@ -/* ng-FitText.js v2.0.0 +/* ng-FitText.js v2.1.0 * https://github.com/patrickmarabeas/ng-FitText.js * * Original jQuery project: https://github.com/davatron5000/FitText.js @@ -39,13 +39,15 @@ angular.module( 'ngFitText', [] ) ) + 'px'; if( !scope.$$phase ) scope.$digest(); - })(); - angular.element( window ).bind( 'resize', function() { + angular.element( window ).bind( 'resize', debounce( function() { scope.elementWidth = element[0].offsetWidth; scope.resizer(); - }); - } + }, 250 )); + + //Underscore's debounce function + function debounce(a,b,c){var d;return function(){var e=this,f=arguments;clearTimeout(d),d=setTimeout(function(){d=null,c||a.apply(e,f)},b),c&&!d&&a.apply(e,f)}} + } } }]); \ No newline at end of file
Added Underscore's debounce function for window resizing
patrickmarabeas_ng-FitText.js
train
b4e59165013c6fe9171243f393d73226f23ae81a
diff --git a/Controller/LegacyKernelController.php b/Controller/LegacyKernelController.php index <HASH>..<HASH> 100644 --- a/Controller/LegacyKernelController.php +++ b/Controller/LegacyKernelController.php @@ -14,6 +14,7 @@ use eZ\Bundle\EzPublishLegacyBundle\LegacyResponse\LegacyResponseManager; use eZ\Publish\Core\MVC\Legacy\Kernel\URIHelper; use Symfony\Component\HttpFoundation\Request; use eZ\Publish\Core\MVC\ConfigResolverInterface; +use ezpKernelRedirect; /** * Controller embedding legacy kernel. @@ -87,6 +88,11 @@ class LegacyKernelController $result = $this->kernel->run(); $this->kernel->setUseExceptions( true ); + if ( $result instanceof ezpKernelRedirect ) + { + return $this->legacyResponseManager->generateRedirectResponse( $result ); + } + $response = $this->legacyResponseManager->generateResponseFromModuleResult( $result ); $response->setLegacyHeaders( headers_list() ); diff --git a/LegacyResponse/LegacyResponseManager.php b/LegacyResponse/LegacyResponseManager.php index <HASH>..<HASH> 100644 --- a/LegacyResponse/LegacyResponseManager.php +++ b/LegacyResponse/LegacyResponseManager.php @@ -11,9 +11,11 @@ namespace eZ\Bundle\EzPublishLegacyBundle\LegacyResponse; use eZ\Bundle\EzPublishLegacyBundle\LegacyResponse; use eZ\Publish\Core\MVC\ConfigResolverInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Templating\EngineInterface; use ezpKernelResult; +use ezpKernelRedirect; /** * Utility class to manage Response from legacy controllers, map headers... @@ -98,12 +100,24 @@ class LegacyResponseManager } /** + * Generates proper RedirectResponse from $redirectResult. + * + * @param \ezpKernelRedirect $redirectResult + * + * @return RedirectResponse + */ + public function generateRedirectResponse( ezpKernelRedirect $redirectResult ) + { + return new RedirectResponse( $redirectResult->getTargetUrl(), $redirectResult->getStatusCode() ); + } + + /** * Renders a view and returns a Response. * * @param string $view The view name * @param array $parameters An array of parameters to pass to the view * - * @return \eZ\Bundle\EzPublishLegacyBundle\LegacyResponse\LegacyResponseManager A LegacyResponse instance + * @return \eZ\Bundle\EzPublishLegacyBundle\LegacyResponse A LegacyResponse instance */ private function render( $view, array $parameters = array() ) {
Fix EZP-<I>: Session is lost when redirecting from a legacy module
ezsystems_LegacyBridge
train
6d6ede8ab99f7e4012bb6af903fa2e85a875386d
diff --git a/lib/comments/view_helpers.rb b/lib/comments/view_helpers.rb index <HASH>..<HASH> 100644 --- a/lib/comments/view_helpers.rb +++ b/lib/comments/view_helpers.rb @@ -6,7 +6,7 @@ module Comments end def comments_tag(commentable, opts = {}) - comments = Comment.where(commentable: commentable).order("lft asc, id asc").page(params[:page]) + comments = Comment.where(commentable: commentable).includes(:user).order("lft asc, id asc").page(params[:page]) render partial: '/comments/comments', locals: { commentable: commentable, comments: comments } end
Fix comment.user N<I> queries.
rails-engine_comments
train
63777fecb8e93c00535d3f9416e660b3d05c8aec
diff --git a/raiden/tests/integration/transfer/test_refundtransfer.py b/raiden/tests/integration/transfer/test_refundtransfer.py index <HASH>..<HASH> 100644 --- a/raiden/tests/integration/transfer/test_refundtransfer.py +++ b/raiden/tests/integration/transfer/test_refundtransfer.py @@ -284,7 +284,6 @@ def test_refund_transfer( assert secrethash not in state_from_raiden(app1.raiden).payment_mapping.secrethashes_to_task -@pytest.mark.skip(reason='Working on it -- Lefteris') @pytest.mark.parametrize('privatekey_seed', ['test_different_view_of_last_bp_during_unlock:{}']) @pytest.mark.parametrize('number_of_nodes', [3]) @pytest.mark.parametrize('channels_per_node', [CHAIN]) @@ -312,6 +311,9 @@ def test_different_view_of_last_bp_during_unlock( payment_network_identifier, token_address, ) + token_proxy = app0.raiden.chain.token(token_address) + initial_balance0 = token_proxy.balance_of(app0.raiden.address) + initial_balance1 = token_proxy.balance_of(app1.raiden.address) # make a transfer to test the path app0 -> app1 -> app2 identifier_path = 1 @@ -432,7 +434,6 @@ def test_different_view_of_last_bp_during_unlock( # and now app1 comes back online app1.raiden.start() - channel_identifier = get_channelstate(app0, app1, token_network_identifier).identifier # and we wait for settlement @@ -445,18 +446,26 @@ def test_different_view_of_last_bp_during_unlock( ) with gevent.Timeout(10): - wait_for_state_change( + unlock_app0 = wait_for_state_change( app0.raiden, ContractReceiveChannelBatchUnlock, - {}, - # {'participant': secrethash}, + {'participant': app0.raiden.address}, + retry_timeout, + ) + assert unlock_app0.returned_tokens == 50 + with gevent.Timeout(10): + unlock_app1 = wait_for_state_change( + app1.raiden, + ContractReceiveChannelBatchUnlock, + {'participant': app1.raiden.address}, retry_timeout, ) - # import pdb - # pdb.set_trace() - # a = 1 + assert unlock_app1.returned_tokens == 50 + final_balance0 = token_proxy.balance_of(app0.raiden.address) + final_balance1 = token_proxy.balance_of(app1.raiden.address) - # TODO: Here assert on amounts + assert final_balance0 - deposit - initial_balance0 == -1 + assert final_balance1 - deposit - initial_balance1 == 1 @pytest.mark.parametrize('privatekey_seed', ['test_refund_transfer:{}'])
Finish and unskip test_different_view_of_last_bp_during_unlock Finish the test left skipped after PR <URL>
raiden-network_raiden
train
fd90995aa6fd79c5debe0869f01eab5d80fe8b10
diff --git a/lib/import_js/js_module.rb b/lib/import_js/js_module.rb index <HASH>..<HASH> 100644 --- a/lib/import_js/js_module.rb +++ b/lib/import_js/js_module.rb @@ -16,6 +16,7 @@ module ImportJS # e.g. ['.js', '.jsx'] # @param make_relative_to [String|nil] a path to a different file which the # resulting import path should be relative to. + # @param strip_from_path [String] def self.construct(lookup_path: nil, relative_file_path: nil, strip_file_extensions: nil,
Document strip_from_path in JSModule This was added by <I>d5eae9 but was not documented.
Galooshi_import-js
train
0b1c6cd63938d7e66e2b52320c8455eff8a76a79
diff --git a/src/AppserverIo/Appserver/Core/AbstractContainerThread.php b/src/AppserverIo/Appserver/Core/AbstractContainerThread.php index <HASH>..<HASH> 100644 --- a/src/AppserverIo/Appserver/Core/AbstractContainerThread.php +++ b/src/AppserverIo/Appserver/Core/AbstractContainerThread.php @@ -242,7 +242,7 @@ abstract class AbstractContainerThread extends AbstractContextThread implements while ($waitForServers === true) { // iterate over all servers to check the state foreach ($this->servers as $server) { - if ($server->serverState === ServerStateKeys::SERVER_SOCKET_STARTED) { + if ($server->serverState === ServerStateKeys::WORKERS_INITIALIZED) { $waitForServers = false; } else { $waitForServers = true;
Fixed error when servers starts faster than container
appserver-io_appserver
train
564b11cd724e2326b5889c639a1d40f75d1e217d
diff --git a/mythril/analysis/modules/user_assertions.py b/mythril/analysis/modules/user_assertions.py index <HASH>..<HASH> 100644 --- a/mythril/analysis/modules/user_assertions.py +++ b/mythril/analysis/modules/user_assertions.py @@ -28,15 +28,11 @@ assertion_failed_hash = ( class UserAssertions(DetectionModule): """This module searches for user supplied exceptions: emit AssertionFailed("Error").""" - def __init__(self): - """""" - super().__init__( - name="External calls", - swc_id=ASSERT_VIOLATION, - description=DESCRIPTION, - entrypoint="callback", - pre_hooks=["LOG1"], - ) + name = "External calls" + swc_id = ASSERT_VIOLATION + description = DESCRIPTION + entry_point = EntryPoint.CALLBACK + pre_hooks = ["LOG1"] def _execute(self, state: GlobalState) -> None: """
use class variables in user assertions module
ConsenSys_mythril-classic
train
97440be853ad30c888a7be77230445dc239ae79a
diff --git a/lockfile.js b/lockfile.js index <HASH>..<HASH> 100644 --- a/lockfile.js +++ b/lockfile.js @@ -241,7 +241,7 @@ function notStale (er, path, opts, cb) { exports.lock(path, newOpts, cb) } - var timer = setTimeout(retry, 100) + var timer = setTimeout(retry, opts.pollPeriod || 100) } exports.lockSync = function (path, opts) {
Fixed #6: polling period should be configurable
npm_lockfile
train
955bc434d159100af8af786104ecdcd594429b9d
diff --git a/core/test/regression/models/model_posts_spec.js b/core/test/regression/models/model_posts_spec.js index <HASH>..<HASH> 100644 --- a/core/test/regression/models/model_posts_spec.js +++ b/core/test/regression/models/model_posts_spec.js @@ -817,7 +817,7 @@ describe('Post Model', function () { createdPost.get('html').should.equal(newPostDB.html); createdPost.has('plaintext').should.equal(true); createdPost.get('plaintext').should.match(/^testing/); - createdPost.get('slug').should.equal(newPostDB.slug + '-2'); + createdPost.get('slug').should.equal(newPostDB.slug + '-3'); (!!createdPost.get('featured')).should.equal(false); (!!createdPost.get('page')).should.equal(false);
Fixed posts model regression test no issue - The failing test was introduced with <URL>
TryGhost_Ghost
train
95c67ed0ffcbacd3e69add178852b5fd44e82341
diff --git a/src/test/java/javax/util/streamex/IntStreamExTest.java b/src/test/java/javax/util/streamex/IntStreamExTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/javax/util/streamex/IntStreamExTest.java +++ b/src/test/java/javax/util/streamex/IntStreamExTest.java @@ -136,6 +136,11 @@ public class IntStreamExTest { assertEquals(0, IntStreamEx.range(0, 0, -2).count()); assertEquals(0, IntStreamEx.range(0, 0, 2).count()); } + + @Test(expected = IllegalArgumentException.class) + public void testRangeIllegalStep() { + IntStreamEx.range(0, 1000, 0); + } @Test(expected = ArrayIndexOutOfBoundsException.class) public void testArrayOffsetUnderflow() {
IntStreamExTest: step = 0 test
amaembo_streamex
train
e47d4d24d6340a5e9978cb325db53f32f2cf4341
diff --git a/lib/guard/reevaluator.rb b/lib/guard/reevaluator.rb index <HASH>..<HASH> 100644 --- a/lib/guard/reevaluator.rb +++ b/lib/guard/reevaluator.rb @@ -10,6 +10,9 @@ module Guard rescue ScriptError, StandardError => e ::Guard::UI.warning("Failed to reevaluate file: #{e}") + options = { watchers: [::Guard::Watcher.new("Guardfile")] } + ::Guard.add_plugin(:reevaluator, options) + throw :task_has_failed ensure ::Guard.restore_scope diff --git a/spec/lib/guard/reevaluator_spec.rb b/spec/lib/guard/reevaluator_spec.rb index <HASH>..<HASH> 100644 --- a/spec/lib/guard/reevaluator_spec.rb +++ b/spec/lib/guard/reevaluator_spec.rb @@ -74,6 +74,22 @@ describe Guard::Reevaluator do expect { subject.run_on_modifications(["Guardfile"]) }. to throw_symbol(:task_has_failed) end + + it "should add itself as an active plugin" do + watcher = instance_double(::Guard::Watcher) + + # TODO: the right pattern? Other custom Guardfile locations? + expect(::Guard::Watcher).to receive(:new).with("Guardfile"). + and_return(watcher) + + options = { watchers: [watcher] } + expect(::Guard).to receive(:add_plugin).with(:reevaluator, options) + + catch(:task_has_failed) do + subject.run_on_modifications(["Guardfile"]) + end + end + end end
have reevaluator add itself to plugins on failure
guard_guard
train
d5bf3d51137efdf544cc779403e2ac20cfa73fb2
diff --git a/src/directives/ccSelectBox/ccSelectBox.js b/src/directives/ccSelectBox/ccSelectBox.js index <HASH>..<HASH> 100644 --- a/src/directives/ccSelectBox/ccSelectBox.js +++ b/src/directives/ccSelectBox/ccSelectBox.js @@ -32,6 +32,9 @@ angular.module('sdk.directives.ccSelectBox') scope.model = null; } } + if (!scope.model && !scope.chooseText && scope.data.length) { + scope.model = scope.data[0]; + } }; return { diff --git a/test/karma/ccSelectBox.spec.js b/test/karma/ccSelectBox.spec.js index <HASH>..<HASH> 100644 --- a/test/karma/ccSelectBox.spec.js +++ b/test/karma/ccSelectBox.spec.js @@ -112,8 +112,8 @@ describe('Unit: sofa-select-box', function () { expect(select.value).toBe('0'); }); - it('should have an empty display value', function () { - expect(valueElement.innerHTML).toBe(''); + it('should have a display value equal to the first options\' label', function () { + expect(valueElement.innerHTML).toBe('test'); }); it('should not display a choose option', function () { @@ -170,14 +170,14 @@ describe('Unit: sofa-select-box', function () { expect(valueElement.innerHTML).toBe('test'); }); - it('should select the null value if the selected one disappears', function() { + it('should select the first of the remaining values if the selected one disappears', function() { expect(valueElement.innerHTML).toBe('preselected_value'); $scope.$apply(function () { $scope.vm.data.splice(0, 1); }); - expect(valueElement.innerHTML).toBe(''); + expect(valueElement.innerHTML).toBe('test'); }); it('it should update model on change', function() { @@ -230,6 +230,45 @@ describe('Unit: sofa-select-box', function () { select = element.querySelector('select'); })); + }); + + describe('(object)', function () { + beforeEach(inject(function ($rootScope, $compile) { + $scope = $rootScope.$new(); + + vm = $scope.vm = {}; + + vm.model = { + title: 'test_title', + value: 'test_value' + }; + vm.data = [ + { + title: 'test_title', + value: 'test_value' + } + ]; + vm.propertyName = 'test_property'; + vm.displayValueExp = 'title'; + + $element = angular.element( + '<div>' + + '<cc-select-box' + + ' model="vm.model" ' + + ' data="vm.data" ' + + ' display-value-exp="vm.displayValueExp" ' + + ' property-name="{{vm.propertyName}}">' + + ' </cc-select-box> ' + + '</div>'); + + $compile($element)($scope); + $scope.$digest(); + + element = $element[0]; + valueElement = getValueElement(element); + select = element.querySelector('select'); + })); + it('should display the selected value', function () { expect(valueElement.innerHTML).toBe('test_title'); }); @@ -239,7 +278,7 @@ describe('Unit: sofa-select-box', function () { expect(value).toEqual(vm.model.title); }); - it('it should restore the selected value if the dataset is updated with equal values', function() { + it('should restore the selected value if the dataset is updated with equal values', function() { $scope.$apply(function () { $scope.vm.data = [ @@ -367,12 +406,12 @@ describe('Unit: sofa-select-box', function () { select = element.querySelector('select'); })); - it('should set the corresponding form controller error', function () { - expect($scope[getFormName(i)].$error.required.length).toBe(1); + it('should not set the corresponding form controller error', function () { + expect($scope[getFormName(i)].$error.required).toBe(false); }); - it('should initially be invalid', function () { - expect($scope[getFormName(i)].test_property.$invalid).toBe(true); + it('should initially be valid', function () { + expect($scope[getFormName(i)].test_property.$valid).toBe(true); }); });
feat(cc-select-box): fall back to first option value if no model and choose text are given.
sofa_angular-sofa-scrolling-shadow
train
01852cd94f986e0b289365a8f86ca86a0721b103
diff --git a/src/Titon/G11n/G11n.php b/src/Titon/G11n/G11n.php index <HASH>..<HASH> 100644 --- a/src/Titon/G11n/G11n.php +++ b/src/Titon/G11n/G11n.php @@ -253,20 +253,24 @@ class G11n implements Listener { return; } - $header = mb_strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']); + $current = null; - if (mb_strpos($header, ';') !== false) { - $header = mb_strstr($header, ';', true); - } + // Determine locale based on HTTP headers + if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { + $header = mb_strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']); - $header = explode(',', $header); - $current = null; + if (mb_strpos($header, ';') !== false) { + $header = mb_strstr($header, ';', true); + } + + $header = explode(',', $header); - if (count($header) > 0) { - foreach ($header as $key) { - if (isset($this->_locales[$key])) { - $current = $key; - break; + if (count($header) > 0) { + foreach ($header as $key) { + if (isset($this->_locales[$key])) { + $current = $key; + break; + } } } }
Check for HTTP_ACCEPT_LANGUAGE first
titon_g11n
train
98ad466221bdf665c4da04abdd064d01e38da48b
diff --git a/README.rst b/README.rst index <HASH>..<HASH> 100644 --- a/README.rst +++ b/README.rst @@ -1,7 +1,7 @@ Commandify ========== -Allows simple creation of Python command line utilities through decorating functions. +Allows simple creation of Python command line utilities through decorating functions. Builds on the ``argparse`` module in the standard library. Optionally uses the ``argcomplete`` module to provide command line tab-completion for bash/zsh. Installation ============ diff --git a/commandify/commandify.py b/commandify/commandify.py index <HASH>..<HASH> 100644 --- a/commandify/commandify.py +++ b/commandify/commandify.py @@ -246,8 +246,19 @@ def commandify(*args, **kwargs): Finds the main_command and all commands and generates command line args from these.''' + if 'use_argcomplete' in kwargs: + use_argcomplete = kwargs.pop('use_argcomplete') + else: + use_argcomplete = False parser = CommandifyArgumentParser(*args, **kwargs) parser.setup_arguments() + if use_argcomplete: + try: + import argcomplete + except ImportError: + print('argcomplete not installed, please install it.') + parser.exit(status=0) + argcomplete.autocomplete(parser) args = parser.parse_args() parser.dispatch_commands() parser.exit(status=0) diff --git a/commandify/commandify_examples.py b/commandify/commandify_examples.py index <HASH>..<HASH> 100755 --- a/commandify/commandify_examples.py +++ b/commandify/commandify_examples.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +# Only required if you want to use argcomplete: +# PYTHON_ARGCOMPLETE_OK '''Examples of a simple set of functions that use commandify usage:: @@ -118,5 +120,8 @@ def cmd6(): if __name__ == '__main__': - commandify(suppress_warnings=['default_true']) - # commandify() + try: + import argcomplete + commandify(suppress_warnings=['default_true'], use_argcomplete=True) + except ImportError: + commandify(suppress_warnings=['default_true']) diff --git a/commandify/version.py b/commandify/version.py index <HASH>..<HASH> 100644 --- a/commandify/version.py +++ b/commandify/version.py @@ -1,4 +1,4 @@ -VERSION = (0, 0, 4, 4, 'alpha') +VERSION = (0, 0, 4, 5, 'alpha') def get_version(form='short'): diff --git a/docs/changelog.rst b/docs/changelog.rst index <HASH>..<HASH> 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,11 @@ Change Log ========== +Version 0.0.4.5 (Alpha) - May 17, 2015 +-------------------------------------- + +* Add support for ``argcomplete`` + Version 0.0.4.3 (Alpha) - May 15, 2015 --------------------------------------
Support for ``argcomplete``. Add references to ``argparse``, ``argcomplete`` to README.
markmuetz_commandify
train
05373425f3d150e2bac2d1b48f7682eeb081c82b
diff --git a/source/Core/Database/Adapter/Doctrine/Database.php b/source/Core/Database/Adapter/Doctrine/Database.php index <HASH>..<HASH> 100644 --- a/source/Core/Database/Adapter/Doctrine/Database.php +++ b/source/Core/Database/Adapter/Doctrine/Database.php @@ -117,9 +117,9 @@ class Database implements DatabaseInterface $connection = $this->getConnectionFromDriverManager(); $connection->connect(); - $this->ensureConnectionIsEstablished($connection); - $this->setConnection($connection); + + $this->ensureConnectionIsEstablished($connection); } catch (DBALException $exception) { $exception = $this->convertException($exception); $this->handleException($exception); @@ -1100,7 +1100,7 @@ class Database implements DatabaseInterface * * @param \Doctrine\DBAL\Connection $connection The connection we want to ensure, if it is established. * - * @throws DBALException If we are not connected correctly to the database. + * @throws \Exception If we are not connected correctly to the database. */ protected function ensureConnectionIsEstablished($connection) {
ESDEV-<I> Add ping check for master/slave connection. Cause the doctrine master slave connection object doesn't have a working isConnected method, we try to overcome this issue with the ping method. (cherry picked from commit fa<I>f2)
OXID-eSales_oxideshop_ce
train
d496b4ff87c91445cad52f7e858c089a15d32b16
diff --git a/webssh/static/js/main.js b/webssh/static/js/main.js index <HASH>..<HASH> 100644 --- a/webssh/static/js/main.js +++ b/webssh/static/js/main.js @@ -76,16 +76,12 @@ jQuery(function($){ } - function restore_items(names, storage) { + function restore_items(names) { var i, name, value; - if (storage === undefined) { - storage = window.localStorage; - } - for (i=0; i < names.length; i++) { name = names[i]; - value = storage.getItem(name); + value = window.localStorage.getItem(name); if (value) { $('#'+name).val(value); } @@ -93,6 +89,17 @@ jQuery(function($){ } + function populate_form(data) { + var names = form_keys.concat(['passphrase']), + i, name; + + for (i=0; i < names.length; i++) { + name = names[i]; + $('#'+name).val(data.get(name)); + } + } + + function get_object_length(object) { return Object.keys(object).length; } @@ -310,12 +317,12 @@ jQuery(function($){ } - function log_status(text, fill_form) { + function log_status(text, to_populate) { console.log(text); status.html(text.split('\n').join('<br/>')); - if (fill_form && validated_form_data) { - restore_items(fields.concat(['password']), validated_form_data); + if (to_populate && validated_form_data) { + populate_form(validated_form_data); validated_form_data = undefined; } @@ -539,7 +546,7 @@ jQuery(function($){ function wrap_object(opts) { var obj = {}; - obj.getItem = obj.get = function(attr) { + obj.get = function(attr) { return opts[attr] || ''; }; @@ -553,7 +560,7 @@ jQuery(function($){ function clean_data(data) { var i, attr, val; - var attrs = fields.concat(['password', 'privatekey', 'passphrase', 'totp']); + var attrs = form_keys.concat(['privatekey', 'passphrase']); for (i = 0; i < attrs.length; i++) { attr = attrs[i];
Use populate_form rather than restore_items
huashengdun_webssh
train
7afb500422db3bbfa392381b809ee8ed28ffdba8
diff --git a/sinatra-contrib/lib/sinatra/cookies.rb b/sinatra-contrib/lib/sinatra/cookies.rb index <HASH>..<HASH> 100644 --- a/sinatra-contrib/lib/sinatra/cookies.rb +++ b/sinatra-contrib/lib/sinatra/cookies.rb @@ -305,7 +305,7 @@ module Sinatra key, value = line.split(';', 2).first.to_s.split('=', 2) next if key.nil? key = Rack::Utils.unescape(key) - if line.include? "expires=Thu, 01-Jan-1970 00:00:00 GMT" + if line =~ /expires=Thu, 01[-\s]Jan[-\s]1970/ @deleted << key else @deleted.delete key diff --git a/sinatra-contrib/spec/cookies_spec.rb b/sinatra-contrib/spec/cookies_spec.rb index <HASH>..<HASH> 100644 --- a/sinatra-contrib/spec/cookies_spec.rb +++ b/sinatra-contrib/spec/cookies_spec.rb @@ -158,7 +158,7 @@ describe Sinatra::Cookies do cookie_route("foo=bar") do cookies.clear response['Set-Cookie'] - end.should include("foo=;", "expires=Thu, 01-Jan-1970 00:00:00 GMT") + end.should include("foo=;", "expires=", "1970 00:00:00") end end @@ -194,7 +194,7 @@ describe Sinatra::Cookies do cookie_route("foo=bar") do cookies.delete 'foo' response['Set-Cookie'] - end.should include("foo=;", "expires=Thu, 01-Jan-1970 00:00:00 GMT") + end.should include("foo=;", "expires=", "1970 00:00:00") end it 'honours the app cookie_options' do
fix cookie extension for Rack <I>
sinatra_sinatra
train
197df65f2b9a92831f234f67c02f9b8ffb889226
diff --git a/javascript/FieldEditor.js b/javascript/FieldEditor.js index <HASH>..<HASH> 100755 --- a/javascript/FieldEditor.js +++ b/javascript/FieldEditor.js @@ -24,13 +24,15 @@ FieldEditor.prototype = { var i, j, div, field, editables = fieldEditor.childNodes; for( i = 0; div = editables[i]; i++ ) { - var fields = div.getElementsByTagName('input'); - /*fields[fields.length - 1].value = i;*/ - for( j = 0; field = fields.item(j); j++ ) { - if( field.name == div.id + '[Sort]' ) { - field.value = i; - } - } + if(div.getElementsByTagName) { + var fields = div.getElementsByTagName('input'); + /*fields[fields.length - 1].value = i;*/ + for( j = 0; field = fields.item(j); j++ ) { + if( field.name == div.id + '[Sort]' ) { + field.value = i; + } + } + } } } },
Updated form editor's javascript to work with SSViewer-generated comments
silverstripe_silverstripe-userforms
train
412aa13f8879ef0d73c4020d8adb0a6276b3f992
diff --git a/client.js b/client.js index <HASH>..<HASH> 100644 --- a/client.js +++ b/client.js @@ -84,7 +84,7 @@ function setupMessage(client, options) { var origin = onMessage.origin window.addEventListener("message", function (ev) { - if (origin.indexOf(ev.origin) === -1) { + if (origin !== "*" && origin.indexOf(ev.origin) === -1) { return }
allow origin to be '*'
Colingo_track-event
train
9235f04ccebd35fb8a60063c2ff1d3d5fb465c00
diff --git a/lib/OpenLayers/Control.js b/lib/OpenLayers/Control.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Control.js +++ b/lib/OpenLayers/Control.js @@ -35,6 +35,6 @@ OpenLayers.Control.prototype = { this.map = null; }, - /** @type String */ + /** @final @type String */ CLASS_NAME: "OpenLayers.Control" }; diff --git a/lib/OpenLayers/Control/LayerSwitcher.js b/lib/OpenLayers/Control/LayerSwitcher.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Control/LayerSwitcher.js +++ b/lib/OpenLayers/Control/LayerSwitcher.js @@ -135,7 +135,7 @@ OpenLayers.Control.LayerSwitcher.prototype = }, - /** @type String */ + /** @final @type String */ CLASS_NAME: "OpenLayers.Control.LayerSwitcher" }); diff --git a/lib/OpenLayers/Tile.js b/lib/OpenLayers/Tile.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Tile.js +++ b/lib/OpenLayers/Tile.js @@ -50,6 +50,7 @@ OpenLayers.Tile.prototype = { remove:function() { }, + /** @final @type String */ CLASS_NAME: "OpenLayers.Tile" }; diff --git a/lib/OpenLayers/Util.js b/lib/OpenLayers/Util.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Util.js +++ b/lib/OpenLayers/Util.js @@ -88,7 +88,7 @@ OpenLayers.Pixel.prototype = { return new OpenLayers.Pixel(this.x + x, this.y + y); }, - /** @type str */ + /** @final @type str */ CLASS_NAME: "OpenLayers.Pixel" }; @@ -117,7 +117,7 @@ OpenLayers.Size.prototype = { /** * @return String representation of OpenLayers.Size object. - * (ex. "w=55,h=66") + * (ex. <i>"w=55,h=66"</i>) * @type String */ toString:function() { @@ -143,7 +143,7 @@ OpenLayers.Size.prototype = { return ((this.w == sz.w) && (this.h == sz.h)); }, - /** @type String */ + /** @final @type String */ CLASS_NAME: "OpenLayers.Size" }; @@ -172,7 +172,7 @@ OpenLayers.LonLat.prototype = { /** * @return String representation of OpenLayers.LonLat object. - * (ex. "lon=5,lat=42") + * (ex. <i>"lon=5,lat=42"</i>) * @type String */ toString:function() { @@ -181,7 +181,7 @@ OpenLayers.LonLat.prototype = { /** * @return Shortened String representation of OpenLayers.LonLat object. - * (ex. "5,42") + * (ex. <i>"5,42"</i>) * @type String */ toShortString:function() { @@ -217,7 +217,7 @@ OpenLayers.LonLat.prototype = { return ((this.lon == ll.lon) && (this.lat == ll.lat)); }, - /** @type String */ + /** @final @type String */ CLASS_NAME: "OpenLayers.LonLat" }; @@ -226,7 +226,8 @@ OpenLayers.LonLat.prototype = { * * @constructor * -* @param {String} str Comma-separated Lon,Lat coordinate string. (ex. "5,40") +* @param {String} str Comma-separated Lon,Lat coordinate string. +* (ex. <i>"5,40"</i>) * * @returns New OpenLayers.LonLat object built from the passed-in String. * @type OpenLayers.LonLat @@ -284,13 +285,13 @@ OpenLayers.Bounds.prototype = { /** * @return String representation of OpenLayers.Bounds object. - * (ex. "Min lon/lat=5/42 Max lon/lat=10/45 width:5 height:3") + * (ex.<i>"Min lon/lat=5/42 Max lon/lat=10/45 width=5 height=3"</i>) * @type String */ toString:function(){ return ("Min lon/lat=" + this.minlon +"/"+ this.minlat + " Max lon/lat=" + this.maxlon +"/"+ this.maxlat - + " width:" + this.width + " height:" + this.height); + + " width=" + this.width + " height=" + this.height); }, /** @@ -304,7 +305,7 @@ OpenLayers.Bounds.prototype = { /** * @return Simple String representation of OpenLayers.Bounds object. - * (ex. "5,42,10,45") + * (ex. <i>"5,42,10,45"</i>) * @type String */ toBBOX:function(){ @@ -323,7 +324,7 @@ OpenLayers.Bounds.prototype = { && (ll.lat >= this.minlat) && (ll.lat <= this.maxlat)); }, - /** @type String */ + /** @final @type String */ CLASS_NAME: "OpenLayers.Bounds" }; @@ -332,7 +333,7 @@ OpenLayers.Bounds.prototype = { * * @constructor * -* @param {String} str Comma-separated bounds string. (ex. "5,42,10,45") +* @param {String} str Comma-separated bounds string. (ex. <i>"5,42,10,45"</i>) * * @returns New OpenLayers.Bounds object built from the passed-in String. * @type OpenLayers.Bounds
properly declare CLASS_NAME member as constant. Also, add <i> tags around examples in comments git-svn-id: <URL>
openlayers_openlayers
train
398c338eb8ff73d65241408ac48a91d7afab8f82
diff --git a/decode_test.go b/decode_test.go index <HASH>..<HASH> 100644 --- a/decode_test.go +++ b/decode_test.go @@ -1,6 +1,7 @@ package toml import ( + "errors" "fmt" "log" "math" @@ -1557,6 +1558,39 @@ cauchy = "cat 2" } } +func TestParseError(t *testing.T) { + file := + `a = "a" +b = "b" +c = 001 # invalid +` + + var s struct { + A, B string + C int + } + _, err := Decode(file, &s) + if err == nil { + t.Fatal("err is nil") + } + + var pErr ParseError + if !errors.As(err, &pErr) { + t.Fatalf("err is not a ParseError: %T %[1]v", err) + } + + want := ParseError{ + Line: 3, + LastKey: "c", + Message: `Invalid integer "001": cannot have leading zeroes`, + } + if !strings.Contains(pErr.Message, `Invalid integer "001"`) || + pErr.Line != want.Line || + pErr.LastKey != want.LastKey { + t.Errorf("unexpected data\nhave: %#v\nwant: %#v", pErr, want) + } +} + // errorContains checks if the error message in have contains the text in // want. // diff --git a/parse.go b/parse.go index <HASH>..<HASH> 100644 --- a/parse.go +++ b/parse.go @@ -31,6 +31,8 @@ type parser struct { implicits map[string]bool } +// ParseError is used when a file can't be parsed: for example invalid integer +// literals, duplicate keys, etc. type ParseError struct { Message string Line int
Add a test and doc comment
BurntSushi_toml
train
6ba9eb0119abef854b722d58343cd1c42bc7995b
diff --git a/packages/node_modules/@webex/plugin-meetings/src/meeting/index.js b/packages/node_modules/@webex/plugin-meetings/src/meeting/index.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@webex/plugin-meetings/src/meeting/index.js +++ b/packages/node_modules/@webex/plugin-meetings/src/meeting/index.js @@ -3258,7 +3258,7 @@ export default class Meeting extends StatelessWebexPlugin { .acknowledgeMeeting({ locusUrl: this.locusUrl, deviceUrl: this.deviceUrl, - id: this.id + correlationId: this.correlationId }) .then((response) => Promise.resolve(response)) .then((response) => { diff --git a/packages/node_modules/@webex/plugin-meetings/src/meeting/request.js b/packages/node_modules/@webex/plugin-meetings/src/meeting/request.js index <HASH>..<HASH> 100644 --- a/packages/node_modules/@webex/plugin-meetings/src/meeting/request.js +++ b/packages/node_modules/@webex/plugin-meetings/src/meeting/request.js @@ -215,7 +215,7 @@ export default class MeetingRequest extends StatelessWebexPlugin { * @param {Object} options * @param {String} options.locusUrl * @param {String} options.deviceUrl - * @param {String} options.id + * @param {String} options.correlationId * @returns {Promise} */ acknowledgeMeeting(options) { @@ -225,7 +225,7 @@ export default class MeetingRequest extends StatelessWebexPlugin { deviceType: this.config.meetings.deviceType, url: options.deviceUrl }, - correlationId: options.id + correlationId: options.correlationId }; return this.request({
feat(plugin-meetings): use correlation for acknowledge
webex_spark-js-sdk
train
2fa09d71d465f63fe6310b03db511945b688b17f
diff --git a/doi2bib/bin/doi2bib b/doi2bib/bin/doi2bib index <HASH>..<HASH> 100644 --- a/doi2bib/bin/doi2bib +++ b/doi2bib/bin/doi2bib @@ -42,6 +42,11 @@ def main(): "--output", "-o", help="bibtex output file") + parser.add_argument( + "--abstract", + action='store_true', + help="try to import the abstract info") + args = parser.parse_known_args() inlinedoi = len(args[1]) > 0 if inlinedoi: @@ -51,7 +56,7 @@ def main(): dois = filter(lambda title: title != "", dois.split("\n")) bibs = [] for doi in dois: - found, bib = get_bib_from_doi(doi) + found, bib = get_bib_from_doi(doi, add_abstract=args[0].abstract) if found: bibs.append(bib) diff --git a/doi2bib/crossref.py b/doi2bib/crossref.py index <HASH>..<HASH> 100644 --- a/doi2bib/crossref.py +++ b/doi2bib/crossref.py @@ -1,6 +1,7 @@ from __future__ import unicode_literals, print_function, absolute_import from builtins import str import requests +import bibtexparser import re bare_url = "http://api.crossref.org/" @@ -47,7 +48,7 @@ def get_json(doi): return found, item -def get_bib_from_doi(doi, abbrev_journal=True): +def get_bib_from_doi(doi, abbrev_journal=True, add_abstract=False): """ Parameters ---------- @@ -66,6 +67,13 @@ def get_bib_from_doi(doi, abbrev_journal=True): found, item = get_json(doi) if found: abbreviated_journal = item["message"]["short-container-title"] + if add_abstract and "abstract" in item["message"].keys(): + + abstract = item["message"]["abstract"] + bi = bibtexparser.loads(bib) + bi.entries[0]["abstract"] = abstract + bib = bibtexparser.dumps(bi) + if len(abbreviated_journal) > 0: abbreviated_journal = abbreviated_journal[0].strip() bib = re.sub( diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -7,9 +7,9 @@ readme.close() setup( name="doi2bib", version="0.3.0", - packages = find_packages(exclude=["build",]), + packages=find_packages(exclude=["build",]), scripts=["doi2bib/bin/doi2bib"], - long_description = README_TEXT, + long_description=README_TEXT, install_requires=["requests", "future", "bibtexparser"], include_package_data=True, license="AGPLv3", @@ -17,7 +17,7 @@ setup( author="Bruno Messias", author_email="messias.physics@gmail.com", download_url="https://github.com/bibcure/doi2bib/archive/0.3.0.tar.gz", - keywords=["bibtex", "science","scientific-journals"], + keywords=["bibtex", "science", "scientific-journals"], classifiers=[ "Development Status :: 4 - Beta",
This it's related with bibcure/bibcure#<I>
bibcure_doi2bib
train
5c66235a355179f2203c21b37ca1e0c418abaefe
diff --git a/src/main/java/org/craftercms/engine/store/s3/S3ContentStoreAdapter.java b/src/main/java/org/craftercms/engine/store/s3/S3ContentStoreAdapter.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/craftercms/engine/store/s3/S3ContentStoreAdapter.java +++ b/src/main/java/org/craftercms/engine/store/s3/S3ContentStoreAdapter.java @@ -161,17 +161,22 @@ public class S3ContentStoreAdapter extends AbstractFileBasedContentStoreAdapter .withBucketName(s3Context.getBucket()) .withPrefix(s3Prefix.getPrefix()) .withDelimiter(DELIMITER); - ListObjectsV2Result result = client.listObjectsV2(request); - if(isResultEmpty(result)) { - return null; - } else { - result.getCommonPrefixes().forEach(prefix -> - children.add(new S3Prefix(StringUtils.appendIfMissing(prefix, DELIMITER)))); - result.getObjectSummaries().forEach(summary -> - children.add(new S3File(client.getObject(s3Context.getBucket(), summary.getKey())))); + ListObjectsV2Result result; + + do { + result = client.listObjectsV2(request); + if (isResultEmpty(result)) { + return null; + } else { + result.getCommonPrefixes().forEach(prefix -> + children.add(new S3Prefix(StringUtils.appendIfMissing(prefix, DELIMITER)))); + result.getObjectSummaries().forEach(summary -> + children.add(new S3File(client.getObject(s3Context.getBucket(), summary.getKey())))); + } + request.setContinuationToken(result.getNextContinuationToken()); + } while (result.isTruncated()); - return children; - } + return children; } /**
Added support for AWS S3 truncated response
craftercms_engine
train
f2a881a2c293454f399d0f809d04123834f9cdb5
diff --git a/src/actions.js b/src/actions.js index <HASH>..<HASH> 100644 --- a/src/actions.js +++ b/src/actions.js @@ -26,6 +26,6 @@ export function handleGotoAction(_parameters, _dynamicState) { }); } -export function handleRestartAction() { - return getInitialDynamicState(); +export function handleRestartAction(_parameters, _dynamicState, _context) { + return getInitialDynamicState(_context); } diff --git a/test/actions.spec.js b/test/actions.spec.js index <HASH>..<HASH> 100644 --- a/test/actions.spec.js +++ b/test/actions.spec.js @@ -1,6 +1,7 @@ import expect from 'expect'; import { handleAction, - handleGotoAction } from '../src/actions'; + handleGotoAction, + handleRestartAction } from '../src/actions'; import { setUpDynamicStateAndContextAndReportErrorSpy } from './testHelpers'; @@ -50,10 +51,42 @@ describe('goto action handling', () => { }); // TODO: Write more tests for passing bad parameters. E.g. object, string. - it('handles goto actions correctly', () => { + it('handles goto action correctly', () => { let originalDynamicState = {currentSceneId: 'first'}; let newDynamicState = handleGotoAction(['second'], originalDynamicState, context); expect(newDynamicState).toEqual({currentSceneId: 'second'}); - expect(reportError.calls.length).toEqual(0); + expect(reportError).toNotHaveBeenCalled(); + }); +}); + + +describe('restart action handling', () => { + let context, reportError; + + beforeEach('set up common test variables', function() { + ({context, reportError} = setUpDynamicStateAndContextAndReportErrorSpy()); + }); + + // TODO: Write more tests for passing bad parameters. E.g. object, string. + it('restarts correctly', () => { + let newDynamicState = handleRestartAction(undefined, undefined, context); + expect(reportError).toNotHaveBeenCalled(); + expect(newDynamicState).toEqual({ + currentSceneId: 'start', + previousSceneId: '', + tagState: {}, + vars: { + currentSceneId: { + readOnly: true, + type: 'string', + value: 'start' + }, + previousSceneId: { + readOnly: true, + type: 'string', + value: '' + } + } + }); }); });
Bugfix, wrote test for restart action.
jhorneman_choba-engine
train
4cfd6bc2858b11cdd331762774c6b06bd5e284ea
diff --git a/sllurp/llrp_proto.py b/sllurp/llrp_proto.py index <HASH>..<HASH> 100644 --- a/sllurp/llrp_proto.py +++ b/sllurp/llrp_proto.py @@ -266,6 +266,13 @@ for m in Error_Name2Type: i = Error_Name2Type[m] Error_Type2Name[i] = m +# 13.2.1 ROReportTrigger +ROReportTrigger_Name2Type = { + 'None': 0, + 'Upon_N_Tags_Or_End_Of_AISpec': 1, + 'Upon_N_Tags_Or_End_Of_ROSpec': 2, +} + # # LLRP Messages # @@ -801,6 +808,7 @@ def encode_ROSpec(par): data = encode('ROBoundarySpec')(par['ROBoundarySpec']) data += encode('AISpec')(par['AISpec']) + data += encode('ROReportSpec')(par['ROReportSpec']) data = struct.pack(msg_header, msgtype, len(data) + msg_header_len, @@ -1150,8 +1158,8 @@ Message_struct['C1G2SingulationControl'] = { # 16.2.7.1 ROReportSpec Parameter def encode_ROReportSpec (par): msgtype = Message_struct['ROReportSpec']['type'] - n = par['N'] - roReportTrigger = par['ROReportTrigger'] + n = int(par['N']) + roReportTrigger = ROReportTrigger_Name2Type[par['ROReportTrigger']] msg_header = '!HHBH' msg_header_len = struct.calcsize(msg_header) diff --git a/sllurp/test.py b/sllurp/test.py index <HASH>..<HASH> 100644 --- a/sllurp/test.py +++ b/sllurp/test.py @@ -132,8 +132,8 @@ class TestDecodeROAccessReport (unittest.TestCase): def tearDown (self): pass -class TestTagReportContentSelector (unittest.TestCase): - selections = { +class TestEncodings (unittest.TestCase): + tagReportContentSelector = { 'EnableROSpecID': False, 'EnableSpecIndex': False, 'EnableInventoryParameterSpecID': False, @@ -143,10 +143,16 @@ class TestTagReportContentSelector (unittest.TestCase): 'EnableFirstSeenTimestamp': True, 'EnableLastSeenTimestamp': True, 'EnableTagSeenCount': True, - 'EnableAccessSpecID': False, - } - def test_start (self): - data = sllurp.llrp_proto.encode_TagReportContentSelector(self.selections) + 'EnableAccessSpecID': False} + def test_roreportspec (self): + par = {'ROReportTrigger': 'Upon_N_Tags_Or_End_Of_ROSpec', + 'N': 1} + par['TagReportContentSelector'] = self.tagReportContentSelector + data = sllurp.llrp_proto.encode_ROReportSpec(par) + + def test_tagreportcontentselector (self): + par = self.tagReportContentSelector + data = sllurp.llrp_proto.encode_TagReportContentSelector(par) self.assertEqual(len(data), 48 / 8) ty = int(binascii.hexlify(data[0:2]), 16) & (2**10 - 1) self.assertEqual(ty, 238)
properly encode ROReportSpec and include in ROSpec
ransford_sllurp
train
0e84ac385b0d5fb595c7c7f95b908fb95022da64
diff --git a/lib/ruote/part/local_participant.rb b/lib/ruote/part/local_participant.rb index <HASH>..<HASH> 100644 --- a/lib/ruote/part/local_participant.rb +++ b/lib/ruote/part/local_participant.rb @@ -211,9 +211,15 @@ module Ruote # expression directly, whereas stash_put and stash_get can point at # any expression. # - def put(hash) + # 'put' can be called as + # + # put('secret' => 'message', 'to' => 'embassy') + # # or + # put('secret', 'message') + # + def put(key, value=nil) - stash_put(fei, hash) + stash_put(fei, key, value) end # See #put diff --git a/lib/ruote/receiver/base.rb b/lib/ruote/receiver/base.rb index <HASH>..<HASH> 100644 --- a/lib/ruote/receiver/base.rb +++ b/lib/ruote/receiver/base.rb @@ -148,7 +148,9 @@ module Ruote # http://groups.google.com/group/openwferu-users/t/2e6a95708c10847b for the # justification. # - def stash_put(workitem_or_fei, hash) + def stash_put(workitem_or_fei, key, value=nil) + + hash = key.is_a?(Hash) ? key : { key => value } exp = fetch_flow_expression(workitem_or_fei) diff --git a/test/functional/ft_38_participant_more.rb b/test/functional/ft_38_participant_more.rb index <HASH>..<HASH> 100644 --- a/test/functional/ft_38_participant_more.rb +++ b/test/functional/ft_38_participant_more.rb @@ -150,10 +150,11 @@ class FtParticipantMoreTest < Test::Unit::TestCase def initialize(opts) end def consume(workitem) - put('token' => workitem.params['token']) + put('token0' => workitem.params['token0']) + put('token1', workitem.params['token1']) end def cancel(fei, flavour) - BLACKBOARD['token'] = get('token') + BLACKBOARD['token0'] = get('token0') BLACKBOARD['all'] = get end end @@ -166,7 +167,7 @@ class FtParticipantMoreTest < Test::Unit::TestCase BLACKBOARD.clear pdef = Ruote.process_definition do - alpha :token => 'of esteem' + alpha :token0 => 'of esteem', :token1 => 'of whatever' end @engine.register_participant :alpha, StashingParticipant @@ -180,13 +181,19 @@ class FtParticipantMoreTest < Test::Unit::TestCase ps = @engine.process(wfid) fexp = ps.expressions.find { |e| e.fei.expid == '0_0' } - assert_equal({ 'token' => 'of esteem' }, fexp.h.stash) + assert_equal( + { 'token0' => 'of esteem', 'token1' => 'of whatever' }, + fexp.h.stash) @engine.cancel_process(wfid) wait_for(wfid) - assert_equal('of esteem', BLACKBOARD['token']) - assert_equal({ 'token' => 'of esteem' }, BLACKBOARD['all']) + assert_equal( + 'of esteem', + BLACKBOARD['token0']) + assert_equal( + { 'token0' => 'of esteem', 'token1' => 'of whatever' }, + BLACKBOARD['all']) end end
stash_put / put : more flexible
jmettraux_ruote
train
12ea8e054de401644aa9aa4e9b978a7bc770e491
diff --git a/Classes/Service/FileService.php b/Classes/Service/FileService.php index <HASH>..<HASH> 100644 --- a/Classes/Service/FileService.php +++ b/Classes/Service/FileService.php @@ -30,7 +30,7 @@ class FileService extends AbstractService { /** * Saves a file. * - * @param array $file The file object + * @param object $file The file object * @param string $uploadsFolderPath The uploads folder path * @return mixed The file name of the saved file or null if the file could not be saved */ @@ -39,8 +39,7 @@ class FileService extends AbstractService { $fileName = $file['name']; $temporaryFileName = $file['tmp_name']; $uploadsFolderPath = GeneralUtility::getFileAbsFileName($uploadsFolderPath); - $newFileName = $this->basicFileUtility->getUniqueName($fileName, $uploadsFolderPath); - $newFileName = strtolower($newFileName); + $newFileName = $this->basicFileUtility->getUniqueName(strtolower($fileName), $uploadsFolderPath); $fileCouldBeMoved = GeneralUtility::upload_copy_move($temporaryFileName, $newFileName); if ($fileCouldBeMoved) { @@ -54,7 +53,7 @@ class FileService extends AbstractService { /** * Deletes a file. * - * @param string $file The file + * @param object $file The file object * @return void */ protected function deleteFile($file) {
[➠] Improved `FileService`.
t3v_t3v_core
train
3c2d1250eac79707ddf29d7da58f4a34770332f4
diff --git a/Tone/source/GrainPlayer.js b/Tone/source/GrainPlayer.js index <HASH>..<HASH> 100644 --- a/Tone/source/GrainPlayer.js +++ b/Tone/source/GrainPlayer.js @@ -21,7 +21,7 @@ Tone.GrainPlayer = function(){ * The audio buffer belonging to the player. * @type {Tone.Buffer} */ - this.buffer = new Tone.Buffer(options.url, options.onload); + this.buffer = new Tone.Buffer(options.url, options.onload.bind(undefined, this)); /** * Create a repeating tick to schedule diff --git a/test/source/GrainPlayer.js b/test/source/GrainPlayer.js index <HASH>..<HASH> 100644 --- a/test/source/GrainPlayer.js +++ b/test/source/GrainPlayer.js @@ -78,12 +78,16 @@ describe("GrainPlayer", function(){ }); }); - it("can be created with an options object", function(){ + it("can be created with an options object", function(done){ var player = new GrainPlayer({ "url" : "./audio/sine.wav", - "loop" : true + "loop" : true, + "onload" : function(grain){ + expect(grain.loop).to.be.true; + player.dispose(); + done(); + } }); - player.dispose(); }); });
passes in the player to the callback fixes #<I>
Tonejs_Tone.js
train
4e3178a47868838189070f9cff20c755dc31cf02
diff --git a/traffic/data/airac.py b/traffic/data/airac.py index <HASH>..<HASH> 100644 --- a/traffic/data/airac.py +++ b/traffic/data/airac.py @@ -3,16 +3,17 @@ import re import zipfile from functools import lru_cache from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple, NamedTuple +from typing import Any, Dict, List, NamedTuple, Optional, Tuple from xml.etree import ElementTree import numpy as np from matplotlib.patches import Polygon as MplPolygon +from fastkml import kml +from fastkml.geometry import Geometry from shapely.geometry import Polygon from shapely.ops import cascaded_union - ExtrudedPolygon = NamedTuple('ExtrudedPolygon', [('polygon', Polygon), ('lower', float), ('upper', float)]) @@ -66,6 +67,30 @@ class Sector(object): def bounds(self) -> Tuple[float, ...]: return self.flatten().bounds + def decompose(self, extr_p): + c = np.stack(extr_p.polygon.exterior.coords) + alt = np.zeros(c.shape[0], dtype=float) + + alt[:] = min(extr_p.upper, 400) * 30.48 + upper_layer = np.c_[c, alt] + yield Polygon(upper_layer) + alt[:] = max(0, extr_p.lower) * 30.48 + lower_layer = np.c_[c, alt][::-1, :] + yield Polygon(lower_layer) + + for i, j in zip(range(c.shape[0]-1), range(c.shape[0], 1, -1)): + yield Polygon(np.r_[lower_layer[i:i+2,:], upper_layer[j-2:j, :]]) + + def export_kml(self, **kwargs): + folder = kml.Folder(name=self.name, description=self.type) + for extr_p in self: + for elt in self.decompose(extr_p): + placemark = kml.Placemark(**kwargs) + placemark.geometry = kml.Geometry( + geometry=elt, altitude_mode='relativeToGround') + folder.append(placemark) + return folder + def cascaded_union_with_alt(polyalt: SectorList) -> SectorList: altitudes = set(alt for _, *low_up in polyalt for alt in low_up) slices = sorted(altitudes) diff --git a/traffic/so6/so6.py b/traffic/so6/so6.py index <HASH>..<HASH> 100644 --- a/traffic/so6/so6.py +++ b/traffic/so6/so6.py @@ -174,10 +174,12 @@ class Flight(object): 'description': f"{self.origin} → {self.destination}"} for key, value in kwargs.items(): params[key] = value - placemark = kml.Placemark(**params) placemark.visibility = 1 - placemark.geometry = Geometry(geometry=self.linestring, + # Convert to meters + coords = np.stack(self.coords) + coords[:, 2] *= 0.3048 + placemark.geometry = Geometry(geometry=LineString(coords), extrude=True, altitude_mode='relativeToGround') return placemark
Export to kml for sectors and trajectories refs #3
xoolive_traffic
train
ec8136f959a46b582315488caed3e67a5f4c4511
diff --git a/src/ServiceManager.php b/src/ServiceManager.php index <HASH>..<HASH> 100644 --- a/src/ServiceManager.php +++ b/src/ServiceManager.php @@ -730,6 +730,7 @@ class ServiceManager implements ServiceLocatorInterface if ($abstractFactory->canCreateServiceWithName($this, $cName, $rName)) { $this->nestedContext[$cName] = $abstractFactory; $result = true; + break; } } $this->checkNestedContextStop();
Fix for zendframework/zf2#<I> - updated ServiceManager, added break after valid abstract factory found
mxc-commons_mxc-servicemanager
train
2a7c1a16337117b1b62e219b43286a6ea2ec2ff2
diff --git a/issue_comment.go b/issue_comment.go index <HASH>..<HASH> 100644 --- a/issue_comment.go +++ b/issue_comment.go @@ -13,11 +13,14 @@ import ( // Comment represents a comment in commit and issue page. type Comment struct { - ID int64 `json:"id"` - Poster *User `json:"user"` - Body string `json:"body"` - Created time.Time `json:"created_at"` - Updated time.Time `json:"updated_at"` + ID int64 `json:"id"` + HTMLURL string `json:"html_url"` + PRURL string `json:"pull_request_url"` + IssueURL string `json:"issue_url"` + Poster *User `json:"user"` + Body string `json:"body"` + Created time.Time `json:"created_at"` + Updated time.Time `json:"updated_at"` } // ListIssueComments list comments on an issue. @@ -26,6 +29,12 @@ func (c *Client) ListIssueComments(owner, repo string, index int64) ([]*Comment, return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/%d/comments", owner, repo, index), nil, nil, &comments) } +// ListRepoIssueComments list comments for a given repo. +func (c *Client) ListRepoIssueComments(owner, repo string) ([]*Comment, error) { + comments := make([]*Comment, 0, 10) + return comments, c.getParsedResponse("GET", fmt.Sprintf("/repos/%s/%s/issues/comments", owner, repo), nil, nil, &comments) +} + // CreateIssueCommentOption is option when creating an issue comment. type CreateIssueCommentOption struct { Body string `json:"body" binding:"Required"` @@ -55,3 +64,9 @@ func (c *Client) EditIssueComment(owner, repo string, index, commentID int64, op comment := new(Comment) return comment, c.getParsedResponse("PATCH", fmt.Sprintf("/repos/%s/%s/issues/%d/comments/%d", owner, repo, index, commentID), jsonHeader, bytes.NewReader(body), comment) } + +// DeleteIssueComment deletes an issue comment. +func (c *Client) DeleteIssueComment(owner, repo string, index, commentID int64) error { + _, err := c.getResponse("DELETE", fmt.Sprintf("/repos/%s/%s/issues/%d/comments/%d", owner, repo, index, commentID), nil, nil) + return err +}
More Issue-Comments API-endpoints (gogs/#<I>) (#<I>) * Issue-comments can be deleted * List all comments for a repo * Moar data in issue-comments
gogs_go-gogs-client
train
091f28ca0af9221c975b9d1cf0ce0006fd0799cb
diff --git a/src/Models/Model.php b/src/Models/Model.php index <HASH>..<HASH> 100644 --- a/src/Models/Model.php +++ b/src/Models/Model.php @@ -38,7 +38,8 @@ abstract class Model implements Entity { */ public function is_valid() { // Check if there are errors - return empty($this->get_errors()); + $isEmpty = empty($this->get_errors()); + return $isEmpty; } abstract public function set();
Hack for overcoming php <I>- limitation in 'empty' function.
konduto_php-sdk
train
fa71756ac03ca8cff9066c4272a99586da6729c8
diff --git a/DependencyInjection/Compiler/BunnyCompilerPass.php b/DependencyInjection/Compiler/BunnyCompilerPass.php index <HASH>..<HASH> 100644 --- a/DependencyInjection/Compiler/BunnyCompilerPass.php +++ b/DependencyInjection/Compiler/BunnyCompilerPass.php @@ -80,6 +80,11 @@ class BunnyCompilerPass implements CompilerPassInterface } $className = $parameterBag->resolveValue($definition->getClass()); + + if (!class_exists($className)) { + continue; + } + $rc = new \ReflectionClass($className); if (strpos($rc->getDocComment(), "@Consumer") === false && strpos($rc->getDocComment(), "@Producer") === false) {
prevent BunnyCompilerPass from using reflection on classes that don't exist
skrz_bunny-bundle
train
08ecb2f97f40272a1598f8cc46553ab92c15d6e8
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -26,7 +26,7 @@ setup(name = 'GPy', long_description=read('README.md'), #ext_modules = [Extension(name = 'GPy.kern.lfmUpsilonf2py', # sources = ['GPy/kern/src/lfmUpsilonf2py.f90'])], - install_requires=['numpy>=1.6', 'scipy','matplotlib>=1.1'], + install_requires=['pylab, numpy>=1.6', 'scipy','matplotlib>=1.1'], setup_requires=['sphinx'], cmdclass = {'build_sphinx': BuildDoc}, classifiers=[
Added pylab to requirements
SheffieldML_GPy
train
41a023ca86b5d9406b3320804ca84699e6bb0417
diff --git a/src/Promise.php b/src/Promise.php index <HASH>..<HASH> 100644 --- a/src/Promise.php +++ b/src/Promise.php @@ -164,17 +164,6 @@ class Promise implements ExtendedPromiseInterface, CancellablePromiseInterface $this->settle(reject($reason)); } - private function notify($update = null) - { - if (null !== $this->result) { - return; - } - - foreach ($this->progressHandlers as $handler) { - $handler($update); - } - } - private function settle(ExtendedPromiseInterface $promise) { $promise = $this->unwrap($promise); @@ -239,6 +228,11 @@ class Promise implements ExtendedPromiseInterface, CancellablePromiseInterface if ($args === 0) { $callback(); } else { + // Store a reference to all progress handlers (will be cleared when settled) + // This way, we can use a static progress callback that is not bound to this promise instance. + // This helps avoiding garbage cycles if the callback creates an Exception. + $progress =& $this->progressHandlers; + $callback( function ($value = null) { $this->resolve($value); @@ -246,9 +240,11 @@ class Promise implements ExtendedPromiseInterface, CancellablePromiseInterface function ($reason = null) { $this->reject($reason); }, - function ($update = null) { - $this->notify($update); - } + \Closure::bind(function ($update = null) use (&$progress) { + foreach ($progress as $handler) { + $handler($update); + } + }, null) ); } } catch (\Throwable $e) { diff --git a/tests/PromiseTest.php b/tests/PromiseTest.php index <HASH>..<HASH> 100644 --- a/tests/PromiseTest.php +++ b/tests/PromiseTest.php @@ -60,6 +60,39 @@ class PromiseTest extends TestCase $this->assertSame(0, gc_collect_cycles()); } + /** + * test that checks number of garbage cycles after throwing from a resolver + * that has its arguments explicitly set to null (reassigned arguments only + * show up in the stack trace in PHP 7, so we can't test this on legacy PHP) + * + * @test + * @requires PHP 7 + * @link https://3v4l.org/OiDr4 + */ + public function shouldRejectWithoutCreatingGarbageCyclesIfResolverThrowsExceptionWithResolveAndRejectUnset() + { + gc_collect_cycles(); + $promise = new Promise(function ($resolve, $reject) { + $resolve = $reject = null; + throw new \Exception('foo'); + }); + unset($promise); + + $this->assertSame(0, gc_collect_cycles()); + } + + /** @test */ + public function shouldIgnoreNotifyAfterReject() + { + $promise = new Promise(function () { }, function ($resolve, $reject, $notify) { + $reject(new \Exception('foo')); + $notify(42); + }); + + $promise->then(null, null, $this->expectCallableNever()); + $promise->cancel(); + } + /** @test */ public function shouldFulfillIfFullfilledWithSimplePromise() {
Use static progress callback without binding to promise
reactphp_promise
train
30ede81c1326a750c8e258c46f57d90fc7eca45c
diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -1412,7 +1412,7 @@ public class Queue extends ResourceController implements Saveable { } // pending -> buildable for (BuildableItem p: lostPendings) { - LOGGER.log(Level.INFO, + LOGGER.log(Level.FINE, "BuildableItem {0}: pending -> buildable as the assigned executor disappeared", p.task.getFullDisplayName()); p.isPending = false;
Downgrade Queue#maintain() message for dead executor from INFO to FINE. (#<I>)
jenkinsci_jenkins
train
67d6a3d548701f669e613fffbe435f69480829d1
diff --git a/lib/chef/provider/service/freebsd.rb b/lib/chef/provider/service/freebsd.rb index <HASH>..<HASH> 100644 --- a/lib/chef/provider/service/freebsd.rb +++ b/lib/chef/provider/service/freebsd.rb @@ -180,7 +180,7 @@ class Chef def set_service_enable(value) lines = read_rc_conf # Remove line that set the old value - lines.delete_if { |line| line =~ /^#{Regexp.escape(service_enable_variable_name)}=/ } + lines.delete_if { |line| line =~ /^\#?\s*#{Regexp.escape(service_enable_variable_name)}=/ } # And append the line that sets the new value at the end lines << "#{service_enable_variable_name}=\"#{value}\"" write_rc_conf(lines) diff --git a/spec/unit/provider/service/freebsd_service_spec.rb b/spec/unit/provider/service/freebsd_service_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/service/freebsd_service_spec.rb +++ b/spec/unit/provider/service/freebsd_service_spec.rb @@ -580,6 +580,13 @@ EOF expect(provider).not_to receive(:write_rc_conf) provider.enable_service end + + it "should remove commented out versions of it being enabled" do + allow(current_resource).to receive(:enabled).and_return(false) + expect(provider).to receive(:read_rc_conf).and_return([ "foo", "bar", "\# #{new_resource.service_name}_enable=\"YES\"", "\# #{new_resource.service_name}_enable=\"NO\""]) + expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"YES\""]) + provider.enable_service() + end end describe Chef::Provider::Service::Freebsd, "disable_service" do @@ -607,5 +614,12 @@ EOF expect(provider).not_to receive(:write_rc_conf) provider.disable_service() end + + it "should remove commented out versions of it being disabled or enabled" do + allow(current_resource).to receive(:enabled).and_return(true) + expect(provider).to receive(:read_rc_conf).and_return([ "foo", "bar", "\# #{new_resource.service_name}_enable=\"YES\"", "\# #{new_resource.service_name}_enable=\"NO\""]) + expect(provider).to receive(:write_rc_conf).with(["foo", "bar", "#{new_resource.service_name}_enable=\"NO\""]) + provider.disable_service() + end end end
Remove commented out versions of a service being enabled/disabled in FreeBSD.
chef_chef
train
b613dbd46a52da36a847a208627154b1aefb9c9a
diff --git a/openquake/commonlib/oqvalidation.py b/openquake/commonlib/oqvalidation.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/oqvalidation.py +++ b/openquake/commonlib/oqvalidation.py @@ -42,8 +42,6 @@ CALCULATORS = HAZARD_CALCULATORS + RISK_CALCULATORS class OqParam(valid.ParamSet): - exports = 'csv' # default value, normally overridden - area_source_discretization = valid.Param( valid.NoneOr(valid.positivefloat), None) asset_correlation = valid.Param(valid.NoneOr(valid.FloatRange(0, 1)), 0) @@ -59,6 +57,7 @@ class OqParam(valid.ParamSet): epsilon_sampling = valid.Param(valid.positiveint, 1000) export_dir = valid.Param(valid.utf8, None) export_multi_curves = valid.Param(valid.boolean, False) + exports = valid.Param(valid.Choice('csv', 'xml', 'geo_json'), 'csv') ground_motion_correlation_model = valid.Param( valid.NoneOr(valid.Choice(*GROUND_MOTION_CORRELATION_MODELS)), None) ground_motion_correlation_params = valid.Param(valid.dictionary)
Added exports as a parameter of job.ini
gem_oq-engine
train
9598b4b718320350066b831095e6226b9a909d27
diff --git a/lib/emitter/push/bind.js b/lib/emitter/push/bind.js index <HASH>..<HASH> 100644 --- a/lib/emitter/push/bind.js +++ b/lib/emitter/push/bind.js @@ -58,7 +58,7 @@ exports.define = { if (!bound) { bound = this.setBind(event, bind, data, true) } - var boundchain = bound + var boundchain = bound // these chains nex optmization for (let i = 0, length = chain.length; i < length; i++) { if (boundchain[chain[i].context.uid]) { boundchain = boundchain[chain[i].context.uid] diff --git a/lib/emitter/trigger/method.js b/lib/emitter/trigger/method.js index <HASH>..<HASH> 100644 --- a/lib/emitter/trigger/method.js +++ b/lib/emitter/trigger/method.js @@ -1,33 +1,26 @@ 'use strict' +var isEmpty = require('../../util/is/empty') module.exports = function triggerInternal (event) { - // = this.lastStamp - var stamp = event.stamp - // var contextBinds = this.contextBinds && this.contextBinds[stamp] - var binds = this.binds && this.binds[stamp] - var isEmpty = require('../../util/is/empty') + var binds = this.binds && this.binds[event.stamp] if (binds) { for (let i in binds) { let bound = binds[i] let data = bound.data + let bind = bound.val + if (bound.context) { execContext.call(this, bound, event, data) bound.context[0].bind.setContextChain(bound.context) } - if (!bound.val) { - delete binds[i] - } - } - for (let i in binds) { - let bound = binds[i] - let data = bound.data - let bind = bound.val if (bind) { bind.clearContextUp() this.execInternal(bind, event, data) delete binds[i] + } else { + delete binds[i] } } diff --git a/test/common/observable/emitter/instances/childconstructor.js b/test/common/observable/emitter/instances/childconstructor.js index <HASH>..<HASH> 100644 --- a/test/common/observable/emitter/instances/childconstructor.js +++ b/test/common/observable/emitter/instances/childconstructor.js @@ -45,10 +45,11 @@ describe('use a childconstructor listener', function () { it('remove field', function () { aInstance.something.b.remove() + console.log(paths) expect(paths).to.deep.equal([ 'bInstance.something.b', - 'bInstance.something', 'aInstance.something.b', + 'bInstance.something', 'aInstance.something' ]) expect(cnt).to.equal(4)
cleaned up trgger method (context and normal binds share the same for loop)
vigour-io_vjs
train
1b25a01a79c97ec28465b13b29bafac1dd628c38
diff --git a/examples/largeimages/main.rb b/examples/largeimages/main.rb index <HASH>..<HASH> 100644 --- a/examples/largeimages/main.rb +++ b/examples/largeimages/main.rb @@ -63,7 +63,7 @@ loop do entry.at_xpath("link[@rel='alternate']")["href"], ] end ) ], - [:source_reddit, 20000000, ( INCLUDE.flat_map do |sortasub| + [:source_reddit, 30000000, ( INCLUDE.flat_map do |sortasub| BOT.new_posts(sortasub).take(100).map do |child| next if child["is_self"] next if EXCLUDE.include? child["subreddit"].downcase
increasing source-reddit treshold
Nakilon_reddit_bot
train
73644f16af8aaac5659ea1398b83b64f984239cd
diff --git a/test/unit/org/apache/cassandra/io/util/BufferedRandomAccessFileTest.java b/test/unit/org/apache/cassandra/io/util/BufferedRandomAccessFileTest.java index <HASH>..<HASH> 100644 --- a/test/unit/org/apache/cassandra/io/util/BufferedRandomAccessFileTest.java +++ b/test/unit/org/apache/cassandra/io/util/BufferedRandomAccessFileTest.java @@ -69,6 +69,30 @@ public class BufferedRandomAccessFileTest r.close(); } + @Test + public void testReadsOnCapacity() throws IOException + { + File tmpFile = File.createTempFile("readtest", "bin"); + BufferedRandomAccessFile rw = new BufferedRandomAccessFile(tmpFile, "rw"); + + // Fully write the file and sync.. + byte[] in = new byte[BufferedRandomAccessFile.BuffSz_]; + rw.write(in); + rw.sync(); + + // Read it into a same size array. + byte[] out = new byte[BufferedRandomAccessFile.BuffSz_]; + rw.read(out); + + // We're really at the end. + long rem = rw.bytesRemaining(); + assert rem == 0 : "BytesRemaining should be 0 but it's " + rem; + + // Cannot read any more. + int negone = rw.read(); + assert negone == -1 : "We read past the end of the file, should have gotten EOF -1. Instead, " + negone; + } + protected void expectException(int size, int offset, int len, BufferedRandomAccessFile braf) { boolean threw = false; @@ -110,4 +134,17 @@ public class BufferedRandomAccessFileTest return f; } + + @Test (expected=UnsupportedOperationException.class) + public void testOverflowMark() throws IOException + { + File tmpFile = File.createTempFile("overflowtest", "bin"); + tmpFile.deleteOnExit(); + BufferedRandomAccessFile rw = new BufferedRandomAccessFile(tmpFile, "rw"); + FileMark mark = rw.mark(); + rw.seek(4L*1024L*1024L*1024L*1024L); //seek 4gb + + //Expect this call to fail, because the distance from mark to current file pointer > 2gb. + int bpm = rw.bytesPastMark(mark); + } }
flesh out BufferedRandomAccessFileTest. patch by Jon Hermes; reviewed by Stu Hood for CASSANDRA-<I> git-svn-id: <URL>
Stratio_stratio-cassandra
train
d42980f4dee6d5ba82cb8e4febe044406b409d41
diff --git a/tbapy/main.py b/tbapy/main.py index <HASH>..<HASH> 100644 --- a/tbapy/main.py +++ b/tbapy/main.py @@ -14,10 +14,10 @@ class TBA: READ_URL_PRE = 'https://www.thebluealliance.com/api/v3/' WRITE_URL_PRE = 'https://www.thebluealliance.com/api/trusted/v1/' session = requests.Session() - auth_secret = None + auth_secret = '' event_key = '' - def __init__(self, auth_key, auth_id=None, auth_secret=None, event_key=''): + def __init__(self, auth_key, auth_id='', auth_secret='', event_key=''): """ Store auth key so we can reuse it as many times as we make a request. @@ -461,6 +461,13 @@ class TBA: """ return self._post('event/%s/matches/delete', json.dumps(data)) + def delete_all_event_matches(self): + """ + Delete all of an event's matches on The Blue Alliance. + + """ + return self._post('event/%s/matches/delete_all', json.dumps(self.event_key)) + def update_event_rankings(self, data): """ Update an event's rankings on The Blue Alliance.
Make auth_id and secret empty strings.
frc1418_tbapy
train
194122b330c80739038662115bd38fb6871eee26
diff --git a/src/object-model.js b/src/object-model.js index <HASH>..<HASH> 100644 --- a/src/object-model.js +++ b/src/object-model.js @@ -22,6 +22,8 @@ export default function ObjectModel() { } extend(ObjectModel, Model, { + sealed: true, + defaults(p){ Object.assign(this.prototype, p) return this @@ -148,7 +150,7 @@ function controlMutation(model, def, path, o, key, applyMutation) { }) } - if (def.hasOwnProperty(key)) { + if (!model.sealed || def.hasOwnProperty(key)) { applyMutation(newPath) checkDefinition(o[key], def[key], newPath, model.errors, []) checkAssertions(o, model, newPath)
add ObjectModel.prototype.seal to allow configuration for arbitrary properties in object models
sylvainpolletvillard_ObjectModel
train
d8e03ac782f310aa33962faa6f49d11c64060cd2
diff --git a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php +++ b/src/Symfony/Bundle/DoctrineBundle/Command/DoctrineCommand.php @@ -70,6 +70,9 @@ abstract class DoctrineCommand extends Command { $entityGenerator = new EntityGenerator(); + if (version_compare(\Doctrine\ORM\Version::VERSION, "2.0.2-DEV") >= 0) { + $entityGenerator->setAnnotationPrefix("orm:"); + } $entityGenerator->setGenerateAnnotations(false); $entityGenerator->setGenerateStubMethods(true); $entityGenerator->setRegenerateEntityIfExists(false);
[DoctrineBundle] Add support to setting the Annotations prefix to @orm: for EntityGeneration beginning with Doctrine ORM <I>-DEV.
symfony_symfony
train