hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
539ae28ba76ed005bf1f83252b0ccb64df9c14fe
diff --git a/lib/base/provisioner.rb b/lib/base/provisioner.rb index <HASH>..<HASH> 100644 --- a/lib/base/provisioner.rb +++ b/lib/base/provisioner.rb @@ -246,7 +246,6 @@ class VCAP::Services::Base::Provisioner < VCAP::Services::Base::Base @logger.debug("[#{service_description}] Unbind instance #{handle_id} from #{node_id}") request = svc[:credentials] - @node_nats.publish("#{service_name}.unbind.#{node_id}", Yajl::Encoder.encode(request)) subscription = nil timer = EM.add_timer(@node_timeout) {
remove legacy code to aviod double-unbind bug
cloudfoundry-attic_vcap-services-base
train
84aba94ee4177c4e8054f6d3a02ec68e7e02b224
diff --git a/scripts/maf_to_concat_fasta.py b/scripts/maf_to_concat_fasta.py index <HASH>..<HASH> 100755 --- a/scripts/maf_to_concat_fasta.py +++ b/scripts/maf_to_concat_fasta.py @@ -3,17 +3,37 @@ """ Read a maf and print the text as a fasta file, concatenating blocks -usage %prog species1,species2 < maf_file +usage %prog species1,species2,... [--fill="expression"] [--wrap=columns] < maf_file """ -from __future__ import division +from optparse import OptionParser import textwrap import sys from bx.align import maf def __main__(): - species = sys.argv[1].split(',') + # Parse command line arguments + + parser = OptionParser() + parser.add_option( "--fill", action="store", default=None, type="string", help="" ) + parser.add_option( "--wrap", action="store", default=None, type="int", help="" ) + parser.add_option( "--nowrap", action="store_true", default=False, dest="nowrap", help="" ) + + ( options, args ) = parser.parse_args() + + species = [] + for arg in args: species.extend(arg.split(',')) + + fill = "" + if options.fill: fill = eval( options.fill ) + + wrap = 50 + if (options.wrap != None): wrap = options.wrap + elif (options.nowrap): wrap = 0 + + # create the concatenated sequences + texts = {} for s in species: texts[s] = [] maf_reader = maf.Reader( sys.stdin ) @@ -21,15 +41,18 @@ def __main__(): for s in species: c = m.get_component_by_src_start( s ) if c: texts[s].append( c.text ) - else: texts[s].append( "-" * m.text_len ) + else: texts[s].append( "-" * m.text_size ) for s in species: print ">" + s - print_n( "".join( texts[s] ), 50 ) + print_n( fill.join( texts[s] ), wrap ) def print_n( s, n, f = sys.stdout ): - p = 0 - while p < len( s ): - print >> f, s[p:min(p+n,len(s))] - p += n + if (n <= 0): + print >> f, s + else: + p = 0 + while p < len( s ): + print >> f, s[p:min(p+n,len(s))] + p += n if __name__ == "__main__": __main__()
was out-of-date with latest alignment class; added a few prettifying options
bxlab_bx-python
train
4fb5b9918b93c267622069734fecf524369e0d28
diff --git a/openquake/calculators/hazard/general.py b/openquake/calculators/hazard/general.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/hazard/general.py +++ b/openquake/calculators/hazard/general.py @@ -780,35 +780,18 @@ class BaseHazardCalculatorNext(base.CalculatorNext): hc_prog.result_matrix = numpy.zeros((num_points, len(imls))) hc_prog.save() - def execute(self): + def get_task_complete_callback(self, task_arg_gen): """ - Calculation work is parallelized over sources, which means that each - task will compute hazard for all sites but only with a subset of the - seismic sources defined in the input model. - - The general workflow is as follows: - - 1. Fill the queue with an initial set of tasks. The number of initial - tasks is configurable using the `concurrent_tasks` parameter in the - `[hazard]` section of the OpenQuake config file. - - 2. Wait for tasks to signal completion (via AMQP message) and enqueue a - new task each time another completes. Once all of the job work is - enqueued, we just wait until all of the tasks conclude. + :param task_arg_gen: + The task arg generator, so the callback can get the next set of + args and enqueue the next task. + :return: + A callback function which responds to a task completion signal. + A response typically includes enqueuing the next task and updating + progress counters. """ - job = self.job - block_size = int(config.get('hazard', 'block_size')) - concurrent_tasks = int(config.get('hazard', 'concurrent_tasks')) - self.progress = dict(total=0, computed=0) - # The following two counters are in a dict so that we can use them in - # the closures below. - # When `self.progress['compute']` becomes equal to - # `self.progress['total']`, # `execute` can conclude. - - task_gen = self.task_arg_gen(block_size) - - def task_complete_callback(body, message): + def callback(body, message): """ :param dict body: ``body`` is the message sent by the task. The dict should @@ -824,7 +807,7 @@ class BaseHazardCalculatorNext(base.CalculatorNext): job_id = body['job_id'] num_sources = body['num_sources'] - assert job_id == job.id + assert job_id == self.job.id self.progress['computed'] += num_sources logs.log_percent_complete(job_id, "hazard") @@ -832,7 +815,7 @@ class BaseHazardCalculatorNext(base.CalculatorNext): # Once we receive a completion signal, enqueue the next # piece of work (if there's anything left to be done). try: - self.core_calc_task.apply_async(task_gen.next()) + self.core_calc_task.apply_async(task_arg_gen.next()) except StopIteration: # There are no more tasks to dispatch; now we just need # to wait until all tasks signal completion. @@ -840,17 +823,48 @@ class BaseHazardCalculatorNext(base.CalculatorNext): message.ack() + return callback + + def execute(self): + """ + Calculation work is parallelized over sources, which means that each + task will compute hazard for all sites but only with a subset of the + seismic sources defined in the input model. + + The general workflow is as follows: + + 1. Fill the queue with an initial set of tasks. The number of initial + tasks is configurable using the `concurrent_tasks` parameter in the + `[hazard]` section of the OpenQuake config file. + + 2. Wait for tasks to signal completion (via AMQP message) and enqueue a + new task each time another completes. Once all of the job work is + enqueued, we just wait until all of the tasks conclude. + """ + block_size = int(config.get('hazard', 'block_size')) + concurrent_tasks = int(config.get('hazard', 'concurrent_tasks')) + + self.progress = dict(total=0, computed=0) + # The following two counters are in a dict so that we can use them in + # the closures below. + # When `self.progress['compute']` becomes equal to + # `self.progress['total']`, # `execute` can conclude. + + task_gen = self.task_arg_gen(block_size) + exchange, conn_args = exchange_and_conn_args() - routing_key = ROUTING_KEY_FMT % dict(job_id=job.id) + routing_key = ROUTING_KEY_FMT % dict(job_id=self.job.id) task_signal_queue = kombu.Queue( - 'htasks.job.%s' % job.id, exchange=exchange, + 'htasks.job.%s' % self.job.id, exchange=exchange, routing_key=routing_key, durable=False, auto_delete=True) with kombu.BrokerConnection(**conn_args) as conn: task_signal_queue(conn.channel()).declare() - with conn.Consumer(task_signal_queue, - callbacks=[task_complete_callback]): + with conn.Consumer( + task_signal_queue, + callbacks=[self.get_task_complete_callback(task_gen)]): + # First: Queue up the initial tasks. for _ in xrange(concurrent_tasks): try:
calcs/hazard/general: Refactored the task complete callback. Now, calculator sublcasses can more easily implement their own task response callbacks.
gem_oq-engine
train
ec0c94190d87e620cee114efea35d1e0433e7a60
diff --git a/bitcoin/authtree.py b/bitcoin/authtree.py index <HASH>..<HASH> 100644 --- a/bitcoin/authtree.py +++ b/bitcoin/authtree.py @@ -6,7 +6,7 @@ # Python 2 and 3 compatibility utilities import six -from .hash import hash256 +from .hash import sha256 from .mixins import HashableMixin, SerializableMixin from .serialize import FlatData, VarInt @@ -251,9 +251,9 @@ class BaseAuthTreeNode(SerializableMixin, HashableMixin): parts.append(skiplist[::-1].tobytes()[::-1]) if digest or link.pruned: if getattr(self, 'level_compress', True): - parts.append(hash256.serialize(link.hash)) + parts.append(sha256.serialize(link.hash)) else: - hash_ = hash256.serialize(link.hash) + hash_ = sha256.serialize(link.hash) for bit in link.prefix[:-len_:-1]: hash_ = self.compressor(''.join([ bit and '\x04' or '\x01', '\x00', hash_ @@ -307,7 +307,7 @@ class BaseAuthTreeNode(SerializableMixin, HashableMixin): prefix += Bits(bytes=bytes_[::-1])[:-bitlength:-1] if prune: initargs['children'].append(link_class(prefix, - hash = hash256.deserialize(file_), + hash = sha256.deserialize(file_), count = VarInt.deserialize(file_), size = VarInt.deserialize(file_))) else: diff --git a/bitcoin/hash.py b/bitcoin/hash.py index <HASH>..<HASH> 100644 --- a/bitcoin/hash.py +++ b/bitcoin/hash.py @@ -6,6 +6,7 @@ __all__ = ( 'hash160', 'hash256', + 'sha256', ) import hashlib @@ -186,3 +187,6 @@ hash160 = _HashAlgorithmInterface(('sha256', 'ripemd160')) # the Merkle-tree compressor, and to generate transaction hash values for # identification. hash256 = _HashAlgorithmInterface(('sha256', 'sha256')) + +# (sha256), “single-SHA256” is used by the authenticated prefix trees +sha256 = _HashAlgorithmInterface(('sha256',))
Switch to single sha<I> for authentication trees.
maaku_python-bitcoin
train
4f3e7659c51a48c5f111717b9efaa5d9a6474d8d
diff --git a/lib/nylas/event.rb b/lib/nylas/event.rb index <HASH>..<HASH> 100644 --- a/lib/nylas/event.rb +++ b/lib/nylas/event.rb @@ -27,6 +27,7 @@ module Nylas attribute :status, :string attribute :title, :string attribute :when, :when + attribute :metadata, :hash attribute :original_start_time, :unix_timestamp attr_accessor :notify_participants
Enable `metadata` field in the Event object
nylas_nylas-ruby
train
76cee5775e48af0644efe645bec9f20871dd458f
diff --git a/gwpy/cli/coherence.py b/gwpy/cli/coherence.py index <HASH>..<HASH> 100644 --- a/gwpy/cli/coherence.py +++ b/gwpy/cli/coherence.py @@ -59,6 +59,10 @@ class Coherence(CliProduct): def get_xlabel(self): return 'Frequency (Hz)' + def get_sup_title(self): + """Override if default lacks critical info""" + return self.get_title() + self.ref_chan_name + def gen_plot(self, arg_list): """Generate the coherence plot from all time series""" import numpy @@ -78,25 +82,32 @@ class Coherence(CliProduct): ref_name = arg_list.ref else: ref_name = self.timeseries[0].channel.name + self.ref_chan_name = ref_name + self.log(3, 'Reference channel: ' + ref_name) # we don't want to compare the reference channel to itself # at a different time - next_ts = 0 - for idx in range(1, len(self.timeseries)): + next_ts = -1 + for idx in range(0, len(self.timeseries)): legend_text = self.timeseries[idx].channel.name if legend_text != ref_name and self.timeseries[idx].min() != \ self.timeseries[idx].data.max(): next_ts = idx break - if next_ts == 0: + if next_ts == -1: raise ValueError('No appropriate channels for ' 'Coherence calculation') cohs = [] for time_group in self.time_groups: + ref_idx = time_group[0] if len(time_group) >= 2: + # find the reference channel in this group + for idx in range(0, len(time_group)): + idxp = time_group[idx] + if self.timeseries[idxp].channel.name == ref_name: + ref_idx = idxp - ref_idx = time_group[0] maxfs = max(maxfs, self.timeseries[ref_idx].sample_rate) if numpy.min(self.timeseries[ref_idx]) == \ numpy.max(self.timeseries[ref_idx]): @@ -105,38 +116,38 @@ class Coherence(CliProduct): % self.timeseries[ref_idx].channel.name, \ self.timeseries[ref_idx].times.epoch.gps else: - for idxp in range(1, len(time_group)): + for idxp in range(0, len(time_group)): next_ts = time_group[idxp] - - if numpy.min(self.timeseries[next_ts]) == \ - numpy.max(self.timeseries[next_ts]): - print 'Channel %s at %d has min=max, coherence ' \ - 'with this channel will not be calculated' \ - % self.timeseries[next_ts].channel.name, \ - self.timeseries[next_ts].times.epoch.gps - else: - maxfs = max(maxfs, - self.timeseries[next_ts].sample_rate) - # calculate and plot the first pair, - # note the first channel is the reference channel - snd_ts = self.timeseries[next_ts] - coh = self.timeseries[ref_idx].\ - coherence(snd_ts, fftlength=fftlen, - overlap=ovlap_frac*fftlen) - - legend_text = self.timeseries[next_ts].channel.name - if len(self.start_list) > 1: - legend_text += ", %s" % snd_ts.times.epoch.gps - coh.name = legend_text - - # coh2 = 1 / (1-coh) : how to implement alt scaler - - if not cohs: - self.plot = coh.plot() + if next_ts != ref_idx: + if numpy.min(self.timeseries[next_ts]) == \ + numpy.max(self.timeseries[next_ts]): + print 'Channel %s at %d has min=max, coherence ' \ + 'with this channel will not be calculated' \ + % self.timeseries[next_ts].channel.name, \ + self.timeseries[next_ts].times.epoch.gps else: - self.plot.add_spectrum(coh) - - cohs.append(coh) + maxfs = max(maxfs, + self.timeseries[next_ts].sample_rate) + # calculate and plot the first pair, + # note the first channel is the reference channel + snd_ts = self.timeseries[next_ts] + coh = self.timeseries[ref_idx].\ + coherence(snd_ts, fftlength=fftlen, + overlap=ovlap_frac*fftlen) + + legend_text = self.timeseries[next_ts].channel.name + if len(self.start_list) > 1: + legend_text += ", %s" % snd_ts.times.epoch.gps + coh.name = legend_text + + # coh2 = 1 / (1-coh) : how to implement alt scaler + + if not cohs: + self.plot = coh.plot() + else: + self.plot.add_spectrum(coh) + + cohs.append(coh) if not cohs: raise ValueError('No coherence was calculated due to data'
cli/coherence.py: Implement ref chan param, don't rely on ldvw Previously the --ref parameter was ignored and ldvw was supposed to put the ref channel first. Problem is command line tool should not work like that.
gwpy_gwpy
train
d8642ae396033c059cb75b3c35a2ece067c17035
diff --git a/CHANGES.txt b/CHANGES.txt index <HASH>..<HASH> 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,5 @@ 2.0.12: + * Increase quarantine delay on replacement (CASSANDRA-8260) * Expose off-heap memory usage stats (CASSANDRA-7897) * Ignore Paxos commits for truncated tables (CASSANDRA-7538) * Validate size of indexed column values (CASSANDRA-8280) diff --git a/src/java/org/apache/cassandra/gms/Gossiper.java b/src/java/org/apache/cassandra/gms/Gossiper.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/gms/Gossiper.java +++ b/src/java/org/apache/cassandra/gms/Gossiper.java @@ -380,7 +380,29 @@ public class Gossiper implements IFailureDetectionEventListener, GossiperMBean */ private void quarantineEndpoint(InetAddress endpoint) { - justRemovedEndpoints.put(endpoint, System.currentTimeMillis()); + quarantineEndpoint(endpoint, System.currentTimeMillis()); + } + + /** + * Quarantines the endpoint until quarantineExpiration + QUARANTINE_DELAY + * + * @param endpoint + * @param quarantineExpiration + */ + private void quarantineEndpoint(InetAddress endpoint, long quarantineExpiration) + { + justRemovedEndpoints.put(endpoint, quarantineExpiration); + } + + /** + * Quarantine endpoint specifically for replacement purposes. + * @param endpoint + */ + public void replacementQuarantine(InetAddress endpoint) + { + // remember, quarantineEndpoint will effectively already add QUARANTINE_DELAY, so this is 2x + logger.debug(""); + quarantineEndpoint(endpoint, System.currentTimeMillis() + QUARANTINE_DELAY); } /** @@ -393,6 +415,7 @@ public class Gossiper implements IFailureDetectionEventListener, GossiperMBean { removeEndpoint(endpoint); evictFromMembership(endpoint); + replacementQuarantine(endpoint); } /** diff --git a/src/java/org/apache/cassandra/service/StorageService.java b/src/java/org/apache/cassandra/service/StorageService.java index <HASH>..<HASH> 100644 --- a/src/java/org/apache/cassandra/service/StorageService.java +++ b/src/java/org/apache/cassandra/service/StorageService.java @@ -1607,7 +1607,11 @@ public class StorageService extends NotificationBroadcasterSupport implements IE tokenMetadata.updateNormalTokens(tokensToUpdateInMetadata, endpoint); for (InetAddress ep : endpointsToRemove) + { removeEndpoint(ep); + if (DatabaseDescriptor.isReplacing() && DatabaseDescriptor.getReplaceAddress().equals(ep)) + Gossiper.instance.replacementQuarantine(ep); // quarantine locally longer than normally; see CASSANDRA-8260 + } if (!tokensToUpdateInSystemKeyspace.isEmpty()) SystemKeyspace.updateTokens(endpoint, tokensToUpdateInSystemKeyspace); if (!localTokensToRemove.isEmpty())
Increase quarantine on replacement Patch by brandonwilliams, reviewed by jasobrown for CASSANDRA-<I>
Stratio_stratio-cassandra
train
7bf9790436be2a9a03fa367a80b03900e18f474f
diff --git a/src/org/opencms/db/CmsDriverManager.java b/src/org/opencms/db/CmsDriverManager.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/db/CmsDriverManager.java +++ b/src/org/opencms/db/CmsDriverManager.java @@ -1,7 +1,7 @@ /* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/db/CmsDriverManager.java,v $ - * Date : $Date: 2003/10/29 13:00:42 $ - * Version: $Revision: 1.283 $ + * Date : $Date: 2003/10/29 15:49:39 $ + * Version: $Revision: 1.284 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System @@ -86,7 +86,7 @@ import source.org.apache.java.util.Configurations; * @author Thomas Weckert (t.weckert@alkacon.com) * @author Carsten Weinholz (c.weinholz@alkacon.com) * @author Michael Emmerich (m.emmerich@alkacon.com) - * @version $Revision: 1.283 $ $Date: 2003/10/29 13:00:42 $ + * @version $Revision: 1.284 $ $Date: 2003/10/29 15:49:39 $ * @since 5.1 */ public class CmsDriverManager extends Object implements I_CmsEventListener { @@ -8305,6 +8305,8 @@ public class CmsDriverManager extends Object implements I_CmsEventListener { // export the folder discAccess.createFolder(currentResource.getRootPath(), currentExportPoint); } else { + // try to create the exportpoint folder + discAccess.createFolder(currentExportPoint, currentExportPoint); // export the file content online CmsFile file = getVfsDriver().readFile(I_CmsConstants.C_PROJECT_ONLINE_ID, false, currentResource.getStructureId()); file.setFullResourceName(currentResource.getRootPath()); diff --git a/src/org/opencms/main/OpenCmsCore.java b/src/org/opencms/main/OpenCmsCore.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/main/OpenCmsCore.java +++ b/src/org/opencms/main/OpenCmsCore.java @@ -1,7 +1,7 @@ /* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/main/OpenCmsCore.java,v $ - * Date : $Date: 2003/10/29 13:00:42 $ - * Version: $Revision: 1.38 $ + * Date : $Date: 2003/10/29 15:49:39 $ + * Version: $Revision: 1.39 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System @@ -31,7 +31,10 @@ package org.opencms.main; -import org.opencms.cron.*; +import org.opencms.cron.CmsCronEntry; +import org.opencms.cron.CmsCronScheduleJob; +import org.opencms.cron.CmsCronScheduler; +import org.opencms.cron.CmsCronTable; import org.opencms.db.CmsDefaultUsers; import org.opencms.db.CmsDriverManager; import org.opencms.flex.CmsFlexCache; @@ -50,7 +53,15 @@ import org.opencms.util.CmsUUID; import com.opencms.boot.CmsBase; import com.opencms.boot.CmsMain; import com.opencms.boot.CmsSetupUtils; -import com.opencms.core.*; +import com.opencms.core.CmsCoreSession; +import com.opencms.core.CmsException; +import com.opencms.core.CmsRequestHttpServlet; +import com.opencms.core.CmsResponseHttpServlet; +import com.opencms.core.I_CmsConstants; +import com.opencms.core.I_CmsRequest; +import com.opencms.core.I_CmsResourceInit; +import com.opencms.core.I_CmsResponse; +import com.opencms.core.OpenCmsServletNotify; import com.opencms.core.exceptions.CmsResourceInitException; import com.opencms.file.CmsFile; import com.opencms.file.CmsFolder; @@ -90,7 +101,7 @@ import source.org.apache.java.util.ExtendedProperties; * * @author Alexander Kandzior (a.kandzior@alkacon.com) * - * @version $Revision: 1.38 $ + * @version $Revision: 1.39 $ * @since 5.1 */ public class OpenCmsCore {
Bugfix in export points: folders without subfolders are now written correctly
alkacon_opencms-core
train
95e2efbe9f21551528e7097e5673fa8b001e6f60
diff --git a/lib/review/latexbuilder.rb b/lib/review/latexbuilder.rb index <HASH>..<HASH> 100644 --- a/lib/review/latexbuilder.rb +++ b/lib/review/latexbuilder.rb @@ -746,6 +746,7 @@ module ReVIEW def bibpaper_bibpaper(id, caption, lines) print split_paragraph(lines).join("") + puts "" end def index(str) diff --git a/test/test_latexbuilder.rb b/test/test_latexbuilder.rb index <HASH>..<HASH> 100644 --- a/test/test_latexbuilder.rb +++ b/test/test_latexbuilder.rb @@ -397,7 +397,7 @@ class LATEXBuidlerTest < Test::Unit::TestCase end @builder.bibpaper(["a", "b"], "samplebib", "sample bib @<b>{bold}") - assert_equal %Q|[1] sample bib \\textbf{bold}\n\\label{bib:samplebib}\n\nab\n|, @builder.raw_result + assert_equal %Q|[1] sample bib \\textbf{bold}\n\\label{bib:samplebib}\n\nab\n\n|, @builder.raw_result end def test_bibpaper_without_body
force to add newline after //bibpaper (cf. #<I>)
kmuto_review
train
53caa39a7abdd63ded10709efb10be495f347089
diff --git a/dbussy.py b/dbussy.py index <HASH>..<HASH> 100644 --- a/dbussy.py +++ b/dbussy.py @@ -1870,7 +1870,8 @@ class Message : dbus.dbus_message_lock(self._dbobj) #end lock - # TODO: allocate/free data slot (freeing slot can set passed-in var to -1 on actual free; do I care?) + # TODO: allocate/free data slot -- static methods + # (freeing slot can set passed-in var to -1 on actual free; do I care?) # TODO: set/get data # TODO: type from/to string # TODO: marshal/demarshal @@ -1968,7 +1969,7 @@ class PendingCall : dbus.dbus.dbus_pending_call_block(self._dbobj) #end block - # TODO: data slots, get/set data + # TODO: data slots (static methods), get/set data #end PendingCall
note data-slot routines should be static methods
ldo_dbussy
train
7b43ecc02c5b5e7190c4071a3530743318763d75
diff --git a/engine/src/main/java/org/camunda/bpm/engine/impl/jobexecutor/JobExecutorLogger.java b/engine/src/main/java/org/camunda/bpm/engine/impl/jobexecutor/JobExecutorLogger.java index <HASH>..<HASH> 100644 --- a/engine/src/main/java/org/camunda/bpm/engine/impl/jobexecutor/JobExecutorLogger.java +++ b/engine/src/main/java/org/camunda/bpm/engine/impl/jobexecutor/JobExecutorLogger.java @@ -18,6 +18,7 @@ package org.camunda.bpm.engine.impl.jobexecutor; import java.util.Collection; +import org.camunda.bpm.engine.OptimisticLockingException; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.impl.ProcessEngineLogger; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; @@ -56,8 +57,15 @@ public class JobExecutorLogger extends ProcessEngineLogger { } public void exceptionWhileExecutingJob(String nextJobId, Throwable t) { - logWarn( - "006", "Exception while executing job {}: ", nextJobId, t); + if(t instanceof OptimisticLockingException && !isDebugEnabled()) { + logWarn( + "006", + "Exception while executing job {}: {}. To see the full stacktrace set logging level to DEBUG.", + nextJobId, t.getClass().getSimpleName()); + } else { + logWarn( + "006", "Exception while executing job {}: ", nextJobId, t); + } } public void couldNotDeterminePriority(ExecutionEntity execution, Object value, ProcessEngineException e) {
chore(engine): log stacktrace of OptimisticLockingException only on DEBUG * log name of exception on level < DEBUG Related to CAM-<I>
camunda_camunda-bpm-platform
train
a0eec8dfe0ca5eabf7d748d49a4a7daf4efb5a52
diff --git a/lib/rprogram/program.rb b/lib/rprogram/program.rb index <HASH>..<HASH> 100644 --- a/lib/rprogram/program.rb +++ b/lib/rprogram/program.rb @@ -1,6 +1,7 @@ require 'rprogram/rprogram' require 'rprogram/system' require 'rprogram/task' +require 'rprogram/sudo_task' require 'rprogram/exceptions/program_not_found' module RProgram @@ -287,6 +288,12 @@ module RProgram # @param [Array] arguments # Additional arguments to run the program with. # + # @yield [sudo] + # If a block is given, it will be passed the sudo task. + # + # @yieldparam [SudoTask] sudo + # The sudo tasks. + # # @return [Boolean] # Specifies whether the program exited successfully. # @@ -297,8 +304,11 @@ module RProgram # # @see System.sudo # - def sudo(*arguments) - System.sudo(@path,*arguments) + def sudo(*arguments,&block) + task = SudoTask.new(&block) + task.command = [@path] + arguments + + return System.sudo(*task.arguments) end # @@ -314,17 +324,41 @@ module RProgram # Specifies the exit status of the program. # # @see #run - # @see #sudo # def run_task(task,options={}) arguments = task.arguments arguments << options unless options.empty? - if task.sudo? - return sudo(*arguments) - else - return run(*arguments) - end + return run(arguments) + end + + # + # Runs the program under `sudo` with the arguments from the given task. + # + # @param [Task] task + # The task who's arguments will be used to run the program. + # + # @param [Hash] options + # Spawn options for the program to be ran. + # + # @yield [sudo] + # If a block is given, it will be passed the sudo task. + # + # @yieldparam [SudoTask] sudo + # The sudo tasks. + # + # @return [true, false] + # Specifies the exit status of the program. + # + # @see #sudo + # + # @since 0.3.0 + # + def sudo_task(task,options={},&block) + arguments = task.arguments + arguments << options unless options.empty? + + return sudo(arguments,&block) end #
Added Program#sudo_task and allow Program#sudo to pass a block to SudoTask.new.
postmodern_rprogram
train
3e1a8947b822d7c181b4746926e50e73301a61c6
diff --git a/scenarios/api.github.com/release-assets/record.js b/scenarios/api.github.com/release-assets/record.js index <HASH>..<HASH> 100644 --- a/scenarios/api.github.com/release-assets/record.js +++ b/scenarios/api.github.com/release-assets/record.js @@ -137,7 +137,7 @@ async function releaseAssets (state) { error = _error } - // await temporaryRepository.delete() + await temporaryRepository.delete() if (error) { return Promise.reject(error)
chore(scenario): delete temporary release-assets repository after recording
octokit_fixtures
train
e6d19225e397116f1d91f9512f0cbe5e04f74fbf
diff --git a/src/bindings/html/view.js b/src/bindings/html/view.js index <HASH>..<HASH> 100644 --- a/src/bindings/html/view.js +++ b/src/bindings/html/view.js @@ -29,7 +29,8 @@ export class View { }); let observer = new MutationObserver( - mutations => onMutations(this, mutations)); + mutations => this.service.languages.then( + langs => onMutations(this.ctx, this, langs, mutations))); this.observe = () => observer.observe(this.doc, observerConfig); this.disconnect = () => observer.disconnect(); @@ -37,15 +38,18 @@ export class View { } formatValue(id, args) { - return this.ctx.formatValue(this.service.languages, id, args); + return this.service.languages.then( + langs => this.ctx.formatValue(langs, id, args)); } formatEntity(id, args) { - return this.ctx.formatEntity(this.service.languages, id, args); + return this.service.languages.then( + langs => this.ctx.formatEntity(langs, id, args)); } translateFragment(frag) { - return translateFragment(this.ctx, this, this.service.languages, frag); + return this.service.languages.then( + langs => translateFragment(this.ctx, this, langs, frag)); } } @@ -57,14 +61,13 @@ export function translate(langs) { return translateDocument(this.ctx, this, langs, this.doc); } -function onMutations(view, mutations) { - let {ctx, service} = view; +function onMutations(ctx, obs, langs, mutations) { let targets = new Set(); for (let mutation of mutations) { switch (mutation.type) { case 'attributes': - translateElement(ctx, view, service.languages, mutation.target); + translateElement(ctx, obs, langs, mutation.target); break; case 'childList': for (let addedNode of mutation.addedNodes) { @@ -77,6 +80,6 @@ function onMutations(view, mutations) { targets.forEach( target => target.childElementCount ? - translateFragment(ctx, view, service.languages, target) : - translateElement(ctx, view, service.languages, target)); + translateFragment(ctx, obs, langs, target) : + translateElement(ctx, obs, langs, target)); } diff --git a/src/lib/context.js b/src/lib/context.js index <HASH>..<HASH> 100644 --- a/src/lib/context.js +++ b/src/lib/context.js @@ -12,8 +12,7 @@ export default class Context { fetch(langs) { // XXX add arg: count of langs to fetch - return Promise.resolve(langs).then( - this._fetchResources.bind(this)); + return this._fetchResources(langs); } formatValue(langs, id, args) {
ctx.fetch accepts only array of langs now, and no longer a promise
l20n_l20n.js
train
9293b1bcb366cdc7f5103d401da1860326de2034
diff --git a/core/src/playn/core/AbstractAssets.java b/core/src/playn/core/AbstractAssets.java index <HASH>..<HASH> 100644 --- a/core/src/playn/core/AbstractAssets.java +++ b/core/src/playn/core/AbstractAssets.java @@ -34,7 +34,7 @@ public abstract class AbstractAssets<IMG> implements Assets { @Override public Image getImageSync(String path) { - Image image = loadImage(path, new ImageReceiver<IMG>() { + return loadImage(path, new ImageReceiver<IMG>() { @Override public Image imageLoaded(IMG impl, Scale scale) { return createStaticImage(impl, scale); @@ -44,8 +44,6 @@ public abstract class AbstractAssets<IMG> implements Assets { return createErrorImage(error); } }); - setDebugPath(image, path); - return image; } @Override @@ -57,7 +55,6 @@ public abstract class AbstractAssets<IMG> implements Assets { @Override public Image imageLoaded(final IMG impl, final Scale scale) { setImageLater(image, impl, scale); - setDebugPath(image, path); return image; } @Override @@ -146,9 +143,6 @@ public abstract class AbstractAssets<IMG> implements Assets { }); } - protected void setDebugPath (Image image, String path) { - } - protected void setErrorLater(final AsyncImage<?> image, final Throwable error) { platform.invokeLater(new Runnable() { public void run () { diff --git a/java/src/playn/java/JavaAssets.java b/java/src/playn/java/JavaAssets.java index <HASH>..<HASH> 100644 --- a/java/src/playn/java/JavaAssets.java +++ b/java/src/playn/java/JavaAssets.java @@ -153,10 +153,6 @@ public class JavaAssets extends AbstractAssets<BufferedImage> { return recv.loadFailed(error != null ? error : new FileNotFoundException(fullPath)); } - protected void setDebugPath (Image image, String path) { - ((JavaImage)image).debugPath = path; - } - protected InputStream getAssetStream(String path) throws IOException { InputStream in = getClass().getClassLoader().getResourceAsStream(pathPrefix + path); if (in == null) { diff --git a/java/src/playn/java/JavaImage.java b/java/src/playn/java/JavaImage.java index <HASH>..<HASH> 100644 --- a/java/src/playn/java/JavaImage.java +++ b/java/src/playn/java/JavaImage.java @@ -36,8 +36,6 @@ public abstract class JavaImage extends ImageGL<Graphics2D> { protected BufferedImage img; - String debugPath; - public JavaImage(GLContext ctx, BufferedImage img, Scale scale) { super(ctx, scale); this.img = img;
Shit, welcome to amateur hour Revert "LOCAL: retain path for image debugging" This reverts commit c0f<I>f<I>ffdde<I>eeebaa<I>ed<I>e<I>ee0.
playn_playn
train
aff2ca959c8fe215a929139ba02d3d867c1296cf
diff --git a/src/MysqltcsOperations.php b/src/MysqltcsOperations.php index <HASH>..<HASH> 100644 --- a/src/MysqltcsOperations.php +++ b/src/MysqltcsOperations.php @@ -114,7 +114,7 @@ class MysqltcsOperations /** - * @return boolean + * @return bool */ public function isQuotes() { @@ -122,7 +122,7 @@ class MysqltcsOperations } /** - * @param boolean $quotes + * @param bool $quotes */ public function setQuotes($quotes) { diff --git a/src/connections/utilis/MysqlUtilisException.php b/src/connections/utilis/MysqlUtilisException.php index <HASH>..<HASH> 100644 --- a/src/connections/utilis/MysqlUtilisException.php +++ b/src/connections/utilis/MysqlUtilisException.php @@ -4,6 +4,18 @@ * User: claudio * Date: 12/07/15 * Time: 1.19 + * 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 2 + * 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, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ namespace it\thecsea\mysqltcs\connections\utilis;
Scurtinizer issues fixed, again ;)
thecsea_mysqltcs
train
8e957841f4c62309746fac323908d095c56510de
diff --git a/pyemma-ipython b/pyemma-ipython index <HASH>..<HASH> 160000 --- a/pyemma-ipython +++ b/pyemma-ipython @@ -1 +1 @@ -Subproject commit 631c744873bc15d72b0f4157c7a8409d3c147743 +Subproject commit 5b8c78293ad9b90b225ff1df7714caecaabf9503 diff --git a/pyemma/coordinates/data/featurizer.py b/pyemma/coordinates/data/featurizer.py index <HASH>..<HASH> 100644 --- a/pyemma/coordinates/data/featurizer.py +++ b/pyemma/coordinates/data/featurizer.py @@ -808,17 +808,21 @@ class MDFeaturizer(object): # counting instances, incremented by name property. _ids = count(0) - def __init__(self, topfile): + def __init__(self, topology): """extracts features from MD trajectories. Parameters ---------- - topfile : str - a path to a topology file (pdb etc.) + topfile : str or mdtraj.Topology + a path to a topology file (pdb etc.) or an mdtraj Topology() object """ - self.topologyfile = topfile - self.topology = (mdtraj.load(topfile)).topology + self.topologyfile = None + if type(topology) is str: + self.topology = (mdtraj.load(topology)).topology + self.topologyfile = topology + else: + self.topology = topology self.active_features = [] self._dim = 0 diff --git a/pyemma/coordinates/tests/test_featurizer.py b/pyemma/coordinates/tests/test_featurizer.py index <HASH>..<HASH> 100644 --- a/pyemma/coordinates/tests/test_featurizer.py +++ b/pyemma/coordinates/tests/test_featurizer.py @@ -245,7 +245,7 @@ class TestFeaturizer(unittest.TestCase): self.assertEqual(len(desc), self.feat.dimension()) def test_backbone_dihedrals(self): - self.feat = MDFeaturizer(topfile=self.asn_leu_pdbfile) + self.feat = MDFeaturizer(topology=self.asn_leu_pdbfile) self.feat.add_backbone_torsions() traj = mdtraj.load(self.asn_leu_pdbfile) @@ -257,7 +257,7 @@ class TestFeaturizer(unittest.TestCase): self.assertEqual(len(desc), self.feat.dimension()) def test_backbone_dihedrals_deg(self): - self.feat = MDFeaturizer(topfile=self.asn_leu_pdbfile) + self.feat = MDFeaturizer(topology=self.asn_leu_pdbfile) self.feat.add_backbone_torsions(deg=True) traj = mdtraj.load(self.asn_leu_pdbfile) @@ -268,7 +268,7 @@ class TestFeaturizer(unittest.TestCase): self.assertEqual(len(desc), self.feat.dimension()) def test_backbone_dihedrals_cossin(self): - self.feat = MDFeaturizer(topfile=self.asn_leu_pdbfile) + self.feat = MDFeaturizer(topology=self.asn_leu_pdbfile) self.feat.add_backbone_torsions(cossin=True) traj = mdtraj.load(self.asn_leu_traj, top=self.asn_leu_pdbfile) @@ -282,7 +282,7 @@ class TestFeaturizer(unittest.TestCase): self.assertEqual(len(desc), self.feat.dimension()) def test_backbone_dihedrials_chi(self): - self.feat = MDFeaturizer(topfile=self.asn_leu_pdbfile) + self.feat = MDFeaturizer(topology=self.asn_leu_pdbfile) self.feat.add_chi1_torsions() traj = mdtraj.load(self.asn_leu_pdbfile) @@ -293,7 +293,7 @@ class TestFeaturizer(unittest.TestCase): self.assertEqual(len(desc), self.feat.dimension()) def test_backbone_dihedrials_chi_cossin(self): - self.feat = MDFeaturizer(topfile=self.asn_leu_pdbfile) + self.feat = MDFeaturizer(topology=self.asn_leu_pdbfile) self.feat.add_chi1_torsions(cossin=True) traj = mdtraj.load(self.asn_leu_pdbfile)
allow using md.Topology for featurizer
markovmodel_PyEMMA
train
b512dedf0d82904dbb2ef2f0e363dcccc8cfc245
diff --git a/irc/tests/test_bot.py b/irc/tests/test_bot.py index <HASH>..<HASH> 100644 --- a/irc/tests/test_bot.py +++ b/irc/tests/test_bot.py @@ -1,3 +1,6 @@ + +import six + import irc.client import irc.bot from irc.bot import ServerSpec @@ -68,4 +71,6 @@ class TestBot(object): """ event = irc.client.Event(type=None, source=None, target=None, arguments=['*', '*', 'nick']) - irc.bot.SingleServerIRCBot._on_namreply.im_func(None, None, event) + _on_namreply = six.get_unbound_function( + irc.bot.SingleServerIRCBot._on_namreply) + _on_namreply(None, None, event) diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -32,6 +32,7 @@ setup_params = dict( "Programming Language :: Python :: 3", ], install_requires=[ + 'six', ] + importlib_req + argparse_req, setup_requires=[ 'hgtools',
Use six for Python 3 compatibility (currently in tests, but this will apply to the lib soon enough)
jaraco_irc
train
bc7828141561b3fd9d6835d70704aa00e574feef
diff --git a/src/main/java/net/jodah/failsafe/FallbackExecutor.java b/src/main/java/net/jodah/failsafe/FallbackExecutor.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/jodah/failsafe/FallbackExecutor.java +++ b/src/main/java/net/jodah/failsafe/FallbackExecutor.java @@ -66,45 +66,50 @@ class FallbackExecutor extends PolicyExecutor<Fallback> { protected Supplier<CompletableFuture<ExecutionResult>> supplyAsync( Supplier<CompletableFuture<ExecutionResult>> supplier, Scheduler scheduler, FailsafeFuture<Object> future) { return () -> supplier.get().thenCompose(result -> { - if (result == null) + if (result == null || future.isDone()) return ExecutionResult.NULL_FUTURE; + if (executionCancelled()) + return CompletableFuture.completedFuture(result); + if (!isFailure(result)) + return postExecuteAsync(result, scheduler, future); CompletableFuture<ExecutionResult> promise = new CompletableFuture<>(); - if (executionCancelled()) { - promise.complete(result); - return promise; - } - - if (isFailure(result)) { - Callable<Object> callable = () -> { - try { - CompletableFuture<Object> fallback = policy.applyStage(result.getResult(), result.getFailure(), - execution.copy()); - fallback.whenComplete((innerResult, failure) -> { - if (failure instanceof CompletionException) - failure = failure.getCause(); - ExecutionResult r = failure == null ? result.withResult(innerResult) : ExecutionResult.failure(failure); - promise.complete(r); - }); - } catch (Throwable t) { - promise.complete(ExecutionResult.failure(t)); - } - return null; - }; - + Callable<Object> callable = () -> { try { - if (!policy.isAsync()) - callable.call(); - else - future.injectPolicy(scheduler.schedule(callable, result.getWaitNanos(), TimeUnit.NANOSECONDS)); + CompletableFuture<Object> fallback = policy.applyStage(result.getResult(), result.getFailure(), + execution.copy()); + fallback.whenComplete((innerResult, failure) -> { + if (failure instanceof CompletionException) + failure = failure.getCause(); + ExecutionResult r = failure == null ? result.withResult(innerResult) : ExecutionResult.failure(failure); + promise.complete(r); + }); } catch (Throwable t) { - promise.completeExceptionally(t); + promise.complete(ExecutionResult.failure(t)); } + return null; + }; + + try { + if (!policy.isAsync()) + callable.call(); + else { + Future<?> scheduledFallback = scheduler.schedule(callable, 0, TimeUnit.NANOSECONDS); - return promise.thenCompose(ss -> postExecuteAsync(ss, scheduler, future)); + // Propagate cancellation to the scheduled retry and promise + future.injectCancelFn(() -> { + System.out.println("cancelling scheduled fallback isdone: " + scheduledFallback.isDone()); + scheduledFallback.cancel(false); + if (executionCancelled()) + promise.complete(null); + }); + } + } catch (Throwable t) { + // Hard scheduling failure + promise.completeExceptionally(t); } - return postExecuteAsync(result, scheduler, future); + return promise.thenCompose(ss -> postExecuteAsync(ss, scheduler, future)); }); }
Reorganize FallbackExecutor supplyAsync and unify cancelFn
jhalterman_failsafe
train
8bf04922888bb8a6e88e71ce489db801bd73236d
diff --git a/tasks/rpm.js b/tasks/rpm.js index <HASH>..<HASH> 100644 --- a/tasks/rpm.js +++ b/tasks/rpm.js @@ -41,9 +41,6 @@ function filterFiles(grunt, files) { // Warn on invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" does not exists'); - } else if (grunt.file.isLink(filepath)) { - // TODO handle links - grunt.log.warn('Source file "' + filepath + '" is a link and it not supported yet'); } else { var fileConfig = grunt.util._.omit(fileMapping, 'src', 'orig', 'filter'); @@ -60,6 +57,9 @@ function filterFiles(grunt, files) { return; } } + if (grunt.file.isLink(filepath)) { + fileConfig.link = _fs.readlinkSync(filepath); + } if (fileMapping.relativeTo) { if (grunt.file.doesPathContain(fileMapping.relativeTo, filepath)) { fileConfig.path = path.relative(fileMapping.relativeTo, filepath); @@ -99,12 +99,18 @@ function copyFilesToPack(grunt, buildPath, filesToPack) { } } else { // Copy a file to the destination directory inside the tmp folder. - grunt.verbose.writeln('Copying file "' + fileConfig.src + '" to "' + filepathDest + '"'); - grunt.file.copy(fileConfig.src, filepathDest); - fs.lstat(fileConfig.src, function(err, stat) { - if (err) throw err; - _fs.chmod(filepathDest, stat.mode, callback); - }); + if (fileConfig.link) { + grunt.verbose.writeln('Copying symlink "' + fileConfig.src + '->' + fileConfig.link + '" to "' + filepathDest + '"'); + _fs.symlink(fileConfig.link, filepathDest, 'file', callback); + } + else { + grunt.verbose.writeln('Copying file "' + fileConfig.src + '" to "' + filepathDest + '"'); + grunt.file.copy(fileConfig.src, filepathDest); + fs.lstat(fileConfig.src, function(err, stat) { + if (err) throw err; + _fs.chmod(filepathDest, stat.mode, callback); + }); + } } } catch(e) {
Handle symlinks when preparing and copying files
gastonelhordoy_grunt-rpm
train
d32fe46ca9a0f4f7b7529295614d20e447118111
diff --git a/django_mysql/cache.py b/django_mysql/cache.py index <HASH>..<HASH> 100644 --- a/django_mysql/cache.py +++ b/django_mysql/cache.py @@ -103,7 +103,7 @@ class MySQLCache(BaseDatabaseCache): if expires < now: return default - return self._decode(value, value_type) + return self.decode(value, value_type) _get_query = collapse_spaces(""" SELECT value, value_type, expires @@ -138,7 +138,7 @@ class MySQLCache(BaseDatabaseCache): continue key = made_key_to_key[made_key] - d[key] = self._decode(value, value_type) + d[key] = self.decode(value, value_type) return d @@ -168,7 +168,7 @@ class MySQLCache(BaseDatabaseCache): now = int(time.time() * 1000) - value, value_type = self._encode(value) + value, value_type = self.encode(value) if mode == 'set': query = self._set_query @@ -231,7 +231,7 @@ class MySQLCache(BaseDatabaseCache): for key, value in six.iteritems(data): made_key = self.make_key(key, version=version) self.validate_key(made_key) - value, value_type = self._encode(value) + value, value_type = self.encode(value) params.extend((made_key, value, value_type, exp)) query = self._set_many_query.replace( @@ -354,15 +354,15 @@ class MySQLCache(BaseDatabaseCache): ) return super(MySQLCache, self).validate_key(key) - def _encode(self, value): + def encode(self, obj): """ Take a Python object and return it as a tuple (value, value_type), a blob and a one-char code for what type it is """ - if self._is_valid_mysql_bigint(value): - return str(value), 'i' + if self._is_valid_mysql_bigint(obj): + return str(obj), 'i' - value = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) + value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL) value_type = 'p' if ( self._compress_min_length and @@ -381,7 +381,7 @@ class MySQLCache(BaseDatabaseCache): BIGINT_SIGNED_MIN <= value <= BIGINT_SIGNED_MAX ) - def _decode(self, value, value_type): + def decode(self, value, value_type): """ Take a value blob and its value_type one-char code and convert it back to a python object
Make encode and decode public methods for easy overriding
adamchainz_django-mysql
train
ac11a598cbe0a44b4cf750906f677a3102838bec
diff --git a/spec/javascripts/integration/core/pusher_spec.js b/spec/javascripts/integration/core/pusher_spec.js index <HASH>..<HASH> 100644 --- a/spec/javascripts/integration/core/pusher_spec.js +++ b/spec/javascripts/integration/core/pusher_spec.js @@ -127,6 +127,41 @@ Integration.describe("Pusher", function() { pusher.unsubscribe(channelName); }); }); + + it("should handle cancelling pending subscription", function() { + var pusher = getPusher(); + var channelName = Integration.getRandomName((prefix || "") + "integration"); + + var eventName = "after_unsubscribing"; + var received = null; + var timer = null; + + var channel = pusher.subscribe(channelName); + channel.bind(eventName, function(message) { + received = message; + }); + + pusher.unsubscribe(channelName); + waitsFor(function() { + return !channel.subscriptionPending; + }, "subscription to succeed", 10000); + runs(function () { + Integration.sendAPIMessage({ + url: Integration.API_URL + "/v2/send", + channel: channelName, + event: eventName, + data: {} + }); + timer = new Timer(3000, function() {}); + }); + waitsFor(function() { + return !timer.isRunning(); + }, "timer to finish", 10000); + runs(function() { + expect(channel.subscribed).toEqual(false); + expect(received).toBe(null); + }); + }); }
added integration test for cancelling a pending subscription
pusher_pusher-js
train
49839cc6f1827e731330b609b6c67263ed58cb10
diff --git a/main.go b/main.go index <HASH>..<HASH> 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "crypto/tls" "errors" "fmt" "io" @@ -183,7 +184,10 @@ func processManifest(c *cli.Context, manifest []byte) (e error) { ccm := enaml.NewCloudConfigManifest(manifest) boshclient := boshapi.NewClient(c.Parent().String("bosh-user"), c.Parent().String("bosh-pass"), c.Parent().String("bosh-url"), c.Parent().Int("bosh-port")) if req, err := boshclient.NewCloudConfigRequest(*ccm); err == nil { - httpClient := new(http.Client) + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + httpClient := &http.Client{Transport: tr} if res, err := httpClient.Do(req); err != nil { lo.G.Error("res: ", res)
[#<I>] ignore self signed certs
enaml-ops_omg-cli
train
e179fed53b92d3d08349a4bac7bb5915b4a0d103
diff --git a/pygmsh/geometry.py b/pygmsh/geometry.py index <HASH>..<HASH> 100644 --- a/pygmsh/geometry.py +++ b/pygmsh/geometry.py @@ -344,7 +344,7 @@ class Geometry(object): top = LineBase(top) extruded = SurfaceBase(extruded) elif isinstance(input_entity, SurfaceBase): - top = SurfaceBase(input_entity.num_edges(), top) + top = SurfaceBase(input_entity.num_edges, top) extruded = VolumeBase(extruded) else: top = Dummy(top) @@ -358,7 +358,7 @@ class Geometry(object): # each lateral surface has 4 edges: the one from input_entity, # the one from top, and the two lines (or splines) connecting their # extreme points. - lat = [SurfaceBase(4, '{}[{}]'.format(name, i+2)) for i in range(input_entity.num_edges())] + lat = [SurfaceBase(4, '{}[{}]'.format(name, i+2)) for i in range(input_entity.num_edges)] return top, extruded, lat diff --git a/pygmsh/plane_surface.py b/pygmsh/plane_surface.py index <HASH>..<HASH> 100644 --- a/pygmsh/plane_surface.py +++ b/pygmsh/plane_surface.py @@ -27,5 +27,5 @@ class PlaneSurface(SurfaceBase): 'Plane Surface({}) = {{{}}};'.format( self.id, ','.join([ll.id for ll in line_loops]) )]) - self._num_edges = len(self.line_loop) + sum(len(h) for h in self.holes) + self.num_edges = len(self.line_loop) + sum(len(h) for h in self.holes) return diff --git a/pygmsh/surface_base.py b/pygmsh/surface_base.py index <HASH>..<HASH> 100644 --- a/pygmsh/surface_base.py +++ b/pygmsh/surface_base.py @@ -4,7 +4,7 @@ class SurfaceBase(object): _ID = 0 - _num_edges = 0 + num_edges = 0 def __init__(self, num_edges=0, id0=None): if id0: @@ -12,8 +12,5 @@ class SurfaceBase(object): else: self.id = 's{}'.format(SurfaceBase._ID) SurfaceBase._ID += 1 - self._num_edges = num_edges + self.num_edges = num_edges return - - def num_edges(self): - return self._num_edges
directly access SurfaceBase.num_edges
nschloe_pygmsh
train
b60cd97bbf8b43b2c6da44efeb51373b401332bc
diff --git a/app/scripts/Chromosome2DGrid.js b/app/scripts/Chromosome2DGrid.js index <HASH>..<HASH> 100644 --- a/app/scripts/Chromosome2DGrid.js +++ b/app/scripts/Chromosome2DGrid.js @@ -30,31 +30,6 @@ export class Chromosome2DGrid extends PixiTrack { this.pMain.addChild(this.lineGraphics); - for (let i = 0; i < this.chromInfo.cumPositions.length; i++) { - const thisTexts = []; - - for (let j = 0; j < this.chromInfo.cumPositions.length; j++) { - const textStr = `${this.chromInfo.cumPositions[i].chr}/${this.chromInfo.cumPositions[j].chr}`; - const text = new PIXI.Text(textStr, - { fontSize: '14px', fontFamily: 'Arial', fill: 'red' }, - ); - - text.anchor.x = 0.5; - text.anchor.y = 0.5; - text.visible = false; - - // give each string a random hash so that some get hidden - // when there's overlaps - text.hashValue = Math.random(); - - thisTexts.push(text); - - this.pMain.addChild(text); - } - - this.texts.push(thisTexts); - } - this.draw(); this.animate(); }); @@ -62,9 +37,9 @@ export class Chromosome2DGrid extends PixiTrack { drawLines() { const graphics = this.lineGraphics; - const strokeColor = colorToHex(this.options.gridStrokeColor ? this.options.gridStrokeColor : 'blue'); + const strokeColor = colorToHex(this.options.lineStrokeColor ? this.options.lineStrokeColor : 'blue'); - const strokeWidth = this.options.gridStrokeWidth ? this.options.gridStrokeWidth : 1; + const strokeWidth = this.options.lineStrokeWidth ? this.options.lineStrokeWidth : 1; graphics.clear(); graphics.lineStyle(strokeWidth, strokeColor, 1.0);
Fixed chromosome grid bug from master
higlass_higlass
train
8d7a1054383abfad40aee936443da09110870e6d
diff --git a/lib/compiler.rb b/lib/compiler.rb index <HASH>..<HASH> 100644 --- a/lib/compiler.rb +++ b/lib/compiler.rb @@ -561,9 +561,16 @@ Viml end end - class DictionarySetNodeVisitor < ScopedVisitor + class DictSetNodeVisitor < ScopedVisitor private def _compile(node) + [node.dict, node.val].each {|n| n.parent_node = node} + node.compiled_output = "let " + node.dict.accept(visitor_for_node(node.dict)) + node.keys.each {|k| node.compiled_output << ".#{k}"} + node.compiled_output << " = " + node.val.accept(visitor_for_node(node.val)) + @value = node.compiled_output << "\n" end end diff --git a/lib/grammar.y b/lib/grammar.y index <HASH>..<HASH> 100644 --- a/lib/grammar.y +++ b/lib/grammar.y @@ -144,7 +144,7 @@ rule ; DictSet: - Dictionary '.' IDENTIFIER '=' Literal { result = DictSetNode.new(val[0], val[2], val[4]) } + LET VariableRetrieval VariableDictGetWithDot '=' Literal { result = DictSetNode.new(val[1], val[2], val[4]) } ; Call: diff --git a/lib/nodes.rb b/lib/nodes.rb index <HASH>..<HASH> 100644 --- a/lib/nodes.rb +++ b/lib/nodes.rb @@ -389,6 +389,7 @@ class DictGetNodeBracket < DictGetNode; end class DictGetNodeDot < DictGetNode; end # dict.key = 'val' -class DictSetNode < Struct.new(:dict, :key, :val) +# dict.key.key2 = 'val' +class DictSetNode < Struct.new(:dict, :keys, :val) include Visitable end diff --git a/test/compiler_test.rb b/test/compiler_test.rb index <HASH>..<HASH> 100644 --- a/test/compiler_test.rb +++ b/test/compiler_test.rb @@ -560,4 +560,16 @@ Viml assert_equal expected, compile(riml) assert_equal expected2, compile(riml2) end + + test "dictionary set value for key with variable" do + riml = <<Riml +dict = {'key': {'key2': 'value2'}} +let dict.key = {'key3': 'value3'} +Riml + expected = <<Viml +let s:dict = {'key': {'key2': 'value2'}} +let s:dict.key = {'key3': 'value3'} +Viml + assert_equal expected, compile(riml) + end end
add compilation for dict.key = 'val'
luke-gru_riml
train
249a92e871b82df018cb6beaf95de6a4bf1b7d9f
diff --git a/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGenerator.java b/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGenerator.java index <HASH>..<HASH> 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGenerator.java +++ b/sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGenerator.java @@ -71,10 +71,11 @@ public final class LeafSnowflakeKeyGenerator implements ShardingKeyGenerator { private static final String WORK_ID_NODE = "/work-id"; private static final String SLANTING_BAR = "/"; - //private static final TimeService timeService = new TimeService(); - @Setter - private static TimeService timeService = new TimeService(); + private static final TimeService timeService = new TimeService(); + + //@Setter + //private static TimeService timeService = new TimeService(); @Getter @Setter diff --git a/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGeneratorTest.java b/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGeneratorTest.java index <HASH>..<HASH> 100644 --- a/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGeneratorTest.java +++ b/sharding-orchestration/sharding-orchestration-core/src/test/java/org/apache/shardingsphere/orchestration/internal/keygen/LeafSnowflakeKeyGeneratorTest.java @@ -62,8 +62,8 @@ public final class LeafSnowflakeKeyGeneratorTest { properties.setProperty("maxTimeDifference", "5000"); properties.setProperty("registryCenterType", "ForthTestRegistryCenter"); leafSnowflakeKeyGenerator.setProperties(properties); - leafSnowflakeKeyGenerator.setTimeService(new FixedTimeService(1)); - //setStaticFinalField(leafSnowflakeKeyGenerator,"timeService",new FixedTimeService(1)); + //leafSnowflakeKeyGenerator.setTimeService(new FixedTimeService(1)); + setStaticFinalField(leafSnowflakeKeyGenerator,"timeService",new FixedTimeService(1)); List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(4198401L, 4198402L, 8392704L, 8392705L, 12587009L, 12587010L, 16781312L, 16781313L, 20975617L, 20975618L); List<Comparable<?>> actual = new ArrayList<>(); for (int i = 0; i < 10; i++) { @@ -81,8 +81,8 @@ public final class LeafSnowflakeKeyGeneratorTest { properties.setProperty("maxTimeDifference", "5000"); properties.setProperty("registryCenterType", "ForthTestRegistryCenter"); leafSnowflakeKeyGenerator.setProperties(properties); - leafSnowflakeKeyGenerator.setTimeService(new FixedTimeService(1)); - //setStaticFinalField(leafSnowflakeKeyGenerator,"timeService",new FixedTimeService(1)); + //leafSnowflakeKeyGenerator.setTimeService(new FixedTimeService(1)); + setStaticFinalField(leafSnowflakeKeyGenerator,"timeService",new FixedTimeService(1)); List<Comparable<?>> expected = Arrays.<Comparable<?>>asList(4198401L); List<Comparable<?>> actual = new ArrayList<>(); actual.add(leafSnowflakeKeyGenerator.generateKey());
Add leaf snowflake key generator and related functions.
apache_incubator-shardingsphere
train
e6fbc05158c8a786c9fa738f3759e4fd24403b6c
diff --git a/src/cr/cube/cubepart.py b/src/cr/cube/cubepart.py index <HASH>..<HASH> 100644 --- a/src/cr/cube/cubepart.py +++ b/src/cr/cube/cubepart.py @@ -291,23 +291,6 @@ class _Slice(CubePartition): return np.array([col.proportions for col in self._matrix.columns]).T @lazyproperty - def columns_dimension_name(self): - """str name assigned to columns-dimension. - - Reflects the resolved dimension-name transform cascade. - """ - return self._columns_dimension.name - - @lazyproperty - def columns_dimension_type(self): - """Member of `cr.cube.enum.DIMENSION_TYPE` describing columns dimension.""" - return self._columns_dimension.dimension_type - - @lazyproperty - def columns_margin(self): - return np.array([column.margin for column in self._matrix.columns]).T - - @lazyproperty def column_proportions_moe(self): """1D/2D np.float64 ndarray of margin-of-error (MoE) for columns proportions. @@ -319,6 +302,14 @@ class _Slice(CubePartition): return Z_975 * self.column_std_err @lazyproperty + def column_std_dev(self): + """standard deviation for column percentages + + `std_deviation = sqrt(variance)` + """ + return np.sqrt(self._column_variance) + + @lazyproperty def column_std_err(self): """standard error for column percentages @@ -327,12 +318,21 @@ class _Slice(CubePartition): return np.sqrt(self._column_variance / self.columns_margin) @lazyproperty - def column_std_dev(self): - """standard deviation for column percentages + def columns_dimension_name(self): + """str name assigned to columns-dimension. - `std_deviation = sqrt(variance)` + Reflects the resolved dimension-name transform cascade. """ - return np.sqrt(self._column_variance) + return self._columns_dimension.name + + @lazyproperty + def columns_dimension_type(self): + """Member of `cr.cube.enum.DIMENSION_TYPE` describing columns dimension.""" + return self._columns_dimension.dimension_type + + @lazyproperty + def columns_margin(self): + return np.array([column.margin for column in self._matrix.columns]).T @lazyproperty def counts(self): @@ -928,6 +928,12 @@ class _Slice(CubePartition): # ---implementation (helpers)------------------------------------- @lazyproperty + def _column_variance(self): + """Variance for column percentages.""" + p = self.counts / self.columns_margin + return p * (1 - p) + + @lazyproperty def _columns_dimension(self): return self._dimensions[1] @@ -937,26 +943,6 @@ class _Slice(CubePartition): return np.array([column.numeric_value for column in self._matrix.columns]) @lazyproperty - def _column_variance(self): - """variance for column percentages - - `variance = p * (1-p)` - """ - return ( - self.counts / self.columns_margin * (1 - self.counts / self.columns_margin) - ) - - @lazyproperty - def _row_variance(self): - """ndarray of variances for row percentages""" - # --- Rows margin is a vector, that's supposed to represent a column (to the - # --- right of the crosstab). We need to devide all values in the crosstab by it - # --- and therefore need to cast it to an actual column (because of how NumPy - # --- does broadcasting). - margin = self.rows_margin[:, np.newaxis] - return self.counts / margin * (1 - self.counts / margin) - - @lazyproperty def _dimensions(self): """tuple of (rows_dimension, columns_dimension) Dimension objects.""" return tuple( @@ -975,6 +961,17 @@ class _Slice(CubePartition): return np.median(values) if values.size != 0 else np.nan @lazyproperty + def _row_variance(self): + """2D np.float64 ndarray of row-percentage variance for each cell.""" + # --- rows-margin is a vector that represents a column (to the right of the + # --- crosstab). We need to divide all values in the crosstab by it and + # --- therefore need to cast it to an actual column (because of how NumPy does + # --- broadcasting). + rows_margin = self.rows_margin[:, np.newaxis] + p = self.counts / rows_margin + return p * (1 - p) + + @lazyproperty def _rows_dimension(self): return self._dimensions[0]
rfctr: normalize method ordering
Crunch-io_crunch-cube
train
ff01fa75675ebe1fb1f7b1fde396724632f39604
diff --git a/js/jquery.storelocator.js b/js/jquery.storelocator.js index <HASH>..<HASH> 100644 --- a/js/jquery.storelocator.js +++ b/js/jquery.storelocator.js @@ -416,12 +416,12 @@ $.fn.storeLocator = function(options) { else if(settings.dataType === 'kml'){ //Process KML $(data).find('Placemark').each(function(){ - var $this = $(this), locationData = { - 'name': $this.find('name').text(), - 'lat': $this.find('coordinates').text().split(",")[1], - 'lng': $this.find('coordinates').text().split(",")[0], + var $placemark = $(this), locationData = { + 'name': $placemark.find('name').text(), + 'lat' : $placemark.find('coordinates').text().split(",")[1], + 'lng' : $placemark.find('coordinates').text().split(",")[0], // Promote setting a locdescription key for a singular description to use in templates instead, as some KML generators (like Google Maps Engine) populates the generic description including all key: values set. - 'description': $this.find('description').text() + 'description': $placemark.find('description').text() }; $this.find('displayName').each(function(){
Renamed variable from $this to $placemark
bjorn2404_jQuery-Store-Locator-Plugin
train
34e89d1578ed05693152b683edcb23ab2708fa21
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,30 @@ //File to hold the gulp task being called in our gulpfile -module.exports = function(file, opt){ - if (!file) { - throw new PluginError('gulp-speckjs', 'Missing file option for gulp-speckjs'); - } - opt = opt || {}; +var gutil = require('gulp-util'); +var through = require('through2'); +// var glob = require('glob'); +var gutil = require('gulp-util'); +var path = require('path'); +var PluginError = gutil.PluginError; +var speck = require('speckjs'); + +//pass files and options into function +module.exports = function(options){ +//Need to add some kind of options or default options logic +var defOption; +options = options || defOption; +var files = []; +var stream = through.obj(function (file, enc, cb) { + if (file.isNull()) { + cb(null, file); + return; + } + if (file.isStream()) { + cb(new gutil.PluginError('gulp-speckjs', 'Streaming not supported')); + return; + } + //Grab each file + //Run speckbuild on each file -- foreach? + //Write string produced from that to a file with file name as origin file + w/e is in options + }); +return stream; };
Added logic psuedocode
speckjs_gulp-speckjs
train
34123a2c5d887f015b2373a81a4fba7d980cb7e8
diff --git a/app/models/neighborly/balanced/event.rb b/app/models/neighborly/balanced/event.rb index <HASH>..<HASH> 100644 --- a/app/models/neighborly/balanced/event.rb +++ b/app/models/neighborly/balanced/event.rb @@ -37,12 +37,12 @@ module Neighborly::Balanced Contribution.find_by(payment_id: @request_params.fetch(:entity).fetch(:id)) end - protected - def type @request_params.fetch(:type) end + protected + def valid_type? TYPES.include? type end diff --git a/spec/models/neighborly/balanced/event_spec.rb b/spec/models/neighborly/balanced/event_spec.rb index <HASH>..<HASH> 100644 --- a/spec/models/neighborly/balanced/event_spec.rb +++ b/spec/models/neighborly/balanced/event_spec.rb @@ -6,6 +6,10 @@ describe Neighborly::Balanced::Event do let(:params) { attributes_for_notification(notification_type) } subject { described_class.new(params) } + it 'gets the type from request params' do + expect(subject.type).to eql('debit.created') + end + describe "validability" do before { subject.stub(:contribution).and_return(contribution) }
Make Event#type a public method
FromUte_dune-balanced
train
fba0abdc228f79c91982e84aadcefaecb53f4c36
diff --git a/lib/filterlib.php b/lib/filterlib.php index <HASH>..<HASH> 100644 --- a/lib/filterlib.php +++ b/lib/filterlib.php @@ -136,12 +136,6 @@ class filter_manager { return new $filterclassname($context, $localconfig); } - // TODO: deprecated since 2.2, will be out in 2.3, see MDL-29996 - $legacyfunctionname = basename($filtername) . '_filter'; - if (function_exists($legacyfunctionname)) { - return new legacy_filter($legacyfunctionname, $context, $localconfig); - } - return null; } @@ -409,50 +403,6 @@ abstract class moodle_text_filter { } /** - * moodle_text_filter implementation that encapsulates an old-style filter that - * only defines a function, not a class. - * - * @deprecated since 2.2, see MDL-29995 - * @todo will be out in 2.3, see MDL-29996 - * @package core - * @subpackage filter - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */ -class legacy_filter extends moodle_text_filter { - /** @var string */ - protected $filterfunction; - protected $courseid; - - /** - * Set any context-specific configuration for this filter. - * - * @param string $filterfunction - * @param object $context The current context. - * @param array $config Any context-specific configuration for this filter. - */ - public function __construct($filterfunction, $context, array $localconfig) { - parent::__construct($context, $localconfig); - $this->filterfunction = $filterfunction; - $this->courseid = get_courseid_from_context($this->context); - } - - /** - * @param string $text - * @param array $options options - not supported for legacy filters - * @return mixed - */ - public function filter($text, array $options = array()) { - if ($this->courseid) { - // old filters are called only when inside courses - return call_user_func($this->filterfunction, $this->courseid, $text); - } else { - return $text; - } - } -} - -/** * This is just a little object to define a phrase and some instructions * for how to process it. Filters can create an array of these to pass * to the filter_phrases function below.
MDL-<I> remove legacy_filter support
moodle_moodle
train
8196051d9b0ea3bff9e91beda1d46134262d65e3
diff --git a/lxd/device/nictype/nictype.go b/lxd/device/nictype/nictype.go index <HASH>..<HASH> 100644 --- a/lxd/device/nictype/nictype.go +++ b/lxd/device/nictype/nictype.go @@ -32,6 +32,8 @@ func NICType(s *state.State, d deviceConfig.Device) (string, error) { nicType = "macvlan" case "sriov": nicType = "sriov" + case "ovn": + nicType = "ovn" default: return "", fmt.Errorf("Unrecognised NIC network type for network %q", d["network"]) }
lxd/device/nictype: Adds ovn support
lxc_lxd
train
7a164c64881494f561b570225dda00973d1297bd
diff --git a/tests/unit/core/oxorderarticleTest.php b/tests/unit/core/oxorderarticleTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/core/oxorderarticleTest.php +++ b/tests/unit/core/oxorderarticleTest.php @@ -51,7 +51,6 @@ class Unit_Core_oxorderarticleTest extends OxidTestCase $oArticle->save(); - $oArticle->resetStaticCache(); } /** @@ -64,7 +63,6 @@ class Unit_Core_oxorderarticleTest extends OxidTestCase $this->cleanUpTable( 'oxorderarticles' ); $this->cleanUpTable( 'oxarticles' ); $oArticle = new oxArticle(); - $oArticle->resetStaticCache(); parent::tearDown(); }
ESDEV-<I> revert
OXID-eSales_oxideshop_ce
train
4a77b58ea144383d088ff66ad559fe5c2ea8e1b8
diff --git a/grs/__init__.py b/grs/__init__.py index <HASH>..<HASH> 100644 --- a/grs/__init__.py +++ b/grs/__init__.py @@ -28,7 +28,7 @@ __copyright__ = 'Copyright (C) 2012 Toomore Chiang' from .best_buy_or_sell import BestFourPoint -from .fetch_data import stock +from .fetch_data import Stock from .realtime import rt_stock from .realtime import rt_weight from .tw_time import Countdown diff --git a/grs/best_buy_or_sell.py b/grs/best_buy_or_sell.py index <HASH>..<HASH> 100644 --- a/grs/best_buy_or_sell.py +++ b/grs/best_buy_or_sell.py @@ -29,7 +29,7 @@ class BestFourPoint(object): def bias_ratio(self, positive_or_negative=False): """ 判斷乖離 """ return self.data.ckMAO(self.data.MAO(3, 6)[0], - pm=positive_or_negative)[0] + positive_or_negative=positive_or_negative)[0] def check_plus_bias_ratio(self): """ 正乖離扣至最大 """ diff --git a/grs/fetch_data.py b/grs/fetch_data.py index <HASH>..<HASH> 100644 --- a/grs/fetch_data.py +++ b/grs/fetch_data.py @@ -38,9 +38,9 @@ class Stock(object): self.__get_mons = 0 self.__get_no = 0 self.__info = () - self.__raw_data = self.__serial_fetch(stock_no, mons) self.__raw_rows_name = [] self.__url = [] + self.__raw_data = self.__serial_fetch(stock_no, mons) @property def url(self): diff --git a/test_unittest.py b/test_unittest.py index <HASH>..<HASH> 100644 --- a/test_unittest.py +++ b/test_unittest.py @@ -8,7 +8,7 @@ import unittest class TestGrs(unittest.TestCase): def setUp(self): self.stock_no = '2618' - self.data = grs.stock(self.stock_no) + self.data = grs.Stock(self.stock_no) def test_stock(self): assert self.data.info[0] == self.stock_no
Fixed a bug because of a variation not assign. #6
toomore_grs
train
99d425c4d454c58e9682c4a41baa56d5905bbd78
diff --git a/lib/weary.rb b/lib/weary.rb index <HASH>..<HASH> 100644 --- a/lib/weary.rb +++ b/lib/weary.rb @@ -71,6 +71,10 @@ module Weary @password = password return nil end + + def always_with(params) + @always_with = params + end # Declare a resource. Use it with a block to setup the resource # @@ -120,6 +124,7 @@ module Weary preparation.format = (@default_format || :json) preparation.domain = @domain preparation.url = (@url_pattern || "<domain><resource>.<format>") + preparation.with = @always_with unless @always_with.nil? return preparation end diff --git a/spec/weary_spec.rb b/spec/weary_spec.rb index <HASH>..<HASH> 100644 --- a/spec/weary_spec.rb +++ b/spec/weary_spec.rb @@ -62,12 +62,23 @@ describe Weary do end describe "Common Request Paramaters" do - it "should define with params that every resource inherits" - # #always_with && #always_requires methods will set with/requires in - # the prepare_resource method of Weary + it "should define with params that every resource inherits" do + @test.on_domain "http://foo.bar" + @test.always_with [:login, :token] + r = @test.get "resource" + r.with.should == [:login, :token] + r.requires = [:foobar] + r.with.should == [:login, :token, :foobar] + end - it "should be able to be a hash" - # new feature of Resources + it "should be able to be a hash" do + @test.on_domain "http://foo.bar" + @test.always_with :foo => "Foo", :bar => "Bar" + r = @test.get "resource" + r.with.should == {:foo => "Foo", :bar => "Bar"} + r.requires = [:foobar] + r.with.should == {:foo => "Foo", :bar => "Bar", :foobar => nil} + end end describe 'Resource Declaration' do
Weary#always_with sets the with commands for every resource
mwunsch_weary
train
fe7d1c9dd84f3a2af35062ce35bd33986a0e7755
diff --git a/build/commands/ApiCommand.php b/build/commands/ApiCommand.php index <HASH>..<HASH> 100644 --- a/build/commands/ApiCommand.php +++ b/build/commands/ApiCommand.php @@ -21,7 +21,7 @@ Yii::import('application.commands.api.ApiModel'); */ class ApiCommand extends CConsoleCommand { - const URL_PATTERN='/\{\{(.*?)\|(.*?)\}\}/s'; + const URL_PATTERN='/\{\{([^\}]+)\|([^\}]+)\}\}/s'; public $classes; public $packages; public $pageTitle;
(Fixes issue <I>)
yiisoft_yii
train
8e000ed3900649a51207a3b6d6e4d99e2ae9aeee
diff --git a/oauth2client/tools.py b/oauth2client/tools.py index <HASH>..<HASH> 100644 --- a/oauth2client/tools.py +++ b/oauth2client/tools.py @@ -90,12 +90,14 @@ class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): pass -def run(flow, storage): +def run(flow, storage, http=None): """Core code for a command-line application. Args: flow: Flow, an OAuth 2.0 Flow to step through. storage: Storage, a Storage to store the credential in. + http: An instance of httplib2.Http.request + or something that acts like it. Returns: Credentials, the obtained credential. @@ -152,7 +154,7 @@ def run(flow, storage): code = raw_input('Enter verification code: ').strip() try: - credential = flow.step2_exchange(code) + credential = flow.step2_exchange(code, http) except FlowExchangeError, e: sys.exit('Authentication has failed: %s' % e)
Allow an http object to be passed into tools.run() so that proxy settings will be used. Reviewed in <URL>
googleapis_oauth2client
train
2bebebd91805dbb931317f7a4057e4e8de9d9781
diff --git a/parse/lexer.go b/parse/lexer.go index <HASH>..<HASH> 100644 --- a/parse/lexer.go +++ b/parse/lexer.go @@ -611,7 +611,8 @@ func lexNegative(l *lexer) stateFn { // is it unary or binary op? // unary if it starts a group ('{' or '(') or an op came just before. var lastType = l.lastEmit.typ - if lastType.isOp() || + if lastType == itemInvalid || + lastType.isOp() || lastType == itemLeftDelim || lastType == itemCase || lastType == itemComma || diff --git a/parse/lexer_test.go b/parse/lexer_test.go index <HASH>..<HASH> 100644 --- a/parse/lexer_test.go +++ b/parse/lexer_test.go @@ -646,39 +646,43 @@ func TestScanNumber(t *testing.T) { } for _, v := range validIntegers { - l := lex("", v) - typ, ok := scanNumber(l) - res := l.input[l.start:l.pos] - if !ok || typ != itemInteger { - t.Fatalf("Expected a valid integer for %q", v) + l := lexExpr("", v) + item := <-l.items + if item.typ != itemInteger { + t.Fatalf("Expected a valid integer for %q, got %v", v, item.val) } - if res != v { - t.Fatalf("Expected %q, got %q", v, res) + if item.val != v { + t.Fatalf("Expected %q, got %q", v, item.val) + } + if err := <-l.items; err.typ != itemError { + t.Fatalf("Expected EOF, got %v", err) } } for _, v := range invalidIntegers { - l := lex("", v) - _, ok := scanNumber(l) - if ok { - t.Fatalf("Expected an invalid integer for %q", v) + l := lexExpr("", v) + item := <-l.items + if item.typ != itemError { + t.Fatalf("Expected an invalid integer for %q, got %v", v, item) } } for _, v := range validFloats { - l := lex("", v) - typ, ok := scanNumber(l) - res := l.input[l.start:l.pos] - if !ok || typ != itemFloat { + l := lexExpr("", v) + item := <-l.items + if item.typ != itemFloat { t.Fatalf("Expected a valid float for %q", v) } - if res != v { - t.Fatalf("Expected %q, got %q", v, res) + if item.val != v { + t.Fatalf("Expected %q, got %q", v, item.val) + } + if err := <-l.items; err.typ != itemError { + t.Fatalf("Expected EOF, got %v", err) } } for _, v := range invalidFloats { - l := lex("", v) - _, ok := scanNumber(l) - if ok { - t.Fatalf("Expected an invalid float for %q", v) + l := lexExpr("", v) + item := <-l.items + if item.typ == itemFloat { + t.Fatalf("Expected an invalid float for %q, got %v", v, item.typ) } } }
Update lexer tests to not have data races
robfig_soy
train
20a81dc8462114c0722171432b87b04048384f70
diff --git a/openquake/calculators/export/risk.py b/openquake/calculators/export/risk.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/export/risk.py +++ b/openquake/calculators/export/risk.py @@ -441,10 +441,11 @@ def modal_damage_array(data, damage_dt): # determine the damage state with the highest probability A, L, MS, D = data.shape dmgstate = damage_dt['structural'].names - arr = numpy.zeros(A, [('ds-' + lt, hdf5.vstr) for lt in damage_dt.names]) + arr = numpy.zeros(A, [('modal-ds-' + lt, hdf5.vstr) + for lt in damage_dt.names]) for l, loss_type in enumerate(damage_dt.names): - arr['ds-' + loss_type] = [dmgstate[data[a, l, 0].argmax()] - for a in range(A)] + arr['modal-ds-' + loss_type] = [dmgstate[data[a, l, 0].argmax()] + for a in range(A)] return arr diff --git a/openquake/calculators/tests/__init__.py b/openquake/calculators/tests/__init__.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/tests/__init__.py +++ b/openquake/calculators/tests/__init__.py @@ -63,7 +63,7 @@ def columns(line): class CalculatorTestCase(unittest.TestCase): - OVERWRITE_EXPECTED = False + OVERWRITE_EXPECTED = True edir = None # will be set to a temporary directory @classmethod diff --git a/openquake/commonlib/writers.py b/openquake/commonlib/writers.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/writers.py +++ b/openquake/commonlib/writers.py @@ -114,7 +114,7 @@ htranslator = HeaderTranslator( '(ordinal):uint32', '(gsims):object', '(branch_path):object', - '(ds-structural):object', + '(modal-ds-structural):object', '(vs30):float64', '(vs30measured):bool', '(z1pt0):float64', diff --git a/openquake/qa_tests_data/scenario_damage/case_1/expected/dmg_by_asset.csv b/openquake/qa_tests_data/scenario_damage/case_1/expected/dmg_by_asset.csv index <HASH>..<HASH> 100644 --- a/openquake/qa_tests_data/scenario_damage/case_1/expected/dmg_by_asset.csv +++ b/openquake/qa_tests_data/scenario_damage/case_1/expected/dmg_by_asset.csv @@ -1,4 +1,4 @@ -asset_ref,CRESTA,region,taxonomy,lon,lat,ds-structural +asset_ref,CRESTA,region,taxonomy,lon,lat,modal-ds-structural a1,"?","?","RM",15.48000,38.09000,LS1 a3,"?","?","RM",15.48000,38.25000,LS2 a2,"01.1","Alhué","RC",15.56000,38.17000,no_damage
Renamed ds-structural->modal-ds-structural
gem_oq-engine
train
1ace5198e2eae88f8b5d46998324dcfb407e4864
diff --git a/src/Resources/Container.php b/src/Resources/Container.php index <HASH>..<HASH> 100644 --- a/src/Resources/Container.php +++ b/src/Resources/Container.php @@ -54,7 +54,7 @@ class Container implements ArrayAccess throw new InvalidArgumentException("Invalid character in resource name [{$name}]."); } - $this->attributes['childs'][$name] = $uses; + $this->set("childs.{$name}", $uses); return $this; } @@ -72,7 +72,7 @@ class Container implements ArrayAccess throw new InvalidArgumentException("Inpecting a boolean, [{$value}] given."); } - $this->attributes['visible'] = $value; + $this->set('visible', $value); return $this; } @@ -98,26 +98,40 @@ class Container implements ArrayAccess } /** - * Set attribute + * Get attribute. * - * @param $key - * @param $value + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + return array_get($this->attributes, $key, $default); + } + + /** + * Set attribute. + * + * @param string $key + * @param mixed $value + * @return void */ public function set($key, $value) { - $this->attributes[$key] = $value; + array_set($this->attributes, $key, $value); } /** - * Get attribute + * Forget attribute. * - * @param $key - * @return mixed + * @param string $key + * @return void */ - public function get($key) + public function forget($key) { - return $this->attributes[$key]; + array_forget($this->attributes, $key); } + /** * Build resource schema. * @@ -155,7 +169,7 @@ class Container implements ArrayAccess */ public function __get($key) { - return isset($this->attributes[$key]) ? $this->attributes[$key] : null; + return $this->get($key); } /** @@ -181,7 +195,7 @@ class Container implements ArrayAccess public function __call($method, $parameters) { if (! empty($parameters)) { - throw new InvalidArgumentException("Unexpected parameters."); + throw new InvalidArgumentException("Parameters is not available."); } return $this->attributes[$method] ?: null; @@ -206,7 +220,7 @@ class Container implements ArrayAccess */ public function offsetGet($key) { - return $this->attributes['childs'][$key]; + return $this->get("childs.{$key}"); } /** @@ -229,6 +243,6 @@ class Container implements ArrayAccess */ public function offsetUnset($key) { - unset($this->attributes['childs'][$key]); + $this->forget("childs.{$key}"); } }
Tweak code to utilize get() and set() method.
orchestral_resources
train
6e7e27d883b68b9e6558b5e167548ce3d08bf45b
diff --git a/spyder/plugins/ipythonconsole/widgets/main_widget.py b/spyder/plugins/ipythonconsole/widgets/main_widget.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/ipythonconsole/widgets/main_widget.py +++ b/spyder/plugins/ipythonconsole/widgets/main_widget.py @@ -2262,7 +2262,7 @@ class IPythonConsoleWidget(PluginMainWidget): # This is necessary to prevent raising the console if the editor # and console are tabified next to each other and the 'Maintain - # focus in the editor' option is activated. + # focus in the editor' option is enabled. # Fixes spyder-ide/spyder#17028 if not focus_to_editor: self.sig_switch_to_plugin_requested.emit() @@ -2435,15 +2435,26 @@ class IPythonConsoleWidget(PluginMainWidget): sw.reset_namespace(warning=False) elif current_client and clear_variables: sw.reset_namespace(warning=False) + # Needed to handle an error when kernel_client is none. # See spyder-ide/spyder#6308. try: sw.execute(str(lines)) except AttributeError: pass - self.activateWindow() + if set_focus: - self.get_current_client().get_control().setFocus() + # The `activateWindow` call below needs to be inside this `if` + # to avoid giving focus to the console when it's undocked, + # users are running code from the editor and the 'Maintain + # focus in the editor' option is enabled. + # Fixes spyder-ide/spyder#3221 + self.activateWindow() + + # Gives focus to the current client + focus_widget = self.get_focus_widget() + if focus_widget: + focus_widget.setFocus() # ---- For error handling def go_to_error(self, text):
IPython console: Don't give it focus when undocked
spyder-ide_spyder
train
1b3d7ff9bda710f9c840ba38b8f65d4aec0bae50
diff --git a/plugins/ScheduledReports/API.php b/plugins/ScheduledReports/API.php index <HASH>..<HASH> 100644 --- a/plugins/ScheduledReports/API.php +++ b/plugins/ScheduledReports/API.php @@ -26,6 +26,9 @@ use Piwik\Site; use Piwik\Tracker; use Piwik\Translate; use Piwik\Translation\Translator; +use Piwik\Url; +use Piwik\UrlHelper; +use Psr\Log\LoggerInterface; /** * The ScheduledReports API lets you manage Scheduled Email reports, as well as generate, download or email any existing report. @@ -61,6 +64,16 @@ class API extends \Piwik\Plugin\API public static $cache = array(); /** + * @var LoggerInterface + */ + private $logger; + + public function __construct(LoggerInterface $logger) + { + $this->logger = $logger; + } + + /** * Creates a new report and schedules it. * * @param int $idSite @@ -377,7 +390,20 @@ class API extends \Piwik\Plugin\API $params['segment'] = false; } - $processedReport = Request::processRequest('API.getProcessedReport', $params); + try { + $processedReport = Request::processRequest('API.getProcessedReport', $params); + } catch (\Exception $ex) { + // NOTE: can't use warning or error because the log message will appear in the UI as a notification + $this->logger->info("Error getting '?{report}' when generating scheduled report: {exception}", array( + 'report' => http_build_query($params), + 'exception' => $ex->getMessage(), + )); + + $this->logger->debug($ex); + + continue; + } + $processedReport['segment'] = $segment; // TODO add static method getPrettyDate($period, $date) in Period
Catch exceptions when getting individual reports during scheduled reports generation so reports will still be sent even if individual reports fail in some way.
matomo-org_matomo
train
140c1ebecf27d23f8bbb3b8328e716388f153bc0
diff --git a/test/main.js b/test/main.js index <HASH>..<HASH> 100644 --- a/test/main.js +++ b/test/main.js @@ -119,7 +119,7 @@ describe('gulp-sass -- async compile', function() { var stream = sass(); stream.on('error', function(err) { - err.message.indexOf('property "font" must be followed by a \':\'').should.equal(0); + err.message.indexOf('property "font" must be followed by a \':\'').should.not.equal(-1); done(); }); stream.write(errorFile); @@ -255,7 +255,7 @@ describe('gulp-sass -- sync compile', function() { var stream = sass.sync(); stream.on('error', function(err) { - err.message.indexOf('property "font" must be followed by a \':\'').should.equal(0); + err.message.indexOf('property "font" must be followed by a \':\'').should.not.equal(-1); done(); }); stream.write(errorFile);
Test should be that error is there, not that it is start of string
dlmanning_gulp-sass
train
79d8768d546ec0546ce41c602d47759fcf1bf029
diff --git a/geist/vision.py b/geist/vision.py index <HASH>..<HASH> 100644 --- a/geist/vision.py +++ b/geist/vision.py @@ -121,8 +121,12 @@ def convolution(bin_template, bin_image, tollerance=0.5): # saw matches found_bitmap = ((convolution_image > (expected - tollerance)) & (convolution_image < (expected + tollerance))) - return [((fx - tw), (fy - th)) for (fy, fx) - in numpy.transpose(numpy.nonzero(found_bitmap))] + + match_point = numpy.transpose(numpy.nonzero(found_bitmap)) # bottom right + + # Find the top left point from the template (remember match_point is + # inside the template (hence -1) + return [((fx - (tw - 1)), (fy - (th - 1))) for (fy, fx) in match_point] def overlapped_convolution(bin_template, bin_image, @@ -171,7 +175,7 @@ def overlapped_convolution(bin_template, bin_image, filterd = ((test >= (count - tollerance)) & (test <= (count + tollerance))) for (fy, fx) in numpy.transpose(numpy.nonzero(filterd)): - results.add((x + fx - tw, y + fy - th)) + results.add((x + fx - (tw - 1), y + fy - (th - 1))) convolution_image %= num return list(results)
Bug fix: result from convolution match. Result is inside template
ten10solutions_Geist
train
19b76d9de0b3ff35e394d87d7249e2475a0e0386
diff --git a/definitions/npm/mongoose_v4.x.x/flow_v0.50.x-/mongoose_v4.x.x.js b/definitions/npm/mongoose_v4.x.x/flow_v0.50.x-/mongoose_v4.x.x.js index <HASH>..<HASH> 100644 --- a/definitions/npm/mongoose_v4.x.x/flow_v0.50.x-/mongoose_v4.x.x.js +++ b/definitions/npm/mongoose_v4.x.x/flow_v0.50.x-/mongoose_v4.x.x.js @@ -74,7 +74,8 @@ type SchemaOpts<Doc> = { | { createdAt?: string, updatedAt?: string - } + }, + discriminatorKey?: string }; type IndexFields = { @@ -178,7 +179,8 @@ type Mongoose$SchemaField<Schema> = { description: ?string }, enumValues?: ?(string[]), - schema?: Schema + schema?: Schema, + _index?: ?{ [optionName: string]: mixed } }; declare class Mongoose$SchemaVirtualField { @@ -261,6 +263,7 @@ declare class Mongoose$Document { static modelName: string; static schema: Mongoose$Schema<this>; static on(type: string, cb: Function): void; + static discriminator(name: string, schema: Mongoose$Schema<any>): Class<this>; collection: Mongoose$Collection; constructor(data?: $Shape<this>): this;
Some additions to mongoose@<I> (#<I>) * Some additions to mongoose@<I> * fix(mongoose): return export statemant back
flow-typed_flow-typed
train
420dbabac7117b3bb53888c8e2446fe003fc5423
diff --git a/src/App/Features/App.php b/src/App/Features/App.php index <HASH>..<HASH> 100644 --- a/src/App/Features/App.php +++ b/src/App/Features/App.php @@ -30,6 +30,60 @@ trait App } /** + * Get an instance of a registered class + * + * @param string $sClass The class name + * + * @return mixed + */ + public function instance($sClassName) + { + return jaxon()->instance($sClassName); + } + + /** + * Get a request to a registered class + * + * @param string $sClass The class name + * + * @return \Jaxon\Request\Factory\Invokable\Request + */ + public function request($sClassName) + { + return jaxon()->request($sClassName); + } + + /** + * Get the request callback manager + * + * @return \Jaxon\Request\Handler\Callback + */ + public function callback() + { + return jaxon()->callback(); + } + + /** + * Determine if a call is a Jaxon request. + * + * @return boolean + */ + public function canProcessRequest() + { + return jaxon()->canProcessRequest(); + } + + /** + * Process an incoming Jaxon request. + * + * @return void + */ + public function processRequest() + { + return jaxon()->processRequest(); + } + + /** * Get the javascript code to be sent to the browser. * * @return string the javascript code diff --git a/src/Jaxon.php b/src/Jaxon.php index <HASH>..<HASH> 100644 --- a/src/Jaxon.php +++ b/src/Jaxon.php @@ -277,6 +277,19 @@ class Jaxon } /** + * Get a request to a registered class + * + * @param string $sClass The class name + * + * @return \Jaxon\Request\Factory\Invokable\Request + */ + public function request($sClassName) + { + $xInstance = $this->instance($sClassName); + return ($xInstance) ? $xInstance->rq() : null; + } + + /** * Returns the Jaxon Javascript header and wrapper code to be printed into the page * * The javascript code returned by this function is dependent on the plugins
Added more methods to the Jaxon\App\Features\App class.
jaxon-php_jaxon-core
train
512688ef7f7601f1a69cb38dc6211b20dc300e33
diff --git a/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractTxtSolutionImporter.java b/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractTxtSolutionImporter.java index <HASH>..<HASH> 100644 --- a/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractTxtSolutionImporter.java +++ b/optaplanner-examples/src/main/java/org/optaplanner/examples/common/persistence/AbstractTxtSolutionImporter.java @@ -251,6 +251,11 @@ public abstract class AbstractTxtSolutionImporter extends AbstractSolutionImport return splitBy(line, "[\\ \\t]+", "spaces or tabs", numberOfTokens, false, false); } + public String[] splitBySpacesOrTabs(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens) { + return splitBy(line, "[\\ \\t]+", "spaces or tabs", minimumNumberOfTokens, maximumNumberOfTokens, + false, false); + } + public String[] splitByPipelineAndTrim(String line, int numberOfTokens) { return splitBy(line, "\\|", "a pipeline (|)", numberOfTokens, true, false); } diff --git a/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/persistence/VehicleRoutingImporter.java b/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/persistence/VehicleRoutingImporter.java index <HASH>..<HASH> 100644 --- a/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/persistence/VehicleRoutingImporter.java +++ b/optaplanner-examples/src/main/java/org/optaplanner/examples/vehiclerouting/persistence/VehicleRoutingImporter.java @@ -152,7 +152,7 @@ public class VehicleRoutingImporter extends AbstractTxtSolutionImporter { locationMap = new HashMap<Long, Location>(locationListSize); for (int i = 0; i < locationListSize; i++) { String line = bufferedReader.readLine(); - String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3); + String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3, 4); Location location = roadDistance ? new RoadDistanceLocation() : new AirDistanceLocation(); location.setId(Long.parseLong(lineTokens[0])); location.setLatitude(Double.parseDouble(lineTokens[1])); @@ -281,7 +281,7 @@ public class VehicleRoutingImporter extends AbstractTxtSolutionImporter { locationMap = new HashMap<Long, Location>(locationListSize); for (int i = 0; i < locationListSize; i++) { String line = bufferedReader.readLine(); - String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3); + String[] lineTokens = splitBySpacesOrTabs(line.trim(), 3, 4); AirDistanceLocation location = new AirDistanceLocation(); location.setId((long) i); location.setLatitude(Double.parseDouble(lineTokens[1]));
vrp importer should support location names too
kiegroup_optaplanner
train
f5e3416281b887f84324723d6f305564fcfcbb8c
diff --git a/lib/ssh.js b/lib/ssh.js index <HASH>..<HASH> 100644 --- a/lib/ssh.js +++ b/lib/ssh.js @@ -1163,7 +1163,7 @@ SSH2Stream.prototype.openssh_directStreamLocal = function(chan, initWindow, var pathlen = Buffer.byteLength(cfg.socketPath); var p = 47; - var buf = new Buffer(1 + 4 + 30 + 4 + 4 + 4 + 4 + pathlen + 4); + var buf = new Buffer(1 + 4 + 30 + 4 + 4 + 4 + 4 + pathlen + 4 + 4); buf[0] = MESSAGE.CHANNEL_OPEN; @@ -1179,6 +1179,9 @@ SSH2Stream.prototype.openssh_directStreamLocal = function(chan, initWindow, buf.writeUInt32BE(pathlen, p, true); buf.write(cfg.socketPath, p += 4, pathlen, 'utf8'); + // reserved fields (string and uint32) + buf.fill(0, buf.length - 8); + this.debug('DEBUG: Outgoing: Writing CHANNEL_OPEN (' + chan + ', direct-streamlocal@openssh.com)');
SSH2Stream: add missing field in OpenSSH unix socket connection request
mscdex_ssh2-streams
train
7d9808870f16ebcae2a23714b985086b658e9d92
diff --git a/evolutionary_search/__init__.py b/evolutionary_search/__init__.py index <HASH>..<HASH> 100644 --- a/evolutionary_search/__init__.py +++ b/evolutionary_search/__init__.py @@ -263,7 +263,7 @@ class EvolutionaryAlgorithmSearchCV(BaseSearchCV): gene_mutation_prob=0.1, gene_crossover_prob=0.5, tournament_size=3, generations_number=10, gene_type=None, n_jobs=1, iid=True, pre_dispatch='2*n_jobs', error_score='raise', - fit_params=None): + fit_params={}): super(EvolutionaryAlgorithmSearchCV, self).__init__( estimator=estimator, scoring=scoring, fit_params=fit_params, n_jobs=n_jobs, iid=iid, refit=refit, cv=cv, verbose=verbose,
fitparams needs to default to an empty dict, or else you will occasionally get a warning that **fit_params must be a mapping not NoneType.
rsteca_sklearn-deap
train
3d045b5f1c4b9efc6b51b09afaf104a24e069a15
diff --git a/blox/dom.py b/blox/dom.py index <HASH>..<HASH> 100644 --- a/blox/dom.py +++ b/blox/dom.py @@ -21,6 +21,77 @@ OTHER DEALINGS IN THE SOFTWARE. ''' from blox.base import Tag, NamedTag +from blox.attributes import AbstractAttribute, Attribute, DirectAttribute, SetAttribute, BooleanAttribute + +from blox.builder import Factory + + +factory = Factory('dom') + + +@factory.add() +class A(Tag): + '''Defines a link that when clicked changes the current viewed page''' + __slots__ = () + tag = "a" + href = Attribute() + media = Attribute() + rel = Attribute() + target = Attribute() + type = Attribute() + + +@factory.add() +class Abr(Tag): + '''Defines an abbreviation or an acronym''' + __slots__ = () + tag = "abr" + + +@factory.add() +class Address(Tag): + '''Defines contact info for the author of a document or article''' + __slots__ = () + tag = "address" + + +@factory.add() +class Area(Tag): + '''Defines an area inside of an image map''' + __slots__ = () + tag = 'area' + alt = Attribute() + coords = Attribute() + href = Attribute() + hreflang = Attribute() + media = Attribute() + rel = Attribute() + shape = Attribute() + target = Attribute() + type = Attribute() + + +@factory.add() +class Article(Tag): + '''Defines an independent, self-contained content''' + __slots__ = () + tag = "article" + + +@factory.add() +class Aside(Tag): + '''Defines content as being aside from the content it is placed in''' + __slots__ = () + tag = "aside" + + +@factory.add() +class Audio(Tag): + '''Defines sound, such as music or other audio streams''' + __slots__ = () + tag = "audio" + autoplay = BooleanAttribute() + controls = BooleanAttribute() + loop = BooleanAttribute() + src = Attribute() -class DOM(Tag): - pass
Add dom tags that start with 'A'
timothycrosley_blox
train
e4419fd3648f29ec2ad7def147d67d3acabef8c9
diff --git a/alot/buffers.py b/alot/buffers.py index <HASH>..<HASH> 100644 --- a/alot/buffers.py +++ b/alot/buffers.py @@ -40,7 +40,7 @@ class Buffer(object): class BufferlistBuffer(Buffer): - """selectable list of active buffers""" + """lists all active buffers""" modename = 'bufferlist' @@ -136,10 +136,7 @@ class EnvelopeBuffer(Buffer): class SearchBuffer(Buffer): - """ - shows a result set for a Thread query, one line per - :class:`~alot.db.Thread` - """ + """shows a result list of threads for a query""" modename = 'search' threads = [] @@ -220,8 +217,7 @@ class SearchBuffer(Buffer): class ThreadBuffer(Buffer): - """shows a single mailthread as a (collapsible) tree of - :class:`MessageWidgets <alot.widgets.MessageWidget>`.""" + """displays a thread as a tree of messages""" modename = 'thread' @@ -323,7 +319,7 @@ class ThreadBuffer(Buffer): class TagListBuffer(Buffer): - """selectable list of tagstrings present in the database""" + """lists all tagstrings present in the notmuch database""" modename = 'taglist'
nicer docstrings for buffers=modes
pazz_alot
train
31ddb8355f7fe842f6f17ae8044bae3358f2c1a7
diff --git a/lib/ChargeBee/Models/Addon.php b/lib/ChargeBee/Models/Addon.php index <HASH>..<HASH> 100644 --- a/lib/ChargeBee/Models/Addon.php +++ b/lib/ChargeBee/Models/Addon.php @@ -11,6 +11,11 @@ class ChargeBee_Addon extends ChargeBee_Model # OPERATIONS #----------- + public static function create($params, $env = null) + { + return ChargeBee_Request::send(ChargeBee_Request::POST, "/addons", $params, $env); + } + public static function all($params = array(), $env = null) { return ChargeBee_Request::send(ChargeBee_Request::GET, "/addons", $params, $env); diff --git a/lib/ChargeBee/Models/Plan.php b/lib/ChargeBee/Models/Plan.php index <HASH>..<HASH> 100644 --- a/lib/ChargeBee/Models/Plan.php +++ b/lib/ChargeBee/Models/Plan.php @@ -11,6 +11,11 @@ class ChargeBee_Plan extends ChargeBee_Model # OPERATIONS #----------- + public static function create($params, $env = null) + { + return ChargeBee_Request::send(ChargeBee_Request::POST, "/plans", $params, $env); + } + public static function all($params = array(), $env = null) { return ChargeBee_Request::send(ChargeBee_Request::GET, "/plans", $params, $env);
Support for creating plans & addons on the fly via API.
chargebee_chargebee-php
train
1b39930dad85970079916bfaa8f960b9f90839a7
diff --git a/src/Symfony/Component/HttpKernel/Kernel.php b/src/Symfony/Component/HttpKernel/Kernel.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/HttpKernel/Kernel.php +++ b/src/Symfony/Component/HttpKernel/Kernel.php @@ -59,12 +59,12 @@ abstract class Kernel implements KernelInterface, TerminableInterface protected $startTime; protected $loadClassCache; - const VERSION = '2.3.24'; - const VERSION_ID = '20324'; + const VERSION = '2.3.25-DEV'; + const VERSION_ID = '20325'; const MAJOR_VERSION = '2'; const MINOR_VERSION = '3'; - const RELEASE_VERSION = '24'; - const EXTRA_VERSION = ''; + const RELEASE_VERSION = '25'; + const EXTRA_VERSION = 'DEV'; /** * Constructor.
bumped Symfony version to <I>
symfony_symfony
train
b33cca664e9a56bd5055ae3675c9abcb1539add2
diff --git a/lib/eckey.js b/lib/eckey.js index <HASH>..<HASH> 100644 --- a/lib/eckey.js +++ b/lib/eckey.js @@ -1,4 +1,6 @@ -var ECPointFp = require('ecurve').ECPointFp; +var ecurve = require('ecurve') +var ECPointFp = ecurve.ECPointFp +var ecparams = ecurve.getECParams('secp256k1') var BigInteger = require('bigi'); module.exports = ECKey @@ -75,7 +77,7 @@ Object.defineProperty(ECKey.prototype, 'publicKey', { Object.defineProperty(ECKey.prototype, 'publicPoint', { get: function() { if (!this._publicPoint) - this._publicPoint = ecparams.getG().multiply(this.keyBigInteger); + this._publicPoint = ecparams.g.multiply(this.keyBigInteger); return this._publicPoint; } })
tests passing with new ecurve
cryptocoinjs_eckey
train
8f509269a80d413fa0151b5cffbfdd21b82bc33c
diff --git a/Helper/ConfigurationHelper.php b/Helper/ConfigurationHelper.php index <HASH>..<HASH> 100644 --- a/Helper/ConfigurationHelper.php +++ b/Helper/ConfigurationHelper.php @@ -48,10 +48,9 @@ final class ConfigurationHelper * @param string $name * @param string[] $signatureAlgorithms * @param string[] $headerCheckers - * @param string[] $serializers * @param bool $is_public */ - public static function addJWSLoader(ContainerBuilder $container, string $name, array $signatureAlgorithms, array $headerCheckers, array $serializers = ['jws_compact'], bool $is_public = true) + public static function addJWSLoader(ContainerBuilder $container, string $name, array $signatureAlgorithms, array $headerCheckers, bool $is_public = true) { $config = [ self::BUNDLE_ALIAS => [ @@ -60,7 +59,6 @@ final class ConfigurationHelper 'is_public' => $is_public, 'signature_algorithms' => $signatureAlgorithms, 'header_checkers' => $headerCheckers, - 'serializers' => $serializers, ], ], ], @@ -188,10 +186,9 @@ final class ConfigurationHelper * @param array $contentEncryptionAlgorithms * @param array $compressionMethods * @param array $headerCheckers - * @param array $serializers * @param bool $is_public */ - public static function addJWELoader(ContainerBuilder $container, string $name, array $keyEncryptionAlgorithm, array $contentEncryptionAlgorithms, array $compressionMethods = ['DEF'], array $headerCheckers = [], array $serializers = ['jwe_compact'], bool $is_public = true) + public static function addJWELoader(ContainerBuilder $container, string $name, array $keyEncryptionAlgorithm, array $contentEncryptionAlgorithms, array $compressionMethods = ['DEF'], array $headerCheckers = [], bool $is_public = true) { $config = [ self::BUNDLE_ALIAS => [ @@ -202,7 +199,6 @@ final class ConfigurationHelper 'content_encryption_algorithms' => $contentEncryptionAlgorithms, 'compression_methods' => $compressionMethods, 'header_checkers' => $headerCheckers, - 'serializers' => $serializers, ], ], ],
Loading is done by the serializers, not the loader
web-token_jwt-bundle
train
b698347abb38fbbd70986b15612c1c103e334bb9
diff --git a/worker/firewaller/firewaller.go b/worker/firewaller/firewaller.go index <HASH>..<HASH> 100644 --- a/worker/firewaller/firewaller.go +++ b/worker/firewaller/firewaller.go @@ -429,11 +429,9 @@ func (fw *Firewaller) startUnit(unit *firewaller.Unit, machineTag names.MachineT if err != nil { return err } + applicationTag := application.Tag() unitTag := unit.Tag() - if err != nil { - return err - } unitd := &unitData{ fw: fw, unit: unit,
Removes superfluous error check from firewaller worker.
juju_juju
train
8d8e23bb935b103b28c18c32bfb24f4ad0ac1e0a
diff --git a/arviz/plots/rankplot.py b/arviz/plots/rankplot.py index <HASH>..<HASH> 100644 --- a/arviz/plots/rankplot.py +++ b/arviz/plots/rankplot.py @@ -52,26 +52,26 @@ def plot_rank( Parameters ---------- data: obj - Any object that can be converted to an az.InferenceData object. Refer to documentation of - az.convert_to_dataset for details + Any object that can be converted to an :class:`arviz.InferenceData` object. + Refer to documentation of :func:`arviz.convert_to_dataset` for details var_names: string or list of variable names - Variables to be plotted. Prefix the variables by `~` when you want to exclude + Variables to be plotted. Prefix the variables by ``~`` when you want to exclude them from the plot. filter_vars: {None, "like", "regex"}, optional, default=None If `None` (default), interpret var_names as the real variables names. If "like", interpret var_names as substrings of the real variables names. If "regex", interpret var_names as regular expressions on the real variables names. A la - `pandas.filter`. + ``pandas.filter``. transform: callable Function to transform data (defaults to None i.e.the identity function) coords: mapping, optional - Coordinates of var_names to be plotted. Passed to `Dataset.sel` + Coordinates of var_names to be plotted. Passed to :meth:`xarray.Dataset.sel` bins: None or passed to np.histogram Binning strategy used for histogram. By default uses twice the result of Sturges' formula. See :func:`numpy.histogram` documentation for, other available arguments. kind: string If bars (defaults), ranks are represented as stacked histograms (one per chain). If vlines - ranks are represented as vertical lines above or below `ref_line`. + ranks are represented as vertical lines above or below ``ref_line``. colors: string or list of strings List with valid matplotlib colors, one color per model. Alternative a string can be passed. If the string is `cycle`, it will automatically choose a color per model from matplotlib's @@ -82,7 +82,7 @@ def plot_rank( labels: bool whether to plot or not the x and y labels, defaults to True labeller : labeller instance, optional - Class providing the method `make_label_vert` to generate the labels in the plot titles. + Class providing the method ``make_label_vert`` to generate the labels in the plot titles. Read the :ref:`label_guide` for more details and usage examples. grid : tuple Number of rows and columns. Defaults to None, the rows and columns are @@ -90,24 +90,26 @@ def plot_rank( figsize: tuple Figure size. If None it will be defined automatically. ax: numpy array-like of matplotlib axes or bokeh figures, optional - A 2D array of locations into which to plot the densities. If not supplied, Arviz will create + A 2D array of locations into which to plot the densities. If not supplied, ArviZ will create its own array of plot areas (and return it). backend: str, optional Select plotting backend {"matplotlib","bokeh"}. Default "matplotlib". ref_line_kwargs : dict, optional Reference line keyword arguments, passed to :meth:`mpl:matplotlib.axes.Axes.axhline` or - :meth:`bokeh:bokeh.model.Span`. + :class:`bokeh:bokeh.models.Span`. bar_kwargs : dict, optional Bars keyword arguments, passed to :meth:`mpl:matplotlib.axes.Axes.bar` or - :meth:`bokeh:bokeh.plotting.figure.Figure.vbar`. + :meth:`bokeh:bokeh.plotting.Figure.vbar`. vlines_kwargs : dict, optional Vlines keyword arguments, passed to :meth:`mpl:matplotlib.axes.Axes.vlines` or - :meth:`bokeh:bokeh.plotting.figure.Figure.multi_line`. + :meth:`bokeh:bokeh.plotting.Figure.multi_line`. marker_vlines_kwargs : dict, optional Marker for the vlines keyword arguments, passed to :meth:`mpl:matplotlib.axes.Axes.plot` or - :meth:`bokeh:bokeh.plotting.figure.Figure.circle`. + :meth:`bokeh:bokeh.plotting.Figure.circle`. backend_kwargs: bool, optional - These are kwargs specific to the backend being used. For additional documentation + These are kwargs specific to the backend being used, passed to + :func:`matplotlib.pyplot.subplots` or + :func:`bokeh.plotting.figure`. For additional documentation check the plotting method of the backend. show: bool, optional Call backend show function. @@ -116,6 +118,11 @@ def plot_rank( ------- axes: matplotlib axes or bokeh figures + See Also + -------- + plot_trace : Plot distribution (histogram or kernel density estimates) and + sampled values or rank plot. + Examples -------- Show a default rank plot
Added references - Plot rank (#<I>) * Added references * Fixed line length * Fixed a word
arviz-devs_arviz
train
6cee8536b7236550f983118e9d1c9a4aa79fa84d
diff --git a/docs/settings.rst b/docs/settings.rst index <HASH>..<HASH> 100644 --- a/docs/settings.rst +++ b/docs/settings.rst @@ -268,15 +268,31 @@ JWT_REFRESH_TOKEN_COOKIE_NAME JWT_COOKIE_SECURE ~~~~~~~~~~~~~~~~~ - Whether to use a secure cookie for the JWT cookie. If this is set to True, the cookie will be marked as "secure", which means browsers may ensure that the cookie is only sent under an HTTPS connection. + Whether to use a secure cookie for the JWT cookie. If this is set to True, the cookie will be marked as "secure", which means browsers may ensure that the cookie is only sent under an HTTPS connection Default: ``False`` +JWT_COOKIE_PATH +~~~~~~~~~~~~~~~~~ + + Document location for the cookie + + Default: ``'/'`` + + +JWT_COOKIE_DOMAIN +~~~~~~~~~~~~~~~~~ + + Use domain if you want to set a cross-domain cookie + + Default: ``None`` + + JWT_HIDE_TOKEN_FIELDS ~~~~~~~~~~~~~~~~~~~~~ - For cookie-based authentications, remove the token fields from the GraphQL schema in order to prevent XSS exploitation. + For cookie-based authentications, remove the token fields from the GraphQL schema in order to prevent XSS exploitation Default: ``False`` @@ -287,7 +303,7 @@ CSRF JWT_CSRF_ROTATION ~~~~~~~~~~~~~~~~~ - Rotate CSRF tokens each time a token or refresh token is issued. + Rotate CSRF tokens each time a token or refresh token is issued Default: ``False`` diff --git a/graphql_jwt/decorators.py b/graphql_jwt/decorators.py index <HASH>..<HASH> 100644 --- a/graphql_jwt/decorators.py +++ b/graphql_jwt/decorators.py @@ -12,6 +12,7 @@ from promise import Promise, is_thenable from . import exceptions, signals from .refresh_token.shortcuts import create_refresh_token, refresh_token_lazy from .settings import jwt_settings +from .utils import delete_cookie, set_cookie __all__ = [ 'user_passes_test', @@ -164,30 +165,29 @@ def jwt_cookie(view_func): if hasattr(request, 'jwt_token'): expires = datetime.utcnow() + jwt_settings.JWT_EXPIRATION_DELTA - response.set_cookie( + set_cookie( + response, jwt_settings.JWT_COOKIE_NAME, request.jwt_token, expires=expires, - httponly=True, - secure=jwt_settings.JWT_COOKIE_SECURE, ) if hasattr(request, 'jwt_refresh_token'): refresh_token = request.jwt_refresh_token expires = refresh_token.created +\ jwt_settings.JWT_REFRESH_EXPIRATION_DELTA - response.set_cookie( + set_cookie( + response, jwt_settings.JWT_REFRESH_TOKEN_COOKIE_NAME, refresh_token.token, expires=expires, - httponly=True, - secure=jwt_settings.JWT_COOKIE_SECURE, ) + if hasattr(request, 'delete_jwt_cookie'): - response.delete_cookie(jwt_settings.JWT_COOKIE_NAME) + delete_cookie(response, jwt_settings.JWT_COOKIE_NAME) if hasattr(request, 'delete_refresh_token_cookie'): - response.delete_cookie(jwt_settings.JWT_REFRESH_TOKEN_COOKIE_NAME) + delete_cookie(response, jwt_settings.JWT_REFRESH_TOKEN_COOKIE_NAME) return response return wrapped_view diff --git a/graphql_jwt/settings.py b/graphql_jwt/settings.py index <HASH>..<HASH> 100644 --- a/graphql_jwt/settings.py +++ b/graphql_jwt/settings.py @@ -42,6 +42,8 @@ DEFAULTS = { 'JWT_COOKIE_NAME': 'JWT', 'JWT_REFRESH_TOKEN_COOKIE_NAME': 'JWT-refresh-token', 'JWT_COOKIE_SECURE': False, + 'JWT_COOKIE_PATH': '/', + 'JWT_COOKIE_DOMAIN': None, } IMPORT_STRINGS = ( diff --git a/graphql_jwt/utils.py b/graphql_jwt/utils.py index <HASH>..<HASH> 100644 --- a/graphql_jwt/utils.py +++ b/graphql_jwt/utils.py @@ -117,3 +117,23 @@ def get_user_by_payload(payload): def refresh_has_expired(orig_iat, context=None): exp = orig_iat + jwt_settings.JWT_REFRESH_EXPIRATION_DELTA.total_seconds() return timegm(datetime.utcnow().utctimetuple()) > exp + + +def set_cookie(response, key, value, expires): + response.set_cookie( + key, + value, + expires=expires, + httponly=True, + secure=jwt_settings.JWT_COOKIE_SECURE, + path=jwt_settings.JWT_COOKIE_PATH, + domain=jwt_settings.JWT_COOKIE_DOMAIN, + ) + + +def delete_cookie(response, key): + response.delete_cookie( + key, + path=jwt_settings.JWT_COOKIE_PATH, + domain=jwt_settings.JWT_COOKIE_DOMAIN, + )
Added JWT_COOKIE_PATH and JWT_COOKIE_DOMAIN settings
flavors_django-graphql-jwt
train
037bc34fa6d2fd63956d9bbc32d0f43fc37ad0d1
diff --git a/controller/src/main/java/org/jboss/as/controller/operations/global/GlobalOperationHandlers.java b/controller/src/main/java/org/jboss/as/controller/operations/global/GlobalOperationHandlers.java index <HASH>..<HASH> 100644 --- a/controller/src/main/java/org/jboss/as/controller/operations/global/GlobalOperationHandlers.java +++ b/controller/src/main/java/org/jboss/as/controller/operations/global/GlobalOperationHandlers.java @@ -896,6 +896,7 @@ public class GlobalOperationHandlers { rrOp.get(PROXIES).set(proxies); rrOp.get(OPERATIONS).set(ops); rrOp.get(INHERITED).set(inheritedOps); + rrOp.get(LOCALE).set(operation.get(LOCALE)); ModelNode rrRsp = new ModelNode(); childResources.put(element, rrRsp);
AS7-<I> Pass locale to recursive description read ops
wildfly_wildfly
train
56d2fec30d78be3f35de8d0e971542b9f20aeece
diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -193,6 +193,10 @@ class Builder return $this; } + if ($this->model->getKeyType() === 'string') { + $id = (string) $id; + } + return $this->where($this->model->getQualifiedKeyName(), '=', $id); } @@ -210,6 +214,10 @@ class Builder return $this; } + if ($this->model->getKeyType() === 'string') { + $id = (string) $id; + } + return $this->where($this->model->getQualifiedKeyName(), '!=', $id); } diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php index <HASH>..<HASH> 100755 --- a/tests/Database/DatabaseEloquentBuilderTest.php +++ b/tests/Database/DatabaseEloquentBuilderTest.php @@ -31,7 +31,9 @@ class DatabaseEloquentBuilderTest extends TestCase public function testFindMethod() { $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]); - $builder->setModel($this->getMockModel()); + $model = $this->getMockModel(); + $builder->setModel($model); + $model->shouldReceive('getKeyType')->once()->andReturn('int'); $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar'); $builder->shouldReceive('first')->with(['column'])->andReturn('baz'); @@ -76,6 +78,7 @@ class DatabaseEloquentBuilderTest extends TestCase public function testFindOrNewMethodModelFound() { $model = $this->getMockModel(); + $model->shouldReceive('getKeyType')->once()->andReturn('int'); $model->shouldReceive('findOrNew')->once()->andReturn('baz'); $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]); @@ -91,6 +94,7 @@ class DatabaseEloquentBuilderTest extends TestCase public function testFindOrNewMethodModelNotFound() { $model = $this->getMockModel(); + $model->shouldReceive('getKeyType')->once()->andReturn('int'); $model->shouldReceive('findOrNew')->once()->andReturn(m::mock(Model::class)); $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]); @@ -109,7 +113,9 @@ class DatabaseEloquentBuilderTest extends TestCase $this->expectException(ModelNotFoundException::class); $builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]); - $builder->setModel($this->getMockModel()); + $model = $this->getMockModel(); + $model->shouldReceive('getKeyType')->once()->andReturn('int'); + $builder->setModel($model); $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar'); $builder->shouldReceive('first')->with(['column'])->andReturn(null); $builder->findOrFail('bar', ['column']); @@ -1038,11 +1044,25 @@ class DatabaseEloquentBuilderTest extends TestCase $int = 1; + $model->shouldReceive('getKeyType')->once()->andReturn('int'); $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '=', $int); $builder->whereKey($int); } + public function testWhereKeyMethodWithStringZero() + { + $model = new EloquentBuilderTestStubStringPrimaryKey(); + $builder = $this->getBuilder()->setModel($model); + $keyName = $model->getQualifiedKeyName(); + + $int = 0; + + $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '=', (string) $int); + + $builder->whereKey($int); + } + public function testWhereKeyMethodWithArray() { $model = $this->getMockModel(); @@ -1069,6 +1089,19 @@ class DatabaseEloquentBuilderTest extends TestCase $builder->whereKey($collection); } + public function testWhereKeyNotMethodWithStringZero() + { + $model = new EloquentBuilderTestStubStringPrimaryKey(); + $builder = $this->getBuilder()->setModel($model); + $keyName = $model->getQualifiedKeyName(); + + $int = 0; + + $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', (string) $int); + + $builder->whereKeyNot($int); + } + public function testWhereKeyNotMethodWithInt() { $model = $this->getMockModel(); @@ -1077,6 +1110,7 @@ class DatabaseEloquentBuilderTest extends TestCase $int = 1; + $model->shouldReceive('getKeyType')->once()->andReturn('int'); $builder->getQuery()->shouldReceive('where')->once()->with($keyName, '!=', $int); $builder->whereKeyNot($int); @@ -1445,3 +1479,12 @@ class EloquentBuilderTestStubWithoutTimestamp extends Model protected $table = 'table'; } + +class EloquentBuilderTestStubStringPrimaryKey extends Model +{ + public $incrementing = false; + + protected $table = 'foo_table'; + + protected $keyType = 'string'; +}
[7.x] Cast primary key to string when $keyType is string (#<I>) * Cast primary key to string when $keyType is string * fix test * fix remaining tests
laravel_framework
train
a9f8e6540e0b653a9d4e7e8ffdd8afeca963dffb
diff --git a/src/v1/Taxonomy.js b/src/v1/Taxonomy.js index <HASH>..<HASH> 100644 --- a/src/v1/Taxonomy.js +++ b/src/v1/Taxonomy.js @@ -135,10 +135,12 @@ class Taxonomy { /* Convinience method to create taxonomies. Since taxonomies are reliying on a 'strict' parent child relation ship. We have to ensure that the parent category was created before the child categories. */ createCategoryLvl(taxonomyLvl, categoryMap) { + let _getname = (obj) => (typeof obj === 'string') ? obj : obj.name; return new Promise((resolve, reject) => { Promise.resolve(taxonomyLvl.childs). - then(childs => resolveall(childs.map(child => this.createCategory({name:child, parent: categoryMap.get(taxonomyLvl.parent)})))). - then(categories => resolveall(categories.map(result => categoryMap.set(result.name, result.id)))). + then(childs => childs.map(child => this.createCategory({name:_getname(child), parent: categoryMap.get(_getname(taxonomyLvl.parent))}))). + then(createPromises => resolveall(createPromises)). + then(categories => categories.map(result => categoryMap.set(result.name, result.id))). then(resolve). catch(reject); });
Create taxonomy method now handles names as string or object.
ibm-wch_sample-wch-node-wrapper
train
68030c74d76bc5b3ab4f4f2760eb037ef008255f
diff --git a/src/main/java/net/malisis/core/client/gui/component/interaction/UIButton.java b/src/main/java/net/malisis/core/client/gui/component/interaction/UIButton.java index <HASH>..<HASH> 100644 --- a/src/main/java/net/malisis/core/client/gui/component/interaction/UIButton.java +++ b/src/main/java/net/malisis/core/client/gui/component/interaction/UIButton.java @@ -38,6 +38,9 @@ import net.malisis.core.client.gui.icon.GuiIcon; import net.malisis.core.util.MouseButton; import com.google.common.eventbus.Subscribe; +import net.minecraft.client.Minecraft; +import net.minecraft.client.audio.PositionedSoundRecord; +import net.minecraft.util.ResourceLocation; /** * UIButton @@ -48,14 +51,13 @@ public class UIButton extends UIComponent<UIButton> { protected GuiIcon iconHovered; protected GuiIcon iconDisabled; + protected GuiIcon iconPressed; private String text; private UIImage image; private boolean autoWidth = true; private boolean isPressed = false; - // this.mc.getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); - /** * Instantiates a new {@link UIButton}. * @@ -70,6 +72,7 @@ public class UIButton extends UIComponent<UIButton> icon = gui.getGuiTexture().getXYResizableIcon(0, 20, 200, 20, 5); iconHovered = gui.getGuiTexture().getXYResizableIcon(0, 40, 200, 20, 5); iconDisabled = gui.getGuiTexture().getXYResizableIcon(0, 0, 200, 20, 5); + iconPressed = (GuiIcon) gui.getGuiTexture().getXYResizableIcon(0, 40, 200, 20, 5).flip(true, true); } /** @@ -189,8 +192,23 @@ public class UIButton extends UIComponent<UIButton> @Override public void drawBackground(GuiRenderer renderer, int mouseX, int mouseY, float partialTick) { - GuiIcon icon = isDisabled() ? iconDisabled : (isHovered() ? iconHovered : this.icon); - icon.flip(isPressed, isPressed); + final GuiIcon icon; + if (isDisabled()) + { + icon = iconDisabled; + } + else if (isPressed) + { + icon = iconPressed; + } + else if (isHovered()) + { + icon = iconHovered; + } + else + { + icon = this.icon; + } rp.icon.set(icon); renderer.drawShape(shape, rp); } @@ -251,6 +269,7 @@ public class UIButton extends UIComponent<UIButton> return; isPressed = false; + Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); fireEvent(new ClickEvent(this, (Release) event)); }
Add iconPressed and fix click sound
Ordinastie_MalisisCore
train
3e44ff3f23812a50a7531403bd6e0e2c7f92a9e9
diff --git a/controllers/socket/lobbyHandlers.go b/controllers/socket/lobbyHandlers.go index <HASH>..<HASH> 100644 --- a/controllers/socket/lobbyHandlers.go +++ b/controllers/socket/lobbyHandlers.go @@ -79,7 +79,7 @@ func lobbyCreateHandler(so socketio.Socket) func(string) string { } lob := models.NewLobby(mapName, lobbytype, league, info, whitelist) - lob.CreatedBy = *player + lob.CreatedByID = player.ID lob.Save() err = lob.SetupServer() diff --git a/models/lobby.go b/models/lobby.go index <HASH>..<HASH> 100644 --- a/models/lobby.go +++ b/models/lobby.go @@ -88,7 +88,6 @@ type Lobby struct { BannedPlayers []Player `gorm:"many2many:banned_players_lobbies"` CreatedByID uint - CreatedBy Player } func NewLobby(mapName string, lobbyType LobbyType, league string, serverInfo ServerRecord, whitelist int) *Lobby {
Use CreatedByID to store lobby leader.
TF2Stadium_Helen
train
a235a25254bd6025a3391ab80a4dff0a8ec6fabe
diff --git a/src/BladeX.php b/src/BladeX.php index <HASH>..<HASH> 100755 --- a/src/BladeX.php +++ b/src/BladeX.php @@ -2,6 +2,7 @@ namespace Spatie\BladeX; +use InvalidArgumentException; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\View; use Symfony\Component\Finder\SplFileInfo; @@ -37,7 +38,22 @@ class BladeX return $this->registeredComponents; } - public function components(string $directory) + public function components($directory) + { + if (is_string($directory)) { + $directory = [$directory]; + } + + if (!is_array($directory)) { + throw new InvalidArgumentException(); + } + + collect($directory)->each(function ($directory) { + $this->registerComponents($directory); + }); + } + + protected function registerComponents(string $directory) { if (! File::isDirectory($directory)) { throw CouldNotRegisterComponent::componentDirectoryNotFound($directory); diff --git a/tests/BladeXTest.php b/tests/BladeXTest.php index <HASH>..<HASH> 100644 --- a/tests/BladeXTest.php +++ b/tests/BladeXTest.php @@ -58,6 +58,43 @@ class BladeXTest extends TestCase } /** @test */ + public function it_can_register_multiple_directories_containing_view_components() + { + BladeX::components([ + $this->getStub('views/components'), + $this->getStub('views/registerDirectoryTest'), + ]); + + $registeredComponents = collect(BladeX::getRegisteredComponents()) + ->mapWithKeys(function (BladeXComponent $bladeXComponent) { + return [$bladeXComponent->name => $bladeXComponent->bladeViewName]; + }) + ->toArray(); + + $this->assertEquals([ + 'my-view1' => 'registerDirectoryTest/myView1', + 'my-view2' => 'registerDirectoryTest/myView2', + 'my-view3' => 'registerDirectoryTest/myView3', + 'alert' => 'components/alert', + 'card' => 'components/card', + 'layout' => 'components/layout', + 'text-field' => 'components/textField', + ], $registeredComponents); + } + + /** @test */ + public function it_will_throw_an_error_when_registering_multiple_directories_where_one_or_more_does_not_exist() + { + $this->expectException(CouldNotRegisterComponent::class); + + BladeX::components([ + $this->getStub('views/components'), + 'non-existing-directory', + $this->getStub('views/registerDirectoryTest'), + ]); + } + + /** @test */ public function it_will_throw_an_error_when_registering_a_directory_that_does_not_exist() { $this->expectException(CouldNotRegisterComponent::class);
Extended BladeX::components() to take an array of directories.
spatie_laravel-blade-x
train
b6639504b66e63e74a43f76280a403fe78508261
diff --git a/superset/connectors/druid/views.py b/superset/connectors/druid/views.py index <HASH>..<HASH> 100644 --- a/superset/connectors/druid/views.py +++ b/superset/connectors/druid/views.py @@ -409,6 +409,9 @@ class Druid(BaseSupersetView): if app.config["DRUID_IS_ACTIVE"]: + + appbuilder.add_separator("Sources") + appbuilder.add_view( DruidDatasourceModelView, "Druid Datasources", diff --git a/superset/connectors/sqla/views.py b/superset/connectors/sqla/views.py index <HASH>..<HASH> 100644 --- a/superset/connectors/sqla/views.py +++ b/superset/connectors/sqla/views.py @@ -438,5 +438,3 @@ appbuilder.add_link( category_label=__("Sources"), category_icon="fa-table", ) - -appbuilder.add_separator("Sources") diff --git a/superset/views/core.py b/superset/views/core.py index <HASH>..<HASH> 100755 --- a/superset/views/core.py +++ b/superset/views/core.py @@ -3018,7 +3018,6 @@ class CssTemplateAsyncModelView(CssTemplateModelView): list_columns = ["template_name", "css"] -appbuilder.add_separator("Sources") appbuilder.add_view( CssTemplateModelView, "CSS Templates", @@ -3061,7 +3060,6 @@ appbuilder.add_link( category_label=__("Sources"), category_icon="fa-wrench", ) -appbuilder.add_separator("Sources") @app.after_request
Removing some dividers to make header dropdown menus more consistent (#<I>) * separators removed, "childs" changed to "children" * changing `children` back to `childs`... it's baked in somewhere in Fab * linting * reverting changes to MenuObject * adding separator above Druid menu items
apache_incubator-superset
train
ac7f11cdde4ee1dc49467b2704ef0f9b2986bc1f
diff --git a/django_mysql/models.py b/django_mysql/models.py index <HASH>..<HASH> 100644 --- a/django_mysql/models.py +++ b/django_mysql/models.py @@ -1,5 +1,6 @@ # -*- coding:utf-8 -*- from copy import copy +from subprocess import PIPE, Popen import sys from django.db import connections @@ -11,7 +12,9 @@ from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from .status import GlobalStatus -from .utils import noop_context, StopWatch, WeightedAverageRate +from .utils import ( + noop_context, settings_to_cmd_args, StopWatch, WeightedAverageRate +) class QuerySetMixin(object): @@ -91,18 +94,36 @@ class QuerySetMixin(object): def visual_explain(self): connection = connections[self.db] - capture = CaptureQueriesContext(connection) - with capture: - list(self) # execute - queries = [q['sql'] for q in capture.captured_queries] - # Assume we're the last query. Django sometimes throws in some SET - # statements when connecting/querying - query = queries[-1] - - # Now to do the explain... - explain = "EXPLAIN " + query - - return query + + # Run one query to ensure we are connected + # This allows us to ensure we capture only the queryset's query below, + # as Django throws in some SET statements when connecting + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + + capturer = CaptureQueriesContext(connection) + with capturer: + list(self) # execute the query, discarding results + + queries = [q['sql'] for q in capturer.captured_queries] + assert len(queries) == 1, \ + "QuerySet executed > 1 query, don't know which to EXPLAIN" + query = queries[0] + + # Now to do the explain and pass through pt-visual-explain + mysql_command = ( + settings_to_cmd_args(connection.settings_dict) + + ['-e', "EXPLAIN EXTENDED " + query] + ) + mysql = Popen(mysql_command, stdout=PIPE) + visual_explain = Popen( + ['pt-visual-explain', '-'], + stdin=mysql.stdout, + stdout=PIPE + ) + mysql.stdout.close() + explanation = visual_explain.communicate()[0] + return explanation class QuerySet(QuerySetMixin, models.QuerySet): diff --git a/django_mysql/utils.py b/django_mysql/utils.py index <HASH>..<HASH> 100644 --- a/django_mysql/utils.py +++ b/django_mysql/utils.py @@ -61,3 +61,38 @@ class StopWatch(object): @contextmanager def noop_context(*args, **kwargs): yield + + +def settings_to_cmd_args(settings_dict): + """ + Copied from django 1.8 MySQL backend DatabaseClient - where the runshell + commandline creation has been extracted and made callable like so. + """ + args = ['mysql'] + db = settings_dict['OPTIONS'].get('db', settings_dict['NAME']) + user = settings_dict['OPTIONS'].get('user', settings_dict['USER']) + passwd = settings_dict['OPTIONS'].get('passwd', settings_dict['PASSWORD']) + host = settings_dict['OPTIONS'].get('host', settings_dict['HOST']) + port = settings_dict['OPTIONS'].get('port', settings_dict['PORT']) + cert = settings_dict['OPTIONS'].get('ssl', {}).get('ca') + defaults_file = settings_dict['OPTIONS'].get('read_default_file') + # Seems to be no good way to set sql_mode with CLI. + + if defaults_file: + args += ["--defaults-file=%s" % defaults_file] + if user: + args += ["--user=%s" % user] + if passwd: + args += ["--password=%s" % passwd] + if host: + if '/' in host: + args += ["--socket=%s" % host] + else: + args += ["--host=%s" % host] + if port: + args += ["--port=%s" % port] + if cert: + args += ["--ssl-ca=%s" % cert] + if db: + args += [db] + return args diff --git a/tests/django_mysql_tests/test_models.py b/tests/django_mysql_tests/test_models.py index <HASH>..<HASH> 100644 --- a/tests/django_mysql_tests/test_models.py +++ b/tests/django_mysql_tests/test_models.py @@ -1,4 +1,6 @@ # -*- coding:utf-8 -*- +from textwrap import dedent + from django.template import Context, Template from django.test import TransactionTestCase @@ -169,5 +171,29 @@ class VisualExplainTests(TransactionTestCase): def test_basic(self): output = Author.objects.all().visual_explain() - self.assertEqual(output, "SELECT .") - + expected = dedent(""" + Table scan + rows 1 + +- Table + table django_mysql_tests_author + """).strip() + "\n" + self.assertEqual(output, expected) + + def test_subquery(self): + subq = Author.objects.all().values_list('id', flat=True) + output = Author.objects.filter(id__in=subq).visual_explain() + expected = dedent(""" + JOIN + +- Unique index lookup + | key U0->PRIMARY + | possible_keys PRIMARY + | key_len 4 + | ref test_django_mysql.django_mysql_tests_author.id + | rows 1 + +- Table scan + rows 1 + +- Table + table django_mysql_tests_author + possible_keys PRIMARY + """).strip() + "\n" + self.assertEqual(output, expected)
Add visual_explain() to queryset which passes its query down to pt-visual-explain
adamchainz_django-mysql
train
239de967f52c8334ea04b628be3103ae243a1794
diff --git a/tensorflow_probability/python/distributions/mvn_linear_operator.py b/tensorflow_probability/python/distributions/mvn_linear_operator.py index <HASH>..<HASH> 100644 --- a/tensorflow_probability/python/distributions/mvn_linear_operator.py +++ b/tensorflow_probability/python/distributions/mvn_linear_operator.py @@ -253,12 +253,7 @@ class MultivariateNormalLinearOperator( if self.loc is None: return tf.zeros(shape, self.dtype) - if has_static_shape and shape == self.loc.shape: - return tf.identity(self.loc) - - # Add dummy tensor of zeros to broadcast. This is only necessary if shape - # != self.loc.shape, but we could not determine if this is the case. - return tf.identity(self.loc) + tf.zeros(shape, self.dtype) + return tf.broadcast_to(self.loc, shape) def _covariance(self): if distribution_util.is_diagonal_scale(self.scale):
Simplify mvn linear operator mean method. PiperOrigin-RevId: <I>
tensorflow_probability
train
5a821bacf6d7f12f1427032c8bf48d1744a43f4a
diff --git a/src/main/java/com/hubspot/dropwizard/guicier/GuiceBundle.java b/src/main/java/com/hubspot/dropwizard/guicier/GuiceBundle.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/hubspot/dropwizard/guicier/GuiceBundle.java +++ b/src/main/java/com/hubspot/dropwizard/guicier/GuiceBundle.java @@ -98,6 +98,7 @@ public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T> this.injector = Guice.createInjector(guiceStage, modulesBuilder.build()); JerseyGuiceUtils.install(new ServiceLocatorGenerator() { + @Override public ServiceLocator create(String name, ServiceLocator parent) { if (!name.startsWith("__HK2_Generated_")) {
Update GuiceBundle.java
HubSpot_dropwizard-guicier
train
d0ec676a025c94a860a7be505f14ac5f63d07480
diff --git a/cfgrib/dataset.py b/cfgrib/dataset.py index <HASH>..<HASH> 100644 --- a/cfgrib/dataset.py +++ b/cfgrib/dataset.py @@ -226,8 +226,9 @@ class OnDiskArray(object): return array -GRID_TYPES_COORD_VAR = ('regular_ll', 'regular_gg') -GRID_TYPES_2D_AUX_COORD_VAR = ('lambert', 'albers') +GRID_TYPES_DIMENSION_COORDS = ('regular_ll', 'regular_gg') +GRID_TYPES_2D_NON_DIMENSION_COORDS = ('lambert', 'albers') +GRID_TYPES_1D_NON_DIMENSION_COORDS = ('reduced_ll', 'reduced_gg') def build_geography_coordinates( @@ -239,7 +240,7 @@ def build_geography_coordinates( first = index.first() geo_coord_vars = collections.OrderedDict() # type: T.Dict[str, Variable] grid_type = index.getone('gridType') - if 'geography' in encode_cf and grid_type in GRID_TYPES_COORD_VAR: + if 'geography' in encode_cf and grid_type in GRID_TYPES_DIMENSION_COORDS: geo_dims = ('latitude', 'longitude') # type: T.Tuple[str, ...] geo_shape = (index.getone('Nj'), index.getone('Ni')) # type: T.Tuple[int, ...] latitudes = np.array(first['distinctLatitudes']) @@ -252,7 +253,7 @@ def build_geography_coordinates( dimensions=('longitude',), data=np.array(first['distinctLongitudes']), attributes=COORD_ATTRS['longitude'], ) - elif 'geography' in encode_cf and grid_type in GRID_TYPES_2D_AUX_COORD_VAR: + elif 'geography' in encode_cf and grid_type in GRID_TYPES_2D_NON_DIMENSION_COORDS: geo_dims = ('y', 'x') geo_shape = (index.getone('Ny'), index.getone('Nx')) geo_coord_vars['latitude'] = Variable( @@ -279,6 +280,8 @@ def build_geography_coordinates( attributes=COORD_ATTRS['longitude'], ) except KeyError: + if grid_type in GRID_TYPES_1D_NON_DIMENSION_COORDS: + raise log.warning('No latitudes/longitudes provided by ecCodes for gridType = %r', grid_type) return geo_dims, geo_shape, geo_coord_vars
Make more explicit what gridType we support. Ref: #<I>.
ecmwf_cfgrib
train
765ee98150eb7c458f33b087bcdf53bee6f6bf77
diff --git a/Configuration/TCA/tx_styleguide_ctrl_common.php b/Configuration/TCA/tx_styleguide_ctrl_common.php index <HASH>..<HASH> 100644 --- a/Configuration/TCA/tx_styleguide_ctrl_common.php +++ b/Configuration/TCA/tx_styleguide_ctrl_common.php @@ -3,14 +3,14 @@ return [ 'ctrl' => [ 'title' => 'Form engine - Common table control', - 'label' => 'title_field', - 'descriptionColumn' => 'description_field', + 'label' => 'title', + 'descriptionColumn' => 'description', 'tstamp' => 'tstamp', 'crdate' => 'crdate', 'cruser_id' => 'cruser_id', 'delete' => 'deleted', 'sortby' => 'sorting', - 'default_sortby' => 'title_field', + 'default_sortby' => 'title', 'versioningWS' => true, 'rootLevel' => -1, 'iconfile' => 'EXT:styleguide/Resources/Public/Icons/tx_styleguide.svg', @@ -19,7 +19,7 @@ return [ 'transOrigPointerField' => 'l10n_parent', 'transOrigDiffSourceField' => 'l10n_diffsource', 'translationSource' => 'l10n_source', - 'searchFields' => 'title_field,description_field', + 'searchFields' => 'title,description', 'enablecolumns' => [ 'disabled' => 'hidden', 'starttime' => 'starttime', @@ -113,7 +113,7 @@ return [ ] ] ], - 'title_field' => [ + 'title' => [ 'label' => 'LLL:EXT:styleguide/Resources/Private/Language/locallang.xlf:minimalTableTitleField', 'config' => [ 'type' => 'input', @@ -121,8 +121,8 @@ return [ 'eval' => 'trim,required' ], ], - 'description_field' => [ - 'label' => 'description_field', + 'description' => [ + 'label' => 'description', 'config' => [ 'type' => 'text', ], @@ -131,7 +131,7 @@ return [ 'types' => [ '0' => [ 'showitem' => ' - title_field, description_field, + title, description, --div--;LLL:EXT:core/Resources/Private/Language/Form/locallang_tabs.xlf:language, --palette--;;language, --div--;LLL:EXT:core/Resources/Private/Language/Form/locallang_tabs.xlf:access, diff --git a/Configuration/TCA/tx_styleguide_ctrl_minimal.php b/Configuration/TCA/tx_styleguide_ctrl_minimal.php index <HASH>..<HASH> 100644 --- a/Configuration/TCA/tx_styleguide_ctrl_minimal.php +++ b/Configuration/TCA/tx_styleguide_ctrl_minimal.php @@ -3,11 +3,11 @@ return [ 'ctrl' => [ 'title' => 'LLL:EXT:styleguide/Resources/Private/Language/locallang.xlf:minimalTableTitle', - 'label' => 'title_field', + 'label' => 'title', 'iconfile' => 'EXT:styleguide/Resources/Public/Icons/tx_styleguide.svg', ], 'columns' => [ - 'title_field' => [ + 'title' => [ 'label' => 'LLL:EXT:styleguide/Resources/Private/Language/locallang.xlf:minimalTableTitleField', 'config' => [ 'type' => 'input' @@ -16,7 +16,7 @@ return [ ], 'types' => [ '0' => [ - 'showitem' => 'title_field', + 'showitem' => 'title', ], ], ]; diff --git a/ext_tables.sql b/ext_tables.sql index <HASH>..<HASH> 100755 --- a/ext_tables.sql +++ b/ext_tables.sql @@ -16,13 +16,13 @@ CREATE TABLE be_users ( CREATE TABLE tx_styleguide_ctrl_common ( - title_field text, - description_field text, + title text, + description text, ); CREATE TABLE tx_styleguide_ctrl_minimal ( - title_field text, + title text, );
[TASK] Simplify two field names
TYPO3_styleguide
train
c67beac1208712575c96238e468b2e48faf5e687
diff --git a/modules/@apostrophecms/image/index.js b/modules/@apostrophecms/image/index.js index <HASH>..<HASH> 100644 --- a/modules/@apostrophecms/image/index.js +++ b/modules/@apostrophecms/image/index.js @@ -162,7 +162,7 @@ module.exports = { if (!outputImage) { continue; } - outputImage._fields = sanitizeFields(inputImage._fields); + outputImage._fields = sanitizeFields(inputImage); output.push(outputImage); } return output; @@ -189,7 +189,8 @@ module.exports = { aspectRatio: [ w, h ] }; } - function sanitizeFields(input) { + function sanitizeFields(inputImage) { + const input = inputImage._fields; const output = {}; if ((input == null) || ((typeof input) !== 'object')) { return output; @@ -215,6 +216,14 @@ module.exports = { if (output.height === 0) { return {}; } + if (output.left + output.width > inputImage.attachment.width) { + // An older crop that does not work with a new attachment file + return {}; + } + if (output.top + output.height > inputImage.attachment.height) { + // An older crop that does not work with a new attachment file + return {}; + } return output; } function sanitizeImage(input) { @@ -226,12 +235,10 @@ module.exports = { }).toObject(); } function closeEnough(image) { - if (!image._fields) { - return false; - } - const ratio = image.attachment.width / image.attachment.height; + const testRatio = image._fields ? (image._fields.width / image._fields.height) : + (image.attachment.width / image.attachment.height); const configuredRatio = widgetOptions.aspectRatio[0] / widgetOptions.aspectRatio[1]; - return withinOnePercent(ratio, configuredRatio); + return withinOnePercent(testRatio, configuredRatio); } async function autocrop(image, widgetOptions) { const nativeRatio = image.attachment.width / image.attachment.height;
* Handle the case where the attachment was replaced with one that is not compatible with the crop (eventually we will want to work on more sophisticated invalidation of crops via backlinks, this isn't really enough but we're past what we had in 2.x) * The aspect ratio to compare to is that of the previous crop, unless there isn't one
apostrophecms_apostrophe
train
7beeb5a0220260f1c0216a2c32da42a000143538
diff --git a/lib/bitescript/builder.rb b/lib/bitescript/builder.rb index <HASH>..<HASH> 100644 --- a/lib/bitescript/builder.rb +++ b/lib/bitescript/builder.rb @@ -232,7 +232,7 @@ module BiteScript flags = Opcodes::ACC_INTERFACE | Opcodes::ACC_ABSTRACT end - @class_writer = ClassWriter.new(ClassWriter::COMPUTE_MAXS) + @class_writer = ClassWriter.new(ClassWriter::COMPUTE_FRAMES | ClassWriter::COMPUTE_MAXS) interface_paths = [] (@interfaces).each {|interface| interface_paths << path(interface)}
Ask ASM to compute frames too.
headius_bitescript
train
b2d8cd6ce59c8dc46a3c2d0383e52ea295fc3141
diff --git a/app/actors/hyrax/actors/interpret_visibility_actor.rb b/app/actors/hyrax/actors/interpret_visibility_actor.rb index <HASH>..<HASH> 100644 --- a/app/actors/hyrax/actors/interpret_visibility_actor.rb +++ b/app/actors/hyrax/actors/interpret_visibility_actor.rb @@ -203,12 +203,20 @@ module Hyrax def apply_lease(env, intention) return true unless intention.wants_lease? env.curation_concern.apply_lease(*intention.lease_params) + # apply_lease returns true if there has been a change in the lease period, + # otherwise it returns nil. Since we want to continue processing, even when the date + # does not change, we return true from this method. + true end # If they want an embargo, we can assume it's valid def apply_embargo(env, intention) return true unless intention.wants_embargo? env.curation_concern.apply_embargo(*intention.embargo_params) + # apply_embargo returns true if there has been a change in the embargo period, + # otherwise it returns nil. Since we want to continue processing, even when the date + # does not change, we return true from this method. + true end end end diff --git a/spec/features/embargo_spec.rb b/spec/features/embargo_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/embargo_spec.rb +++ b/spec/features/embargo_spec.rb @@ -30,6 +30,23 @@ RSpec.describe 'embargo' do click_button 'Update Embargo' expect(page).to have_content(later_future_date.to_date.to_formatted_s(:standard)) + + click_link 'Edit' + fill_in 'Title', with: 'Embargo test CHANGED' + click_button 'Save' + + expect(page).to have_content('CHANGED') + + click_link 'Edit' + click_link "Files" # switch tab + expect(page).to have_content "Add files" + expect(page).to have_content "Add folder" + within('div#add-files') do + attach_file("files[]", "#{Hyrax::Engine.root}/spec/fixtures/image.jp2", visible: false) + end + + click_button 'Save' # Save the work + expect(page).to have_content('CHANGED') end end diff --git a/spec/features/lease_spec.rb b/spec/features/lease_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/lease_spec.rb +++ b/spec/features/lease_spec.rb @@ -30,6 +30,23 @@ RSpec.describe 'leases' do click_button 'Update Lease' expect(page).to have_content(later_future_date.to_date.to_formatted_s(:standard)) # new lease date is displayed in message + + click_link 'Edit' + fill_in 'Title', with: 'Lease test CHANGED' + click_button 'Save' + + expect(page).to have_content('CHANGED') + + click_link 'Edit' + click_link "Files" # switch tab + expect(page).to have_content "Add files" + expect(page).to have_content "Add folder" + within('div#add-files') do + attach_file("files[]", "#{Hyrax::Engine.root}/spec/fixtures/image.jp2", visible: false) + end + + click_button 'Save' # Save the work + expect(page).to have_content('CHANGED') end end end
allow embargo and lease works to be updated
samvera_hyrax
train
51df50e762f834847f81521303a624235f4a713c
diff --git a/lib/conjure/docker/host.rb b/lib/conjure/docker/host.rb index <HASH>..<HASH> 100644 --- a/lib/conjure/docker/host.rb +++ b/lib/conjure/docker/host.rb @@ -19,8 +19,14 @@ module Conjure end def start(image_name, daemon_command, options = {}) + container_name = options[:name] all_options = "#{start_options options} #{image_name} #{daemon_command}" - Container.new @server, @server.run("docker run #{all_options}").strip, options[:name] + if running_container_names.include? container_name + puts "#{container_name} container already running." + else + puts "#{container_name} container not detected, starting..." + Container.new @server, @server.run("docker run #{all_options}").strip, container_name + end end private @@ -57,6 +63,10 @@ module Conjure values ||= {} values.map { |from, to| "#{command} #{from}:#{to}" } end + + def running_container_names + @server.run("docker ps --format='{{.Names}}'").split("\n").compact + end end end end
Don’t start containers if already running
brianauton_conjure
train
6bc24ac7b6b3d8d870b3a78391d4c7b0b2809ea2
diff --git a/lib/amq/protocol/frame.rb b/lib/amq/protocol/frame.rb index <HASH>..<HASH> 100644 --- a/lib/amq/protocol/frame.rb +++ b/lib/amq/protocol/frame.rb @@ -38,10 +38,8 @@ module AMQ data = readable.read(size + 1) payload, frame_end = data[0..-2], data[-1] raise RuntimeError.new("Frame doesn't end with #{FINAL_OCTET} as it must, which means the size is miscalculated.") unless frame_end == FINAL_OCTET - # raise RuntimeError.new("invalid size: is #{payload.bytesize}, expected #{size}") if @payload.bytesize != size # We obviously can't test that, because we used read(size), so it's pointless. raise FrameTypeError.new(TYPES_OPTIONS) unless TYPES_OPTIONS.include?(type) - self.new(type, payload, size, channel) - # TODO: omit the size + self.new(type, payload, channel) end end @@ -61,13 +59,17 @@ module AMQ end attr_accessor :channel - attr_reader :payload, :size - def initialize(payload, size = payload.bytesize, channel = 0) - @payload, @size, @channel = payload, size, channel + attr_reader :payload + def initialize(payload, channel = 0) + @payload, @channel = payload, channel + end + + def size + @payload.bytesize end def encode - [self.class.id, channel, payload.bytesize].pack("cnN") + payload + FINAL_OCTET + [self.class.id, channel, self.size].pack("cnN") + payload + FINAL_OCTET end end @@ -92,7 +94,7 @@ module AMQ class BodyFrame < FrameSubclass @id = 3 end - + class HeartbeatFrame < FrameSubclass @id = 4 end
Hide size, we shall count it dynamically, hence we won't have problems with changing payload later etc.
ruby-amqp_amq-protocol
train
8ebf7d99061399ea11ae94d0bd2254911e142687
diff --git a/presto-tests/src/test/java/com/facebook/presto/execution/TestQueues.java b/presto-tests/src/test/java/com/facebook/presto/execution/TestQueues.java index <HASH>..<HASH> 100644 --- a/presto-tests/src/test/java/com/facebook/presto/execution/TestQueues.java +++ b/presto-tests/src/test/java/com/facebook/presto/execution/TestQueues.java @@ -140,7 +140,7 @@ public class TestQueues waitForQueryState(queryRunner, secondDashboardQuery, RUNNING); } - @Test(timeOut = 240_000, enabled = false) + @Test(timeOut = 60_000) public void testExceedSoftLimits() throws Exception { @@ -328,8 +328,7 @@ public class TestQueues } } - // disabled due to https://github.com/prestodb/presto/issues/16126 - @Test(timeOut = 240_000, enabled = false) + @Test(timeOut = 60_000) public void testQueuedQueryInteraction() throws Exception {
Enabling flaky TestQueues test We fixed the test flakyness issue as part of this presto/pull/<I> so enabling disabled flaky tests
prestodb_presto
train
619ebb8bde02365c391d9e2a7ced35eb3335af98
diff --git a/src/python/dxpy/__init__.py b/src/python/dxpy/__init__.py index <HASH>..<HASH> 100644 --- a/src/python/dxpy/__init__.py +++ b/src/python/dxpy/__init__.py @@ -297,10 +297,9 @@ def DXHTTPRequest(resource, data, method='POST', headers=None, auth=True, timeou pass _UPGRADE_NOTIFY = False - # If HTTP code that is not 200 (OK) is received and the content is - # JSON, parse it and throw the appropriate error. Otherwise, - # raise the usual exception. - if response.status_code != requests.codes.ok: + # If an HTTP code that is not in the 200 series is received and the content is JSON, parse it and throw the + # appropriate error. Otherwise, raise the usual exception. + if response.status_code // 100 != 2: # response.headers key lookup is case-insensitive if response.headers.get('content-type', '').startswith('application/json'): content = json.loads(response.content)
Accept all HTTP status codes in the <I> series as OK
dnanexus_dx-toolkit
train
30c73b8a2bf1e84fe3977c061abd138493270d03
diff --git a/asteval/asteval.py b/asteval/asteval.py index <HASH>..<HASH> 100644 --- a/asteval/asteval.py +++ b/asteval/asteval.py @@ -14,6 +14,7 @@ from __future__ import division, print_function from sys import exc_info, stdout, stderr, version_info import ast import math +from time import time from .astutils import (FROM_PY, FROM_MATH, FROM_NUMPY, UNSAFE_ATTRS, LOCALFUNCS, NUMPY_RENAMES, op2func, @@ -33,6 +34,7 @@ builtins = __builtins__ if not isinstance(builtins, dict): builtins = builtins.__dict__ +MAX_EXEC_TIME = 2 # sec # noinspection PyIncorrectDocstring class Interpreter: @@ -78,9 +80,11 @@ class Interpreter: 'slice', 'str', 'subscript', 'try', 'tuple', 'unaryop', 'while') - def __init__(self, symtable=None, writer=None, use_numpy=True, err_writer=None): + def __init__(self, symtable=None, writer=None, use_numpy=True, err_writer=None, max_time=MAX_EXEC_TIME): self.writer = writer or stdout self.err_writer = err_writer or stderr + self.start = 0 + self.max_time = max_time if symtable is None: symtable = {} @@ -172,6 +176,8 @@ class Interpreter: """executes parsed Ast representation for an expression""" # Note: keep the 'node is None' test: internal code here may run # run(None) and expect a None in return. + if time() - self.start > self.max_time: + raise RuntimeError("Execution exceeded time limit, max runtime is {}s".format(MAX_EXEC_TIME)) if len(self.error) > 0: return if node is None: @@ -209,6 +215,7 @@ class Interpreter: """evaluates a single statement""" self.lineno = lineno self.error = [] + self.start = time() # noinspection PyBroadException try: node = self.parse(expr) diff --git a/tests/testsuite.py b/tests/testsuite.py index <HASH>..<HASH> 100644 --- a/tests/testsuite.py +++ b/tests/testsuite.py @@ -765,6 +765,13 @@ def fcn(x, y): self.interp('open("foo", "rb", 2<<18)') self.check_error('RuntimeError') + def test_dos(self): + self.interp("""for x in range(2<<21): pass""") + self.check_error('RuntimeError', 'time limit') + self.interp("""while True: pass""") + self.check_error('RuntimeError', 'time limit') + + class TestCase2(unittest.TestCase): def test_stringio(self):
Execution time limit - Added simple execution time limit
newville_asteval
train
5da093c86d72dcb24bee38b1fb72de93f62cb179
diff --git a/cmd/tsr/suite_test.go b/cmd/tsr/suite_test.go index <HASH>..<HASH> 100644 --- a/cmd/tsr/suite_test.go +++ b/cmd/tsr/suite_test.go @@ -6,6 +6,7 @@ package main import ( "github.com/globocom/config" + "github.com/globocom/tsuru/db" "launchpad.net/gocheck" "testing" ) @@ -19,3 +20,10 @@ func Test(t *testing.T) { gocheck.TestingT(t) } func (s *S) SetUpSuite(c *gocheck.C) { config.ReadConfigFile("testdata/tsuru.conf") } + +func (s *S) TearDownSuite(c *gocheck.C) { + conn, err := db.Conn() + c.Assert(err, gocheck.IsNil) + defer conn.Close() + conn.Apps().Database.DropDatabase() +}
cmd/tsr/test: delete database on TearDownSuite
tsuru_tsuru
train
b8fa33f61087eefdbb38252c3b203901b0e005de
diff --git a/src/Illuminate/Exception/Handler.php b/src/Illuminate/Exception/Handler.php index <HASH>..<HASH> 100644 --- a/src/Illuminate/Exception/Handler.php +++ b/src/Illuminate/Exception/Handler.php @@ -56,12 +56,22 @@ class Handler { $code = 500; } - $response = $handler($exception, $code, $fromConsole); + // We will wrap this handler in a try / catch and avoid white screens of + // death if any exceptions are thrown from a handler itself. This way + // we will at least log some errors, and avoid errors with no data. + try + { + $response = $handler($exception, $code, $fromConsole); + } + catch (\Exception $e) + { + // + } // If the handler returns a "non-null" response, we will return it so it // will get sent back to the browsers. Once a handler returns a valid // response we will cease iterating and calling the other handlers. - if ( ! is_null($response)) + if (isset($response) and ! is_null($response)) { return $response; }
Run exception handlers in a try / catch to avoid WSOD.
laravel_framework
train
3786334ccd1a883ac00cb4dd7c9ec33b58160a39
diff --git a/lib/Doctrine/SkeletonMapper/Collections/PersistentCollection.php b/lib/Doctrine/SkeletonMapper/Collections/PersistentCollection.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/SkeletonMapper/Collections/PersistentCollection.php +++ b/lib/Doctrine/SkeletonMapper/Collections/PersistentCollection.php @@ -83,7 +83,7 @@ class PersistentCollection implements Collection return array_udiff_assoc( $this->snapshot, $this->collection->toArray(), - function ($a, $b) { return $a === $b ? 0 : 1; } + function($a, $b) { return $a === $b ? 0 : 1; } ); } @@ -92,7 +92,7 @@ class PersistentCollection implements Collection return array_udiff_assoc( $this->collection->toArray(), $this->snapshot, - function ($a, $b) { return $a === $b ? 0 : 1; } + function($a, $b) { return $a === $b ? 0 : 1; } ); } @@ -115,7 +115,7 @@ class PersistentCollection implements Collection { $removed = $this->collection->removeElement($element); - if ( ! $removed) { + if (!$removed) { return $removed; } @@ -238,7 +238,7 @@ class PersistentCollection implements Collection public function offsetSet($offset, $value) { - if ( ! isset($offset)) { + if (!isset($offset)) { return $this->add($value); }
Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on <URL>
doctrine_skeleton-mapper
train
bd7f81dd23e4164148fbae5283bf396831f28290
diff --git a/lib/haml/util.rb b/lib/haml/util.rb index <HASH>..<HASH> 100644 --- a/lib/haml/util.rb +++ b/lib/haml/util.rb @@ -15,7 +15,7 @@ module Haml # @param file [String] The filename relative to the Haml root # @return [String] The filename relative to the the working directory def scope(file) - File.expand_path File.join(File.dirname(__FILE__), '..', '..', file) + File.join(File.dirname(__FILE__), '..', '..', file) end # Converts an array of `[key, value]` pairs to a hash.
[Haml] Don't use File.expand_path in Util.scope. This dies when there are symbolic links involved.
sass_ruby-sass
train
9251e1324eafb2bbc6089501daede6ade04bb1a5
diff --git a/src/sap.m/src/sap/m/TitleAlignmentMixin.js b/src/sap.m/src/sap/m/TitleAlignmentMixin.js index <HASH>..<HASH> 100644 --- a/src/sap.m/src/sap/m/TitleAlignmentMixin.js +++ b/src/sap.m/src/sap/m/TitleAlignmentMixin.js @@ -37,6 +37,9 @@ function( */ var _setupBarTitleAlignment = function (oBar, sKey) { // add bar instance to the list + if (!this._oTitleAlignmentBarInstances) { + this._oTitleAlignmentBarInstances = {}; + } this._oTitleAlignmentBarInstances[sKey] = oBar; this._determineTitleAlignment(oBar); }; @@ -86,9 +89,11 @@ function( sControlAlignment = sThemeAlignment === undefined ? TitleAlignment.Center : sThemeAlignment; } // do bar alignment - if (oBar === undefined) { // no Bar passes as argument, align all Bars "registered" for alignment - for (var k in this._oTitleAlignmentBarInstances) { - _setBarClass(this._oTitleAlignmentBarInstances[k]); + if (!oBar) { // no Bar passes as argument, align all Bars "registered" for alignment + if (this._oTitleAlignmentBarInstances) { + for (var k in this._oTitleAlignmentBarInstances) { + _setBarClass(this._oTitleAlignmentBarInstances[k]); + } } } else { // align only passed Bar (initial setup) _setBarClass(oBar); @@ -115,8 +120,10 @@ function( var setTitleAlignment = function (oAlignment) { this.setProperty("titleAlignment", oAlignment, true); this._determineTitleAlignment(); - for (var k in this._oTitleAlignmentBarInstances) { - this._oTitleAlignmentBarInstances[k].invalidate(); + if (this._oTitleAlignmentBarInstances) { + for (var k in this._oTitleAlignmentBarInstances) { + this._oTitleAlignmentBarInstances[k].invalidate(); + } } return this; @@ -138,7 +145,9 @@ function( var fnInit = oControlPrototype.init; oControlPrototype.init = function (sId) { - this._oTitleAlignmentBarInstances = {}; + if (!this._oTitleAlignmentBarInstances) { + this._oTitleAlignmentBarInstances = {}; + } var res = fnInit.apply(this, arguments); this._attachTitleAlignmentEventDelegate(); return res;
[FIX] Multiple controls: titleAlignment now handles missing _oTitleAlignmentBarInstance Change-Id: I<I>cd<I>ebf<I>e<I>cffa<I>dea<I>a1d<I>ec8 BCP: <I>
SAP_openui5
train
87a00eb226ebd27d86c067fa24e25fb16627f59d
diff --git a/lib/Enlighten.php b/lib/Enlighten.php index <HASH>..<HASH> 100644 --- a/lib/Enlighten.php +++ b/lib/Enlighten.php @@ -5,6 +5,7 @@ namespace Enlighten; use Enlighten\Http\Request; use Enlighten\Http\Response; use Enlighten\Http\ResponseCode; +use Enlighten\Routing\Route; use Enlighten\Routing\Router; /** @@ -101,7 +102,10 @@ class Enlighten // Dispatch the request to the router $routingResult = $this->router->route($this->request); - if ($routingResult == null) { + if ($routingResult != null) { + $this->response->setResponseCode(ResponseCode::HTTP_OK); + $this->dispatch($routingResult); + } else { $this->response->setResponseCode(ResponseCode::HTTP_NOT_FOUND); } @@ -119,4 +123,16 @@ class Enlighten // That's all folks! Execution has completed successfully. return $this->response; } + + /** + * Dispatches a Route. + * + * @param Route $route + */ + public function dispatch(Route $route) + { + $this->beforeStart(); + + $this->router->dispatch($route, $this->request); + } } \ No newline at end of file diff --git a/lib/Routing/Route.php b/lib/Routing/Route.php index <HASH>..<HASH> 100644 --- a/lib/Routing/Route.php +++ b/lib/Routing/Route.php @@ -28,7 +28,7 @@ class Route * * @var string */ - public $regexPattern; + protected $regexPattern; /** * The target of this route. @@ -39,7 +39,7 @@ class Route * * @var string|callable */ - public $target; + protected $target; /** * A collection of constraints this route is subject to. @@ -64,6 +64,16 @@ class Route } /** + * Returns the target for this route. + * + * @return callable|string + */ + public function getTarget() + { + return $this->target; + } + + /** * Registers a new constraint to this route. * A constraint should be a callable function, which will be invoked with the Request as parameter. * diff --git a/lib/Routing/Router.php b/lib/Routing/Router.php index <HASH>..<HASH> 100644 --- a/lib/Routing/Router.php +++ b/lib/Routing/Router.php @@ -62,4 +62,32 @@ class Router return null; } + + /** + * Dispatches a Request to a Route. + * + * @param Route $route + * @param Request $request + * @return mixed Route target function return value, if any + */ + public function dispatch(Route $route, Request $request) + { + $targetFunc = null; + $params = []; + + if ($route->isCallable()) { + // A callable function that should be invoked directly, add the Request as first parameter + $targetFunc = $route->getTarget(); + $params[] = $request; + } else { + // A string path to a controller: resolve the controller and verify its validity + throw new \Exception('Only callable route targets are currently implemented'); // TODO + } + + // Inject the route variables into the arguments passed to the function + $params = array_merge($params, $route->mapPathVariables($request)); + + // Finally, invoke the specified controller function or the specified callable with the appropriate params + return call_user_func_array($targetFunc, $params); + } } \ No newline at end of file diff --git a/tests/EnlightenTest.php b/tests/EnlightenTest.php index <HASH>..<HASH> 100644 --- a/tests/EnlightenTest.php +++ b/tests/EnlightenTest.php @@ -2,6 +2,10 @@ use Enlighten\Enlighten; use Enlighten\Http\Request; +use Enlighten\Http\RequestMethod; +use Enlighten\Http\ResponseCode; +use Enlighten\Routing\Route; +use Enlighten\Routing\Router; class EnlightenTest extends PHPUnit_Framework_TestCase { @@ -30,4 +34,32 @@ class EnlightenTest extends PHPUnit_Framework_TestCase $this->assertEmpty($response->getBody()); } + + /** + * @runInSeparateProcess + */ + public function testApplicationRouting() + { + $enlighten = new Enlighten(); + + $request = new Request(); + $request->setRequestUri('/'); + $request->setMethod(RequestMethod::GET); + + $route = new Route('/', function (Request $request) { + echo 'test output'; + }); + + $router = new Router(); + $router->register($route); + + $enlighten->setRouter($router); + $enlighten->setRequest($request); + + $response = $enlighten->start(); + + $this->assertEquals(ResponseCode::HTTP_OK, $response->getResponseCode()); + $this->assertEquals('test output', $response->getBody()); + $this->expectOutputString('test output'); + } } \ No newline at end of file diff --git a/tests/Routing/RouterTest.php b/tests/Routing/RouterTest.php index <HASH>..<HASH> 100644 --- a/tests/Routing/RouterTest.php +++ b/tests/Routing/RouterTest.php @@ -45,4 +45,26 @@ class RouterTest extends PHPUnit_Framework_TestCase $this->assertNull($router->route($request)); } + + /** + * @runInSeparateProcess + */ + public function testDispatch() + { + $route = new Route('/', function () { + echo 'hello world'; + return 'retVal'; + }); + + $request = new Request(); + $request->setRequestUri('/'); + + $router = new Router(); + $router->register($route); + $router->clear(); + + $this->assertEquals('retVal', $router->dispatch($route, $request)); + + $this->expectOutputString('hello world'); + } } \ No newline at end of file
Routing: Implement route dispatching across the board
roydejong_Enlighten
train
86f93b6b8654d98ac7b427b6c0391a9e4ed0ecb3
diff --git a/src/Queries/Mysql/Select.php b/src/Queries/Mysql/Select.php index <HASH>..<HASH> 100644 --- a/src/Queries/Mysql/Select.php +++ b/src/Queries/Mysql/Select.php @@ -78,13 +78,25 @@ class Select extends BaseQuery */ public function relatedWith(RowInterface $row, $through = null) { + $entity = $row->getEntity(); + if ($through !== null) { - $row = $this->entity->getDb()->select($through) - ->relatedWith($row) - ->all(); - } + $through = $this->entity->getDb()->$through; - $entity = $row->getEntity(); + if (!$through->hasOne($entity)) { + throw new SimpleCrudException("The relationship between '{$through->table}' and '{$entity->table}' must be RELATION_HAS_ONE"); + } + if (!$through->hasOne($this->entity)) { + throw new SimpleCrudException("The relationship between '{$through->table}' and '{$this->entity->table}' must be RELATION_HAS_ONE"); + } + + $this->from($through->table); + + $this->where("`{$through->table}`.`{$this->entity->foreignKey}` = `{$this->entity->table}`.`id`"); + $this->where("`{$through->table}`.`{$entity->foreignKey}` IN (:{$through->name})", [":{$through->name}" => $row->get('id')]); + + return $this; + } if ($this->entity->hasOne($entity)) { return $this->by($entity->foreignKey, $row->get('id')); @@ -94,7 +106,7 @@ class Select extends BaseQuery return $this->byId($row->get($this->entity->foreignKey)); } - throw new SimpleCrudException("The tables {$this->entity->table} and {$row->getEntity()->table} are no related"); + throw new SimpleCrudException("The tables {$this->entity->table} and {$entity->table} are no related"); } /**
improved many-to-many selections
oscarotero_simple-crud
train
ccf235e473cd8f8c3d2b30ed82297ddee23b2a2e
diff --git a/libraries/commerce/cart/actions/addProductsToCart.js b/libraries/commerce/cart/actions/addProductsToCart.js index <HASH>..<HASH> 100644 --- a/libraries/commerce/cart/actions/addProductsToCart.js +++ b/libraries/commerce/cart/actions/addProductsToCart.js @@ -15,10 +15,12 @@ import { messagesHaveErrors } from '../helpers'; * @return {Function} A redux thunk. */ const addToCart = productData => (dispatch, getState) => { - const pendingProductCount = getProductPendingCount(getState()); + // Summarize the quantities of all products that are about to be added. + const nextPendingCount = productData.reduce((count, { quantity }) => + count + quantity, getProductPendingCount(getState())); dispatch(addProductsToCart(productData)); - dispatch(setCartProductPendingCount(pendingProductCount + 1)); + dispatch(setCartProductPendingCount(nextPendingCount)); const request = new PipelineRequest(pipelines.SHOPGATE_CART_ADD_PRODUCTS); request.setInput({ products: productData })
CCP-<I>: Improved cartProductPendingCount - it's now reflects the correct quantities of the products that are supposed to be added to the cart
shopgate_pwa
train
83340225d5e809ea3d099c09d910cf1e930d6e9d
diff --git a/lib/conject/version.rb b/lib/conject/version.rb index <HASH>..<HASH> 100644 --- a/lib/conject/version.rb +++ b/lib/conject/version.rb @@ -1,3 +1,3 @@ module Conject - VERSION = "0.1.0" + VERSION = "0.1.1" end
Version <I> includes canonical private accessors for module-scoped object dependencies.
dcrosby42_conject
train
33ad6d801ac9fd2a1a8acd8afa58d55ddd62767d
diff --git a/anycast_healthchecker/main.py b/anycast_healthchecker/main.py index <HASH>..<HASH> 100644 --- a/anycast_healthchecker/main.py +++ b/anycast_healthchecker/main.py @@ -120,6 +120,9 @@ def main(): print("Cleaning stale pid file, past pid:{}".format(pid)) os.unlink(args.pidfile) + if not touch(args.bird_conf_file): + sys.exit(1) + # Get a PID lock file. pid_lockfile = PIDLockFile(args.pidfile) # Map log level to numeric which can be accepted by loggers.
exit if we can't write to bird configuration file
unixsurfer_anycast_healthchecker
train
8268b176d25452343973c40e7784b5d7a53b624d
diff --git a/src/helper/jsonify/jsonify.js b/src/helper/jsonify/jsonify.js index <HASH>..<HASH> 100644 --- a/src/helper/jsonify/jsonify.js +++ b/src/helper/jsonify/jsonify.js @@ -13,11 +13,17 @@ module.exports = function(Velocity, utils, BLOCK_TYPES){ utils.forEach(ast.path, function(a){ + var isIgnore = a.type === 'method' && a.id === 'size'; + var isGet = a.type === 'method' && a.id.indexOf('get') === 0 && a.args === false; + if (isIgnore) { + return; + } + if (a.type === 'index') { if (a.id && (a.id.type === 'integer' || a.id.type === 'string')) ret.push(a.id.value); } else { - ret.push(a.id); + ret.push(isGet ? a.id.slice(3) : a.id); } });
slice get for method getXXX
shepherdwind_velocity.js
train
ab92a241a89535b9b688b57cf0d79f122c10be5d
diff --git a/revisioner.js b/revisioner.js index <HASH>..<HASH> 100644 --- a/revisioner.js +++ b/revisioner.js @@ -393,7 +393,7 @@ var Revisioner = (function () { */ Revisioner.prototype.shouldFileBeRenamed = function (file) { - var filename = this.Tool.get_relative_path(file.base, file.path); + var filename = this.Tool.get_relative_path(file.base, file.revPathOriginal); for (var i = this.options.dontGlobal.length; i--;) { var regex = (this.options.dontGlobal[i] instanceof RegExp) ? this.options.dontGlobal[i] : new RegExp(this.options.dontGlobal[i] + '$', 'ig'); @@ -418,7 +418,7 @@ var Revisioner = (function () { */ Revisioner.prototype.shouldUpdateReference = function (file) { - var filename = this.Tool.get_relative_path(file.base, file.path); + var filename = this.Tool.get_relative_path(file.base, file.revPathOriginal); for (var i = this.options.dontGlobal.length; i--;) { var regex = (this.options.dontGlobal[i] instanceof RegExp) ? this.options.dontGlobal[i] : new RegExp(this.options.dontGlobal[i] + '$', 'ig'); @@ -442,7 +442,7 @@ var Revisioner = (function () { */ Revisioner.prototype.shouldSearchFile = function (file) { - var filename = this.Tool.get_relative_path(file.base, file.path); + var filename = this.Tool.get_relative_path(file.base, file.revPathOriginal); for (var i = this.options.dontGlobal.length; i--;) { var regex = (this.options.dontGlobal[i] instanceof RegExp) ? this.options.dontGlobal[i] : new RegExp(this.options.dontGlobal[i] + '$', 'ig');
Use the original file path when using should* regular expressions
smysnk_gulp-rev-all
train
9110f12a3ece9d4f997255e545279a1c4f2dab14
diff --git a/commerce-api/src/main/java/com/liferay/commerce/payment/engine/CommercePaymentEngine.java b/commerce-api/src/main/java/com/liferay/commerce/payment/engine/CommercePaymentEngine.java index <HASH>..<HASH> 100644 --- a/commerce-api/src/main/java/com/liferay/commerce/payment/engine/CommercePaymentEngine.java +++ b/commerce-api/src/main/java/com/liferay/commerce/payment/engine/CommercePaymentEngine.java @@ -21,6 +21,7 @@ import com.liferay.commerce.payment.method.CommercePaymentMethod; import com.liferay.commerce.payment.result.CommercePaymentResult; import com.liferay.commerce.payment.result.CommerceSubscriptionStatusResult; import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.theme.ThemeDisplay; import java.util.List; import java.util.Locale; @@ -87,6 +88,10 @@ public interface CommercePaymentEngine { public int getOrderStatusUpdateMaxIntervalMinutes(long commerceOrderId) throws PortalException; + public String getPaymentMethodImageURL( + ThemeDisplay themeDisplay, String paymentMethodKey) + throws PortalException; + public String getPaymentMethodName(String paymentMethodKey, Locale locale); /** diff --git a/commerce-payment-service/src/main/java/com/liferay/commerce/payment/engine/impl/CommercePaymentEngineImpl.java b/commerce-payment-service/src/main/java/com/liferay/commerce/payment/engine/impl/CommercePaymentEngineImpl.java index <HASH>..<HASH> 100644 --- a/commerce-payment-service/src/main/java/com/liferay/commerce/payment/engine/impl/CommercePaymentEngineImpl.java +++ b/commerce-payment-service/src/main/java/com/liferay/commerce/payment/engine/impl/CommercePaymentEngineImpl.java @@ -33,6 +33,7 @@ import com.liferay.commerce.service.CommerceOrderPaymentLocalService; import com.liferay.petra.string.StringPool; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.language.LanguageUtil; +import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.transaction.Propagation; import com.liferay.portal.kernel.transaction.Transactional; import com.liferay.portal.kernel.util.Portal; @@ -328,6 +329,19 @@ public class CommercePaymentEngineImpl implements CommercePaymentEngine { } @Override + public String getPaymentMethodImageURL( + ThemeDisplay themeDisplay, String paymentMethodKey) + throws PortalException { + + CommercePaymentMethodGroupRel commercePaymentMethodGroupRel = + _commercePaymentMethodGroupRelLocalService. + getCommercePaymentMethodGroupRel( + themeDisplay.getSiteGroupId(), paymentMethodKey); + + return commercePaymentMethodGroupRel.getImageURL(themeDisplay); + } + + @Override public String getPaymentMethodName(String paymentMethodKey, Locale locale) { CommercePaymentMethod commercePaymentMethod = _commercePaymentMethodRegistry.getCommercePaymentMethod(
COMMERCE-<I> new method for retrieving payment method image
liferay_com-liferay-commerce
train
aec5074f3d5c33e63e440e9e383dd16b9f097e68
diff --git a/client.go b/client.go index <HASH>..<HASH> 100644 --- a/client.go +++ b/client.go @@ -291,6 +291,22 @@ func (me *Client) initiateConn(peer Peer, torrent *torrent) { }() } +func (cl *Client) incomingPeerPort() int { + if cl.Listener == nil { + return 0 + } + _, p, err := net.SplitHostPort(cl.Listener.Addr().String()) + if err != nil { + panic(err) + } + var i int + _, err = fmt.Sscanf(p, "%d", &i) + if err != nil { + panic(err) + } + return i +} + func (me *Client) runConnection(sock net.Conn, torrent *torrent) (err error) { conn := &connection{ Socket: sock, @@ -364,10 +380,14 @@ func (me *Client) runConnection(sock net.Conn, torrent *torrent) (err error) { "m": map[string]int{ "ut_metadata": 1, }, + "v": "go.torrent dev", } if torrent.metadataSizeKnown() { d["metadata_size"] = torrent.metadataSize() } + if p := me.incomingPeerPort(); p != 0 { + d["p"] = p + } b, err := bencode.Marshal(d) if err != nil { panic(err) @@ -599,12 +619,21 @@ func (me *Client) connectionLoop(t *torrent, c *connection) error { case pp.Extended: switch msg.ExtendedID { case pp.HandshakeExtendedID: + // TODO: Create a bencode struct for this. var d map[string]interface{} err = bencode.Unmarshal(msg.ExtendedPayload, &d) if err != nil { err = fmt.Errorf("error decoding extended message payload: %s", err) break } + if reqq, ok := d["reqq"]; ok { + if i, ok := reqq.(int64); ok { + c.PeerMaxRequests = int(i) + } + } + if v, ok := d["v"]; ok { + c.PeerClientName = v.(string) + } m, ok := d["m"] if !ok { err = errors.New("handshake missing m item") diff --git a/connection.go b/connection.go index <HASH>..<HASH> 100644 --- a/connection.go +++ b/connection.go @@ -35,6 +35,7 @@ type connection struct { PeerPieces []bool PeerMaxRequests int // Maximum pending requests the peer allows. PeerExtensionIDs map[string]int64 + PeerClientName string } func (cn *connection) completedString() string {
Add support for extended handshake "v", "reqq", and "p" fields
anacrolix_torrent
train
c58e80497059c5ddedbee42f11cab432a3608f65
diff --git a/galpy/orbit_src/Orbit.py b/galpy/orbit_src/Orbit.py index <HASH>..<HASH> 100644 --- a/galpy/orbit_src/Orbit.py +++ b/galpy/orbit_src/Orbit.py @@ -614,7 +614,7 @@ class Orbit: """ self._orb._setupaA(pot=pot,**kwargs) - return self._orb._aA(self)[0][0] + return self._orb._aA(self)[0] def jp(self,pot=None,**kwargs): """ @@ -690,7 +690,7 @@ class Orbit: """ self._orb._setupaA(pot=pot,**kwargs) - return self._orb._aA(self)[2][0] + return self._orb._aA(self)[2] def wr(self,pot=None,**kwargs): """
fix orbit interface to radial and vertical action
jobovy_galpy
train
f3bdbae01b62d5e43b2b4002739c0ac5432916d2
diff --git a/Controller/Front/AbstractFrontController.php b/Controller/Front/AbstractFrontController.php index <HASH>..<HASH> 100755 --- a/Controller/Front/AbstractFrontController.php +++ b/Controller/Front/AbstractFrontController.php @@ -15,7 +15,7 @@ use WellCommerce\Bundle\CatalogBundle\Storage\CategoryStorageInterface; use WellCommerce\Bundle\ClientBundle\Entity\Client; use WellCommerce\Bundle\CoreBundle\Controller\AbstractController; use WellCommerce\Bundle\OrderBundle\Provider\Front\OrderProviderInterface; -use WellCommerce\Bundle\ProducerBundle\Storage\ProducerStorageInterface; +use WellCommerce\Bundle\CatalogBundle\Storage\ProducerStorageInterface; use WellCommerce\Bundle\ProductBundle\Storage\ProductStorageInterface; use WellCommerce\Bundle\ProductStatusBundle\Storage\ProductStatusStorageInterface;
Moved ProducerBundle to CatalogBundle
WellCommerce_CouponBundle
train
ed8131f4be61c5290b421e5cd857e68fb13ff6a6
diff --git a/src/org/opencms/file/CmsProject.java b/src/org/opencms/file/CmsProject.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/file/CmsProject.java +++ b/src/org/opencms/file/CmsProject.java @@ -466,6 +466,16 @@ public class CmsProject implements Cloneable, Comparable<CmsProject> { } /** + * Returns true if this is a workflow project.<p> + * + * @return true if this is a workflow project + */ + public boolean isWorkflowProject() { + + return getType().getMode() == PROJECT_TYPE_WORKFLOW.getMode(); + } + + /** * Sets the delete After Publishing flag.<p> * * @param deleteAfterPublishing the delete After Publishing flag to set diff --git a/src/org/opencms/workplace/CmsFrameset.java b/src/org/opencms/workplace/CmsFrameset.java index <HASH>..<HASH> 100644 --- a/src/org/opencms/workplace/CmsFrameset.java +++ b/src/org/opencms/workplace/CmsFrameset.java @@ -105,6 +105,24 @@ public class CmsFrameset extends CmsWorkplace { } /** + * Performs additional filtering on the list of projects for the project selector.<p> + * + * @param projects the original project list + * + * @return the filtered project list + */ + public List<CmsProject> filterProjectsForSelector(List<CmsProject> projects) { + + List<CmsProject> result = new ArrayList<CmsProject>(); + for (CmsProject project : projects) { + if (!project.isWorkflowProject()) { + result.add(project); + } + } + return result; + } + + /** * Returns the javascript code for the broadcast message alert in the foot of the workplace.<p> * * @return javascript code showing an alert box when the foot load @@ -198,6 +216,7 @@ public class CmsFrameset extends CmsWorkplace { } allProjects = Collections.emptyList(); } + allProjects = filterProjectsForSelector(allProjects); boolean singleOu = true; String ouFqn = null;
Added a filtering function for the workplace project selector which filters out workflow projects.
alkacon_opencms-core
train
089a179553a7795d882fa9cfcc9abedeca82b606
diff --git a/tools/cocopy/cocopy/lib/compiler.py b/tools/cocopy/cocopy/lib/compiler.py index <HASH>..<HASH> 100644 --- a/tools/cocopy/cocopy/lib/compiler.py +++ b/tools/cocopy/cocopy/lib/compiler.py @@ -356,8 +356,8 @@ class Transformer: # Generate the argument list, visit the body, and then return the AST node. # TODO: varargs, kwargs, defaults, decorators, type annotations. - if node.name == "__init__": - id = self.ident(tokens.func_init) + if is_class_method and node.name == "__init__": + id = self.ident(tokens.func_ctor) else: id = self.ident(node.name)
Mark class __init__ methods as ctors
pulumi_pulumi
train
03431b412607996846a7256ef45829a8682b1a1a
diff --git a/deep-aerospike/src/main/java/com/stratio/deep/aerospike/utils/UtilAerospike.java b/deep-aerospike/src/main/java/com/stratio/deep/aerospike/utils/UtilAerospike.java index <HASH>..<HASH> 100644 --- a/deep-aerospike/src/main/java/com/stratio/deep/aerospike/utils/UtilAerospike.java +++ b/deep-aerospike/src/main/java/com/stratio/deep/aerospike/utils/UtilAerospike.java @@ -166,7 +166,7 @@ final public class UtilAerospike { AerospikeDeepJobConfig aerospikeConfig) throws IllegalAccessException, InstantiationException, InvocationTargetException { - String namespace = key.namespace + "." + key.setName; + String namespace = aerospikeConfig.getNamespace() + "." + aerospikeConfig.getSet(); String setName = aerospikeConfig.getSet(); String[] inputColumns = aerospikeConfig.getInputColumns(); Tuple2<String, Object> equalsFilter = aerospikeConfig.getEqualsFilter();
Small change for getting namespace on UtilAerospike.
Stratio_deep-spark
train
9c0acab83900d0b40b1f624e6069e663a77479b3
diff --git a/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java b/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java index <HASH>..<HASH> 100644 --- a/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java +++ b/flink-java/src/main/java/org/apache/flink/api/java/ExecutionEnvironment.java @@ -384,7 +384,7 @@ public abstract class ExecutionEnvironment { /** * Creates a {@link DataSet} that represents the Strings produced by reading the given file line wise. - * The file will be read with the system's default character set. + * The file will be read with the UTF-8 character set. * * @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path"). * @return A {@link DataSet} that represents the data read from the given file as text lines. @@ -419,7 +419,7 @@ public abstract class ExecutionEnvironment { * {@link StringValue} objects, rather than Java Strings. StringValues can be used to tune implementations * to be less object and garbage collection heavy. * - * <p>The file will be read with the system's default character set. + * <p>The file will be read with the UTF-8 character set. * * @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path"). * @return A {@link DataSet} that represents the data read from the given file as text lines. diff --git a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java index <HASH>..<HASH> 100644 --- a/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java +++ b/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java @@ -923,7 +923,7 @@ public abstract class StreamExecutionEnvironment { /** * Reads the given file line-by-line and creates a data stream that contains a string with the - * contents of each such line. The file will be read with the system's default character set. + * contents of each such line. The file will be read with the UTF-8 character set. * * <p><b>NOTES ON CHECKPOINTING: </b> The source monitors the path, creates the * {@link org.apache.flink.core.fs.FileInputSplit FileInputSplits} to be processed, forwards
[FLINK-<I>][javadoc] Fix character set in readTextFile* methods
apache_flink
train
8d08503dc0d3bcda110338c8e7b13448a4a74c5a
diff --git a/snapshot/lib/snapshot/reports_generator.rb b/snapshot/lib/snapshot/reports_generator.rb index <HASH>..<HASH> 100644 --- a/snapshot/lib/snapshot/reports_generator.rb +++ b/snapshot/lib/snapshot/reports_generator.rb @@ -53,6 +53,7 @@ module Snapshot 'iPhone6' => "iPhone6 (4.7-Inch)", 'iPhone5' => "iPhone5 (4-Inch)", 'iPhone4' => "iPhone4 (3.5-Inch)", + 'iPhone SE' => "iPhone SE", 'iPad2' => "iPad2", 'iPadAir2' => 'iPad Air 2', 'iPadPro(12.9-inch)' => 'iPad Air Pro (12.9 inch)',
snapshot support for iPhone SE (#<I>)
fastlane_fastlane
train