hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
3893e0cdca64616e059b704c640ee5ea33a9d884 | diff --git a/thefuck/rules/cargo_no_command.py b/thefuck/rules/cargo_no_command.py
index <HASH>..<HASH> 100644
--- a/thefuck/rules/cargo_no_command.py
+++ b/thefuck/rules/cargo_no_command.py
@@ -4,7 +4,7 @@ from thefuck.utils import replace_argument, for_app
@for_app('cargo', at_least=1)
def match(command):
- return ('o such subcommand' in command.stderr
+ return ('no such subcommand' in command.stderr.lower()
and 'Did you mean' in command.stderr) | #<I>: Little refactoring | nvbn_thefuck | train |
2da09723e81b579d65a0c3ffb7ac138cf13ced30 | diff --git a/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java b/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
index <HASH>..<HASH> 100644
--- a/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
+++ b/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
@@ -37,4 +37,19 @@ public final class JVMUtils {
Runtime.getRuntime().addShutdownHook(new Thread(new ClosingRunnable(closeable)));
}
+ /**
+ * @return approximate heap used, in bytes
+ */
+ public static long getUsedMemory() {
+ Runtime runtime = Runtime.getRuntime();
+ return runtime.totalMemory() - runtime.freeMemory();
+ }
+
+ /**
+ * @return maximum size that the heap may grow to, in bytes
+ */
+ public static long getMaxMemory() {
+ return Runtime.getRuntime().maxMemory();
+ }
+
}
diff --git a/oryx-common/src/test/java/com/cloudera/oryx/common/OryxTest.java b/oryx-common/src/test/java/com/cloudera/oryx/common/OryxTest.java
index <HASH>..<HASH> 100644
--- a/oryx-common/src/test/java/com/cloudera/oryx/common/OryxTest.java
+++ b/oryx-common/src/test/java/com/cloudera/oryx/common/OryxTest.java
@@ -50,12 +50,12 @@ public abstract class OryxTest extends Assert {
}
@Before
- public final void setUp() {
+ public final void initRandom() {
RandomManager.useTestSeed();
}
@After
- public final void tearDown() throws IOException {
+ public final void deleteTempDir() throws IOException {
if (tempDir != null) {
IOUtils.deleteRecursively(tempDir);
tempDir = null; | Add JVM memory methods, rename Before/After methods to be less conflicting | OryxProject_oryx | train |
6e11966a68fc4fd2615923e735c9b10f0d78d3b4 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -2,33 +2,47 @@
"""Package Keysmith."""
+
+import codecs
+import os.path
+import re
+
import setuptools # type: ignore
-import keysmith
+def read(*parts):
+ """Read a file in this repository."""
+ here = os.path.abspath(os.path.dirname(__file__))
+ with codecs.open(os.path.join(here, *parts), 'r') as file_:
+ return file_.read()
+
+
+def find_version(*file_paths):
+ """
+ Read the file in setup.py and parse the version with a regex.
+
+ https://packaging.python.org/guides/single-sourcing-package-version/
+ """
+ version_file = read(*file_paths)
+ version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
+ version_file, re.M)
+ if version_match:
+ return version_match.group(1)
+ raise RuntimeError("Unable to find version string.")
-with open('README.rst') as readme_file:
- README = readme_file.read()
setuptools.setup(
- name=keysmith.__name__,
- version=keysmith.__version__,
- description=keysmith.__doc__,
- long_description=README,
+ name='keysmith',
+ version=find_version('keysmith.py'),
+ description='A Diceware-style Password Generator',
+ long_description=read('README.rst'),
author='David Tucker',
author_email='[email protected]',
license='LGPLv2+',
url='https://github.com/dmtucker/keysmith',
python_requires='~=3.5',
- py_modules=[keysmith.__name__],
- entry_points={
- 'console_scripts': [
- '{script_name}={module}:main'.format(
- script_name=keysmith.CONSOLE_SCRIPT,
- module=keysmith.__name__,
- ),
- ],
- },
+ py_modules=['keysmith'],
+ entry_points={'console_scripts': ['keysmith=keysmith:main']},
keywords='password generator keygen',
classifiers=[
'Development Status :: 5 - Production/Stable', | Stop importing keysmith in setup.py | dmtucker_keysmith | train |
c0c36474223e2b07d062d718d5f7f24bed4261ca | diff --git a/docs/source/conf.py b/docs/source/conf.py
index <HASH>..<HASH> 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -27,7 +27,7 @@ author = "The Font Bakery Authors"
# The short X.Y version
version = "0.7"
# The full version, including alpha/beta/rc tags
-release = "0.7.1"
+release = "0.7.2"
# -- General configuration --------------------------------------------------- | update version on docs/source/conf.py | googlefonts_fontbakery | train |
091336dc6bad40db9ba1e87a976b07da2cb3ba9e | diff --git a/src/test/org/openscience/cdk/ringsearch/cyclebasis/SimpleCycleBasisTest.java b/src/test/org/openscience/cdk/ringsearch/cyclebasis/SimpleCycleBasisTest.java
index <HASH>..<HASH> 100644
--- a/src/test/org/openscience/cdk/ringsearch/cyclebasis/SimpleCycleBasisTest.java
+++ b/src/test/org/openscience/cdk/ringsearch/cyclebasis/SimpleCycleBasisTest.java
@@ -33,6 +33,7 @@ import java.util.Arrays;
import org._3pq.jgrapht.graph.SimpleGraph;
import org.junit.Assert;
import org.junit.BeforeClass;
+import org.junit.Test;
import org.openscience.cdk.CDKTestCase;
/**
@@ -78,10 +79,12 @@ public class SimpleCycleBasisTest extends CDKTestCase {
}
+ @Test
public void testSimpleCycleBasis() {
Assert.assertTrue(basis.cycles().size() == g.edgeSet().size() - g.vertexSet().size() + 1);
}
+ @Test
public void testSimpleCycleBasisCompleteGraph() {
g = new SimpleGraph();
g.addVertex( "a" );
@@ -109,22 +112,27 @@ public class SimpleCycleBasisTest extends CDKTestCase {
Assert.assertEquals(1, basis.equivalenceClasses().size());
}
+ @Test
public void testWeightVector() {
Assert.assertArrayEquals(basis.weightVector(), new int[] {3,3,3,3,3,3,3,3});
}
+ @Test
public void testRelevantCycles() {
Assert.assertEquals(10, basis.relevantCycles().size());
}
+ @Test
public void testEssentialCycles() {
Assert.assertEquals(2, basis.essentialCycles().size());
}
+ @Test
public void testEquivalenceClasses() {
Assert.assertEquals(4, basis.equivalenceClasses().size());
}
+ @Test
public void testEquivalenceClassesEmptyIntersection() {
SimpleGraph h = new SimpleGraph( ); | Make sure the tests are also run with JUnit4
Change-Id: Ie<I>f2f8ea4cba<I>e4f<I>f<I>b9ec<I>c<I>aa | cdk_cdk | train |
296da81fc809f71e8e08bda612ba89925880fb6c | diff --git a/src/java/org/apache/cassandra/net/OutboundTcpConnection.java b/src/java/org/apache/cassandra/net/OutboundTcpConnection.java
index <HASH>..<HASH> 100644
--- a/src/java/org/apache/cassandra/net/OutboundTcpConnection.java
+++ b/src/java/org/apache/cassandra/net/OutboundTcpConnection.java
@@ -27,7 +27,10 @@ import java.net.SocketException;
import java.nio.ByteBuffer;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
@@ -50,6 +53,8 @@ public class OutboundTcpConnection extends Thread
private volatile boolean isStopped = false;
private static final int OPEN_RETRY_DELAY = 100; // ms between retries
+ private static final int WAIT_FOR_VERSION_MAX_TIME = 5000;
+ private static final int NO_VERSION = Integer.MIN_VALUE;
// sending thread reads from "active" (one of queue1, queue2) until it is empty.
// then it swaps it with "backlog."
@@ -288,11 +293,10 @@ public class OutboundTcpConnection extends Thread
if (logger.isDebugEnabled())
logger.debug("attempting to connect to " + poolReference.endPoint());
- targetVersion = MessagingService.instance().getVersion(poolReference.endPoint());
-
long start = System.currentTimeMillis();
while (System.currentTimeMillis() < start + DatabaseDescriptor.getRpcTimeout())
{
+ targetVersion = MessagingService.instance().getVersion(poolReference.endPoint());
try
{
socket = poolReference.newSocket();
@@ -325,7 +329,16 @@ public class OutboundTcpConnection extends Thread
out.flush();
DataInputStream in = new DataInputStream(socket.getInputStream());
- int maxTargetVersion = in.readInt();
+ int maxTargetVersion = handshakeVersion(in);
+ if (maxTargetVersion == NO_VERSION)
+ {
+ // no version is returned, so disconnect an try again: we will either get
+ // a different target version (targetVersion < MessagingService.VERSION_12)
+ // or if the same version the handshake will finally succeed
+ logger.debug("Target max version is {}; no version information yet, will retry", maxTargetVersion);
+ disconnect();
+ continue;
+ }
if (targetVersion > maxTargetVersion)
{
logger.debug("Target max version is {}; will reconnect with that version", maxTargetVersion);
@@ -371,6 +384,47 @@ public class OutboundTcpConnection extends Thread
}
return false;
}
+
+ private int handshakeVersion(final DataInputStream inputStream)
+ {
+ final AtomicInteger version = new AtomicInteger(NO_VERSION);
+ final CountDownLatch versionLatch = new CountDownLatch(1);
+ new Thread("HANDSHAKE-" + poolReference.endPoint())
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ logger.info("Handshaking version with {}", poolReference.endPoint());
+ version.set(inputStream.readInt());
+ }
+ catch (IOException ex)
+ {
+ final String msg = "Cannot handshake version with " + poolReference.endPoint();
+ if (logger.isTraceEnabled())
+ logger.trace(msg, ex);
+ else
+ logger.info(msg);
+ }
+ finally
+ {
+ //unblock the waiting thread on either success or fail
+ versionLatch.countDown();
+ }
+ }
+ }.start();
+
+ try
+ {
+ versionLatch.await(WAIT_FOR_VERSION_MAX_TIME, TimeUnit.MILLISECONDS);
+ }
+ catch (InterruptedException ex)
+ {
+ throw new AssertionError(ex);
+ }
+ return version.get();
+ }
private void expireMessages()
{ | Race condition in detecting version on a mixed <I>/<I> cluster
patch by Sergio Bossa; reviewed by jasobrown for CASSANDRA-<I> | Stratio_stratio-cassandra | train |
212997bb061d92d7a69bc375b9913bee1a11c32c | diff --git a/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/ADStarForward.java b/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/ADStarForward.java
index <HASH>..<HASH> 100644
--- a/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/ADStarForward.java
+++ b/hipster-core/src/main/java/es/usc/citius/hipster/algorithm/ADStarForward.java
@@ -220,6 +220,12 @@ public class ADStarForward<A,S,C extends Comparable<C>, N extends es.usc.citius.
//s removed from OPEN
open.remove(state);
//this.queue.remove(current);
+ //expand successors
+ for (N successorNode : expander.expand(current)) {
+ if(successorNode.isDoUpdate()){
+ updateQueues(successorNode);
+ }
+ }
//if v(s) > g(s)
if (current.isConsistent()) {
//v(s) = g(s)
@@ -231,12 +237,6 @@ public class ADStarForward<A,S,C extends Comparable<C>, N extends es.usc.citius.
expander.setMaxV(current);
updateQueues(current);
}
-
- for (N successorNode : expander.expand(current)) {
- if(successorNode.isDoUpdate()){
- updateQueues(successorNode);
- }
- }
} else {
// for all directed edges (u, v) with changed edge costs
for(N nodeTransitionsChanged : expander.expandTransitionsChanged(beginNode.state(), current, transitionsChanged)){
diff --git a/hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeExpander.java b/hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeExpander.java
index <HASH>..<HASH> 100644
--- a/hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeExpander.java
+++ b/hipster-core/src/main/java/es/usc/citius/hipster/model/function/impl/ADStarNodeExpander.java
@@ -90,6 +90,7 @@ public class ADStarNodeExpander<A, S, C extends Comparable<C>, N extends es.usc.
@Override
public Iterable<N> expand(N node) {
Collection<N> nodes = new ArrayList<N>();
+ boolean consistency = node.isConsistent();
//if s' not visited before: v(s')=g(s')=Infinity; bp(s')=null
for (Transition<A, S> transition : successorFunction.transitionsFrom(node.state())) {
N successorNode = visited.get(transition.getState());
@@ -98,7 +99,7 @@ public class ADStarNodeExpander<A, S, C extends Comparable<C>, N extends es.usc.
visited.put(transition.getState(), successorNode);
}
//if consistent
- if (node.isConsistent()) {
+ if (consistency) {
//if g(s') > g(s) + c(s, s')
// bp(s') = s
// g(s') = g(s) + c(s, s') | close #<I> : node expander executed before changing values of V and G in the parent node | citiususc_hipster | train |
612fe5c831879066d0b6807f8e99dfb390cbb50f | diff --git a/mhcflurry/class1_affinity_predictor.py b/mhcflurry/class1_affinity_predictor.py
index <HASH>..<HASH> 100644
--- a/mhcflurry/class1_affinity_predictor.py
+++ b/mhcflurry/class1_affinity_predictor.py
@@ -707,7 +707,7 @@ class Class1AffinityPredictor(object):
throw=True,
include_individual_model_predictions=False,
include_percentile_ranks=True,
- centrality_measure="robust_mean"):
+ centrality_measure="mean"):
"""
Predict nM binding affinities. Gives more detailed output than `predict`
method, including 5-95% prediction intervals.
@@ -748,6 +748,8 @@ class Class1AffinityPredictor(object):
raise TypeError("peptides must be a list or array, not a string")
if isinstance(alleles, string_types):
raise TypeError("alleles must be a list or array, not a string")
+ if allele is None and alleles is None:
+ raise ValueError("Must specify 'allele' or 'alleles'.")
if allele is not None:
if alleles is not None:
raise ValueError("Specify exactly one of allele or alleles") | Switch back to mean instead of robust_mean default | openvax_mhcflurry | train |
08ed43585d398fc5efea097ac6e2baedc64ce1a8 | diff --git a/lib/draper/railtie.rb b/lib/draper/railtie.rb
index <HASH>..<HASH> 100755
--- a/lib/draper/railtie.rb
+++ b/lib/draper/railtie.rb
@@ -17,7 +17,7 @@ module Draper
config.after_initialize do |app|
app.config.paths.add 'app/decorators', eager_load: true
- unless Rails.env.production?
+ if Rails.env.test?
require 'draper/test_case'
require 'draper/test/rspec_integration' if defined?(RSpec) and RSpec.respond_to?(:configure)
require 'draper/test/minitest_integration' if defined?(MiniTest::Rails) | restrict inclusion of test dependencies to test environment only | drapergem_draper | train |
6e43506e8eca60dbc42bbb482d5cce54a7c7c2ce | diff --git a/src/Collection/index.js b/src/Collection/index.js
index <HASH>..<HASH> 100644
--- a/src/Collection/index.js
+++ b/src/Collection/index.js
@@ -53,15 +53,26 @@ export default class Collection<Record: Model> {
// (with the same semantics as when calling `model.observe()`)
findAndObserve(id: RecordId): Observable<Record> {
return Observable.create(observer => {
+ let unsubscribe = null
+ let unsubscribed = false
this._fetchRecord(id, result => {
if (result.value) {
- observer.next(result.value)
- observer.complete()
+ const record = result.value
+ observer.next(record)
+ unsubscribe = record.experimentalSubscribe(isDeleted => {
+ if (!unsubscribed) {
+ isDeleted ? observer.complete() : observer.next(record)
+ }
+ })
} else {
observer.error(result.error)
}
})
- }).pipe(switchMap(model => model.observe()))
+ return () => {
+ unsubscribed = true
+ unsubscribe && unsubscribe()
+ }
+ })
}
// Query records of this type | Make findAndObserve even leaner | Nozbe_WatermelonDB | train |
f9d6877c33618c642718ad273237210e96c0b239 | diff --git a/service/logger/default.go b/service/logger/default.go
index <HASH>..<HASH> 100644
--- a/service/logger/default.go
+++ b/service/logger/default.go
@@ -128,7 +128,7 @@ func (l *defaultLogger) Log(level Level, v ...interface{}) {
}
t := rec.Timestamp.Format("2006-01-02 15:04:05")
- fmt.Printf("%s %s %v\n", t, metadata, rec.Message)
+ fmt.Fprintf(l.opts.Out, "%s %s %v\n", t, metadata, rec.Message)
}
func (l *defaultLogger) Logf(level Level, format string, v ...interface{}) {
@@ -167,7 +167,7 @@ func (l *defaultLogger) Logf(level Level, format string, v ...interface{}) {
}
t := rec.Timestamp.Format("2006-01-02 15:04:05")
- fmt.Printf("%s %s %v\n", t, metadata, rec.Message)
+ fmt.Fprintf(l.opts.Out, "%s %s %v\n", t, metadata, rec.Message)
}
func (l *defaultLogger) Options() Options {
diff --git a/service/logger/logger_test.go b/service/logger/logger_test.go
index <HASH>..<HASH> 100644
--- a/service/logger/logger_test.go
+++ b/service/logger/logger_test.go
@@ -15,6 +15,9 @@
package logger
import (
+ "bufio"
+ "bytes"
+ "strings"
"testing"
)
@@ -30,3 +33,13 @@ func TestLogger(t *testing.T) {
l.Fields(map[string]interface{}{"key3": "val4"}).Log(InfoLevel, "test_msg")
}
+
+func TestLoggerRedirection(t *testing.T) {
+ var b bytes.Buffer
+ wr := bufio.NewWriter(&b)
+ NewLogger(WithOutput(wr)).Logf(InfoLevel, "test message")
+ wr.Flush()
+ if !strings.Contains(b.String(), "level=info test message") {
+ t.Fatalf("Redirection failed, received '%s'", b.String())
+ }
+} | Fix logger redirection (#<I>) | micro_micro | train |
4d9a43c77af06fac6f4ed27d09c46a4b1671b264 | diff --git a/contrib/py_stress/stress.py b/contrib/py_stress/stress.py
index <HASH>..<HASH> 100644
--- a/contrib/py_stress/stress.py
+++ b/contrib/py_stress/stress.py
@@ -177,7 +177,7 @@ class Operation(Thread):
class Inserter(Operation):
def run(self):
data = md5(str(get_ident())).hexdigest()
- columns = [Column('C' + str(j), data, 0) for j in xrange(columns_per_key)]
+ columns = [Column('C' + str(j), data, Clock(0)) for j in xrange(columns_per_key)]
fmt = '%0' + str(len(str(total_keys))) + 'd'
if 'super' == options.cftype:
supers = [SuperColumn('S' + str(j), columns) for j in xrange(supers_per_key)] | Adapt stress.py to the thrift clock api changes. Patch by johan, review by jbellis. CASSANDRA-<I>
git-svn-id: <URL> | Stratio_stratio-cassandra | train |
4a4528b75b321282ac27c26f886759184b0f3d2e | diff --git a/account/state/state.go b/account/state/state.go
index <HASH>..<HASH> 100644
--- a/account/state/state.go
+++ b/account/state/state.go
@@ -33,7 +33,7 @@ type StorageGetter interface {
}
type StorageSetter interface {
- // Store a 32-byte value at key for the account at address
+ // Store a 32-byte value at key for the account at address, setting to Zero256 removes the key
SetStorage(address acm.Address, key, value binary.Word256) error
}
diff --git a/execution/state.go b/execution/state.go
index <HASH>..<HASH> 100644
--- a/execution/state.go
+++ b/execution/state.go
@@ -235,7 +235,11 @@ func (s *State) GetStorage(address acm.Address, key binary.Word256) (binary.Word
func (s *State) SetStorage(address acm.Address, key, value binary.Word256) error {
s.Lock()
defer s.Unlock()
- s.tree.Set(prefixedKey(storagePrefix, address.Bytes(), key.Bytes()), value.Bytes())
+ if value == binary.Zero256 {
+ s.tree.Remove(key.Bytes())
+ } else {
+ s.tree.Set(prefixedKey(storagePrefix, address.Bytes(), key.Bytes()), value.Bytes())
+ }
return nil
} | Ensure storing zero value removes the key rather than panics | hyperledger_burrow | train |
8fba0a5ccbe49d759d80d24d2552978277726155 | diff --git a/lib/active_record/connection_adapters/sqlserver_adapter.rb b/lib/active_record/connection_adapters/sqlserver_adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/active_record/connection_adapters/sqlserver_adapter.rb
+++ b/lib/active_record/connection_adapters/sqlserver_adapter.rb
@@ -176,7 +176,7 @@ module ActiveRecord
end
# TODO: Find less hack way to convert DateTime objects into Times
- def self.string_to_time(value)
+ def string_to_time(value)
if value.is_a?(DateTime)
return new_time(value.year, value.mon, value.day, value.hour, value.min, value.sec)
else | Fix another def self.<method> vs class << self collision. | rails-sqlserver_activerecord-sqlserver-adapter | train |
964366d957e2ab113f23e1ae6f19d12f9f4b20d3 | diff --git a/test/decorators/on.spec.js b/test/decorators/on.spec.js
index <HASH>..<HASH> 100644
--- a/test/decorators/on.spec.js
+++ b/test/decorators/on.spec.js
@@ -13,16 +13,4 @@ describe('@on decorator', () => {
});
- describe('view.helper.prepareEventDomain', () => {
-
- it('should prepare eventDomain string into event and delegateSelector', () => {
-
- on.helper.prepareEventDomain('click').should.containDeep(['click', undefined]);;
- on.helper.prepareEventDomain('dbclick .abc').should.containDeep(['dbclick', '.abc']);;
- on.helper.prepareEventDomain('mouseup .abc .def').should.containDeep(['mouseup', '.abc .def']);
-
- });
-
- });
-
}); | test/decorators/on.spec.js: moved tests to test/lib/eventhandler.spec.js | SerkanSipahi_app-decorators | train |
eb1681e3fec7ed6b3cec541ac52e34857413f002 | diff --git a/test/integrations/awesomatic.js b/test/integrations/awesomatic.js
index <HASH>..<HASH> 100644
--- a/test/integrations/awesomatic.js
+++ b/test/integrations/awesomatic.js
@@ -52,14 +52,15 @@ describe('#initialize', function () {
describe('#identify', function () {
before(function () {
this.stub = sinon.stub(Awesomatic, 'load');
- analytics.identify('x', { email: '[email protected]' });
});
it('should call load()', function () {
+ analytics.identify('x');
assert(this.stub.called);
});
it('should set email', function () {
+ analytics.identify('x', { email: '[email protected]' });
assert(this.stub.calledWith({
email: '[email protected]'
})); | Awesomatic integration: moving identify call in test to individual tests instead of before(). | segmentio_analytics.js-core | train |
9acf2c19fd0a8fae9a929d4d17d27d3abfd3bb3c | diff --git a/natsort/natsort.py b/natsort/natsort.py
index <HASH>..<HASH> 100644
--- a/natsort/natsort.py
+++ b/natsort/natsort.py
@@ -64,6 +64,14 @@ You can mix types with natsorted. This can get around the new
>>> natsorted(a)
[{u}'2.5', 4.5, 6, {u}'7']
+Natsort will recursively descend into lists of lists so you can sort by the sublist contents.
+
+ >>> data = [['a1', 'a5'], ['a1', 'a40'], ['a10', 'a1'], ['a2', 'a5']]
+ >>> sorted(data)
+ [[{u}'a1', {u}'a40'], [{u}'a1', {u}'a5'], [{u}'a10', {u}'a1'], [{u}'a2', {u}'a5']]
+ >>> natsorted(data)
+ [[{u}'a1', {u}'a5'], [{u}'a1', {u}'a40'], [{u}'a2', {u}'a5'], [{u}'a10', {u}'a1']]
+
"""
from __future__ import unicode_literals
@@ -181,11 +189,24 @@ def natsort_key(s, number_type=float, signed=True, exp=True):
>>> natsort_key('a-5.034e1', number_type=None) == natsort_key('a-5.034e1', number_type=int, signed=False)
True
+ Iterables are parsed recursively so you can sort lists of lists.
+
+ >>> natsort_key(('a1', 'a10'))
+ (({u}'a', 1.0), ({u}'a', 10.0))
+
+ You can give numbers, too.
+
+ >>> natsort_key(10)
+ (10,)
+
"""
# If we are dealing with non-strings, return now
if not isinstance(s, py23_basestring):
- return (s,)
+ if hasattr(s, '__getitem__'):
+ return tuple(natsort_key(x) for x in s)
+ else:
+ return (s,)
# Convert to the proper tuple and return
inp_options = (number_type, signed, exp) | Added algorithm that allows natsort to sort lists of lists. | SethMMorton_natsort | train |
2cdfd69b6ff0b7be1bc11aeff71ff1f58ce58d2e | diff --git a/src/main/java/org/culturegraph/mf/stream/converter/RegexDecoder.java b/src/main/java/org/culturegraph/mf/stream/converter/RegexDecoder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/culturegraph/mf/stream/converter/RegexDecoder.java
+++ b/src/main/java/org/culturegraph/mf/stream/converter/RegexDecoder.java
@@ -125,10 +125,12 @@ public final class RegexDecoder extends DefaultObjectPipe<String, StreamReceiver
public void process(final String string) {
matcher.reset(string);
- String id = null;
+ final String id;
final int groupIndex = captureGroupNames.indexOf(ID_CAPTURE_GROUP) + 1;
if (groupIndex > 0 && matcher.find()) {
id = matcher.group(groupIndex);
+ } else {
+ id = "";
}
getReceiver().startRecord(id);
diff --git a/src/test/java/org/culturegraph/mf/stream/converter/RegexDecoderTest.java b/src/test/java/org/culturegraph/mf/stream/converter/RegexDecoderTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/culturegraph/mf/stream/converter/RegexDecoderTest.java
+++ b/src/test/java/org/culturegraph/mf/stream/converter/RegexDecoderTest.java
@@ -44,7 +44,7 @@ public final class RegexDecoderTest {
public void testRegex() {
final EventList expected = new EventList();
- expected.startRecord(null);
+ expected.startRecord("");
expected.literal(DEFAULT_LITERAL_NAME, INPUT);
expected.literal(GROUP_NAME_1, "42");
expected.literal(GROUP_NAME_2, "xyzzy"); | RegexDecoder should not emit null record ids.
Fixes issue #<I> | metafacture_metafacture-core | train |
cfd9ba03ca0f63e6ad67666484b6cd93ec5632d4 | diff --git a/format/extractjson.go b/format/extractjson.go
index <HASH>..<HASH> 100644
--- a/format/extractjson.go
+++ b/format/extractjson.go
@@ -26,12 +26,11 @@ import (
// message.
// Configuration example
//
-// - "stream.Broadcast":
-// Formatter: "format.ExtractJSON"
-// ExtractJSONdataFormatter: "format.Forward"
-// ExtractJSONField: ""
-// ExtractJSONTrimValues: true
-// ExtractJSONPrecision: 0
+// - format.ExtractJSON:
+// Field: ""
+// TrimValues: true
+// Precision: 0
+// ApplyTo: "payload" # payload or <metaKey>
//
// ExtractJSONDataFormatter formatter that will be applied before
// the field is extracted. Set to format.Forward by default.
@@ -50,6 +49,7 @@ type ExtractJSON struct {
field string
trimValues bool
numberFormat string
+ applyTo string
}
func init() {
@@ -64,36 +64,59 @@ func (format *ExtractJSON) Configure(conf core.PluginConfigReader) error {
format.trimValues = conf.GetBool("TrimValues", true)
precision := conf.GetInt("Precision", 0)
format.numberFormat = fmt.Sprintf("%%.%df", precision)
+ format.applyTo = conf.GetString("ApplyTo", core.APPLY_TO_PAYLOAD)
return conf.Errors.OrNil()
}
// ApplyFormatter update message payload
func (format *ExtractJSON) ApplyFormatter(msg *core.Message) error {
+ content := format.GetAppliedContent(msg)
+
+ value, err := format.extractJson(content)
+ if err != nil {
+ return err
+ }
+
+ if value != nil {
+ format.SetAppliedContent(msg, value)
+ } else {
+ if format.applyTo == core.APPLY_TO_PAYLOAD {
+ msg.Resize(0)
+ } else {
+ msg.MetaData().ResetValue(format.applyTo)
+ }
+ }
+
+ return nil
+}
+
+func (format *ExtractJSON) extractJson(content []byte) ([]byte, error) {
values := tcontainer.NewMarshalMap()
- err := json.Unmarshal(msg.Data(), &values)
+
+ err := json.Unmarshal(content, &values)
if err != nil {
format.Log.Warning.Print("ExtractJSON failed to unmarshal a message: ", err)
- return err
+ return nil, err
}
if value, exists := values[format.field]; exists {
switch value.(type) {
case int64:
val, _ := value.(int64)
- msg.Store([]byte(fmt.Sprintf("%d", val)))
+ return []byte(fmt.Sprintf("%d", val)), nil
case string:
val, _ := value.(string)
- msg.Store([]byte(val))
+ return []byte(val), nil
case float64:
val, _ := value.(float64)
- msg.Store([]byte(fmt.Sprintf(format.numberFormat, val)))
+ return []byte(fmt.Sprintf(format.numberFormat, val)), nil
default:
- msg.Store([]byte(fmt.Sprintf("%v", value)))
+ return []byte(fmt.Sprintf("%v", value)), nil
}
- } else {
- msg.Resize(0)
}
- return nil
-}
+ format.Log.Warning.Print("ExtractJSON field not exists: ", format.field)
+
+ return nil, nil
+}
\ No newline at end of file
diff --git a/format/extractjson_test.go b/format/extractjson_test.go
index <HASH>..<HASH> 100644
--- a/format/extractjson_test.go
+++ b/format/extractjson_test.go
@@ -61,3 +61,26 @@ func TestExtractJSONPrecision(t *testing.T) {
expect.Equal("999999999", string(msg.Data()))
}
+
+func TestExtractJSONApplyTo(t *testing.T) {
+ expect := ttesting.NewExpect(t)
+
+ config := core.NewPluginConfig("", "format.ExtractJSON")
+ config.Override("ApplyTo", "foo")
+ config.Override("Field", "test")
+
+ plugin, err := core.NewPluginWithConfig(config)
+ expect.NoError(err)
+ formatter, casted := plugin.(*ExtractJSON)
+ expect.True(casted)
+
+ msg := core.NewMessage(nil, []byte("{\"foo\":\"bar\"}"),
+ 0, core.InvalidStreamID)
+ msg.MetaData().SetValue("foo", []byte("{\"foo\":\"bar\",\"test\":\"valid\"}"))
+
+ err = formatter.ApplyFormatter(msg)
+ expect.NoError(err)
+
+ expect.Equal("valid", msg.MetaData().GetValueString("foo"))
+ expect.Equal("{\"foo\":\"bar\"}", msg.String())
+} | added `applyTo` handling to ExtractJSON formatter | trivago_gollum | train |
10efcdbe511b5a24a01caf3594cfd71000f3486a | diff --git a/src/Api/Monetization/Structure/Reports/Criteria/RevenueReportCriteria.php b/src/Api/Monetization/Structure/Reports/Criteria/RevenueReportCriteria.php
index <HASH>..<HASH> 100644
--- a/src/Api/Monetization/Structure/Reports/Criteria/RevenueReportCriteria.php
+++ b/src/Api/Monetization/Structure/Reports/Criteria/RevenueReportCriteria.php
@@ -31,7 +31,7 @@ final class RevenueReportCriteria extends AbstractCriteria
/**
* @var \DateTimeImmutable|null
*/
- private $endDate;
+ private $toDate;
/**
* Array of developer attributes to be displayed in the report.
@@ -59,12 +59,12 @@ final class RevenueReportCriteria extends AbstractCriteria
* RevenueReportCriteria constructor.
*
* @param \DateTimeImmutable $fromDate
- * @param \DateTimeImmutable|null $endDate
+ * @param \DateTimeImmutable|null $toDate
*/
- public function __construct(\DateTimeImmutable $fromDate, ?\DateTimeImmutable $endDate = null)
+ public function __construct(\DateTimeImmutable $fromDate, ?\DateTimeImmutable $toDate = null)
{
$this->fromDate = $fromDate;
- $this->endDate = $endDate;
+ $this->toDate = $toDate;
}
/**
@@ -78,9 +78,9 @@ final class RevenueReportCriteria extends AbstractCriteria
/**
* @return \DateTimeImmutable|null
*/
- public function getEndDate(): ?\DateTimeImmutable
+ public function getToDate(): ?\DateTimeImmutable
{
- return $this->endDate;
+ return $this->toDate;
}
/** | Use toDate instead of endDate for revenue report criteria (#<I>) | apigee_apigee-client-php | train |
ada44e4e0214f2ded64f459dc4854397b02bba49 | diff --git a/lib/rubocop/cli.rb b/lib/rubocop/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/rubocop/cli.rb
+++ b/lib/rubocop/cli.rb
@@ -47,7 +47,7 @@ module Rubocop
cop.correlations = correlations
config = $options[:config] || config_from_dotfile(File.dirname(file))
cop_config = config[cop_klass.name.split('::').last] if config
- cop_klass.enabled = cop_config.nil? || cop_config['Enable']
+ cop_klass.enabled = cop_config.nil? || cop_config['Enabled']
cop.inspect(file, source, tokens, sexp)
total_offences += cop.offences.count
report << cop if cop.has_report?
diff --git a/spec/rubocop/cli_spec.rb b/spec/rubocop/cli_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rubocop/cli_spec.rb
+++ b/spec/rubocop/cli_spec.rb
@@ -72,10 +72,10 @@ module Rubocop
File.open('example1.rb', 'w') { |f| f.puts 'x = 0 ' }
File.open('rubocop.yml', 'w') do |f|
f.puts('Encoding:',
- ' Enable: false',
+ ' Enabled: false',
'',
'Indentation:',
- ' Enable: false')
+ ' Enabled: false')
end
begin
return_code = cli.run(['-c', 'rubocop.yml', 'example1.rb'])
@@ -97,10 +97,10 @@ module Rubocop
File.open('example_src/example1.rb', 'w') { |f| f.puts 'x = 0 ' }
File.open('example_src/.rubocop.yml', 'w') do |f|
f.puts('Encoding:',
- ' Enable: false',
+ ' Enabled: false',
'',
'Indentation:',
- ' Enable: false')
+ ' Enabled: false')
end
begin
return_code = cli.run(['example_src/example1.rb']) | The configuration property should be "Enabled", not "Enable". | rubocop-hq_rubocop | train |
0dc36c5937a331f8d4dc1f28194bc172ce4eca85 | diff --git a/perceval/backend.py b/perceval/backend.py
index <HASH>..<HASH> 100644
--- a/perceval/backend.py
+++ b/perceval/backend.py
@@ -23,17 +23,54 @@
import argparse
import sys
+from .cache import Cache
from .utils import DEFAULT_DATETIME
class Backend:
+ """Abstract class for backends.
- def __init__(self):
- pass
+ Base class to fetch data from a repository. During the
+ initialization, a `Cache` object can be provided for caching
+ raw data from the repositories.
+
+ Derivated classes have to implement `fetch` and `fetch_from_cache`
+ methods. Otherwise, `NotImplementedError` exception will be raised.
+
+ :param cache: object to cache raw data
+
+ :raises ValueError: raised when `cache` is not an instance of
+ `Cache` class
+ """
+ def __init__(self, cache=None):
+ if cache and not isinstance(cache, Cache):
+ msg = "cache is not an instance of Cache. %s object given" \
+ % (str(type(cache)))
+ raise ValueError(msg)
+
+ self.cache = cache
+ self.cache_queue = []
def fetch(self, from_date=DEFAULT_DATETIME):
raise NotImplementedError
+ def fetch_from_cache(self):
+ raise NotImplementedError
+
+ def _purge_cache_queue(self):
+ self.cache_queue = []
+
+ def _flush_cache_queue(self):
+ if not self.cache:
+ return
+ self.cache.store(*self.cache_queue)
+ self._purge_cache_queue()
+
+ def _push_cache_queue(self, item):
+ if not self.cache:
+ return
+ self.cache_queue.append(item)
+
class BackendCommand:
"""Abstract class to run backends from the command line.
diff --git a/tests/test_backend.py b/tests/test_backend.py
index <HASH>..<HASH> 100644
--- a/tests/test_backend.py
+++ b/tests/test_backend.py
@@ -29,10 +29,21 @@ if not '..' in sys.path:
import argparse
import unittest
-from perceval.backend import BackendCommand
+from perceval.backend import Backend, BackendCommand
+
+
+class TestBackend(unittest.TestCase):
+ """Unit tests for Backend"""
+
+ def test_cache_value_error(self):
+ """Test whether it raises a error on invalid cache istances"""
+
+ with self.assertRaises(ValueError):
+ Backend(cache=8)
class TestBackendCommand(unittest.TestCase):
+ """Unit tests for BackendCommand"""
def test_parsing_on_init(self):
"""Test if the arguments are parsed when the class is initialized""" | [backend] Add Cache support on abstract backend class
The commit adds the method fetch_from_cache(), that must
be implemeted by derived classes. It also adds some methods
to delay the insertion of items to the cache, such as
_push_cache_queue() and _flush_cache_queue(). | chaoss_grimoirelab-perceval | train |
2ca5c8de7f1d1834b954ce1cdfac42555fc676f2 | diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -1,5 +1,6 @@
var Promise = require('bluebird');
-var hasher = require('object-hash');
+var CircularJSON = require('circular-json');
+var crypto = require('crypto');
var redis = null;
var sequelize = null;
@@ -46,7 +47,7 @@ Cacher.prototype.query = function query(options, queryOptions) {
this.options = options;
this.queryOptions = queryOptions;
var key = this.key();
- return this.fetchFromCache(key);
+ return this.fetchFromCache();
};
/**
@@ -106,9 +107,10 @@ Cacher.prototype.setCache = function setCache(key, results, ttl) {
* Clear cache with given query
*/
Cacher.prototype.clearCache = function clearCache(opts) {
+ var self = this;
this.options = opts || this.options;
- var key = this.key();
return new Promise(function promiser(resolve, reject) {
+ var key = self.key();
return redis.del(key, function onDel(err) {
if (err) {
return reject(err);
@@ -121,9 +123,10 @@ Cacher.prototype.clearCache = function clearCache(opts) {
/**
* Fetch data from cache
*/
-Cacher.prototype.fetchFromCache = function fetchFromCache(key) {
+Cacher.prototype.fetchFromCache = function fetchFromCache() {
var self = this;
return new Promise(function promiser(resolve, reject) {
+ var key = self.key();
return redis.get(key, function(err, res) {
if (err) {
return reject(err);
@@ -145,7 +148,9 @@ Cacher.prototype.fetchFromCache = function fetchFromCache(key) {
* Create redis key
*/
Cacher.prototype.key = function key() {
- var hash = hasher(this.options);
+ var hash = crypto.createHash('sha1')
+ .update(CircularJSON.stringify(this.options))
+ .digest('hex');
return [this.cachePrefix, this.modelName, this.method, hash].join(':');
};
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "sequelize-redis-cache",
- "version": "0.0.1",
+ "version": "0.0.2",
"description": "Caching module for sequelize queries",
"main": "lib/index.js",
"scripts": {
@@ -29,6 +29,6 @@
},
"dependencies": {
"bluebird": "2.3.2",
- "object-hash": "0.3.0"
+ "circular-json": "0.1.6"
}
}
diff --git a/test/sequelize-redis-cache.test.js b/test/sequelize-redis-cache.test.js
index <HASH>..<HASH> 100644
--- a/test/sequelize-redis-cache.test.js
+++ b/test/sequelize-redis-cache.test.js
@@ -27,6 +27,7 @@ describe('Sequelize-Redis-Cache', function() {
var rc;
var db;
var Entity;
+ var Entity2;
var inst;
var cacher;
@@ -43,11 +44,23 @@ describe('Sequelize-Redis-Cache', function() {
},
name: Sequelize.STRING(255)
});
+ Entity2 = db.define('entity2', {
+ id: {
+ type: Sequelize.INTEGER,
+ primaryKey: true,
+ autoIncrement: true
+ }
+ });
+ Entity2.belongsTo(Entity, { foreignKey: 'entityId' });
+ Entity.hasMany(Entity2, { foreignKey: 'entityId' });
Entity.sync({ force: true })
.success(function() {
- Entity.create({ name: 'Test Instance' }).success(function(entity) {
- inst = entity;
- return done();
+ Entity2.sync({ force: true }).success(function() {
+ Entity.create({ name: 'Test Instance' }).success(function(entity) {
+ inst = entity;
+ return done();
+ })
+ .error(onErr);
})
.error(onErr);
})
@@ -102,4 +115,14 @@ describe('Sequelize-Redis-Cache', function() {
}, onErr);
}, onErr);
});
+
+ it('should not blow up with circular reference queries (includes)', function(done) {
+ var query = { where: { createdAt: inst.createdAt }, include: [Entity2] };
+ var obj = cacher('entity')
+ .ttl(1);
+ return obj.find(query)
+ .then(function(res) {
+ return done();
+ }, onErr);
+ });
}); | Fix for circular references (hasMany to belongsTo) | rfink_sequelize-redis-cache | train |
ce08f828bf89f839834f0b9b559f39fe47af8116 | diff --git a/pmml-evaluator-testing/src/main/java/org/jpmml/evaluator/testing/IntegrationTestBatch.java b/pmml-evaluator-testing/src/main/java/org/jpmml/evaluator/testing/IntegrationTestBatch.java
index <HASH>..<HASH> 100644
--- a/pmml-evaluator-testing/src/main/java/org/jpmml/evaluator/testing/IntegrationTestBatch.java
+++ b/pmml-evaluator-testing/src/main/java/org/jpmml/evaluator/testing/IntegrationTestBatch.java
@@ -26,7 +26,6 @@ import java.util.function.Predicate;
import com.esotericsoftware.kryo.Kryo;
import com.google.common.base.Equivalence;
import org.dmg.pmml.Application;
-import org.dmg.pmml.MiningSchema;
import org.dmg.pmml.PMML;
import org.dmg.pmml.Visitor;
import org.dmg.pmml.VisitorAction;
@@ -150,8 +149,7 @@ public class IntegrationTestBatch extends ArchiveBatch {
protected void validatePMML(PMML pmml) throws Exception {
List<Visitor> visitors = Arrays.<Visitor>asList(
- new MissingMarkupInspector(),
- new InvalidMarkupInspector(){
+ new MissingMarkupInspector(){
@Override
public VisitorAction visit(Application application){
@@ -163,17 +161,8 @@ public class IntegrationTestBatch extends ArchiveBatch {
return super.visit(application);
}
-
- @Override
- public VisitorAction visit(MiningSchema miningSchema){
-
- if(!miningSchema.hasMiningFields()){
- return VisitorAction.SKIP;
- }
-
- return super.visit(miningSchema);
- }
},
+ new InvalidMarkupInspector(),
new UnsupportedMarkupInspector()
); | Improved commit 7fde<I>b3 | jpmml_jpmml-evaluator | train |
378f253eebcef7119fc80b45e00ec66924081314 | diff --git a/src/main/java/org/whitesource/agent/dependency/resolver/maven/MavenDependencyResolver.java b/src/main/java/org/whitesource/agent/dependency/resolver/maven/MavenDependencyResolver.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/whitesource/agent/dependency/resolver/maven/MavenDependencyResolver.java
+++ b/src/main/java/org/whitesource/agent/dependency/resolver/maven/MavenDependencyResolver.java
@@ -184,7 +184,7 @@ public class MavenDependencyResolver extends AbstractDependencyResolver {
@Override
public String[] getBomPattern() {
- return new String[]{POM_XML};
+ return new String[]{Constants.PATTERN + POM_XML};
}
@Override
diff --git a/src/main/java/org/whitesource/agent/dependency/resolver/sbt/SbtDependencyResolver.java b/src/main/java/org/whitesource/agent/dependency/resolver/sbt/SbtDependencyResolver.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/whitesource/agent/dependency/resolver/sbt/SbtDependencyResolver.java
+++ b/src/main/java/org/whitesource/agent/dependency/resolver/sbt/SbtDependencyResolver.java
@@ -151,7 +151,7 @@ public class SbtDependencyResolver extends AbstractDependencyResolver {
@Override
public String[] getBomPattern() {
- return new String[]{"**" + fileSeparator + BUILD_SBT};
+ return new String[]{Constants.PATTERN + BUILD_SBT};
}
@Override | WSE-<I> - fixed 'getBomPatten' on maven-resolver (there was no '**/*' before the 'pom.xml' | whitesource_fs-agent | train |
66f88d9d5077c859f7e20a445060f4bfff8a9496 | diff --git a/lib/core.js b/lib/core.js
index <HASH>..<HASH> 100644
--- a/lib/core.js
+++ b/lib/core.js
@@ -237,10 +237,6 @@ function createDynamicDecl (dyn, append) {
}
}
-function isFloatArray (array) {
- return Array.isArray(array) || (array instanceof Float32Array)
-}
-
var SCOPE_DECL = new Declaration(false, false, false, function () {})
module.exports = function reglCore (
@@ -2162,26 +2158,23 @@ module.exports = function reglCore (
if (!filter(arg)) {
continue
}
- if (arg.static) {
+ if (isStatic(arg)) {
var value = arg.value
if (type === GL_SAMPLER_2D || type === GL_SAMPLER_CUBE) {
check.command(
typeof value === 'function' &&
- value._reglType === 'texture' &&
- ((type === GL_SAMPLER_CUBE &&
- value._texture.target === GL_TEXTURE_CUBE_MAP) ||
- (type === GL_SAMPLER_2D &&
- value._texutre.target === GL_TEXTURE_2D)),
+ ((value._reglType === 'texture2d' && type === GL_SAMPLER_2D) ||
+ (value._reglType === 'textureCube' && type === GL_SAMPLER_CUBE)),
'invalid texture for uniform ' + name)
var TEX_VALUE = env.link(value._texture)
- scope(GL, '.uniform1i(', LOCATION, TEX_VALUE + '.bind());')
- scope.exit(TEX_VALUE, '.unbind()')
+ scope(GL, '.uniform1i(', LOCATION, ',', TEX_VALUE + '.bind());')
+ scope.exit(TEX_VALUE, '.unbind();')
} else if (
type === GL_FLOAT_MAT2 ||
type === GL_FLOAT_MAT3 ||
type === GL_FLOAT_MAT4) {
check.optional(function () {
- check.command(isFloatArray(value),
+ check.command(isArrayLike(value),
'invalid matrix for uniform ' + name)
check.command(
(type === GL_FLOAT_MAT2 && value.length === 4) ||
@@ -2189,7 +2182,8 @@ module.exports = function reglCore (
(type === GL_FLOAT_MAT4 && value.length === 16),
'invalid length for matrix uniform ' + name)
})
- var MAT_VALUE = env.global.def('[' + value + ']')
+ var MAT_VALUE = env.global.def('new Float32Array([' +
+ Array.prototype.slice.call(value) + '])')
var dim = 2
if (type === GL_FLOAT_MAT3) {
dim = 3
@@ -2267,10 +2261,10 @@ module.exports = function reglCore (
'uniform ' + name)
infix = '4i'
break
- default:
- check.raise('unsupported uniform type')
}
- scope(GL, '.uniform', infix, '(', LOCATION, ',', value, ');')
+ scope(GL, '.uniform', infix, '(', LOCATION, ',',
+ isArrayLike(value) ? Array.prototype.slice.call(value) : value,
+ ');')
}
continue
} else { | fix code generation bug for static uniforms | regl-project_regl | train |
507a6bbfc7055516881aa925070b71ec1b0d612e | diff --git a/src/system/modules/metamodels/TableContent.php b/src/system/modules/metamodels/TableContent.php
index <HASH>..<HASH> 100644
--- a/src/system/modules/metamodels/TableContent.php
+++ b/src/system/modules/metamodels/TableContent.php
@@ -175,8 +175,12 @@ class TableContent extends Backend
*/
public function editRenderSetting(DataContainer $dc)
{
- return ($dc->value < 1) ? '' : sprintf('<a href="contao/main.php?%s&act=edit&id=%s" title="%s" style="padding-left:3px">%s</a>', 'do=metamodels&table=tl_metamodel_rendersettings', $dc->value, sprintf(specialchars($GLOBALS['TL_LANG']['tl_module']['editrendersetting'][1]), $dc->value), $this->generateImage('alias.gif', $GLOBALS['TL_LANG']['tl_module']['editrendersetting'][0], 'style="vertical-align:top"')
- );
+ return ($dc->value < 1) ? '' : sprintf('<a href="contao/main.php?%s&id=%s" title="%s" style="padding-left:3px">%s</a>',
+ 'do=metamodels&table=tl_metamodel_rendersetting',
+ $dc->value,
+ sprintf(specialchars($GLOBALS['TL_LANG']['tl_module']['editrendersetting'][1]), $dc->value),
+ $this->generateImage('alias.gif', $GLOBALS['TL_LANG']['tl_module']['editrendersetting'][0], 'style="vertical-align:top"')
+ );
}
/**
diff --git a/src/system/modules/metamodels/TableModule.php b/src/system/modules/metamodels/TableModule.php
index <HASH>..<HASH> 100644
--- a/src/system/modules/metamodels/TableModule.php
+++ b/src/system/modules/metamodels/TableModule.php
@@ -105,8 +105,8 @@ class TableModule extends Backend
*/
public function editRenderSetting(DataContainer $dc)
{
- return ($dc->value < 1) ? '' : sprintf('<a href="contao/main.php?%s&act=edit&id=%s" title="%s" style="padding-left:3px">%s</a>',
- 'do=metamodels&table=tl_metamodel_rendersettings',
+ return ($dc->value < 1) ? '' : sprintf('<a href="contao/main.php?%s&id=%s" title="%s" style="padding-left:3px">%s</a>',
+ 'do=metamodels&table=tl_metamodel_rendersetting',
$dc->value,
sprintf(specialchars($GLOBALS['TL_LANG']['tl_module']['editrendersetting'][1]), $dc->value),
$this->generateImage('alias.gif', $GLOBALS['TL_LANG']['tl_module']['editrendersetting'][0], 'style="vertical-align:top"')
@@ -120,8 +120,8 @@ class TableModule extends Backend
*/
public function editFilterSetting(DataContainer $dc)
{
- return ($dc->value < 1) ? '' : sprintf('<a href="contao/main.php?%s&act=edit&id=%s" title="%s" style="padding-left:3px">%s</a>',
- 'do=metamodels&table=tl_metamodel_filter',
+ return ($dc->value < 1) ? '' : sprintf('<a href="contao/main.php?%s&id=%s" title="%s" style="padding-left:3px">%s</a>',
+ 'do=metamodels&table=tl_metamodel_filtersetting',
$dc->value,
sprintf(specialchars($GLOBALS['TL_LANG']['tl_module']['editfiltersetting'][1]), $dc->value),
$this->generateImage('alias.gif', $GLOBALS['TL_LANG']['tl_module']['editfiltersetting'][0], 'style="vertical-align:top"') | Fix issue #<I> - make content elements and filters point to child list for
render settings and filter settings instead of editing the parent element. | MetaModels_core | train |
0457b21c7c013bc7c81e432d11605c96ddee5a30 | diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "js-github",
- "version": "0.0.4",
+ "version": "0.1.0",
"description": "An implementation of the js-git interface that mounts a live github repo.",
"main": "src/repo.js",
"browser": {
diff --git a/src/decoders.js b/src/decoders.js
index <HASH>..<HASH> 100644
--- a/src/decoders.js
+++ b/src/decoders.js
@@ -1,10 +1,12 @@
var from = require('bops/from.js');
+var to = require('bops/to.js');
module.exports = {
commit: decodeCommit,
tag: decodeTag,
tree: decodeTree,
- blob: decodeBlob
+ blob: decodeBlob,
+ text: decodeText
};
function decodeCommit(result) {
@@ -35,14 +37,15 @@ function decodeTag(result) {
function decodeTree(result) {
var typeCache = this.typeCache;
- return result.tree.map(function (entry) {
+ var tree = {};
+ result.tree.forEach(function (entry) {
typeCache[entry.sha] = entry.type;
- return {
+ tree[entry.path] = {
mode: parseInt(entry.mode, 8),
- name: entry.path,
hash: entry.sha
};
});
+ return tree;
}
function decodeBlob(result) {
@@ -55,6 +58,16 @@ function decodeBlob(result) {
throw new Error("Unknown blob encoding: " + result.encoding);
}
+function decodeText(result) {
+ if (result.encoding === 'base64') {
+ return to(from(result.content.replace(/\n/g, ''), 'base64'), "utf8");
+ }
+ if (result.encoding === 'utf-8') {
+ return result.content;
+ }
+ throw new Error("Unknown blob encoding: " + result.encoding);
+}
+
function pickPerson(person) {
return {
name: person.name,
diff --git a/src/objects.js b/src/objects.js
index <HASH>..<HASH> 100644
--- a/src/objects.js
+++ b/src/objects.js
@@ -64,11 +64,12 @@ function loadAs(type, hash, callback) {
if (hash in repo.bodyCache) {
return callback(null, repo.bodyCache[hash], hash);
}
- repo.apiGet("/repos/:root/git/" + type + "s/" + hash, onValue);
+ var typeName = type === "text" ? "blob" : type;
+ repo.apiGet("/repos/:root/git/" + typeName + "s/" + hash, onValue);
}
function onValue(err, result) {
- if (err) return callback(err);
+ if (result === undefined) return callback(err);
repo.typeCache[hash] = type;
var body;
try { | Update to work with later js-git APIs | creationix_js-github | train |
a08a04b11736ccc8a8533d69fe733e4001cb81e7 | diff --git a/kubespawner/objects.py b/kubespawner/objects.py
index <HASH>..<HASH> 100644
--- a/kubespawner/objects.py
+++ b/kubespawner/objects.py
@@ -402,9 +402,9 @@ def make_pod(
# populate with fs_gid / supplemental_gids
if fs_gid is not None:
psc["fsGroup"] = int(fs_gid)
- if supplemental_gids is not None:
+ if supplemental_gids:
psc["supplementalGroups"] = [int(gid) for gid in supplemental_gids]
- if pod_security_context is not None:
+ if pod_security_context:
for key in pod_security_context.keys():
if "_" in key:
raise ValueError(
@@ -425,7 +425,7 @@ def make_pod(
csc["privileged"] = True
if not allow_privilege_escalation: # true as default
csc["allowPrivilegeEscalation"] = False
- if container_security_context is not None:
+ if container_security_context:
for key in container_security_context.keys():
if "_" in key:
raise ValueError( | Ensure to omit empty lists in security contexts | jupyterhub_kubespawner | train |
f0f4b3194f330f4fd29cb8b568f09c5701faa3ec | diff --git a/src/webargs/pyramidparser.py b/src/webargs/pyramidparser.py
index <HASH>..<HASH> 100644
--- a/src/webargs/pyramidparser.py
+++ b/src/webargs/pyramidparser.py
@@ -138,7 +138,7 @@ class PyramidParser(core.Parser):
location = location or self.location
# Optimization: If argmap is passed as a dictionary, we only need
# to generate a Schema once
- if isinstance(argmap, collections.Mapping):
+ if isinstance(argmap, collections.abc.Mapping):
argmap = core.dict2schema(argmap, self.schema_class)()
def decorator(func): | Import ABC from collections.abc instead of collections for Python <I> compatibility. | marshmallow-code_webargs | train |
1f0177c8274ab119a151989123f0d0a4596c0053 | diff --git a/commitizen/commands/check.py b/commitizen/commands/check.py
index <HASH>..<HASH> 100644
--- a/commitizen/commands/check.py
+++ b/commitizen/commands/check.py
@@ -89,7 +89,7 @@ class Check:
with open(self.commit_msg_file, "r", encoding="utf-8") as commit_file:
msg = commit_file.read()
# Get commit message from command line (--message)
- elif self.commit_msg:
+ elif self.commit_msg is not None:
msg = self.commit_msg
if msg is not None:
msg = self._filter_comments(msg) | fix(Check): process empty commit message
`elif self.commit_msg` will be skipped if the commit message is empty string, but this should be handled. | Woile_commitizen | train |
2c345d4207096b0e41f89ff07ecadeb4aa6b6979 | diff --git a/Collection.php b/Collection.php
index <HASH>..<HASH> 100755
--- a/Collection.php
+++ b/Collection.php
@@ -188,7 +188,7 @@ class Collection implements ArrayAccess, ArrayableInterface, Countable, Iterator
*/
public function map(Closure $callback)
{
- return new static(array_map($callback, $this->items));
+ return new static(array_map($callback, $this->items, array_keys($this->items)));
}
/** | pass keys to the map method on the Collection. | illuminate_support | train |
8aae3421d41f379a4b8fc082d3b3d5c304353fff | diff --git a/fulltext/util.py b/fulltext/util.py
index <HASH>..<HASH> 100644
--- a/fulltext/util.py
+++ b/fulltext/util.py
@@ -141,7 +141,7 @@ def is_windows64():
"""
Determine if platform is 64 bit Windows.
"""
- return is_windows() and 'PROGRAMFILES(X86)' in os.environ
+ return is_windows() and sys.maxsize > 2 ** 32
def get_data_dir():
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -1,5 +1,7 @@
#!/bin/env python
+import os
+import sys
from os.path import dirname
from os.path import join as pathjoin
from setuptools import find_packages
@@ -8,6 +10,10 @@ from setuptools import setup
NAME = 'fulltext'
VERSION = '0.7'
+if os.name == 'nt' and not sys.maxsize > 2 ** 32:
+ # https://github.com/btimby/fulltext/issues/79
+ raise RuntimeError("Python 32 bit is not supported")
+
with open(pathjoin(dirname(__file__), 'README.rst')) as f:
DESCRIPTION = f.read() | do not support python <I> bit explicitly | btimby_fulltext | train |
fe8c897d775d8be5e3e7b51fef73c0745a0196f8 | diff --git a/nsq/Reader.py b/nsq/Reader.py
index <HASH>..<HASH> 100644
--- a/nsq/Reader.py
+++ b/nsq/Reader.py
@@ -380,7 +380,7 @@ class Reader(object):
try:
data = json.loads(data)
- except json.JSONDecodeError:
+ except ValueError:
logging.warning("[%s] failed to parse JSON from nsqd: %r", conn.id, data)
return
@@ -420,7 +420,7 @@ class Reader(object):
try:
lookup_data = json.loads(response.body)
- except json.JSONDecodeError:
+ except ValueError:
logging.warning("[%s] failed to parse JSON from lookupd: %r", endpoint, response.body)
return | fix JSONDecodeError, it is only existed in simplejson | nsqio_pynsq | train |
684dba96ff8f7f005928fb26da5b64d67a1b862a | diff --git a/lib/api_auth/request_drivers/rest_client.rb b/lib/api_auth/request_drivers/rest_client.rb
index <HASH>..<HASH> 100644
--- a/lib/api_auth/request_drivers/rest_client.rb
+++ b/lib/api_auth/request_drivers/rest_client.rb
@@ -24,7 +24,7 @@ module ApiAuth
def calculated_md5
if @request.payload
- body = @request.payload.to_s
+ body = @request.payload.inspect
else
body = ''
end | So apparently I didn't read the api. Now api auth doesn't destroy restclient requests. | mgomes_api_auth | train |
4a4c1ed29051b69f540741a8f3846ff0e290bd79 | diff --git a/aioredis/client.py b/aioredis/client.py
index <HASH>..<HASH> 100644
--- a/aioredis/client.py
+++ b/aioredis/client.py
@@ -1278,16 +1278,16 @@ class Redis:
pieces.append(b"-@%s" % category[1:])
else:
raise DataError(
- 'Category "%s" must be prefixed with '
- '"+" or "-"' % encoder.decode(category, force=True)
+ f'Category "{encoder.decode(category, force=True)}" must be '
+ 'prefixed with "+" or "-"'
)
if commands:
for cmd in commands:
cmd = encoder.encode(cmd)
if not cmd.startswith(b"+") and not cmd.startswith(b"-"):
raise DataError(
- 'Command "%s" must be prefixed with '
- '"+" or "-"' % encoder.decode(cmd, force=True)
+ f'Command "{encoder.decode(cmd, force=True)}" must be '
+ 'prefixed with "+" or "-"'
)
pieces.append(cmd)
@@ -3413,8 +3413,8 @@ class Redis:
key and value from the ``mapping`` dict.
"""
warnings.warn(
- "%s.hmset() is deprecated. Use %s.hset() instead."
- % (self.__class__.__name__, self.__class__.__name__),
+ f"{self.__class__.__name__}.hmset() is deprecated. "
+ f"Use {self.__class__.__name__}.hset() instead.",
DeprecationWarning,
stacklevel=2,
)
@@ -3761,7 +3761,7 @@ class Monitor:
# check that monitor returns 'OK', but don't return it to user
response = await self.connection.read_response()
if not bool_ok(response):
- raise RedisError("MONITOR failed: %s" % response)
+ raise RedisError(f"MONITOR failed: {response}")
return self
async def __aexit__(self, *args):
@@ -4137,10 +4137,10 @@ class PubSub:
) -> "PubSubWorkerThread":
for channel, handler in self.channels.items():
if handler is None:
- raise PubSubError("Channel: '%s' has no handler registered" % channel)
+ raise PubSubError(f"Channel: '{channel}' has no handler registered")
for pattern, handler in self.patterns.items():
if handler is None:
- raise PubSubError("Pattern: '%s' has no handler registered" % pattern)
+ raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
thread = PubSubWorkerThread(
self, daemon=daemon, exception_handler=exception_handler
diff --git a/aioredis/connection.py b/aioredis/connection.py
index <HASH>..<HASH> 100644
--- a/aioredis/connection.py
+++ b/aioredis/connection.py
@@ -1005,7 +1005,7 @@ class RedisSSLContext:
}
if cert_reqs not in CERT_REQS:
raise RedisError(
- "Invalid SSL Certificate Requirements Flag: %s" % cert_reqs
+ f"Invalid SSL Certificate Requirements Flag: {cert_reqs}"
)
self.cert_reqs = CERT_REQS[cert_reqs]
self.ca_certs = ca_certs
@@ -1133,7 +1133,7 @@ def parse_url(url: str) -> ConnectKwargs:
try:
kwargs[name] = parser(value)
except (TypeError, ValueError):
- raise ValueError("Invalid value for `%s` in connection URL." % name)
+ raise ValueError(f"Invalid value for `{name}` in connection URL.")
else:
kwargs[name] = value
@@ -1167,8 +1167,7 @@ def parse_url(url: str) -> ConnectKwargs:
else:
valid_schemes = "redis://, rediss://, unix://"
raise ValueError(
- "Redis URL must specify one of the following "
- "schemes (%s)" % valid_schemes
+ f"Redis URL must specify one of the following schemes ({valid_schemes})"
)
return kwargs | Use f-strings for performance | aio-libs_aioredis | train |
feda399843db36bd50056ee5ce2ae7e38346e6ed | diff --git a/memberlist.go b/memberlist.go
index <HASH>..<HASH> 100644
--- a/memberlist.go
+++ b/memberlist.go
@@ -105,24 +105,24 @@ type Memberlist struct {
func DefaultConfig() *Config {
hostname, _ := os.Hostname()
return &Config{
- hostname,
- "0.0.0.0",
- 7946,
- 7946,
- 10 * time.Second, // Timeout after 10 seconds
- 3, // Use 3 nodes for the indirect ping
- 4, // Retransmit a message 4 * log(N+1) nodes
- 5, // Suspect a node for 5 * log(N+1) * Interval
- 30 * time.Second, // Low frequency
- 20 * time.Millisecond, // Reasonable RTT time for LAN
- 1 * time.Second, // Failure check every second
-
- 3, // Gossip to 3 nodes
- 200 * time.Millisecond, // Gossip more rapidly
-
- nil,
- nil,
- nil,
+ Name: hostname,
+ BindAddr: "0.0.0.0",
+ UDPPort: 7946,
+ TCPPort: 7946,
+ TCPTimeout: 10 * time.Second, // Timeout after 10 seconds
+ IndirectChecks: 3, // Use 3 nodes for the indirect ping
+ RetransmitMult: 4, // Retransmit a message 4 * log(N+1) nodes
+ SuspicionMult: 5, // Suspect a node for 5 * log(N+1) * Interval
+ PushPullInterval: 30 * time.Second, // Low frequency
+ RTT: 20 * time.Millisecond, // Reasonable RTT time for LAN
+ ProbeInterval: 1 * time.Second, // Failure check every second
+
+ GossipNodes: 3, // Gossip to 3 nodes
+ GossipInterval: 200 * time.Millisecond, // Gossip more rapidly
+
+ JoinCh: nil,
+ LeaveCh: nil,
+ UserDelegate: nil,
}
} | Good form to use keys with big structs | hashicorp_memberlist | train |
21d920ed2dfbb3f35072c265638e8c72c0c1476f | diff --git a/packages/node_modules/@webex/plugin-meetings/src/locus-info/selfUtils.js b/packages/node_modules/@webex/plugin-meetings/src/locus-info/selfUtils.js
index <HASH>..<HASH> 100644
--- a/packages/node_modules/@webex/plugin-meetings/src/locus-info/selfUtils.js
+++ b/packages/node_modules/@webex/plugin-meetings/src/locus-info/selfUtils.js
@@ -160,7 +160,7 @@ selfUtils.isAdmittedGuest = (oldSelf, changedSelf) => {
return selfUtils.isLocusGuestUnadmitted(oldSelf) && selfUtils.isLocusGuestAdmitted(changedSelf);
};
-selfUtils.mutedByOthers = (oldSelf, changedSelf) => {
+selfUtils.mutedByOthers = (oldSelf = {}, changedSelf) => {
if (!changedSelf) {
throw new ParameterError('New self must be defined to determine if self was muted by others.');
} | fix(meetings): mutedByOthers empty param
If "mute on join" is set, there will be no
"oldSelf" object to compare against. | webex_spark-js-sdk | train |
a56e35ad0a2f534f9d7f4138bffbfe91bf31e244 | diff --git a/stdlib/sql.go b/stdlib/sql.go
index <HASH>..<HASH> 100644
--- a/stdlib/sql.go
+++ b/stdlib/sql.go
@@ -73,6 +73,7 @@ func init() {
databaseSqlOids[pgx.Float8Oid] = true
databaseSqlOids[pgx.DateOid] = true
databaseSqlOids[pgx.TimestampTzOid] = true
+ databaseSqlOids[pgx.TimestampOid] = true
}
type Driver struct {
diff --git a/values.go b/values.go
index <HASH>..<HASH> 100644
--- a/values.go
+++ b/values.go
@@ -1089,6 +1089,7 @@ func decodeTimestamp(vr *ValueReader) time.Time {
if vr.Len() != 8 {
vr.Fatal(ProtocolError(fmt.Sprintf("Received an invalid size for an timestamp: %d", vr.Len())))
+ return zeroTime
}
microsecSinceY2K := vr.ReadInt64() | Support decoding of TimestampOid in stdlib driver | jackc_pgx | train |
84a059d7e3a83fa754c9b69be0c2ed591de68b55 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100755
--- a/index.js
+++ b/index.js
@@ -19,8 +19,8 @@ var Sharp = function(input) {
interpolator: 'bilinear',
progressive: false,
sequentialRead: false,
- quality: 80,
- compressionLevel: 6,
+ quality: 80,
+ compressionLevel: 6,
output: '__jpeg'
};
if (typeof input === 'string') {
@@ -68,7 +68,7 @@ Sharp.prototype.rotate = function(angle) {
} else if (!Number.isNaN(angle) && [0, 90, 180, 270].indexOf(angle) !== -1) {
this.options.angle = angle;
} else {
- throw 'Unsupport angle (0, 90, 180, 270) ' + angle;
+ throw new Error('Unsupported angle (0, 90, 180, 270) ' + angle);
}
return this;
};
@@ -167,19 +167,19 @@ Sharp.prototype.resize = function(width, height) {
*/
Sharp.prototype.toFile = function(output, callback) {
if (!output || output.length === 0) {
- var err = new Error('Invalid output');
+ var errOutputInvalid = new Error('Invalid output');
if (typeof callback === 'function') {
- callback(err);
+ callback(errOutputInvalid);
} else {
- return Promise.reject(err);
+ return Promise.reject(errOutputInvalid);
}
} else {
if (this.options.fileIn === output) {
- var err = new Error('Cannot use same file for input and output');
+ var errOutputIsInput = new Error('Cannot use same file for input and output');
if (typeof callback === 'function') {
- callback(err);
+ callback(errOutputIsInput);
} else {
- return Promise.reject(err);
+ return Promise.reject(errOutputIsInput);
}
} else {
return this._sharp(output, callback); | Rotate should throw Error, not String.
Minor JSLint and whitespace fixes. | lovell_sharp | train |
f3018776b8d0ae1f4746aaf3a664271b40b1eddc | diff --git a/mithril.js b/mithril.js
index <HASH>..<HASH> 100644
--- a/mithril.js
+++ b/mithril.js
@@ -194,7 +194,7 @@ Mithril = m = new function app(window, undefined) {
clear(cached.nodes)
if (cached.configContext && isFn(cached.configContext.onunload)) cached.configContext.onunload()
}
- if (typeof data.tag != "string") return
+ if (!isStr(data.tag)) return
var node, isNew = cached.nodes.length === 0
if (data.attrs.xmlns) namespace = data.attrs.xmlns
diff --git a/tests/mithril-tests.js b/tests/mithril-tests.js
index <HASH>..<HASH> 100644
--- a/tests/mithril-tests.js
+++ b/tests/mithril-tests.js
@@ -156,6 +156,18 @@ function testMithril(mock) {
})
test(function() {
var root = mock.document.createElement("div")
+ m.render(root, m("ul", [m("li")]))
+ m.render(root, m("ul", [{tag: "b", attrs: {}}]))
+ return root.childNodes[0].childNodes[0].nodeName == "B"
+ })
+ test(function() {
+ var root = mock.document.createElement("div")
+ m.render(root, m("ul", [m("li")]))
+ m.render(root, m("ul", [{tag: new String("b"), attrs: {}}]))
+ return root.childNodes[0].childNodes[0].nodeName == "B"
+ })
+ test(function() {
+ var root = mock.document.createElement("div")
m.render(root, m("ul", [m("li", [m("a")])]))
m.render(root, m("ul", [{subtree: "retain"}]))
return root.childNodes[0].childNodes[0].childNodes[0].nodeName === "A" | Check for weird edge-case & tests | MithrilJS_mithril.js | train |
91a2493a7adee77b5ffc1163a5948f5c95cfd240 | diff --git a/packages/lib/examples/complex/index.js b/packages/lib/examples/complex/index.js
index <HASH>..<HASH> 100644
--- a/packages/lib/examples/complex/index.js
+++ b/packages/lib/examples/complex/index.js
@@ -21,7 +21,7 @@ async function setupApp(txParams) {
// On-chain, single entry point of the entire application.
log.info(`<< Setting up App >> network: ${network}`)
const initialVersion = '0.0.1'
- return await App.deploy(initialVersion, txParams)
+ return await App.deploy(initialVersion, 0x0, txParams)
}
async function deployVersion1(app) {
diff --git a/packages/lib/examples/complex/test/App.test.js b/packages/lib/examples/complex/test/App.test.js
index <HASH>..<HASH> 100644
--- a/packages/lib/examples/complex/test/App.test.js
+++ b/packages/lib/examples/complex/test/App.test.js
@@ -6,8 +6,8 @@ const deploy = require('../index.js');
const validateAddress = require('./helpers/validateAddress.js');
const shouldBehaveLikeDonations = require('./Donations.behavior.js');
const shouldBehaveLikeDonationsWithTokens = require('./DonationsWithTokens.behavior.js');
-
require('chai').should()
+
contract('App', ([_, owner, donor, wallet]) => {
const initialVersion = '0.0.1';
const updatedVersion = '0.0.2'; | Update complex example to latest lib changes | zeppelinos_zos | train |
c4c54b5299d4fafebc1ad817de54749feb2fc977 | diff --git a/mutable_tree.go b/mutable_tree.go
index <HASH>..<HASH> 100644
--- a/mutable_tree.go
+++ b/mutable_tree.go
@@ -323,7 +323,11 @@ func (tree *MutableTree) LazyLoadVersion(targetVersion int64) (int64, error) {
iTree := &ImmutableTree{
ndb: tree.ndb,
version: targetVersion,
- root: tree.ndb.GetNode(rootHash),
+ }
+ if len(rootHash) > 0 {
+ // If rootHash is empty then root of tree should be nil
+ // This makes `LazyLoadVersion` to do the same thing as `LoadVersion`
+ iTree.root = tree.ndb.GetNode(rootHash)
}
tree.orphans = map[string]int64{}
diff --git a/mutable_tree_test.go b/mutable_tree_test.go
index <HASH>..<HASH> 100644
--- a/mutable_tree_test.go
+++ b/mutable_tree_test.go
@@ -358,3 +358,25 @@ func TestMutableTree_DeleteVersion(t *testing.T) {
// cannot delete latest version
require.Error(t, tree.DeleteVersion(2))
}
+
+func TestMutableTree_LazyLoadVersionWithEmptyTree(t *testing.T) {
+ mdb := db.NewMemDB()
+ tree, err := NewMutableTree(mdb, 1000)
+ require.NoError(t, err)
+ _, v1, err := tree.SaveVersion()
+ require.NoError(t, err)
+
+ newTree1, err := NewMutableTree(mdb, 1000)
+ require.NoError(t, err)
+ v2, err := newTree1.LazyLoadVersion(1)
+ require.NoError(t, err)
+ require.True(t, v1 == v2)
+
+ newTree2, err := NewMutableTree(mdb, 1000)
+ require.NoError(t, err)
+ v2, err = newTree1.LoadVersion(1)
+ require.NoError(t, err)
+ require.True(t, v1 == v2)
+
+ require.True(t, newTree1.root == newTree2.root)
+} | fix: make LazyLoadVersion possible to load empty root | tendermint_iavl | train |
16e8eb45cd93d9f0e0ab037ee0560794552b6d0d | diff --git a/lib/Unexpected.js b/lib/Unexpected.js
index <HASH>..<HASH> 100644
--- a/lib/Unexpected.js
+++ b/lib/Unexpected.js
@@ -488,8 +488,6 @@ Unexpected.prototype.fail = function (arg) {
var value = arg[key];
if (key === 'diff') {
error.createDiff = value;
- } else if (key === 'stack') {
- error._stack = value;
} else if (key !== 'message') {
error[key] = value;
}
diff --git a/lib/UnexpectedError.js b/lib/UnexpectedError.js
index <HASH>..<HASH> 100644
--- a/lib/UnexpectedError.js
+++ b/lib/UnexpectedError.js
@@ -223,8 +223,8 @@ UnexpectedError.prototype.serializeMessage = function (outputFormat) {
format: htmlFormat ? 'text' : outputFormat
}).toString() + '\n';
- if (this._stack) {
- this.stack = this.message + this._stack.replace(/^.*/, '');
+ if (this.originalError && this.originalError instanceof Error) {
+ this.stack = this.message + this.originalError.stack.replace(/^.*/, '');
}
if (this.stack && !this.useFullStackTrace) {
var newStack = [];
diff --git a/lib/assertions.js b/lib/assertions.js
index <HASH>..<HASH> 100644
--- a/lib/assertions.js
+++ b/lib/assertions.js
@@ -602,7 +602,7 @@ module.exports = function (expect) {
return expect(error, 'to satisfy', arg);
}
}, function (e) {
- e._stack = error && error.stack;
+ e.originalError = error;
throw e;
});
});
@@ -624,7 +624,7 @@ module.exports = function (expect) {
output.error(threw ? 'threw' : 'returned promise rejected with').error(': ')
.appendErrorMessage(error);
},
- stack: error && error.stack
+ originalError: error
});
});
});
@@ -646,7 +646,7 @@ module.exports = function (expect) {
output: function (output) {
output.error('threw: ').appendErrorMessage(error);
},
- stack: error && error.stack
+ originalError: error
});
}
});
@@ -673,7 +673,7 @@ module.exports = function (expect) {
return expect(error, 'to satisfy', arg);
}
}, function (err) {
- err._stack = error && error.stack;
+ err.originalError = error;
throw err;
});
});
@@ -1427,7 +1427,7 @@ module.exports = function (expect) {
return expect(err, 'to satisfy', value);
}
}, function (e) {
- e._stack = err && err.stack;
+ e.originalError = err;
throw e;
});
});
@@ -1452,7 +1452,7 @@ module.exports = function (expect) {
output.sp().text('with').sp().appendInspected(err);
}
},
- stack: err && err.stack
+ originalError: err
});
});
});
@@ -1502,7 +1502,7 @@ module.exports = function (expect) {
return expect.withError(function () {
return expect.shift(err);
}, function (e) {
- e._stack = err && err.stack;
+ e.originalError = err;
throw e;
});
});
@@ -1537,7 +1537,7 @@ module.exports = function (expect) {
output.sp().text('with').sp().appendInspected(err);
}
},
- stack: err && err.stack
+ originalError: err
});
});
});
diff --git a/lib/createWrappedExpectProto.js b/lib/createWrappedExpectProto.js
index <HASH>..<HASH> 100644
--- a/lib/createWrappedExpectProto.js
+++ b/lib/createWrappedExpectProto.js
@@ -76,7 +76,7 @@ module.exports = function createWrappedExpectProto(unexpected) {
result = result.then(undefined, function (e) {
if (e && e._isUnexpected) {
var wrappedError = new UnexpectedError(that, e);
- wrappedError._stack = e._stack;
+ wrappedError.originalError = e.originalError;
throw wrappedError;
}
throw e;
@@ -88,7 +88,7 @@ module.exports = function createWrappedExpectProto(unexpected) {
} catch (e) {
if (e && e._isUnexpected) {
var wrappedError = new UnexpectedError(that, e);
- wrappedError._stack = e._stack;
+ wrappedError.originalError = e.originalError;
if (that._context.serializeErrorsFromWrappedExpect) {
expect.setErrorMessage(wrappedError);
}
diff --git a/lib/types.js b/lib/types.js
index <HASH>..<HASH> 100644
--- a/lib/types.js
+++ b/lib/types.js
@@ -691,7 +691,7 @@ module.exports = function (expect) {
}
});
- var unexpectedErrorMethodBlacklist = ['output', '_isUnexpected', 'htmlMessage', '_hasSerializedErrorMessage', 'expect', 'assertion', '_stack'].reduce(function (result, prop) {
+ var unexpectedErrorMethodBlacklist = ['output', '_isUnexpected', 'htmlMessage', '_hasSerializedErrorMessage', 'expect', 'assertion', 'originalError'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {}); | Store a reference to the original error instead of just the stack. | unexpectedjs_unexpected | train |
9d857c0408b2701b0973459e112139cecf292ba6 | diff --git a/mbed/mbed.py b/mbed/mbed.py
index <HASH>..<HASH> 100755
--- a/mbed/mbed.py
+++ b/mbed/mbed.py
@@ -2435,15 +2435,14 @@ def status_(ignore=False):
# Helper function for compile subcommand
def _safe_append_profile_to_build_path(build_path, profile):
- append_str = 'DEFAULT'
-
if profile:
- if isinstance(profile, basestring):
- append_str = profile
- else:
- append_str = profile[0]
+ # profile is (or can be) a list, so just get the first element
+ if not isinstance(profile, basestring):
+ profile = profile[0]
- build_path = os.path.join(build_path, os.path.splitext(os.path.basename(append_str))[0].upper())
+ if profile:
+ profile_name_without_extension = os.path.splitext(os.path.basename(profile))[0].upper()
+ build_path += '__' + profile_name_without_extension
return build_path | Append profile name to default build dir with underscores, not as subdir.
Also, no append for default profile, since CI tools are sensitive to build dir, but all use default profile, so this preserves the prior behavior for them. | ARMmbed_mbed-cli | train |
53d6d0fe2be2c9529eb6ae26cef867a977837435 | diff --git a/src/Hprose/Writer.php b/src/Hprose/Writer.php
index <HASH>..<HASH> 100644
--- a/src/Hprose/Writer.php
+++ b/src/Hprose/Writer.php
@@ -380,7 +380,7 @@ namespace Hprose {
$name = $prop->getName();
$fl = ord($name[0]);
if ($fl >= ord('A') && $fl <= ord('Z')) {
- $name = strtolower($fl) . substr($name, 1);
+ $name = strtolower($name[0]) . substr($name, 1);
}
$this->writeString($name);
} | Fixed the bug of serializing the properties with the name of beginning of a capital letter. | hprose_hprose-php | train |
329928b288f45a1afca40bd17b1fff9a97e141eb | diff --git a/src/ibmiotf/__init__.py b/src/ibmiotf/__init__.py
index <HASH>..<HASH> 100644
--- a/src/ibmiotf/__init__.py
+++ b/src/ibmiotf/__init__.py
@@ -29,7 +29,7 @@ from datetime import datetime
from pkg_resources import get_distribution
from encodings.base64_codec import base64_encode
-__version__ = "0.2.0"
+__version__ = "0.1.9"
class Message:
def __init__(self, data, timestamp=None): | Version incorrectly bumped in last commit | ibm-watson-iot_iot-python | train |
99378472b32878bec7f08bd35f6da30f409a737c | diff --git a/CHANGES.md b/CHANGES.md
index <HASH>..<HASH> 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,5 +1,8 @@
# Changes
+## 7.1.2 (2018-05-22)
+- do NOT log `Authorization: Basic` request header
+
## 7.1.1 (2018-05-22)
- include a very simple `psr/log` logger `ErrorLogger`
- mention `psr/log` support in the README.md
diff --git a/src/Http/Request.php b/src/Http/Request.php
index <HASH>..<HASH> 100644
--- a/src/Http/Request.php
+++ b/src/Http/Request.php
@@ -35,7 +35,7 @@ class Request
/** @var string|null */
private $requestBody;
- /** @var array */
+ /** @var array<string,string> */
private $requestHeaders;
/**
@@ -59,6 +59,12 @@ class Request
{
$requestHeaders = [];
foreach ($this->requestHeaders as $k => $v) {
+ // we do NOT want to log HTTP Basic credentials
+ if (0 === \strcasecmp('Authorization', $k)) {
+ if (0 === \strpos($v, 'Basic ')) {
+ $v = 'XXX-REPLACED-XXX';
+ }
+ }
$requestHeaders[] = \sprintf('%s: %s', $k, $v);
}
diff --git a/tests/Http/RequestTest.php b/tests/Http/RequestTest.php
index <HASH>..<HASH> 100644
--- a/tests/Http/RequestTest.php
+++ b/tests/Http/RequestTest.php
@@ -42,4 +42,18 @@ class RequestTest extends TestCase
(string) $request
);
}
+
+ public function testReplacedBasicAuth()
+ {
+ $request = new Request(
+ 'GET',
+ 'http://example.org/foo',
+ ['Authorization' => 'Basic Zm9vOmJhcg=='],
+ 'Hello World!'
+ );
+ $this->assertSame(
+ '[requestMethod=GET, requestUri=http://example.org/foo, requestHeaders=[Authorization: XXX-REPLACED-XXX], requestBody=Hello World!]',
+ (string) $request
+ );
+ }
} | do NOT log `Authorization: Basic` request header | fkooman_php-oauth2-client | train |
c300789daa20b0092e4be6d326aa8cf2b7a3c199 | diff --git a/src/it/unitn/disi/smatch/matchers/structure/tree/spsm/ted/data/impl/CTXMLTreeAccessor.java b/src/it/unitn/disi/smatch/matchers/structure/tree/spsm/ted/data/impl/CTXMLTreeAccessor.java
index <HASH>..<HASH> 100644
--- a/src/it/unitn/disi/smatch/matchers/structure/tree/spsm/ted/data/impl/CTXMLTreeAccessor.java
+++ b/src/it/unitn/disi/smatch/matchers/structure/tree/spsm/ted/data/impl/CTXMLTreeAccessor.java
@@ -5,10 +5,16 @@ import it.unitn.disi.smatch.data.trees.IContext;
import it.unitn.disi.smatch.data.trees.INode;
import java.util.List;
-import java.util.Vector;
public class CTXMLTreeAccessor extends AbstractTreeAccessor {
+ //TODO try to understand Mikalai's code!
+
+ //TODO Juan, do we now need this? And is CTXML a good name for it?
+ //TODO Juan, please, check unused commented code, unnecessary casts,
+ //javadocs and comments, constants on the left in comparisons, etc
+ //TODO Juan, P.S. applies for other classes as well.
+ //TODO Juan, why fixed constant?
ITreeNode[] path = new ITreeNode[100];
IContext context = null;
@@ -18,15 +24,15 @@ public class CTXMLTreeAccessor extends AbstractTreeAccessor {
}
void addNode(INode node, int depth) {
-// TreePath toAdd = null;
- path[depth] = new TreeNode(node/*.getNodeName()*/, true);
+ path[depth] = new TreeNode(node, true);
if (depth > 0) {
path[depth - 1].add(path[depth]);
}
List<INode> children = node.getChildrenList();
if (children != null) {
- for (int i = 0; i < children.size(); i++) {
- INode child = (INode) children.get(i);
+
+ for (INode aChildren : children) {
+ INode child = aChildren;
addNode(child, depth + 1);
}
}
@@ -48,7 +54,7 @@ public class CTXMLTreeAccessor extends AbstractTreeAccessor {
* @return length of longest directed path
*/
public double getMaximumDirectedPathLength() {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
+ return 0; //TODO, check whether we actually need to compute this, if used somewhere else
}
/**
@@ -60,6 +66,6 @@ public class CTXMLTreeAccessor extends AbstractTreeAccessor {
* @return length of the shortest path
*/
public double getShortestPath(ITreeNode nodeA, ITreeNode nodeB) {
- return 0; //To change body of implemented methods use File | Settings | File Templates.
+ return 0; //TODO, check whether we actually need to compute this, if used somewhere else
}
} | still to be understand the work of Mikalai | opendatatrentino_s-match | train |
f84a4885ab4a3c30d4836d82937c7867d0b325ad | diff --git a/numina/array/stats.py b/numina/array/stats.py
index <HASH>..<HASH> 100644
--- a/numina/array/stats.py
+++ b/numina/array/stats.py
@@ -20,6 +20,7 @@
from __future__ import division
from __future__ import print_function
+import numpy
import numpy as np
@@ -42,16 +43,11 @@ def robust_std(x, debug=False):
Robust estimator of the standar deviation
"""
- # protections
- if type(x) is not np.ndarray:
- raise ValueError('x=' + str(x) + ' must be a numpy.ndarray')
-
- if x.ndim is not 1:
- raise ValueError('x.dim=' + str(x.ndim) + ' must be 1')
+ x = numpy.asarray(x)
# compute percentiles and robust estimator
- q25 = np.percentile(x, 25)
- q75 = np.percentile(x, 75)
+ q25 = numpy.percentile(x, 25)
+ q75 = numpy.percentile(x, 75)
sigmag = 0.7413 * (q75 - q25)
if debug:
diff --git a/numina/user/clidal.py b/numina/user/clidal.py
index <HASH>..<HASH> 100644
--- a/numina/user/clidal.py
+++ b/numina/user/clidal.py
@@ -72,6 +72,7 @@ class CommandLineDAL(AbsDAL):
this_drp = self.drps.query_by_name(obsres.instrument)
tagger = None
for mode in this_drp.modes:
+ print(mode.key, obsres.mode)
if mode.key == obsres.mode:
tagger = mode.tagger
break
diff --git a/numina/user/clirundal.py b/numina/user/clirundal.py
index <HASH>..<HASH> 100644
--- a/numina/user/clirundal.py
+++ b/numina/user/clirundal.py
@@ -144,7 +144,9 @@ def mode_run_common_obs(args, extra_args):
os.chdir(cwd)
- recipe = recipeclass()
+ # Enable intermediate results by default
+ _logger.debug('enable intermediate results')
+ recipe = recipeclass(intermediate_results=True)
_logger.debug('recipe created')
# Logging and task control | Make robust_std work with n-dimensional arrays | guaix-ucm_numina | train |
b1b727bb345a256a1edd2ca47edb23a7bfc74739 | diff --git a/php_fpm/test_php_fpm.py b/php_fpm/test_php_fpm.py
index <HASH>..<HASH> 100644
--- a/php_fpm/test_php_fpm.py
+++ b/php_fpm/test_php_fpm.py
@@ -101,6 +101,7 @@ class PHPFPMCheckTest(AgentCheckTest):
self.assertServiceCheck('php_fpm.can_ping', status=AgentCheck.OK,
count=1,
- tags=['ping_url:http://localhost:181/ping'])
+ tags=['ping_url:http://localhost:181/ping',
+ 'cluster:forums'])
self.assertMetric('php_fpm.processes.max_reached', count=1) | [phpfpm][test] fixing test. | DataDog_integrations-core | train |
94d0ced90193cd957ef0dcdafae2509100433e91 | diff --git a/dpark/rdd.py b/dpark/rdd.py
index <HASH>..<HASH> 100644
--- a/dpark/rdd.py
+++ b/dpark/rdd.py
@@ -151,7 +151,7 @@ class RDD(object):
return self.mapPartitions(lambda it: sorted(it, key=key, reverse=reverse))
if numSplits is None:
numSplits = min(self.ctx.defaultMinSplits, len(self))
- n = numSplits * 10 / len(self)
+ n = max(numSplits * 10 / len(self), 1)
samples = self.mapPartitions(lambda x:itertools.islice(x, n)).map(key).collect()
keys = sorted(samples, reverse=reverse)[5::10][:numSplits-1]
parter = RangePartitioner(keys, reverse=reverse) | Bugfix: Sampling error in `RDD.sort`.
If the length of rdd is big than `numSplits * <I>`,
the sample keys will be an empty list, so there will
be only one bin. | douban_dpark | train |
3a44f2a68a9925eb843dc60e734f450b7c49ee75 | diff --git a/core-bundle/src/Resources/contao/library/Contao/DcaExtractor.php b/core-bundle/src/Resources/contao/library/Contao/DcaExtractor.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/library/Contao/DcaExtractor.php
+++ b/core-bundle/src/Resources/contao/library/Contao/DcaExtractor.php
@@ -364,9 +364,12 @@ class DcaExtractor extends \Controller
{
foreach ($arrTable['TABLE_CREATE_DEFINITIONS'] as $strKey)
{
- $strKey = preg_replace('/^([A-Z]+ )?KEY .+\(`([^`]+)`\)$/', '$2 $1', $strKey);
- list($field, $type) = explode(' ', $strKey);
- $sql['keys'][$field] = ($type != '') ? strtolower($type) : 'index';
+ if(preg_match('/^([A-Z]+ )?KEY .+\(([^)]+)\)$/', $strKey, $arrMatches) && preg_match_all('/`([^`]+)`/', $arrMatches[2], $arrFields))
+ {
+ $type = trim($arrMatches[1]);
+ $field = implode(',', $arrFields[1]);
+ $sql['keys'][$field] = ($type != '') ? strtolower($type) : 'index';
+ }
}
}
} | [Core] fix handling of legacy database.sql multicolumn keys in dca extractor | contao_contao | train |
56f7acad7609152a90effee872aae60b5aae6b41 | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,6 +41,7 @@ This project adheres to [Semantic Versioning](https://semver.org).
* ``ID3v2GeneralEncapsulatedObject``.
* ``ID3v2PrivateInfo``.
* ``ID3v2UserURLLink``.
+* ``ID3v2UserText``.
### Changed
@@ -71,6 +72,12 @@ This project adheres to [Semantic Versioning](https://semver.org).
that contains a single user URL link object.
* Change ``ID3v2Frames`` to present a list of user URL link
objects for ``WXXX`` key.
+* Rework ID3v2 user text frame abstractions.
+ * Add ``ID3v2UserText`` class.
+ * Change ``ID3v2UserTextFrame`` to have only value attribute.
+ that contains a single user text object.
+ * Change ``ID3v2Frames`` to present a list of user text
+ objects for ``TXXX`` key.
### Removed
diff --git a/src/audio_metadata/formats/id3v2.py b/src/audio_metadata/formats/id3v2.py
index <HASH>..<HASH> 100644
--- a/src/audio_metadata/formats/id3v2.py
+++ b/src/audio_metadata/formats/id3v2.py
@@ -250,7 +250,7 @@ class ID3v2Frames(Tags):
f"Ignoring '{frame.id}' frame with value '{frame.value}'.\n"
f"'{frame.id}' is not supported in the ID3v2.{id3_version.value[1]} specification.\n"
),
- AudioMetadataWarning
+ AudioMetadataWarning,
)
continue
@@ -266,11 +266,6 @@ class ID3v2Frames(Tags):
frames[f'{frame.id}:{frame.description}:{frame.language}'].append(frame.value)
elif isinstance(
frame,
- ID3v2UserTextFrame,
- ):
- frames[f'{frame.id}:{frame.description}'].append(frame.value)
- elif isinstance(
- frame,
(
ID3v2GenreFrame,
ID3v2MappingListFrame,
diff --git a/src/audio_metadata/formats/id3v2_frames.py b/src/audio_metadata/formats/id3v2_frames.py
index <HASH>..<HASH> 100644
--- a/src/audio_metadata/formats/id3v2_frames.py
+++ b/src/audio_metadata/formats/id3v2_frames.py
@@ -23,6 +23,7 @@ __all__ = [
'ID3v2TimestampFrame',
'ID3v2UnsynchronizedLyricsFrame',
'ID3v2URLLinkFrame',
+ 'ID3v2UserText',
'ID3v2UserTextFrame',
'ID3v2UserURLLink',
'ID3v2UserURLLinkFrame',
@@ -115,6 +116,15 @@ class ID3v2PrivateInfo(AttrMapping):
repr=False,
kw_only=True,
)
+class ID3v2UserText(AttrMapping):
+ description = attrib()
+ text = attrib()
+
+
+@attrs(
+ repr=False,
+ kw_only=True,
+)
class ID3v2UserURLLink(AttrMapping):
description = attrib()
url = attrib()
@@ -319,7 +329,6 @@ class ID3v2UserURLLinkFrame(ID3v2BaseFrame):
kw_only=True,
)
class ID3v2UserTextFrame(ID3v2BaseFrame):
- description = attrib()
value = attrib()
@@ -711,6 +720,14 @@ class ID3v2Frame(ID3v2BaseFrame):
kwargs['value'] = decode_bytestring(description, encoding)
elif frame_type is ID3v2URLLinkFrame:
kwargs['value'] = unquote(decode_bytestring(frame_data))
+ elif frame_type is ID3v2UserTextFrame:
+ encoding = determine_encoding(frame_data)
+
+ description, text = split_encoded(frame_data[1:], encoding)
+ kwargs['value'] = ID3v2UserText(
+ description=decode_bytestring(description, encoding),
+ text=decode_bytestring(text, encoding),
+ )
elif frame_type is ID3v2UserURLLinkFrame:
encoding = determine_encoding(frame_data)
@@ -719,13 +736,7 @@ class ID3v2Frame(ID3v2BaseFrame):
description=decode_bytestring(description, encoding),
url=unquote(decode_bytestring(url)),
)
- elif issubclass(
- frame_type,
- (
- ID3v2NumberFrame,
- ID3v2UserTextFrame,
- ),
- ):
+ elif issubclass(frame_type, ID3v2NumberFrame):
encoding = determine_encoding(frame_data[0:1])
kwargs['value'] = decode_bytestring(frame_data[1:], encoding)
elif issubclass( | Rework ID3v2 user text frame abstractions [#<I>]
* Add ``ID3v2UserText`` class.
* Change ``ID3v2UserTextFrame`` to have only value attribute.
that contains a single user text object.
* Change ``ID3v2Frames`` to present a list of user text
objects for ``TXXX`` key. | thebigmunch_audio-metadata | train |
b9166512f18155e77ad468e3693d16fae7461a89 | diff --git a/lib/chiketto/user.rb b/lib/chiketto/user.rb
index <HASH>..<HASH> 100644
--- a/lib/chiketto/user.rb
+++ b/lib/chiketto/user.rb
@@ -16,5 +16,16 @@ module Chiketto
def emails
@emails.map { |email| Chiketto::Email.new email }
end
+
+ def events(params = {})
+ events = Chiketto::User.find_events @id, params
+ events['events'].map { |e| Chiketto::Event.new e }
+ end
+
+ private
+
+ def self.find_events(id, params)
+ get "users/#{id}/owned_events", params
+ end
end
end
diff --git a/lib/chiketto/version.rb b/lib/chiketto/version.rb
index <HASH>..<HASH> 100644
--- a/lib/chiketto/version.rb
+++ b/lib/chiketto/version.rb
@@ -1,3 +1,3 @@
module Chiketto
- VERSION = "0.0.8"
+ VERSION = "0.0.9"
end
diff --git a/test/user_test.rb b/test/user_test.rb
index <HASH>..<HASH> 100644
--- a/test/user_test.rb
+++ b/test/user_test.rb
@@ -40,4 +40,12 @@ class UserTest < MiniTest::Test
find_me
assert_kind_of Chiketto::Email, @user.email
end
+
+ def test_user_has_events
+ find_me
+
+ VCR.use_cassette 'user-events' do
+ assert_kind_of Chiketto::Event, @user.events.first
+ end
+ end
end | Add #events method onto User to return all owned events | chrisradford_chiketto | train |
6e56ad2040b20b5a3b62e0f16ae72be7743d667e | diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index <HASH>..<HASH> 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -1718,6 +1718,11 @@ class Cmd(cmd.Cmd):
try:
# Get sigint protection while we set up redirection
with self.sigint_protection:
+ if self._in_py:
+ # Start saving the command's output at this point to match what redirection captures
+ self.stdout.pause_storage = False
+ sys.stderr.pause_storage = False
+
redir_error, saved_state = self._redirect_output(statement)
self.cur_pipe_proc_reader = saved_state.pipe_proc_reader
@@ -1763,6 +1768,11 @@ class Cmd(cmd.Cmd):
if not already_redirecting:
self.redirecting = False
+ if self._in_py:
+ # Stop saving command's output before command finalization hooks run
+ self.stdout.pause_storage = True
+ sys.stderr.pause_storage = True
+
except EmptyStatement:
# don't do anything, but do allow command finalization hooks to run
pass
@@ -3026,7 +3036,6 @@ class Cmd(cmd.Cmd):
if self._in_py:
err = "Recursively entering interactive Python consoles is not allowed."
self.perror(err, traceback_war=False)
- self._last_result = CommandResult('', err)
return False
try:
diff --git a/cmd2/pyscript_bridge.py b/cmd2/pyscript_bridge.py
index <HASH>..<HASH> 100644
--- a/cmd2/pyscript_bridge.py
+++ b/cmd2/pyscript_bridge.py
@@ -92,6 +92,10 @@ class PyscriptBridge(object):
# This will be used to capture sys.stderr
copy_stderr = StdSim(sys.stderr, echo)
+ # Pause the storing of any output until onecmd_plus_hooks enables it
+ copy_cmd_stdout.pause_storage = True
+ copy_stderr.pause_storage = True
+
self._cmd2_app._last_result = None
try:
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index <HASH>..<HASH> 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -268,9 +268,8 @@ def test_recursive_pyscript_not_allowed(base_app, request):
python_script = os.path.join(test_dir, 'scripts', 'recursive.py')
expected = 'Recursively entering interactive Python consoles is not allowed.'
- run_cmd(base_app, "pyscript {}".format(python_script))
- err = base_app._last_result.stderr
- assert err == expected
+ out, err = run_cmd(base_app, "pyscript {}".format(python_script))
+ assert err[0] == expected
def test_pyscript_with_nonexist_file(base_app):
python_script = 'does_not_exist.py' | Pyscript now saves command output during the same period that redirection does | python-cmd2_cmd2 | train |
67d90150302114a9d0c41a42f35aa1feb84b4f94 | diff --git a/Model/Service/ApiHandlerService.php b/Model/Service/ApiHandlerService.php
index <HASH>..<HASH> 100644
--- a/Model/Service/ApiHandlerService.php
+++ b/Model/Service/ApiHandlerService.php
@@ -180,19 +180,19 @@ class ApiHandlerService
// Get the billing address
$billingAddress = $entity->getBillingAddress();
+ // Create the address
+ $address = new Address();
+ $address->address_line1 = $billingAddress->getStreetLine(1);
+ $address->address_line2 = $billingAddress->getStreetLine(2);
+ $address->city = $billingAddress->getCity();
+ $address->zip = $billingAddress->getPostcode();
+ $address->country = $billingAddress->getCountry();
+
// Create the customer
$customer = new Customer();
$customer->email = $billingAddress->getEmail();
$customer->name = $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname();
-
- // Create the address
- $address = new Address();
- $address->address_line1 = '14-17 Wells Mews';
- $address->address_line2 = 'Fitzrovia';
- $address->city = 'London';
- $address->state = 'London';
- $address->zip = 'W1T 3HF';
- $address->country = 'UK';
+ $customer->address = $address;
return $customer;
} catch (\Exception $e) { | Implemented the API Handler billing address logic | checkout_checkout-magento2-plugin | train |
8ba0615cc781e40391b946dea8c80abd096788f7 | diff --git a/tasks/download.js b/tasks/download.js
index <HASH>..<HASH> 100644
--- a/tasks/download.js
+++ b/tasks/download.js
@@ -112,7 +112,7 @@ module.exports = function(grunt) {
* Deletes the downloaded zip & temporary directory.
*/
var cleanUp = function () {
- fs.rmdir(options.tempDir);
+ grunt.file.delete(options.tempDir, { force: true });
fs.exists(options.downloadDestination, function (exists) {
if (exists) { | Fix issue with deleting non-empty temp directory | moov2_grunt-orchard-development | train |
b2111b9306e75623eebe607bf8decc571b683a6f | diff --git a/examples/wordcount/index.js b/examples/wordcount/index.js
index <HASH>..<HASH> 100644
--- a/examples/wordcount/index.js
+++ b/examples/wordcount/index.js
@@ -27,7 +27,7 @@ app.get('/doWordCount', function (req, res) {
if (err) {
res.status(500).send({error: err.msg});
} else {
- res.json(result);
+ res.json({result: result});
}
});
});
diff --git a/lib/kernel.js b/lib/kernel.js
index <HASH>..<HASH> 100644
--- a/lib/kernel.js
+++ b/lib/kernel.js
@@ -148,7 +148,7 @@ Kernel.createKernelSession = function(jobName) {
baseUrl: "http://" + hostURL,
wsUrl: "ws://" + hostURL,
kernelName: "eclair",
- notebookPath: jobName
+ path: jobName
}).then(function(session) {
//when we have kernel info we know the spark kernel is ready.
session.kernel.kernelInfo().then(function(info) {
@@ -158,11 +158,11 @@ Kernel.createKernelSession = function(jobName) {
resolve(session);
});
}).catch(function(e) {
- Utils.error('Failed to start Jupyter session', e);
+ console.error('Failed to start Jupyter session', e);
reject(err);
});
}).catch(function(e) {
- Utils.error('Failed to connect to Jupyter instance', e);
+ console.error('Failed to connect to Jupyter instance', e);
reject(e);
})
});
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -9,10 +9,10 @@
"url": "git://github.com/EclairJS/eclairjs-node.git"
},
"dependencies": {
- "jupyter-js-services": "^0.10",
+ "jupyter-js-services": "^0.16.3",
"request": "2.67.x",
- "ws": "^0.8.0",
- "xmlhttprequest": "^1.8.0"
+ "xmlhttprequest": "^1.8.0",
+ "ws": "^1.1.1"
},
"devDependencies": {
"chai": "3.4.x", | Update dependencies to latest version, also make sure we always output an visible error if we can't connect to jupyter | EclairJS_eclairjs | train |
d45e0f444dfcd600ba0d73e4d8431d8bbf9c098c | diff --git a/features/step_definitions/renalware/peritonitis_episodes_steps.rb b/features/step_definitions/renalware/peritonitis_episodes_steps.rb
index <HASH>..<HASH> 100644
--- a/features/step_definitions/renalware/peritonitis_episodes_steps.rb
+++ b/features/step_definitions/renalware/peritonitis_episodes_steps.rb
@@ -82,3 +82,10 @@ Then(/^Clyde can revise the peritonitis episode$/) do
expect_peritonitis_episodes_revisions_recorded(patient: @patty)
end
+
+Then(/^Clyde can terminate the organism for the episode$/) do
+ terminate_organism_for(
+ infectable: @patty.peritonitis_episodes.last!,
+ user: @clyde
+ )
+end | Implement step for terminating an organism associated with an episode | airslie_renalware-core | train |
349e4a614f571aa79a266acf4d283d07daa67522 | diff --git a/addon/models/user.js b/addon/models/user.js
index <HASH>..<HASH> 100644
--- a/addon/models/user.js
+++ b/addon/models/user.js
@@ -39,5 +39,15 @@ export default OsfModel.extend({
// Calculated fields
profileURL: Ember.computed.alias('links.html'),
- profileImage: Ember.computed.alias('links.profile_image')
+ profileImage: Ember.computed.alias('links.profile_image'),
+ name: Ember.computed('fullname', 'giveName', 'familyName', function () {
+ let fullName = this.get('fullName');
+ let givenName = this.get('givenName');
+ let familyName = this.get('familyName');
+ if (givenName && familyName){
+ return `${givenName} ${familyName}`;
+ } else {
+ return fullName;
+ }
+ }),
});
diff --git a/tests/unit/models/user-test.js b/tests/unit/models/user-test.js
index <HASH>..<HASH> 100644
--- a/tests/unit/models/user-test.js
+++ b/tests/unit/models/user-test.js
@@ -105,3 +105,35 @@ test('institutions relationship', function(assert) {
assert.equal(relationship.type, 'institution');
assert.equal(relationship.kind, 'hasMany');
});
+
+test('name computed correctly: givenName, familyName and fullName are defined', function (assert) {
+ let mitsuha = this.subject({
+ givenName: 'Mitsuha',
+ familyName: 'Miyamizu',
+ fullName: 'Mitsuha Miyamizu of Itomori'
+ });
+ assert.equal(mitsuha.get('name'), 'Mitsuha Miyamizu');
+});
+
+test('name computed correctly: only givenName and fullName are defined', function (assert) {
+ let mitsuha = this.subject({
+ givenName: 'Mitsuha',
+ fullName: 'Mitsuha Miyamizu of Itomori'
+ });
+ assert.equal(mitsuha.get('name'), 'Mitsuha Miyamizu of Itomori');
+});
+
+test('name computed correctly: only familyName and fullName are defined', function (assert) {
+ let mitsuha = this.subject({
+ familyName: 'Miyamizu',
+ fullName: 'Mitsuha Miyamizu of Itomori'
+ });
+ assert.equal(mitsuha.get('name'), 'Mitsuha Miyamizu of Itomori');
+});
+
+test('name computed correctly: only fullName is defined', function (assert) {
+ let mitsuha = this.subject({
+ fullName: 'Mitsuha Miyamizu of Itomori'
+ });
+ assert.equal(mitsuha.get('name'), 'Mitsuha Miyamizu of Itomori');
+}); | add computed field to user model; add tests | CenterForOpenScience_ember-osf | train |
c4226167d53d1955a286256283debcac3d43fd29 | diff --git a/Gemfile.lock b/Gemfile.lock
index <HASH>..<HASH> 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
- zencodable (0.1.2)
+ zencodable (0.1.3)
aws-s3
rails (~> 3.1.0)
typhoeus
diff --git a/lib/generators/zencodable/templates/zencodable_add_tracking_columns_and_tables.rb b/lib/generators/zencodable/templates/zencodable_add_tracking_columns_and_tables.rb
index <HASH>..<HASH> 100644
--- a/lib/generators/zencodable/templates/zencodable_add_tracking_columns_and_tables.rb
+++ b/lib/generators/zencodable/templates/zencodable_add_tracking_columns_and_tables.rb
@@ -1,6 +1,7 @@
class ZencodableAddTrackingColumnsAndTables < ActiveRecord::Migration
def change
add_column :<%= name.tableize %>, :origin_url, :string
+ add_column :<%= name.tableize %>, :zencoder_job_id, :string
add_column :<%= name.tableize %>, :zencoder_job_status, :string
add_column :<%= name.tableize %>, :zencoder_job_created, :datetime
add_column :<%= name.tableize %>, :zencoder_job_finished, :datetime
diff --git a/lib/zencodable/version.rb b/lib/zencodable/version.rb
index <HASH>..<HASH> 100644
--- a/lib/zencodable/version.rb
+++ b/lib/zencodable/version.rb
@@ -1,3 +1,3 @@
module Zencodable
- VERSION = "0.1.3"
+ VERSION = "0.1.4"
end
diff --git a/test/zencodable_generators_test.rb b/test/zencodable_generators_test.rb
index <HASH>..<HASH> 100644
--- a/test/zencodable_generators_test.rb
+++ b/test/zencodable_generators_test.rb
@@ -18,6 +18,7 @@ class ZencodableGeneratorTest < Rails::Generators::TestCase
assert_match /t\.integer\s+\"kitteh_movie_id\"/, migration
assert_match /add_column :kitteh_movies, :origin_url, :string/, migration
+ assert_match /add_column :kitteh_movies, :zencoder_job_id, :string/, migration
assert_match /add_column :kitteh_movies, :zencoder_job_status, :string/, migration
assert_match /add_column :kitteh_movies, :zencoder_job_created, :datetime/, migration
assert_match /add_column :kitteh_movies, :zencoder_job_finished, :datetime/, migration | add important zencoder_job_id column to migration | sbeam_zencodable | train |
52e251db17fed1326114e904048c645802f01b6c | diff --git a/torext/handlers/base.py b/torext/handlers/base.py
index <HASH>..<HASH> 100644
--- a/torext/handlers/base.py
+++ b/torext/handlers/base.py
@@ -181,9 +181,9 @@ class BaseHandler(tornado.web.RequestHandler):
chunk could be any type of (str, dict, list)
"""
assert chunk is not None, 'None cound not be written in write_json'
+ self.set_header("Content-Type", "application/json; charset=UTF-8")
if isinstance(chunk, dict) or isinstance(chunk, list):
chunk = self.json_encode(chunk)
- self.set_header("Content-Type", "application/json; charset=UTF-8")
# convert chunk to utf8 before `RequestHandler.write()`
# so that if any error occurs, we can catch and log it | fix json header unset in write_json when chunk is str | reorx_torext | train |
69e4dc7c9f3515b908a445be5dd102e1eb7dd9a1 | diff --git a/cellbase-build/src/main/java/org/opencb/cellbase/build/transform/VariationParser.java b/cellbase-build/src/main/java/org/opencb/cellbase/build/transform/VariationParser.java
index <HASH>..<HASH> 100644
--- a/cellbase-build/src/main/java/org/opencb/cellbase/build/transform/VariationParser.java
+++ b/cellbase-build/src/main/java/org/opencb/cellbase/build/transform/VariationParser.java
@@ -146,7 +146,7 @@ public class VariationParser extends CellBaseParser {
// Preparing displayConsequenceType and consequenceTypes attributes
consequenceTypes = (variationFeatureFields != null) ? Arrays.asList(variationFeatureFields[12].split(",")): Arrays.asList("intergenic_variant");
- if(consequenceTypes.size() == 0) {
+ if(consequenceTypes.size() == 1) {
displayConsequenceType = consequenceTypes.get(0);
}else {
for(String cons: consequenceTypes) { | Fixed bug in Variation Parser: when variation has only one consequence type that is 'intergenic_variant' displayConsequenceType is not set | opencb_cellbase | train |
463eb0eac711629c3d83e51ff3a222dac8f956c2 | diff --git a/lib/plugin/components/services/storage/Memory-model.js b/lib/plugin/components/services/storage/Memory-model.js
index <HASH>..<HASH> 100644
--- a/lib/plugin/components/services/storage/Memory-model.js
+++ b/lib/plugin/components/services/storage/Memory-model.js
@@ -138,7 +138,7 @@ class MemoryModel {
options.where,
function (condition, propertyId) {
const conditionType = _.keys(condition)[0]
- const expression = _.values(condition)[0]
+ let expression = _.values(condition)[0]
switch (conditionType) {
case 'equals':
@@ -166,6 +166,11 @@ class MemoryModel {
matches = false
}
break
+ case 'like':
+ if (!(row[propertyId].includes(expression))) {
+ matches = false
+ }
+ break
}
}
)
diff --git a/test/memory-model-spec.js b/test/memory-model-spec.js
index <HASH>..<HASH> 100644
--- a/test/memory-model-spec.js
+++ b/test/memory-model-spec.js
@@ -53,9 +53,9 @@ describe('Memory Model tests', function () {
expect(idProperties).to.eql(
{
idProperties:
- {
- employeeNo: 1
- }
+ {
+ employeeNo: 1
+ }
}
)
done()
@@ -158,7 +158,7 @@ describe('Memory Model tests', function () {
)
})
- it("should fail finding a person that's not there", function (done) {
+ it('should fail finding a person that\'s not there', function (done) {
personModel.findById(
6,
function (err, doc) {
@@ -171,7 +171,7 @@ describe('Memory Model tests', function () {
it('should find 5 people', function (done) {
personModel.find(
- { },
+ {},
function (err, doc) {
expect(err).to.equal(null)
@@ -240,6 +240,32 @@ describe('Memory Model tests', function () {
)
})
+ it('should find Bart by part of his name', function (done) {
+ personModel.find(
+ {
+ where: {
+ firstName: {like: 'art'}
+ }
+ },
+ function (err, doc) {
+ expect(err).to.equal(null)
+ expect(doc).to.have.length(1)
+ expect(doc).to.containSubset(
+ [
+ {
+ 'age': 10,
+ 'employeeNo': 5,
+ 'firstName': 'Bart',
+ 'lastName': 'Simpson'
+ }
+ ]
+ )
+
+ done()
+ }
+ )
+ })
+
it('should get one Homer by name', function (done) {
personModel.findOne(
{
@@ -264,7 +290,7 @@ describe('Memory Model tests', function () {
)
})
- it("shouldn't get one missing person", function (done) {
+ it('shouldn\'t get one missing person', function (done) {
personModel.findOne(
{
where: {
@@ -280,7 +306,7 @@ describe('Memory Model tests', function () {
)
})
- it("should update Maggie's age to 1", (done) => {
+ it('should update Maggie\'s age to 1', (done) => {
personModel.update(
{
employeeNo: 2,
@@ -329,7 +355,7 @@ describe('Memory Model tests', function () {
)
})
- it("should find Maggie's age has gone again", function (done) {
+ it('should find Maggie\'s age has gone again', function (done) {
personModel.findById(
2,
function (err, doc) { | added 'like' comparator for the where clause so we can find date times on a date for max capacity checking | wmfs_tymly-core | train |
cdfb510e0225c53f773cd85a2dfee803a5926b94 | diff --git a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java
index <HASH>..<HASH> 100644
--- a/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java
+++ b/common/test/unit/com/thoughtworks/go/domain/PipelineLabelTest.java
@@ -19,6 +19,7 @@ package com.thoughtworks.go.domain;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.materials.ScmMaterial;
import com.thoughtworks.go.config.materials.mercurial.HgMaterial;
+import com.thoughtworks.go.config.materials.svn.SvnMaterial;
import com.thoughtworks.go.domain.label.PipelineLabel;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.helper.MaterialsMother;
@@ -221,7 +222,7 @@ public class PipelineLabelTest {
public void canMatchWithOneTruncationAsFirstRevision() throws Exception {
final String[][] expectedGroups = { {"git", "4"}, { "svn" } };
String res = assertLabelGroupsMatchingAndReplace("release-${git[:4]}-${svn}", expectedGroups);
- assertThat(res, is("release-" + GIT_REVISION.substring(0, 4) + "-" + SVN_REVISION));
+ assertThat(res, is("release-" + GIT_REVISION.substring(0, 4) + "-" + SVN_REVISION));
}
@Test
@@ -231,6 +232,21 @@ public class PipelineLabelTest {
assertThat(res, is("release-" + GIT_REVISION.substring(0, 5) + "-" + SVN_REVISION.substring(0, 3)));
}
+ @Test
+ public void shouldReplaceTheTemplateWithSpecialCharacters() throws Exception {
+ ensureLabelIsReplaced("SVNMaterial");
+ ensureLabelIsReplaced("SVN-Material");
+ ensureLabelIsReplaced("SVN_Material");
+ ensureLabelIsReplaced("SVN!Material");
+ ensureLabelIsReplaced("SVN*MATERIAL");
+ ensureLabelIsReplaced("SVN**__##Material_1023_WithNumbers");
+ ensureLabelIsReplaced("SVN_Material-_!!_**");
+ ensureLabelIsReplaced("svn_Material'WithQuote");
+
+ ensureLabelIsNOTReplaced("SVN+Material");
+ ensureLabelIsNOTReplaced("SVN^Material");
+ }
+
@BeforeClass
public static void setup() {
MATERIAL_REVISIONS.put(new CaseInsensitiveString("svnRepo.verynice"), SVN_REVISION);
@@ -285,4 +301,23 @@ public class PipelineLabelTest {
}
return builder.toString();
}
+
+ private void ensureLabelIsReplaced(String name) {
+ PipelineLabel label = getReplacedLabelFor(name, String.format("release-${%s}", name));
+ assertThat(label.toString(), is("release-" + ModificationsMother.currentRevision()));
+ }
+
+ private void ensureLabelIsNOTReplaced(String name) {
+ String labelFormat = String.format("release-${%s}", name);
+ PipelineLabel label = getReplacedLabelFor(name, labelFormat);
+ assertThat(label.toString(), is(labelFormat));
+ }
+
+ private PipelineLabel getReplacedLabelFor(String name, String labelFormat) {
+ MaterialRevisions materialRevisions = ModificationsMother.oneUserOneFile();
+ PipelineLabel label = PipelineLabel.create(labelFormat);
+ ((SvnMaterial) materialRevisions.getRevisions().get(0).getMaterial()).setName(new CaseInsensitiveString(name));
+ label.updateLabel(materialRevisions.getNamedRevisions());
+ return label;
+ }
}
diff --git a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java
index <HASH>..<HASH> 100644
--- a/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java
+++ b/config/config-api/src/com/thoughtworks/go/domain/label/PipelineLabel.java
@@ -42,7 +42,7 @@ public class PipelineLabel implements Serializable {
return label;
}
- public static final Pattern PATTERN = Pattern.compile("(?i)\\$\\{([\\w\\.]+)(\\[:(\\d+)\\])?\\}");
+ public static final Pattern PATTERN = Pattern.compile("(?i)\\$\\{([a-zA-Z0-9_\\-\\.!~*'()#]+)(\\[:(\\d+)\\])?\\}");
private String replaceRevisionsInLabel(Map<CaseInsensitiveString, String> materialRevisions) {
final Matcher matcher = PATTERN.matcher(this.label); | #<I> - Allow special chars is pipeline label format.
Use parts of the regex from the XSD, when replacing the variables in the label,
so that special characters can be used. | gocd_gocd | train |
feeaac41b60172495adb7d60779ff0f1330dfa6f | diff --git a/lib/formatters/codeclimate.js b/lib/formatters/codeclimate.js
index <HASH>..<HASH> 100644
--- a/lib/formatters/codeclimate.js
+++ b/lib/formatters/codeclimate.js
@@ -17,6 +17,7 @@ module.exports = function (err, data) {
check_name: 'Vulnerable module "' + data[i].module + '" identified',
description: '`' + data[i].module + '` ' + data[i].title,
categories: ['Security'],
+ remediation_points: 300000,
content: {
body: data[i].content
}, | Add Remediation Points to issues | nodesecurity_nsp | train |
fd0797d766b1933ade4b9f6c12c341ddc9c9f95f | diff --git a/test/cri-containerd/main.go b/test/cri-containerd/main.go
index <HASH>..<HASH> 100644
--- a/test/cri-containerd/main.go
+++ b/test/cri-containerd/main.go
@@ -37,6 +37,8 @@ const (
imageLcowAlpine = "docker.io/library/alpine:latest"
imageLcowCosmos = "cosmosarno/spark-master:2.4.1_2019-04-18_8e864ce"
testGPUBootFiles = "C:\\ContainerPlat\\LinuxBootFiles\\nvidiagpu"
+ alpineAspNet = "mcr.microsoft.com/dotnet/core/aspnet:3.1-alpine3.11"
+ alpineAspnetUpgrade = "mcr.microsoft.com/dotnet/core/aspnet:3.1.2-alpine3.11"
)
var (
diff --git a/test/cri-containerd/stopcontainer_test.go b/test/cri-containerd/stopcontainer_test.go
index <HASH>..<HASH> 100644
--- a/test/cri-containerd/stopcontainer_test.go
+++ b/test/cri-containerd/stopcontainer_test.go
@@ -148,3 +148,48 @@ func Test_StopContainer_WithExec_LCOW(t *testing.T) {
Stdout: true,
})
}
+
+func Test_StopContainer_ReusePod_LCOW(t *testing.T) {
+ pullRequiredLcowImages(t, []string{alpineAspNet, alpineAspnetUpgrade})
+
+ client := newTestRuntimeClient(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ sandboxRequest := &runtime.RunPodSandboxRequest{
+ Config: &runtime.PodSandboxConfig{
+ Metadata: &runtime.PodSandboxMetadata{
+ Name: t.Name() + "-Sandbox",
+ Namespace: testNamespace,
+ },
+ },
+ RuntimeHandler: lcowRuntimeHandler,
+ }
+
+ podID := runPodSandbox(t, client, ctx, sandboxRequest)
+ defer removePodSandbox(t, client, ctx, podID)
+ defer stopPodSandbox(t, client, ctx, podID)
+
+ request := &runtime.CreateContainerRequest{
+ PodSandboxId: podID,
+ Config: &runtime.ContainerConfig{
+ Metadata: &runtime.ContainerMetadata{
+ Name: t.Name() + "-Container",
+ },
+ Image: &runtime.ImageSpec{
+ Image: alpineAspNet,
+ },
+ Command: []string{
+ "top",
+ },
+ },
+ SandboxConfig: sandboxRequest.Config,
+ }
+
+ containerID := createContainer(t, client, ctx, request)
+ runContainerLifetime(t, client, ctx, containerID)
+
+ request.Config.Image.Image = alpineAspnetUpgrade
+ containerID = createContainer(t, client, ctx, request)
+ runContainerLifetime(t, client, ctx, containerID)
+} | Test for starting/stopping container and reusing pod
* The test case covers starting and stopping two containers in the same pod. | Microsoft_hcsshim | train |
dc6f115383c4bdc0b7867062dc91191834a41df3 | diff --git a/test/helpers/bitcoin.rb b/test/helpers/bitcoin.rb
index <HASH>..<HASH> 100644
--- a/test/helpers/bitcoin.rb
+++ b/test/helpers/bitcoin.rb
@@ -8,7 +8,7 @@ module BitVaultTests
def keypair
@keypair ||= begin
- key = Bitcoin::Key.new
+ key = ::Bitcoin::Key.new
key.generate
key
end | fixed constant resolution problem in test helper | GemHQ_round-rb | train |
95db2bb6025918cfa24308c39dbc92326da436f9 | diff --git a/gami.go b/gami.go
index <HASH>..<HASH> 100644
--- a/gami.go
+++ b/gami.go
@@ -6,6 +6,8 @@ import (
"errors"
"net/textproto"
"strings"
+ "net"
+ "time"
)
var errInvalidLogin error = errors.New("InvalidLogin AMI Interface")
@@ -14,10 +16,22 @@ var errNotAMI error = errors.New("Server not AMI interface")
type AMIClient struct {
conn *textproto.Conn
+ conn_raw *net.Conn
+
+ address string
+ amiUser string
+ amiPass string
+
+ //Timeout on read
+ ReadTimeout time.Duration
response chan *AMIResponse
+ //Events for client parse
Events chan *AMIEvent
+
+ //Raise error
+ Error chan error
}
type AMIResponse struct {
@@ -46,6 +60,26 @@ func (client *AMIClient) Login(username, password string) error {
if (*response).Status == "Error" {
return errors.New((*response).Params["Message"])
}
+
+ client.amiUser = username
+ client.amiPass = password
+ return nil
+}
+
+//Reconnect the session, autologin
+func (client *AMIClient) Reconnect() error {
+ client.conn.Close()
+
+ reconnect, err := Dial(client.address)
+ if err != nil {
+ return err
+ }
+ if err := reconnect.Login(client.amiUser, client.amiPass); err != nil {
+ return err
+ }
+
+ client.conn = reconnect.conn
+ client.conn_raw = reconnect.conn_raw
return nil
}
@@ -55,13 +89,14 @@ func (client *AMIClient) Action(action string, params map[string]string) (*AMIRe
if err := client.conn.PrintfLine("Action: %s", strings.TrimSpace(action)); err != nil {
return nil, err
-
}
+
for k, v := range params {
if err := client.conn.PrintfLine("%s: %s", k, strings.TrimSpace(v)); err != nil {
return nil, err
}
}
+
if err := client.conn.PrintfLine(""); err != nil {
return nil, err
}
@@ -76,12 +111,20 @@ func (client *AMIClient) run() {
go func() {
for {
+ if client.ReadTimeout > 0 {
+ //close the connection if not read something
+ (*client.conn_raw).SetReadDeadline(time.Now().Add(client.ReadTimeout))
+ }
+
+ data, err := client.conn.ReadMIMEHeader()
- data, _ := client.conn.ReadMIMEHeader()
+ if err != nil {
+ client.Error <- err
+ continue
+ }
if ev, err := newEvent(&data); err == nil {
client.Events <- ev
-
}
if response, err := newResponse(&data); err == nil {
client.response <- response
@@ -125,17 +168,31 @@ func newEvent(data *textproto.MIMEHeader) (*AMIEvent, error) {
}
func Dial(address string) (*AMIClient, error) {
- conn, err := textproto.Dial("tcp", address)
+ conn_raw, err := net.Dial("tcp", address)
+
if err != nil {
return nil, err
}
-
- label, _ := conn.ReadLine()
+ conn := textproto.NewConn(conn_raw)
+ label, err := conn.ReadLine()
+ if err != nil {
+ return nil, err
+ }
+
if strings.Contains(label, "Asterisk Call Manager") != true {
return nil, errNotAMI
}
- client := &AMIClient{conn, make(chan *AMIResponse), make(chan *AMIEvent, 100)}
+ client := &AMIClient{
+ conn: conn,
+ conn_raw: &conn_raw,
+ address: address,
+ amiUser: "",
+ amiPass: "",
+ response: make(chan *AMIResponse),
+ ReadTimeout: 0,
+ Events: make(chan *AMIEvent, 100),
+ Error: make(chan error)}
client.run()
return client, nil
} | client have ReadTimeout for closing connection, and chan Error for parsing errors raise on network connections | bit4bit_gami | train |
ba1ee6855d904aaf734ab9804da91acceadd7a28 | diff --git a/daemon/endpoint.go b/daemon/endpoint.go
index <HASH>..<HASH> 100644
--- a/daemon/endpoint.go
+++ b/daemon/endpoint.go
@@ -276,15 +276,10 @@ func (h *putEndpointID) Handle(params PutEndpointIDParams) middleware.Responder
if err := e.RLockAlive(); err != nil {
return api.Error(PutEndpointIDFailedCode, fmt.Errorf("error locking endpoint: %s", err.Error()))
}
- epState := e.GetStateLocked()
hasSidecarProxy := e.HasSidecarProxy()
e.RUnlock()
- if epState == endpoint.StateDisconnected || epState == endpoint.StateDisconnecting {
- // Short circuit in case a call to delete the endpoint is
- // made while we are waiting.
- return api.Error(PutEndpointIDFailedCode, fmt.Errorf("endpoint %d went into state %s while waiting for regeneration to succeed", e.ID, epState))
- } else if hasSidecarProxy {
+ if hasSidecarProxy {
// If the endpoint is determined to have a sidecar proxy,
// return immediately to let the sidecar container start,
// in case it is required to enforce L7 rules. | daemon: Remove the explicit state check in sync endpoint create
The recently added call to e.RLockAlive was already checking whether
the endpoint is disconnecting. Remove the explicit state check,
which was now dead code. | cilium_cilium | train |
5544b922ba2aad38b2bd0c35d6d5de494146918b | diff --git a/src/client/pps.go b/src/client/pps.go
index <HASH>..<HASH> 100644
--- a/src/client/pps.go
+++ b/src/client/pps.go
@@ -553,6 +553,20 @@ func (c APIClient) ListPipeline() ([]*pps.PipelineInfo, error) {
return pipelineInfos.PipelineInfo, nil
}
+// ListPipelineHistory returns historical information about pipelines.
+func (c APIClient) ListPipelineHistory(history int64) ([]*pps.PipelineInfo, error) {
+ pipelineInfos, err := c.PpsAPIClient.ListPipeline(
+ c.Ctx(),
+ &pps.ListPipelineRequest{
+ History: history,
+ },
+ )
+ if err != nil {
+ return nil, grpcutil.ScrubGRPC(err)
+ }
+ return pipelineInfos.PipelineInfo, nil
+}
+
// DeletePipeline deletes a pipeline along with its output Repo.
func (c APIClient) DeletePipeline(name string, force bool) error {
_, err := c.PpsAPIClient.DeletePipeline(
diff --git a/src/server/pps/cmds/cmds.go b/src/server/pps/cmds/cmds.go
index <HASH>..<HASH> 100644
--- a/src/server/pps/cmds/cmds.go
+++ b/src/server/pps/cmds/cmds.go
@@ -596,6 +596,7 @@ All jobs created by a pipeline will create commits in the pipeline's output repo
commands = append(commands, cmdutil.CreateAlias(editPipeline, "edit pipeline"))
var spec bool
+ var history int64
listPipeline := &cobra.Command{
Short: "Return info about all pipelines.",
Long: "Return info about all pipelines.",
@@ -605,7 +606,7 @@ All jobs created by a pipeline will create commits in the pipeline's output repo
return fmt.Errorf("error connecting to pachd: %v", err)
}
defer client.Close()
- pipelineInfos, err := client.ListPipeline()
+ pipelineInfos, err := client.ListPipelineHistory(history)
if err != nil {
return err
}
@@ -635,6 +636,7 @@ All jobs created by a pipeline will create commits in the pipeline's output repo
listPipeline.Flags().BoolVarP(&spec, "spec", "s", false, "Output 'create pipeline' compatibility specs.")
listPipeline.Flags().AddFlagSet(rawFlags)
listPipeline.Flags().AddFlagSet(fullTimestampsFlags)
+ listPipeline.Flags().Int64Var(&history, "history", 0, "Return revision history for pipelines.")
commands = append(commands, cmdutil.CreateAlias(listPipeline, "list pipeline"))
var all bool
diff --git a/src/server/pps/server/api_server.go b/src/server/pps/server/api_server.go
index <HASH>..<HASH> 100644
--- a/src/server/pps/server/api_server.go
+++ b/src/server/pps/server/api_server.go
@@ -2118,6 +2118,20 @@ func (a *apiServer) ListPipeline(ctx context.Context, request *pps.ListPipelineR
return err
}
pipelineInfos.PipelineInfo = append(pipelineInfos.PipelineInfo, pipelineInfo)
+ if request.History != 0 {
+ id := pipelinePtr.SpecCommit.ID
+ for i := 1; i <= int(request.History) || request.History == -1; i++ {
+ pipelinePtr.SpecCommit.ID = ancestry.Add(id, i)
+ pipelineInfo, err := ppsutil.GetPipelineInfo(pachClient, pipelinePtr, true)
+ if err != nil {
+ if isNotFoundErr(err) {
+ break
+ }
+ return err
+ }
+ pipelineInfos.PipelineInfo = append(pipelineInfos.PipelineInfo, pipelineInfo)
+ }
+ }
return nil
}); err != nil {
return nil, err | Adds implementation of history flag for pipelines. | pachyderm_pachyderm | train |
472ed2ee9a2205872732a0f31462eb8036f66d5c | diff --git a/tests/unit/auth/test_ldap.py b/tests/unit/auth/test_ldap.py
index <HASH>..<HASH> 100644
--- a/tests/unit/auth/test_ldap.py
+++ b/tests/unit/auth/test_ldap.py
@@ -12,24 +12,27 @@ from tests.support.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON
from tests.support.unit import skipIf, TestCase
-class Bind(object):
-
- @staticmethod
- def search_s(*args, **kwargs):
- return [
- (
- 'cn=saltusers,cn=groups,cn=compat,dc=saltstack,dc=com',
- {'memberUid': [b'saltuser'], 'cn': [b'saltusers']},
- ),
- ]
-
-
@skipIf(NO_MOCK, NO_MOCK_REASON)
@skipIf(not salt.auth.ldap.HAS_LDAP, 'Install python-ldap for this test')
class LDAPAuthTestCase(TestCase):
'''
Unit tests for salt.auth.ldap
'''
+
+ class Bind(object):
+ '''
+ fake search_s return
+ '''
+
+ @staticmethod
+ def search_s(*args, **kwargs):
+ return [
+ (
+ 'cn=saltusers,cn=groups,cn=compat,dc=saltstack,dc=com',
+ {'memberUid': [b'saltuser'], 'cn': [b'saltusers']},
+ ),
+ ]
+
def setUp(self):
salt.auth.ldap.__opts__ = {
'auth.ldap.binddn': 'uid={{username}},cn=users,cn=compat,dc=saltstack,dc=com',
@@ -47,21 +50,33 @@ class LDAPAuthTestCase(TestCase):
salt.auth.ldap.__opts__['auth.ldap.activedirectory'] = False
def test_config(self):
+ '''
+ Test that the _config function works correctly
+ '''
self.assertEqual(salt.auth.ldap._config('basedn'), 'dc=saltstack,dc=com')
self.assertEqual(salt.auth.ldap._config('group_filter'), '(&(memberUid={{ username }})(objectClass=posixgroup))')
self.assertEqual(salt.auth.ldap._config('accountattributename'), 'memberUid')
self.assertEqual(salt.auth.ldap._config('groupattribute'), 'memberOf')
def test_groups_freeipa(self):
+ '''
+ test groups in freeipa
+ '''
salt.auth.ldap.__opts__['auth.ldap.freeipa'] = True
with patch('salt.auth.ldap.auth', return_value=Bind):
self.assertIn('saltusers', salt.auth.ldap.groups('saltuser', password='password'))
def test_groups(self):
+ '''
+ test groups in ldap
+ '''
with patch('salt.auth.ldap.auth', return_value=Bind):
self.assertIn('saltusers', salt.auth.ldap.groups('saltuser', password='password'))
def test_groups_activedirectory(self):
+ '''
+ test groups in activedirectory
+ '''
salt.auth.ldap.__opts__['auth.ldap.activedirectory'] = True
with patch('salt.auth.ldap.auth', return_value=Bind):
self.assertIn('saltusers', salt.auth.ldap.groups('saltuser', password='password')) | fix class for pylint | saltstack_salt | train |
5062c0ce96f23b771354459ef3fae6a7a5cdbaab | diff --git a/lib/Server.js b/lib/Server.js
index <HASH>..<HASH> 100644
--- a/lib/Server.js
+++ b/lib/Server.js
@@ -69,8 +69,11 @@ class Server extends EventEmitter {
}
close (cb) {
- debug('Server: closing socket.')
+ debug('Server: closing sockets...')
cb = cb || noop
+ for (var c in this._clients) {
+ this._clients[c].destroy() // closing existing sockets
+ }
if (this.server) this.server.close(cb)
return this
}
@@ -86,7 +89,7 @@ class Server extends EventEmitter {
function connection (socket) {
socket.id = shortid.generate()
- debug('New connection', socket.id, socket.remoteAddress, socket.remotePort)
+ debug('New connection', socket.id, socket.remoteAddress + ':' + socket.remotePort)
self._clients[socket.id] = socket
/* outcoming */
@@ -134,7 +137,8 @@ class Server extends EventEmitter {
}
function close () {
- debug('Server close event')
+ self.server.unref()
+ debug('Server closed')
self._clients = {}
self.emit('srvClose')
} | destroy all the clients sockets and use unref() to avoid hanging | roccomuso_netcat | train |
215a878316e5bb81e68185dfc01e399a19fc224f | diff --git a/lewis/core/utils.py b/lewis/core/utils.py
index <HASH>..<HASH> 100644
--- a/lewis/core/utils.py
+++ b/lewis/core/utils.py
@@ -374,6 +374,6 @@ def is_compatible_with_framework(version):
if version is None:
return None
- lewis_version = Version(__version__)
+ lewis_version = Version.coerce(__version__)
- return lewis_version == Version(''.join(version.split()))
+ return lewis_version == Version.coerce(version.strip()) | Coerce versions so that 1.X matches 1.X<I> | DMSC-Instrument-Data_lewis | train |
f6d64920f4c85c6244af412810ab243c5c4ba954 | diff --git a/upload/admin/model/openbay/version.php b/upload/admin/model/openbay/version.php
index <HASH>..<HASH> 100644
--- a/upload/admin/model/openbay/version.php
+++ b/upload/admin/model/openbay/version.php
@@ -1,6 +1,6 @@
<?php
class ModelOpenbayVersion extends Model {
public function version() {
- return (int)2652;
+ return (int)2654;
}
}
\ No newline at end of file | <I> release. non-beta | opencart_opencart | train |
8ac8129fe708532f10fbe7cde1c7af04da5682c8 | diff --git a/lib/devise/models/database_authenticatable.rb b/lib/devise/models/database_authenticatable.rb
index <HASH>..<HASH> 100644
--- a/lib/devise/models/database_authenticatable.rb
+++ b/lib/devise/models/database_authenticatable.rb
@@ -31,7 +31,7 @@ module Devise
extend self
def required_fields
- [:encrypted_password, :email]
+ [:encrypted_password] + Devise.authentication_keys
end
end
diff --git a/test/models/database_authenticatable_test.rb b/test/models/database_authenticatable_test.rb
index <HASH>..<HASH> 100644
--- a/test/models/database_authenticatable_test.rb
+++ b/test/models/database_authenticatable_test.rb
@@ -11,7 +11,7 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
user.save!
assert_equal email.downcase, user.email
end
-
+
test 'should remove whitespace from strip whitespace keys when saving' do
# strip_whitespace_keys is set to :email by default.
email = ' [email protected] '
@@ -92,14 +92,14 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
:password => 'pass321', :password_confirmation => 'pass321')
assert user.reload.valid_password?('pass321')
end
-
+
test 'should update password with valid current password and :as option' do
user = create_user
assert user.update_with_password(:current_password => '123456',
:password => 'pass321', :password_confirmation => 'pass321', :as => :admin)
assert user.reload.valid_password?('pass321')
end
-
+
test 'should add an error to current password when it is invalid' do
user = create_user
assert_not user.update_with_password(:current_password => 'other',
@@ -151,7 +151,7 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
user.update_without_password(:email => '[email protected]')
assert_equal '[email protected]', user.email
end
-
+
test 'should update the user without password with :as option' do
user = create_user
user.update_without_password(:email => '[email protected]', :as => :admin)
@@ -170,4 +170,20 @@ class DatabaseAuthenticatableTest < ActiveSupport::TestCase
user = User.create(:email => "[email protected]", :password => "123456")
assert !user.valid?
end
+
+ test 'required_fiels should be encryptable_password and the email field by default' do
+ assert_equal Devise::Models::DatabaseAuthenticatable::ModuleMethods.required_fields.sort, [
+ :email,
+ :encrypted_password
+ ]
+ end
+
+ test 'required_fields should be encryptable_password and the login when the login is on authentication_keys' do
+ swap Devise, :authentication_keys => [:login] do
+ assert_equal Devise::Models::DatabaseAuthenticatable::ModuleMethods.required_fields.sort, [
+ :encrypted_password,
+ :login
+ ]
+ end
+ end
end | Added required_fields to database_authenticatable | plataformatec_devise | train |
60ad25d6b76b33fd450e37252f4126f7dff4e42b | diff --git a/src/Crawler.php b/src/Crawler.php
index <HASH>..<HASH> 100644
--- a/src/Crawler.php
+++ b/src/Crawler.php
@@ -56,7 +56,7 @@ class Crawler
/** @var \Tree\Node\Node */
protected $depthTree;
- /** @var boolean */
+ /** @var bool */
protected $executeJavaScript = false;
/** @var Browsershot */ | Apply fixes from StyleCI (#<I>) | spatie_crawler | train |
75af4bffc73b684e36dd14eff49ccfd836a2e511 | diff --git a/lib/solargraph/api_map.rb b/lib/solargraph/api_map.rb
index <HASH>..<HASH> 100755
--- a/lib/solargraph/api_map.rb
+++ b/lib/solargraph/api_map.rb
@@ -544,7 +544,9 @@ module Solargraph
if n.kind_of?(AST::Node)
if n.type == :class and !n.children[1].nil?
s = unpack_name(n.children[1])
- meths += inner_get_instance_methods(s, namespace, skip)
+ # @todo This skip might not work properly. We might need to get a
+ # fully qualified namespace from it first
+ meths += get_instance_methods(s, namespace) unless skip.include?(s)
end
current_scope = :public
n.children.each { |c|
diff --git a/lib/solargraph/code_map.rb b/lib/solargraph/code_map.rb
index <HASH>..<HASH> 100755
--- a/lib/solargraph/code_map.rb
+++ b/lib/solargraph/code_map.rb
@@ -41,10 +41,10 @@ module Solargraph
STDERR.puts "Retrying..."
tries += 1
spot = e.diagnostic.location.begin_pos
- STDERR.puts "CODE>>>>"
- STDERR.puts tmp
- STDERR.puts "<<<<CODE"
- STDERR.puts "Spot #{spot}: #{tmp[spot]}"
+ #STDERR.puts "CODE>>>>"
+ #STDERR.puts tmp
+ #STDERR.puts "<<<<CODE"
+ #STDERR.puts "Spot #{spot}: #{tmp[spot]}"
repl = '_'
if tmp[spot] == '@' or tmp[spot] == ':'
# Stub unfinished instance variables and symbols
@@ -66,9 +66,9 @@ module Solargraph
#else
tmp = tmp[0..spot] + repl + tmp[spot+repl.length+1..-1].to_s
#end
- STDERR.puts "CHNG>>>>"
- STDERR.puts tmp
- STDERR.puts "<<<<CHNG"
+ #STDERR.puts "CHNG>>>>"
+ #STDERR.puts tmp
+ #STDERR.puts "<<<<CHNG"
retry
end
raise e
diff --git a/lib/solargraph/yard_map.rb b/lib/solargraph/yard_map.rb
index <HASH>..<HASH> 100755
--- a/lib/solargraph/yard_map.rb
+++ b/lib/solargraph/yard_map.rb
@@ -21,7 +21,11 @@ module Solargraph
unless used.include?(g)
used.push g
gy = YARD::Registry.yardoc_file_for_gem(g)
- yardocs.push gy unless gy.nil?
+ if gy.nil?
+ STDERR.puts "Required path not found: #{r}"
+ else
+ yardocs.push gy
+ end
end
end
} | Get superclass instance methods from ApiMap. | castwide_solargraph | train |
c191cf3d201e93489f182c2a24b23ed25b319680 | diff --git a/platform/pure/backend.js b/platform/pure/backend.js
index <HASH>..<HASH> 100644
--- a/platform/pure/backend.js
+++ b/platform/pure/backend.js
@@ -22,11 +22,32 @@ var registerGenericListener = function(target) {
)
}
+var updatedItems = new Set()
+var rootItem = null
+
+var PureText = function(data) {
+ this.layout(data)
+}
+
+PureText.prototype.constructor = PureText
+PureText.prototype.layout = function(data) {
+ log('laying out "' + data.text + '"')
+}
+
+var PureImage = function(src) {
+ this.load(src)
+}
+
+PureImage.prototype.constructor = PureImage
+PureImage.prototype.load = function(src) {
+ log('loading image from ' + src)
+}
var Element = function(context, tag) {
_globals.core.RAIIEventEmitter.apply(this)
this._context = context
this._styles = {}
+ this._pure = null
this.children = []
registerGenericListener(this)
}
@@ -76,7 +97,7 @@ Element.prototype.remove = function() {
}
exports.init = function(ctx) {
- ctx.element = new Element(ctx, ctx.getTag())
+ rootItem = ctx.element = new Element(ctx, ctx.getTag())
}
exports.run = function(ctx) {
@@ -88,14 +109,15 @@ exports.createElement = function(ctx, tag) {
}
exports.initImage = function(image) {
+ image._pure = new PureImage(image.source)
}
exports.loadImage = function(image) {
- log('loading image from ' + image.source)
+ image._pure.load(image.source)
}
exports.layoutText = function(text) {
- log('laying out text "' + text.text + '"')
+ text._pure = new PureText(text)
}
exports.requestAnimationFrame = function(callback) { | added PureText and PureImage classes | pureqml_qmlcore | train |
97cea2188a6a2af8dd10e3208111b3d1b9699331 | diff --git a/Tests/ConnectionFactoryTest.php b/Tests/ConnectionFactoryTest.php
index <HASH>..<HASH> 100644
--- a/Tests/ConnectionFactoryTest.php
+++ b/Tests/ConnectionFactoryTest.php
@@ -145,6 +145,7 @@ class FakeDriver implements Driver
* @psalm-suppress InvalidReturnStatement
* @psalm-suppress InvalidReturnType
* @psalm-suppress UndefinedClass
+ * @psalm-suppress InvalidClass
*/
public function getDatabasePlatform(): AbstractPlatform
{ | Suppress `InvalidClass: Class, interface or enum Doctrine\DBAL\Platforms\MySQLPlatform has wrong casing` | doctrine_DoctrineBundle | train |
a18282ec872bba70578ecdf852b61c591ce72955 | diff --git a/user/class.userabstract.php b/user/class.userabstract.php
index <HASH>..<HASH> 100644
--- a/user/class.userabstract.php
+++ b/user/class.userabstract.php
@@ -3,7 +3,7 @@
* abstract base class for for admins and members
*
* @author Gregor Kofler
- * @version 0.5.3 2012-04-14
+ * @version 0.5.5 2012-04-16
*/
abstract class UserAbstract {
@@ -266,22 +266,30 @@ abstract class UserAbstract {
/**
* submits notification to user, when notification is assigned to user
+ * when $overridePreferences is set to true, notification is sent, ignoring user preferences or admin group assignments
*
* @param string $alias
* @param array $varData
+ * @param boolean $overridePreferences
*
* @return boolean success
*/
- public function notify($alias, Array $varData = array()) {
- if(!$this->getsNotified($alias)) {
- return true;
+ public function notify($alias, Array $varData = array(), $overridePreferences = FALSE) {
+ if($overridePreferences) {
+ $notification = new Notification($alias);
+ }
+ else {
+ if(!$this->getsNotified($alias)) {
+ return TRUE;
+ }
+
+ $notification = $this->cachedNotifications[$alias];
}
- $notification = $this->cachedNotifications[$alias];
$txt = $notification->fillMessage($varData);
if(empty($txt)) {
- return true;
+ return TRUE;
}
$m = new Email();
@@ -299,9 +307,9 @@ abstract class UserAbstract {
if($m->send()) {
$this->logNotification($notification);
- return true;
+ return TRUE;
}
- return false;
+ return FALSE;
}
private function logNotification(Notification $notification) { | Allows forced notification, which ignores user preference and admin
group assignment.
Change-Id: Ieea<I>c9b2a<I>ad<I>a2bdb1d<I>c<I> | Vectrex_vxPHP | train |
d873ad610e2217dca23ab07320f50d2ecc348f2a | diff --git a/src/Engine/Solr/SolrComparisonFormatter.php b/src/Engine/Solr/SolrComparisonFormatter.php
index <HASH>..<HASH> 100644
--- a/src/Engine/Solr/SolrComparisonFormatter.php
+++ b/src/Engine/Solr/SolrComparisonFormatter.php
@@ -30,6 +30,8 @@ class SolrComparisonFormatter implements ComparisonFormatterInterface
return $name . self::COLON . self::CURLY_BRACKET_OPEN . self::WILDCARD . self::EMPTY_SPACE . self::TO . self::EMPTY_SPACE . $value . self::CURLY_BRACKET_CLOSE;
} elseif ($operator->getSymbol() === Operator::GRATER_THAN_OR_EQUAL) {
return $name . self::COLON . self::BRACKET_OPEN . $value . self::EMPTY_SPACE . self::TO . self::EMPTY_SPACE . self::WILDCARD . self::BRACKET_CLOSE;
+ } elseif ($operator->getSymbol() === Operator::LESS_THAN_OR_EQUAL) {
+ return $name . self::COLON . self::BRACKET_OPEN . self::WILDCARD . self::EMPTY_SPACE . self::TO . self::EMPTY_SPACE . $value . self::BRACKET_CLOSE;
}
}
} | <I> - Added logic for less than or equal operation. | g4code_data-mapper | train |
a266446746c49f55c3447c467f053f88c2059c66 | diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index <HASH>..<HASH> 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -3246,6 +3246,12 @@ class Cmd(cmd.Cmd):
"""
expanded_filename = os.path.expanduser(filename)
+ if not expanded_filename.endswith('.py'):
+ self.pwarning("'{}' does not appear to be a Python file".format(expanded_filename))
+ selection = self.select('Yes No', 'Continue to try to run it as a Python script? ')
+ if selection != 'Yes':
+ return
+
# cmd_echo defaults to False for scripts. The user can always toggle this value in their script.
py_bridge.cmd_echo = False
@@ -3756,9 +3762,9 @@ class Cmd(cmd.Cmd):
self.perror("'{}' is not an ASCII or UTF-8 encoded text file".format(expanded_path))
return
- if expanded_path.endswith('.py') or expanded_path.endswith('.pyc'):
+ if expanded_path.endswith('.py'):
self.pwarning("'{}' appears to be a Python file".format(expanded_path))
- selection = self.select('Yes No', 'Continue to try to run it as a text file script? ')
+ selection = self.select('Yes No', 'Continue to try to run it as a text script? ')
if selection != 'Yes':
return | Print warning if a user tries to run something other than a *.py file with run_pyscript and ask them if they want to continue | python-cmd2_cmd2 | train |
11f4411c5f5d53d95a7ec00b623dbdc41e1bc924 | diff --git a/lib/chef/provider/package/paludis.rb b/lib/chef/provider/package/paludis.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/provider/package/paludis.rb
+++ b/lib/chef/provider/package/paludis.rb
@@ -39,6 +39,8 @@ class Chef
shell_out!("cave -L warning print-ids -m \"#{package}\" -f \"%c/%p %v %r\n\"").stdout.each_line do |line|
case line
+ when /accounts/
+ next
when /(.*)\s+(.*)\s+(.*)\sinstalled/
installed = true
@current_resource.version($2) | fix detection of accounts and installed-accounts packages | chef_chef | train |
54c2b6060e65be850735ef93e673978dfb7be75e | diff --git a/kernel/workflow/workflowlist.php b/kernel/workflow/workflowlist.php
index <HASH>..<HASH> 100644
--- a/kernel/workflow/workflowlist.php
+++ b/kernel/workflow/workflowlist.php
@@ -118,8 +118,6 @@ foreach( $tempworkflow_list as $tmpWorkflow )
{
foreach ( $templist_in_group as $tmpInGroup )
{
- $id = $tmpWorkflow->attribute("id");
- $workflow_id = $tmpInGroup->attribute("workflow_id");
if ( $tmpWorkflow->attribute( 'id' ) === $tmpWorkflow->attribute( 'workflow_id' ) )
{
$temp_list[] = $tmpWorkflow; | Fixed #<I>: Wrong logic to fetch temporary workflows in workflowlist view | ezsystems_ezpublish-legacy | train |
fb59d5352a069be7c8d56a1b003786cb5ad038fa | diff --git a/mod/assign/submission/onlinetext/locallib.php b/mod/assign/submission/onlinetext/locallib.php
index <HASH>..<HASH> 100644
--- a/mod/assign/submission/onlinetext/locallib.php
+++ b/mod/assign/submission/onlinetext/locallib.php
@@ -139,10 +139,6 @@ class assign_submission_onlinetext extends assign_submission_plugin {
$onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
- $text = format_text($data->onlinetext,
- $data->onlinetext_editor['format'],
- array('context'=>$this->assignment->get_context()));
-
$fs = get_file_storage();
$files = $fs->get_area_files($this->assignment->get_context()->id,
@@ -157,7 +153,8 @@ class assign_submission_onlinetext extends assign_submission_plugin {
'objectid' => $submission->id,
'other' => array(
'pathnamehashes' => array_keys($files),
- 'content' => trim($text)
+ 'content' => trim($data->onlinetext),
+ 'format' => $data->onlinetext_editor['format']
)
);
$event = \assignsubmission_onlinetext\event\assessable_uploaded::create($params);
@@ -423,12 +420,9 @@ class assign_submission_onlinetext extends assign_submission_plugin {
// Format the info for each submission plugin (will be logged).
$onlinetextsubmission = $this->get_onlinetext_submission($submission->id);
$onlinetextloginfo = '';
- $text = format_text($onlinetextsubmission->onlinetext,
- $onlinetextsubmission->onlineformat,
- array('context'=>$this->assignment->get_context()));
$onlinetextloginfo .= get_string('numwordsforlog',
'assignsubmission_onlinetext',
- count_words($text));
+ count_words($onlinetextsubmission->onlinetext));
return $onlinetextloginfo;
}
diff --git a/mod/assign/submission/onlinetext/tests/events_test.php b/mod/assign/submission/onlinetext/tests/events_test.php
index <HASH>..<HASH> 100644
--- a/mod/assign/submission/onlinetext/tests/events_test.php
+++ b/mod/assign/submission/onlinetext/tests/events_test.php
@@ -60,6 +60,7 @@ class assignsubmission_onlinetext_events_testcase extends advanced_testcase {
$this->assertEquals($context->id, $event->contextid);
$this->assertEquals($submission->id, $event->objectid);
$this->assertEquals(array(), $event->other['pathnamehashes']);
+ $this->assertEquals(FORMAT_PLAIN, $event->other['format']);
$this->assertEquals('Submission text', $event->other['content']);
$expected = new stdClass();
$expected->modulename = 'assign';
diff --git a/mod/assign/upgrade.txt b/mod/assign/upgrade.txt
index <HASH>..<HASH> 100644
--- a/mod/assign/upgrade.txt
+++ b/mod/assign/upgrade.txt
@@ -1,5 +1,12 @@
This files describes API changes in the assign code.
+=== 2.6.1 ===
+
+* format_text() is no longer used for formating assignment content to be used in events (assign_submission_onlinetext::save()) or
+ the word count (assign_submission_onlinetext::format_for_log()) in mod/assign/submission/onlinetext/locallib.php. format_text()
+ should only be used when displaying information to the screen. It was being used incorrectly before in these areas. Plugins using
+ the event assessable_uploaded() should use file_rewrite_pluginfile_urls() to translate the text back to the desired output.
+
=== 2.6 ===
* To see submission/grades of inactive users, user should have moodle/course:viewsuspendedusers capability.
* count_* functions will return only active participants. | MDL-<I> mod_assign: Removed wrongly used format_text call in online text submission. | moodle_moodle | train |
6d29905cdf1762d15d1829f2cbc40dacb6b16d02 | diff --git a/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/BasicPublisher.java b/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/BasicPublisher.java
index <HASH>..<HASH> 100644
--- a/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/BasicPublisher.java
+++ b/aeron-samples/src/main/java/uk/co/real_logic/aeron/samples/BasicPublisher.java
@@ -44,28 +44,36 @@ public class BasicPublisher
SamplesUtil.useSharedMemoryOnLinux();
final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launch() : null;
+
+ // Create an Aeron context for client connection to media driver
final Aeron.Context ctx = new Aeron.Context();
+ // Connect to media driver and add a publisher to Aeron instance
try (final Aeron aeron = Aeron.connect(ctx);
final Publication publication = aeron.addPublication(CHANNEL, STREAM_ID))
{
+ // Try to send messages
for (int i = 0; i < NUMBER_OF_MESSAGES; i++)
{
+ //Prepare a buffer to be sent
final String message = "Hello World! " + i;
BUFFER.putBytes(0, message.getBytes());
System.out.print("offering " + i + "/" + NUMBER_OF_MESSAGES);
+ // Try to send the message on configured CHANNEL and STREAM
final boolean result = publication.offer(BUFFER, 0, message.getBytes().length);
if (!result)
{
+ // Message offer did not succeed
System.out.println(" ah?!");
}
else
{
+ // Successful message send
System.out.println(" yay!");
}
-
+ //Sleep for a second
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
} | Adding new simple publisher and subscriber | real-logic_aeron | train |
6410b404b3313e7e90f1ca4663e38ed5db0613f2 | diff --git a/salt/minion.py b/salt/minion.py
index <HASH>..<HASH> 100644
--- a/salt/minion.py
+++ b/salt/minion.py
@@ -876,9 +876,6 @@ class Minion(MinionBase):
errors = functions['_errors']
functions.pop('_errors')
- functions.clear()
- returners.clear()
-
# we're done, reset the limits!
if modules_max_memory is True:
resource.setrlimit(resource.RLIMIT_AS, old_mem_limit) | We aren't doing singleton module loaders, lets not clear what we just made | saltstack_salt | train |
c1412f3d5383725a0940d7b3d7d552ecd77bf4d7 | diff --git a/clair/vulns.go b/clair/vulns.go
index <HASH>..<HASH> 100644
--- a/clair/vulns.go
+++ b/clair/vulns.go
@@ -1,6 +1,7 @@
package clair
import (
+ "encoding/base64"
"fmt"
"strings"
"time"
@@ -88,19 +89,32 @@ func (c *Clair) NewClairLayer(r *registry.Registry, image string, fsLayers []sch
// form the path
p := strings.Join([]string{r.URL, "v2", image, "blobs", fsLayers[index].BlobSum.String()}, "/")
+ useBasicAuth := false
+
// get the token
token, err := r.Token(p)
if err != nil {
- return nil, err
+ // if we get an error here of type: malformed auth challenge header: 'Basic realm="Registry Realm"'
+ // we need to use basic auth for the registry
+ if !strings.Contains(err.Error(), `malformed auth challenge header: 'Basic realm="Registry Realm"'`) {
+ return nil, err
+ }
+ useBasicAuth = true
}
h := make(map[string]string)
- if token != "" {
+ if token != "" && !useBasicAuth {
h = map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", token),
}
}
+ if useBasicAuth {
+ h = map[string]string{
+ "Authorization": fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(r.Username+":"+r.Password))),
+ }
+ }
+
return &Layer{
Name: fsLayers[index].BlobSum.String(),
Path: p, | fix basic auth with clair
closes #<I> | genuinetools_reg | train |
43bd99528d7f44d4ba834a1cca9ac2ebd12dc21c | diff --git a/install/lang/fi_utf8/installer.php b/install/lang/fi_utf8/installer.php
index <HASH>..<HASH> 100644
--- a/install/lang/fi_utf8/installer.php
+++ b/install/lang/fi_utf8/installer.php
@@ -125,7 +125,7 @@ $string['gdversion'] = 'GD versio';
$string['gdversionerror'] = 'GD kirjaston pitäisi olla päällä, että voidaan käsitellä ja luoda kuvia.';
$string['gdversionhelp'] = '<p>Palvelimellasi ei näyttäisi olevan GD:tä asennettuna.</p>
-<p>GD on kirjasto jonka PHP vaatii voidakseen antaa Moodlen käsitellä kuvia (esimerkiksi käyttäjäprofiili kuvakkeita) ja luoda uusia kuvia (esimerkiksi kirjauskuvioita) Moodle toimii ilman GD:täkin, mutta silloin nämä toiminnot eivät ole saatavilla.</p>
+<p>GD on kirjasto jonka PHP vaatii jotta Moodlen voisi käsitellä kuvia (esimerkiksi käyttäjä kuvia) ja luoda uusia kuvia (esimerkiksi kaavioita) Moodle toimii ilman GD:täkin, mutta silloin nämä toiminnot eivät ole saatavilla.</p>
<p>Lisätäksesi GD:n PHP:hen Unix:in alaisena, käännä PHP käyttäen --with-gd parametria.</p> | Automatic installer.php lang files by installer_builder (<I>) | moodle_moodle | train |
e77ec8dabbdf2e01c42207a783927d58e077f6a7 | diff --git a/src/main/java/com/sonoport/freesound/query/sound/UploadSound.java b/src/main/java/com/sonoport/freesound/query/sound/UploadSound.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/sonoport/freesound/query/sound/UploadSound.java
+++ b/src/main/java/com/sonoport/freesound/query/sound/UploadSound.java
@@ -131,6 +131,21 @@ public class UploadSound extends JSONResponseQuery<UploadedSoundDetails> {
}
/**
+ * Specify an individual tag associated with the sound.
+ *
+ * @param tag The tag associated with the sound
+ * @return The current {@link UploadSound} instance
+ */
+ public UploadSound tag(final String tag) {
+ if (this.tags == null) {
+ this.tags = new HashSet<>();
+ }
+
+ this.tags.add(tag);
+ return this;
+ }
+
+ /**
* Specify the tags associated with the sound.
*
* @param tags The tags associated with the sound
diff --git a/src/test/java/com/sonoport/freesound/query/sound/UploadSoundTest.java b/src/test/java/com/sonoport/freesound/query/sound/UploadSoundTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/sonoport/freesound/query/sound/UploadSoundTest.java
+++ b/src/test/java/com/sonoport/freesound/query/sound/UploadSoundTest.java
@@ -47,6 +47,9 @@ public class UploadSoundTest extends JSONResponseQueryTest<UploadSound> {
/** Tag to use in tests. Contains a space that should be replaced with a hypen before being passed in to the API. */
private static final String TAG_2 = "second tag";
+ /** Tag to use in tests. */
+ private static final String TAG_3 = "another-tag";
+
/** Collection of tags to use in tests. */
private static final Set<String> TAGS = new HashSet<>(Arrays.asList(TAG_1, TAG_2));
@@ -118,6 +121,7 @@ public class UploadSoundTest extends JSONResponseQueryTest<UploadSound> {
.description(DESCRIPTION)
.license(LICENSE)
.tags(TAGS)
+ .tag(TAG_3)
.name(NAME)
.pack(PACK)
.geotag(GEOTAG);
@@ -129,9 +133,10 @@ public class UploadSoundTest extends JSONResponseQueryTest<UploadSound> {
final String tagsString = (String) uploadSound.getQueryParameters().get(UploadSound.TAGS_PARAMETER_NAME);
final Set<String> tags = new HashSet<>(Arrays.asList(tagsString.split(" ")));
- assertTrue(tags.size() == 2);
+ assertTrue(tags.size() == 3);
assertTrue(tags.contains(TAG_1));
assertTrue(tags.contains(EXPECTED_TAG_2));
+ assertTrue(tags.contains(TAG_3));
assertEquals(NAME, uploadSound.getQueryParameters().get(UploadSound.SOUND_NAME_PARAMETER_NAME));
assertEquals(PACK, uploadSound.getQueryParameters().get(UploadSound.PACK_PARAMETER_NAME)); | Added option to add a single tag [Issue #9] | Sonoport_freesound-java | train |
aa05642e7c0c6e17c83cf949e8a5c6f132dcdfe6 | diff --git a/lib/apiMethods.js b/lib/apiMethods.js
index <HASH>..<HASH> 100644
--- a/lib/apiMethods.js
+++ b/lib/apiMethods.js
@@ -17,6 +17,7 @@ module.exports = {
"preauthorization_create" : [ "/${apiVersion}/${clientId}/preauthorizations/card/direct", "POST" ],
"preauthorization_get" : [ "/${apiVersion}/${clientId}/preauthorizations/${id}", "GET" ],
"preauthorization_save" : [ "/${apiVersion}/${clientId}/preauthorizations/${id}", "PUT" ],
+ "preauthorizations_get_for_user" : [ "/${apiVersion}/${clientId}/users/${id}/preauthorizations", "GET"],
"card_get" : [ "/${apiVersion}/${clientId}/cards/${id}", "GET" ],
"cards_get_by_fingerprint" : [ "/${apiVersion}/${clientId}/cards/fingerprints/${fingerprint}", "GET"],
diff --git a/lib/services/Users.js b/lib/services/Users.js
index <HASH>..<HASH> 100644
--- a/lib/services/Users.js
+++ b/lib/services/Users.js
@@ -23,7 +23,7 @@ var KycDocument = require('../models/KycDocument');
var KycPage = require('../models/KycPage');
var EMoney = require('../models/EMoney');
var UboDeclaration = require('../models/UboDeclaration');
-
+var PreAuthorization = require('../models/CardPreAuthorization');
var Users = Service.extend({
/**
@@ -427,6 +427,17 @@ var Users = Service.extend({
return this._api.method('ubo_declaration_create', callback, options);
},
+ getPreAuthorizations: function(userId, callback, options) {
+ options = this._api._getOptions(callback, options, {
+ path: {
+ id: userId
+ },
+ dataClass: PreAuthorization
+ });
+
+ return this._api.method('preauthorizations_get_for_user', callback, options);
+ },
+
/**
* Gets the details for a user instance of hash of properties
* @param {Object|UserNatural|UserLegal} user
diff --git a/test/services/Users.js b/test/services/Users.js
index <HASH>..<HASH> 100644
--- a/test/services/Users.js
+++ b/test/services/Users.js
@@ -642,4 +642,20 @@ describe('Users', function() {
expect(createdDeclaration.DeclaredUBOs[0].UserId).to.equal(declarativeUser.Id);
});
});
+
+ describe('Get PreAuthorizations', function() {
+ var getPreAuthorizations;
+
+ before(function(done) {
+ api.Users.getPreAuthorizations(john.Id, function(data, response) {
+ getPreAuthorizations = data;
+ done();
+ });
+ });
+
+ it('should be retrieved', function() {
+ expect(getPreAuthorizations).not.to.be.undefined;
+ expect(getPreAuthorizations).to.be.an('array');
+ });
+ });
}); | Implemented Get PreAuthorizations for a User. | Mangopay_mangopay2-nodejs-sdk | train |
37d5dd6530857a1abc1db50a48ba22c3459826a1 | diff --git a/reflect.go b/reflect.go
index <HASH>..<HASH> 100644
--- a/reflect.go
+++ b/reflect.go
@@ -1023,6 +1023,8 @@ func isEmpty(rt reflect.Type, rv reflect.Value, opts Options) bool {
}
return false
} else {
+ // TODO: A faster alternative might be to call writeReflectJSON
+ // onto a buffer and check if its "{}" or not.
switch rt.Kind() {
case reflect.Struct:
// check fields | isEmpty note from review | tendermint_go-amino | train |
bf55324eb0032f2fa1cd87d873d72e9bb9525500 | diff --git a/lib/mongoid/criteria.rb b/lib/mongoid/criteria.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/criteria.rb
+++ b/lib/mongoid/criteria.rb
@@ -10,16 +10,16 @@ module Mongoid #:nodoc:
@selector, @options = {}, {}
end
- # Specify what fields to be returned from the database.
- # Similar to a SQL select field1, field2, field3
- def select(*args)
- @options[:fields] = args.flatten; self
+ # Limits the number of results returned by the query, usually used in
+ # conjunction with skip() for pagination.
+ def limit(value = 20)
+ @options[:limit] = value; self
end
# The conditions that must prove true on each record in the
# database in order for them to be a part of the result set.
# This is a hash that maps to a selector in the driver.
- def where(selector = {})
+ def matches(selector = {})
@selector = selector; self
end
@@ -29,17 +29,17 @@ module Mongoid #:nodoc:
@options[:sort] = params; self
end
+ # Specify what fields to be returned from the database.
+ # Similar to a SQL select field1, field2, field3
+ def select(*args)
+ @options[:fields] = args.flatten; self
+ end
+
# Skips the supplied number of records, as offset behaves in traditional
# pagination.
def skip(value = 0)
@options[:skip] = value; self
end
- # Limits the number of results returned by the query, usually used in
- # conjunction with skip() for pagination.
- def limit(value = 20)
- @options[:limit] = value; self
- end
-
end
end
diff --git a/spec/unit/mongoid/criteria_spec.rb b/spec/unit/mongoid/criteria_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/mongoid/criteria_spec.rb
+++ b/spec/unit/mongoid/criteria_spec.rb
@@ -2,36 +2,32 @@ require File.join(File.dirname(__FILE__), "/../../spec_helper.rb")
describe Mongoid::Criteria do
- describe "#select" do
+ describe "#limit" do
before do
@criteria = Mongoid::Criteria.new
end
- it "adds the options for limiting by fields" do
- @criteria.select(:title, :text)
- @criteria.options.should == { :fields => [ :title, :text ] }
- end
+ context "when value provided" do
- it "returns self" do
- @criteria.select.should == @criteria
- end
+ it "adds the limit to the options" do
+ @criteria.limit(100)
+ @criteria.options.should == { :limit => 100 }
+ end
- end
+ end
- describe "#where" do
+ context "when value not provided" do
- before do
- @criteria = Mongoid::Criteria.new
- end
+ it "defaults to 20" do
+ @criteria.limit
+ @criteria.options.should == { :limit => 20 }
+ end
- it "adds the clause to the selector" do
- @criteria.where(:title => "Title", :text => "Text")
- @criteria.selector.should == { :title => "Title", :text => "Text" }
end
it "returns self" do
- @criteria.where.should == @criteria
+ @criteria.limit.should == @criteria
end
end
@@ -57,6 +53,23 @@ describe Mongoid::Criteria do
end
+ describe "#select" do
+
+ before do
+ @criteria = Mongoid::Criteria.new
+ end
+
+ it "adds the options for limiting by fields" do
+ @criteria.select(:title, :text)
+ @criteria.options.should == { :fields => [ :title, :text ] }
+ end
+
+ it "returns self" do
+ @criteria.select.should == @criteria
+ end
+
+ end
+
describe "#skip" do
before do
@@ -87,32 +100,19 @@ describe Mongoid::Criteria do
end
- describe "#limit" do
+ describe "#matches" do
before do
@criteria = Mongoid::Criteria.new
end
- context "when value provided" do
-
- it "adds the limit to the options" do
- @criteria.limit(100)
- @criteria.options.should == { :limit => 100 }
- end
-
- end
-
- context "when value not provided" do
-
- it "defaults to 20" do
- @criteria.limit
- @criteria.options.should == { :limit => 20 }
- end
-
+ it "adds the clause to the selector" do
+ @criteria.matches(:title => "Title", :text => "Text")
+ @criteria.selector.should == { :title => "Title", :text => "Text" }
end
it "returns self" do
- @criteria.limit.should == @criteria
+ @criteria.matches.should == @criteria
end
end | Make sure alphabetical in spec and class | mongodb_mongoid | train |
816ba289e57a95e64c294badacedd378d44cd1b8 | diff --git a/lib/plugins/create/tests/create.js b/lib/plugins/create/tests/create.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/create/tests/create.js
+++ b/lib/plugins/create/tests/create.js
@@ -42,6 +42,23 @@ describe('Create', () => {
expect(() => create.create()).to.throw(Error);
});
+ it('should overwrite the name for the service if user passed name', () => {
+ const tmpDir = path.join(os.tmpdir(), (new Date()).getTime().toString());
+ const cwd = process.cwd();
+ fse.mkdirsSync(tmpDir);
+ process.chdir(tmpDir);
+ create.options.template = 'aws-nodejs';
+ create.options.name = 'my_service';
+
+ return create.create().then(() => {
+ return create.serverless.yamlParser.parse(path.join(tmpDir, 'serverless.yml')).then((obj) => {
+ expect(obj.service).to.equal('my_service')
+
+ process.chdir(cwd);
+ });
+ });
+ });
+
it('should set servicePath based on cwd', () => {
const tmpDir = path.join(os.tmpdir(), (new Date()).getTime().toString());
const cwd = process.cwd(); | Add failing test for name option in create | serverless_serverless | train |
793348a47cb7fd85cd2aa0a229c43835800f6845 | diff --git a/tests/test_optimize.py b/tests/test_optimize.py
index <HASH>..<HASH> 100644
--- a/tests/test_optimize.py
+++ b/tests/test_optimize.py
@@ -55,6 +55,7 @@ def test_mono_not_inverted(resources, outdir):
assert im.getpixel((0, 0)) == 255, "Expected white background"
[email protected](not pngquant.available(), reason='need pngquant')
def test_jpg_png_params(resources, outpdf, spoof_tesseract_noop):
check_ocrmypdf(
resources / 'crom.png', | tests: mark test as requiring pngquant | jbarlow83_OCRmyPDF | train |
b6bb77b7560400a027f5cd2d1b370ab46c989b9c | diff --git a/lib/Doctrine/Common/Annotations/DocLexer.php b/lib/Doctrine/Common/Annotations/DocLexer.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Common/Annotations/DocLexer.php
+++ b/lib/Doctrine/Common/Annotations/DocLexer.php
@@ -79,6 +79,17 @@ final class DocLexer extends AbstractLexer
];
/**
+ * Whether the token next token starts immediately, of if there were
+ * non-captured symbols before that
+ */
+ public function nextTokenIsAdjacent() : bool
+ {
+ return $this->token === null
+ || ($this->lookahead !== null
+ && ($this->lookahead['position'] - $this->token['position']) === strlen($this->token['value']));
+ }
+
+ /**
* {@inheritdoc}
*/
protected function getCatchablePatterns()
diff --git a/tests/Doctrine/Tests/Common/Annotations/DocLexerTest.php b/tests/Doctrine/Tests/Common/Annotations/DocLexerTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/Tests/Common/Annotations/DocLexerTest.php
+++ b/tests/Doctrine/Tests/Common/Annotations/DocLexerTest.php
@@ -293,4 +293,20 @@ class DocLexerTest extends TestCase
self::assertEquals($expectedTokens, $actualTokens);
}
+
+ public function testTokenAdjacency()
+ {
+ $lexer = new DocLexer();
+
+ $lexer->setInput('-- -');
+
+ self::assertTrue($lexer->nextTokenIsAdjacent());
+ self::assertTrue($lexer->moveNext());
+ self::assertTrue($lexer->nextTokenIsAdjacent());
+ self::assertTrue($lexer->moveNext());
+ self::assertTrue($lexer->nextTokenIsAdjacent());
+ self::assertTrue($lexer->moveNext());
+ self::assertFalse($lexer->nextTokenIsAdjacent());
+ self::assertFalse($lexer->moveNext());
+ }
} | `DocLexer#nextTokenIsAdjacent()`: are there are non-captured sequences between tokens? | doctrine_annotations | train |
669c3175570fd25e6d0ed6a18d5114c33809e71c | diff --git a/telemetry/telemetry/core/backends/chrome/chrome_trace_result.py b/telemetry/telemetry/core/backends/chrome/chrome_trace_result.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/backends/chrome/chrome_trace_result.py
+++ b/telemetry/telemetry/core/backends/chrome/chrome_trace_result.py
@@ -21,6 +21,9 @@ class ChromeTraceResult(object):
"""Parses the trace result into a timeline model for in-memory
manipulation."""
timeline = self._CreateTimelineModel()
+ for thread in timeline.GetAllThreads():
+ if thread.name == 'CrBrowserMain':
+ timeline.browser_process = thread.parent
for key, value in self._tab_to_marker_mapping.iteritems():
timeline_markers = timeline.FindTimelineMarkers(value)
assert(len(timeline_markers) == 1)
diff --git a/telemetry/telemetry/core/backends/chrome/tracing_backend_unittest.py b/telemetry/telemetry/core/backends/chrome/tracing_backend_unittest.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/backends/chrome/tracing_backend_unittest.py
+++ b/telemetry/telemetry/core/backends/chrome/tracing_backend_unittest.py
@@ -133,3 +133,14 @@ class ChromeTraceResultTest(unittest.TestCase):
assert 'traceEvents' in j
self.assertEquals(j['traceEvents'],
['foo', 'bar', 'baz'])
+
+ def testBrowserProcess(self):
+ ri = self._chromeTraceResultClass([
+ '{"name": "process_name",'
+ '"args": {"name": "Browser"},'
+ '"pid": 5, "ph": "M"}',
+ '{"name": "thread_name",'
+ '"args": {"name": "CrBrowserMain"},'
+ '"pid": 5, "tid": 32578, "ph": "M"}'])
+ model = ri.AsTimelineModel()
+ self.assertEquals(model.browser_process.pid, 5)
diff --git a/telemetry/telemetry/core/timeline/model.py b/telemetry/telemetry/core/timeline/model.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/timeline/model.py
+++ b/telemetry/telemetry/core/timeline/model.py
@@ -42,6 +42,7 @@ class TimelineModel(object):
self._bounds = bounds.Bounds()
self._thread_time_bounds = {}
self._processes = {}
+ self._browser_process = None
self._frozen = False
self.import_errors = []
self.metadata = []
@@ -65,6 +66,14 @@ class TimelineModel(object):
def processes(self):
return self._processes
+ @property
+ def browser_process(self):
+ return self._browser_process
+
+ @browser_process.setter
+ def browser_process(self, browser_process):
+ self._browser_process = browser_process
+
def ImportTraces(self, traces, shift_world_to_zero=True):
if self._frozen:
raise Exception("Cannot add events once recording is done")
diff --git a/telemetry/telemetry/core/timeline/process.py b/telemetry/telemetry/core/timeline/process.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/timeline/process.py
+++ b/telemetry/telemetry/core/timeline/process.py
@@ -34,6 +34,11 @@ class Process(event_container.TimelineEventContainer):
for s in thread.IterAllSlicesOfName(name):
yield s
+ def IterAllAsyncSlicesOfName(self, name):
+ for thread in self._threads.itervalues():
+ for s in thread.IterAllAsyncSlicesOfName(name):
+ yield s
+
def IterEventsInThisContainer(self):
return
yield # pylint: disable=W0101
diff --git a/telemetry/telemetry/core/timeline/thread.py b/telemetry/telemetry/core/timeline/thread.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/timeline/thread.py
+++ b/telemetry/telemetry/core/timeline/thread.py
@@ -64,6 +64,11 @@ class Thread(event_container.TimelineEventContainer):
for sub_slice in async_slice.IterEventsInThisContainerRecrusively():
yield sub_slice
+ def IterAllAsyncSlicesOfName(self, name):
+ for s in self.IterAllAsyncSlices():
+ if s.name == name:
+ yield s
+
def IterEventsInThisContainer(self):
return itertools.chain(
iter(self._newly_added_slices), | Make timeline model able to return browser process
When parsing tracing data into timeline model, also find the browser
process and save it into timeline model. This is to support querying
async slices starting in browser process.
BUG=<I>
TEST=Run telemetry smoothness test and make sure input latency trace
can be retrieved from querying async slices on browser process.
Review URL: <URL> | catapult-project_catapult | train |
e04b51ec85631eaa4a6ebc217f2caf4a01599788 | diff --git a/aesh/src/main/java/org/aesh/readline/ShellImpl.java b/aesh/src/main/java/org/aesh/readline/ShellImpl.java
index <HASH>..<HASH> 100644
--- a/aesh/src/main/java/org/aesh/readline/ShellImpl.java
+++ b/aesh/src/main/java/org/aesh/readline/ShellImpl.java
@@ -115,6 +115,8 @@ class ShellImpl implements Shell {
@Override
public Key read() throws InterruptedException {
+ printCollectedOutput();
+ pagingSupport.reset();
ActionDecoder decoder = new ActionDecoder();
final Key[] key = {null};
CountDownLatch latch = new CountDownLatch(1); | Fix for AESH-<I> | aeshell_aesh | train |
Subsets and Splits