hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
14ba3523593bbd2558b8fe2290e49b5ca0edfd07
|
diff --git a/statuspage/statuspage.py b/statuspage/statuspage.py
index <HASH>..<HASH> 100644
--- a/statuspage/statuspage.py
+++ b/statuspage/statuspage.py
@@ -144,7 +144,7 @@ def run_upgrade(name, token, org):
content = f.read()
if template in files:
repo_template = repo.get_contents(
- path="/" + template,
+ path=template,
ref=head_sha,
)
if not is_same_content(
@@ -177,7 +177,7 @@ def run_update(name, token, org):
# get the template from the repo
template_file = repo.get_contents(
- path="/template.html",
+ path="template.html",
ref=sha
)
@@ -196,7 +196,7 @@ def run_update(name, token, org):
try:
# get the index.html file, we need the sha to update it
index = repo.get_contents(
- path="/index.html",
+ path="index.html",
ref=sha,
)
diff --git a/statuspage/tests.py b/statuspage/tests.py
index <HASH>..<HASH> 100644
--- a/statuspage/tests.py
+++ b/statuspage/tests.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import unittest
+import traceback
from datetime import datetime
from unittest import TestCase
from mock import patch, Mock
@@ -50,8 +51,8 @@ class CLITestCase(TestCase):
self.template = Mock()
self.template.decoded_content = b"some foo"
self.template.content = codecs.encode(b"some other foo", "base64")
- self.gh().get_user().get_repo().get_file_contents.return_value = self.template
- self.gh().get_organization().get_repo().get_file_contents.return_value = self.template
+ self.gh().get_user().get_repo().get_contents.return_value = self.template
+ self.gh().get_organization().get_repo().get_contents.return_value = self.template
self.collaborator = Mock()
self.collaborator.login = "some-dude"
|
fix: create and update github commands #<I> (#<I>)
* Fix create and update github commands #<I>
- Change get_file_contents to get_contents
- Remove beginning '/' on paths
* Fix the unit tests
|
jayfk_statuspage
|
train
|
d3e7d1549b7efe37e552cf57f99f39609d76662f
|
diff --git a/src/FeedIo/Reader/Fixer/LastModified.php b/src/FeedIo/Reader/Fixer/LastModified.php
index <HASH>..<HASH> 100644
--- a/src/FeedIo/Reader/Fixer/LastModified.php
+++ b/src/FeedIo/Reader/Fixer/LastModified.php
@@ -12,11 +12,28 @@ namespace FeedIo\Reader\Fixer;
use FeedIo\FeedInterface;
use FeedIo\Reader\FixerInterface;
+use Psr\Log\LoggerInterface;
class LastModified implements FixerInterface
{
- public function setRight(FeedInterface $feed)
+ /**
+ * @var \Psr\Log\LoggerInterface
+ */
+ protected $logger;
+
+ /**
+ * @param \Psr\Log\LoggerInterface
+ * @return $this
+ */
+ public function setLogger(LoggerInterface $logger)
+ {
+ $this->logger = $logger;
+
+ return $this;
+ }
+
+ public function correct(FeedInterface $feed)
{
if ( is_null($feed->getLastModified()) ) {
$feed->setLastModified(
diff --git a/src/FeedIo/Reader/FixerInterface.php b/src/FeedIo/Reader/FixerInterface.php
index <HASH>..<HASH> 100644
--- a/src/FeedIo/Reader/FixerInterface.php
+++ b/src/FeedIo/Reader/FixerInterface.php
@@ -11,13 +11,19 @@
namespace FeedIo\Reader;
use FeedIo\FeedInterface;
+use Psr\Log\LoggerInterface;
interface FixerInterface
{
/**
+ * @param Psr\Log\LoggerInterface $logger
+ */
+ public function setLogger(LoggerInterface $logger);
+
+ /**
* @param FeedIo\FeedInterface $feed
*/
- public function setRight(FeedInterface $feed);
+ public function correct(FeedInterface $feed);
}
diff --git a/src/FeedIo/Reader/FixerSet.php b/src/FeedIo/Reader/FixerSet.php
index <HASH>..<HASH> 100644
--- a/src/FeedIo/Reader/FixerSet.php
+++ b/src/FeedIo/Reader/FixerSet.php
@@ -32,10 +32,10 @@ class FixerSet
* @param FeedInterface $feed
* @return $this
*/
- public function setRight(FeedInterface $feed)
+ public function correct(FeedInterface $feed)
{
foreach( $this->fixers as $fixer ) {
- $fixer->setRight($feed);
+ $fixer->correct($feed);
}
return $this;
diff --git a/tests/FeedIo/Reader/Fixer/LastModifiedTest.php b/tests/FeedIo/Reader/Fixer/LastModifiedTest.php
index <HASH>..<HASH> 100644
--- a/tests/FeedIo/Reader/Fixer/LastModifiedTest.php
+++ b/tests/FeedIo/Reader/Fixer/LastModifiedTest.php
@@ -44,12 +44,12 @@ class LastModifiedTest extends \PHPUnit_Framework_TestCase
);
}
- public function testSetRight()
+ public function testCorrect()
{
$feed = $this->getFeed();
$this->assertNull($feed->getLastModified());
- $this->object->setRight($feed);
+ $this->object->correct($feed);
$this->assertEquals($this->newest, $feed->getLastModified());
}
|
rename setRight() to correct()
|
alexdebril_feed-io
|
train
|
68cd8f89d188e7cbc1f9698fa576c704e73550d6
|
diff --git a/kodi_voice/kodi.py b/kodi_voice/kodi.py
index <HASH>..<HASH> 100644
--- a/kodi_voice/kodi.py
+++ b/kodi_voice/kodi.py
@@ -737,6 +737,10 @@ class Kodi:
return self.SendCommand(RPCString("Input.Back"), False)
+ def DownloadSubtitles(self):
+ return self.SendCommand(RPCString("GUI.ActivateWindow", {"window": "subtitlesearch"}))
+
+
def ShowMovies(self):
return self.SendCommand(RPCString("GUI.ActivateWindow", {"window": "videos", "parameters": ["MovieTitles", "return"]}), False)
|
Add command for opening Download Subtitles window
|
m0ngr31_kodi-voice
|
train
|
9bacf2464ff68b88ee5d3211dbfa35fbe553889c
|
diff --git a/tang/src/test/java/com/microsoft/tang/implementation/protobuf/TestClassHierarchyRoundTrip.java b/tang/src/test/java/com/microsoft/tang/implementation/protobuf/TestClassHierarchyRoundTrip.java
index <HASH>..<HASH> 100644
--- a/tang/src/test/java/com/microsoft/tang/implementation/protobuf/TestClassHierarchyRoundTrip.java
+++ b/tang/src/test/java/com/microsoft/tang/implementation/protobuf/TestClassHierarchyRoundTrip.java
@@ -44,7 +44,7 @@ public class TestClassHierarchyRoundTrip extends TestClassHierarchy{
private void setup3() {
TangImpl.reset();
- final String relPath = getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
+ final String relPath = this.getClass().getClassLoader().getResource("").getPath();
final String fileName = relPath + "testProto.bin";
try {
|
change the generated test file to target folder
|
apache_reef
|
train
|
8d6c9c27e8fb0d90e51e1f9f10d222bd5c85660c
|
diff --git a/src/global.js b/src/global.js
index <HASH>..<HASH> 100644
--- a/src/global.js
+++ b/src/global.js
@@ -1,6 +1,7 @@
// Global mind map parameters
export default {
options: {
+ "font-family": "Arial, Helvetica, sans-serif",
"center-onresize": true,
"drag": true,
"zoom": true,
diff --git a/src/map/update.js b/src/map/update.js
index <HASH>..<HASH> 100644
--- a/src/map/update.js
+++ b/src/map/update.js
@@ -35,6 +35,7 @@ export function update() {
color: ${n.value["text-color"]};
font-style: ${Utils.fontStyle(n.value.italic)};
font-weight: ${Utils.fontWeight(n.value.bold)};
+ font-family: ${glob.options["font-family"]};
text-align: center;
" contenteditable spellcheck="false">${n.value.name}</div>`)
.each(setNodeName)
|
[fix] fix mind map font family
|
Mindmapp_mmp
|
train
|
ac7de6bc28e359e3f4573831285fcabd3c1aa36b
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -12,7 +12,7 @@ function ImmutableThunk(renderFn, state, proto, equalStates, equalRenders) {
var proto = proto !== undefined && proto !== null ? proto : {};
if (Object.prototype.toString.call(proto) !== '[object Object]') {
- throw new TypeError('proto must be an object');
+ throw new TypeError('proto must be an object');
}
xtendMutable(this, proto);
@@ -20,32 +20,32 @@ function ImmutableThunk(renderFn, state, proto, equalStates, equalRenders) {
this.state = state;
this.equalStates = equalStates !== undefined && equalStates !== null ? equalStates : defaultEqualStates;
this.equalRenders = equalRenders !== undefined && equalRenders !== null ? equalRenders : defaultEqualRenders;
-
- function defaultEqualStates(first, second) {
- return deepEqual(first, second, { strict: true });
- }
-
- function defaultEqualRenders(first, second) {
- return first === second;
- }
}
ImmutableThunk.prototype.type = 'Thunk';
ImmutableThunk.prototype.render = function render(previous) {
- if (shouldUpdate(this, previous)) {
+ if (shouldUpdate(this, previous)) {
return this.renderFn.call(null, this.state);
- } else {
+ } else {
return previous.vnode;
- }
-
- function shouldUpdate(current, previous) {
- return current === undefined || current === null
- || previous === undefined || previous === null
- || previous.type !== 'Thunk'
- || !current.equalStates(current.state, previous.state)
- || !current.equalRenders(current.renderFn, previous.renderFn);
- }
+ }
};
+function defaultEqualStates(first, second) {
+ return deepEqual(first, second, { strict: true });
+}
+
+function defaultEqualRenders(first, second) {
+ return first === second;
+}
+
+function shouldUpdate(current, previous) {
+ return current === undefined || current === null
+ || previous === undefined || previous === null
+ || previous.type !== 'Thunk'
+ || !current.equalStates(current.state, previous.state)
+ || !current.equalRenders(current.renderFn, previous.renderFn);
+}
+
module.exports = ImmutableThunk;
|
enhancement(index.js): make some functions out of scope (thanks @neonstalwart)
|
kuraga_vnode-immutable-thunk
|
train
|
7f1f93d48c7d043027e2778f6d7ccbb646049df1
|
diff --git a/protocol.go b/protocol.go
index <HASH>..<HASH> 100644
--- a/protocol.go
+++ b/protocol.go
@@ -12,7 +12,7 @@ import (
// be read from the wire, if Listener.ReaderHeaderTimeout is not set.
// It's kept as a global variable so to make it easier to find and override,
// e.g. go build -ldflags -X "github.com/pires/go-proxyproto.DefaultReadHeaderTimeout=1s"
-var DefaultReadHeaderTimeout = 200 * time.Millisecond
+var DefaultReadHeaderTimeout = 10 * time.Second
// Listener is used to wrap an underlying listener,
// whose connections may be using the HAProxy Proxy Protocol.
diff --git a/protocol_test.go b/protocol_test.go
index <HASH>..<HASH> 100644
--- a/protocol_test.go
+++ b/protocol_test.go
@@ -265,6 +265,8 @@ func TestReadHeaderTimeoutIsReset(t *testing.T) {
// we expect the actual address and port to be returned,
// rather than the ProxyHeader we defined.
func TestReadHeaderTimeoutIsEmpty(t *testing.T) {
+ DefaultReadHeaderTimeout = 200 * time.Millisecond
+
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("err: %v", err)
|
Bump DefaultReadHeaderTimeout to <I>s
When dealing with slow networks and TLS, <I>ms is often hit. Bump
the default timeout to <I>s, which is what crupto/tls uses for the
TLS handshake.
Closes: <URL>
|
pires_go-proxyproto
|
train
|
4cb6ed323642fb8b59d5d22eee0b4340b9c46cca
|
diff --git a/lib/ohai/mixin/command.rb b/lib/ohai/mixin/command.rb
index <HASH>..<HASH> 100644
--- a/lib/ohai/mixin/command.rb
+++ b/lib/ohai/mixin/command.rb
@@ -32,11 +32,17 @@ module Ohai
m = Mixlib::ShellOut.new(cmd)
begin
m.run_command
- Ohai::Log.debug("Plugin #{self.name} successfully ran command #{cmd}")
+
+ if m.exitstatus == 0
+ Ohai::Log.debug("Plugin #{self.name} successfully ran command #{cmd}")
+ else
+ Ohai::Log.debug("Plugin #{self.name} command #{cmd} returned status #{m.exitstatus}")
+ end
+
m
rescue Errno::ENOENT => e
Ohai::Log.debug("Plugin #{self.name} failed to run command #{cmd}")
- raise
+ raise Ohai::Exceptions::Exec, e
end
end
|
Log non-0 exit codes and raise our own exception
|
chef_ohai
|
train
|
cb15e642e678d4fc568531ca23d575cf51e29d74
|
diff --git a/spec/pivotal/story_spec.rb b/spec/pivotal/story_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/pivotal/story_spec.rb
+++ b/spec/pivotal/story_spec.rb
@@ -31,12 +31,12 @@ describe Pivotal::Story do
end
it "should be able to update other attributes when marking the story as started" do
- verify_response :put do |result|
- result.css("story current_state").inner_text == "started" &&
- result.css("story owned_by").inner_text == "Jeff Tucker"
- end
-
+ # Check the XML contains the right options.
+ # Can't just check the XML string, because the elements may be in a
+ # different order (because it's built from a hash).
+ @xpath = "//current_state = 'started' and //owned_by = 'Jeff Tucker'"
+ @story.resource.expects(:put).with {|xml| Nokogiri.XML(xml).xpath(@xpath) }
@story.start!(:owned_by => "Jeff Tucker")
end
-end
\ No newline at end of file
+end
|
story spec shouldn't depend on order of items in a hash
|
trydionel_git-pivotal
|
train
|
09c986715e718841fa2f025450f3964009d04406
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -16,5 +16,5 @@ setup(name='windpowerlib',
'windpowerlib': [os.path.join('data', '*.csv')]},
long_description=read('README.rst'),
zip_safe=False,
- install_requires=['pandas >= 0.19.1',
+ install_requires=['pandas >= 0.19.1, < 0.25 ',
'requests'])
|
Limit pandas version to the <I>.x major release
|
wind-python_windpowerlib
|
train
|
8dc65e11bfdd7ee9b37aa2f57ab69621adb3abfb
|
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/widgets/browse/staticDataSource.js b/bundles/org.eclipse.orion.client.ui/web/orion/widgets/browse/staticDataSource.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/widgets/browse/staticDataSource.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/widgets/browse/staticDataSource.js
@@ -124,7 +124,7 @@ define([
{ id: "application/zip",
"extends": "application/octet-stream",
name: "ZIP",
- extension: ["war", "zip", "rar"]
+ extension: ["war", "jar", "zip", "rar"]
},
// Image types
{ id: "image/gif",
|
Readonly file widget: Make *.jar files downloadable.
|
eclipse_orion.client
|
train
|
159120cddda176a46246b0b60cc37701644eafd4
|
diff --git a/hugolib/config.go b/hugolib/config.go
index <HASH>..<HASH> 100644
--- a/hugolib/config.go
+++ b/hugolib/config.go
@@ -110,7 +110,7 @@ func LoadConfig(d ConfigSourceDescriptor, doWithConfig ...func(cfg config.Provid
// Config deprecations.
// We made this a Glob pattern in Hugo 0.75, we don't need both.
if l.cfg.GetBool("ignoreVendor") {
- helpers.Deprecated("--ignoreVendor", "--ignoreVendorPaths **", true)
+ helpers.Deprecated("--ignoreVendor", "Use --ignoreVendorPaths \"**\"", true)
l.cfg.Set("ignoreVendorPaths", "**")
}
|
Fix deprecation notice
Asterisks needs to be quoted on command line.
|
gohugoio_hugo
|
train
|
81cbab2c66cc7a8f207a04427323ae8e628465da
|
diff --git a/pprofile.py b/pprofile.py
index <HASH>..<HASH> 100755
--- a/pprofile.py
+++ b/pprofile.py
@@ -231,8 +231,11 @@ class _FileTiming(object):
entry[2] += duration
def getHitStatsFor(self, line):
- for code, (hits, duration) in self.line_dict.get(line, {None: (0, 0)}).iteritems():
- yield code, hits, duration
+ try:
+ for code, (hits, duration) in self.line_dict[line].iteritems():
+ yield code, hits, duration
+ except KeyError:
+ pass
def getLastLine(self):
return max(
@@ -438,7 +441,7 @@ class ProfileBase(object):
)
return filename
- def _iterFile(self, name, call_list_by_line):
+ def _iterFile(self, name):
file_timing = self.file_dict[name]
last_line = file_timing.getLastLine()
for lineno, line in LineIterator(
@@ -449,14 +452,6 @@ class ProfileBase(object):
if not line and lineno > last_line:
break
for code, hits, duration in file_timing.getHitStatsFor(lineno):
- if code is None:
- # In case the line has no hit but has a call (happens in
- # statistical profiling, as hits are on leaves only).
- # code are expected to be constant on a
- # given line (accumulated data is redundant)
- call_list = call_list_by_line.get(lineno)
- if call_list:
- code = call_list[0][0]
yield lineno, code, hits, duration, line or LINESEP
def callgrind(self, out, filename=None, commandline=None, relative_path=False):
@@ -530,24 +525,20 @@ class ProfileBase(object):
# Note: cost line is a list just to be mutable. A single item is
# expected.
func_dict = defaultdict(lambda: defaultdict(lambda: ([], [])))
- for lineno, code, hits, duration, _ in self._iterFile(
- current_file, call_list_by_line):
- call_list = call_list_by_line.get(lineno, ())
- if not hits and not call_list:
- continue
- ticks = int(duration * 1000000)
- if hits == 0:
- ticksperhit = 0
- else:
- ticksperhit = ticks // hits
- func_dict[getCodeName(current_file, code)][lineno][0].append(
- u'%i %i %i %i' % (lineno, hits, ticks, ticksperhit),
- )
+ for lineno, code, hits, duration, _ in self._iterFile(current_file):
+ if hits:
+ ticks = int(duration * 1000000)
+ func_dict[getCodeName(current_file, code)][lineno][0].append(
+ u'%i %i %i %i' % (lineno, hits, ticks, ticks // hits),
+ )
for (
caller,
call_hits, call_duration,
callee_file, callee,
- ) in sorted(call_list, key=lambda x: x[2:4]):
+ ) in sorted(
+ call_list_by_line.get(lineno, ()),
+ key=lambda x: x[2:4],
+ ):
call_ticks = int(call_duration * 1000000)
func_call_list = func_dict[
getCodeName(current_file, caller)
@@ -604,8 +595,7 @@ class ProfileBase(object):
percent(file_total_time, total_time)), file=out)
print(_ANNOTATE_HEADER, file=out)
print(_ANNOTATE_HORIZONTAL_LINE, file=out)
- for lineno, _, hits, duration, line in self._iterFile(name,
- call_list_by_line):
+ for lineno, _, hits, duration, line in self._iterFile(name):
if hits:
time_per_hit = duration / hits
else:
|
pprofile: Do not emit 0-hit, 0-microseconds lines in cachegrind output.
In turn, this allows simplifying _iterFile.
|
vpelletier_pprofile
|
train
|
2addeae2db6db6fa5ac95b01907b5a5939b80abb
|
diff --git a/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java b/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java
index <HASH>..<HASH> 100644
--- a/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java
+++ b/netty/src/main/java/io/grpc/transport/netty/NettyClientHandler.java
@@ -31,6 +31,7 @@
package io.grpc.transport.netty;
+import static io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception;
import static io.netty.util.CharsetUtil.UTF_8;
import com.google.common.annotations.VisibleForTesting;
@@ -248,6 +249,17 @@ class NettyClientHandler extends Http2ConnectionHandler {
}
@Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+ if (getEmbeddedHttp2Exception(cause) == null) {
+ // Kill the connection instead of propagating the exceptionCaught(). Http2ConnectionHandler
+ // only handles Http2Exceptions and propagates everything else.
+ goAwayStatus(Status.fromThrowable(cause));
+ cause = new Http2Exception(Http2Error.INTERNAL_ERROR, null, cause);
+ }
+ super.exceptionCaught(ctx, cause);
+ }
+
+ @Override
protected void onConnectionError(ChannelHandlerContext ctx, Throwable cause,
Http2Exception http2Ex) {
logger.log(Level.FINE, "Caught a connection error", cause);
|
NettyClientHandler should handle all exceptionCaught()s
If NettyClientHandler doesn't then the exception will propagate to the
end of the pipeline, get logged, and cause any open calls to hang.
|
grpc_grpc-java
|
train
|
1267ed047f2f6fe0c2085e0d4a120cb1b463cd76
|
diff --git a/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py b/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
index <HASH>..<HASH> 100644
--- a/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
+++ b/gremlin-python/src/main/jython/gremlin_python/structure/io/graphson.py
@@ -293,11 +293,7 @@ class Int32IO(_NumberIO):
def dictify(cls, n, writer):
if isinstance(n, bool):
return n
- if isinstance(n, LongType):
- graphson_base_type = Int64IO.graphson_base_type
- else:
- graphson_base_type = cls.graphson_base_type
- return GraphSONUtil.typedValue(graphson_base_type, n)
+ return GraphSONUtil.typedValue(cls.graphson_base_type, n)
class VertexDeserializer(_GraphSONTypeIO):
|
removed unuseful type check in Int<I>IO class
|
apache_tinkerpop
|
train
|
3d5eac698290c4bc6ea7d23c2584a948372d4fb2
|
diff --git a/tasks/angular-builder.js b/tasks/angular-builder.js
index <HASH>..<HASH> 100644
--- a/tasks/angular-builder.js
+++ b/tasks/angular-builder.js
@@ -153,6 +153,8 @@ module.exports = function (grunt)
// On release mode, output an optimized script.
else buildReleasePackage (options.main, fileGroup.dest);
+ exportRequiredResources (options.main);
+
}.bind (this));
});
@@ -320,6 +322,31 @@ module.exports = function (grunt)
}
//------------------------------------------------------------------------------
+ // EXPORT REQUIRED RESOURCES
+ //------------------------------------------------------------------------------
+
+ function exportRequiredResources (mainName)
+ {
+ var scripts = []
+ , stylesheets = []
+ , templates = [];
+
+ // Export paths of application-required scripts.
+
+ if (standaloneScripts.length)
+ util.arrayAppend (scripts, standaloneScripts.map (function (e)
+ {
+ return e.path;
+ }));
+ loaded = []; // Reset tracer.
+ traceModule (mainName, null, function (module)
+ {
+ util.arrayAppend (scripts, module.filePaths);
+ });
+ grunt.config (options.scriptsConfigProperty, scripts);
+ }
+
+ //------------------------------------------------------------------------------
// DEBUG BUILD
//------------------------------------------------------------------------------
@@ -359,8 +386,8 @@ module.exports = function (grunt)
{
if (rep)
for (var i = 0, m = rep.length; i < m; ++i)
- path = path.replace(rep[i].match, rep[i].replaceWith);
- console.log("PORRA",path);
+ path = path.replace (rep[i].match, rep[i].replaceWith);
+ console.log ("PORRA", path);
output.push (sprintf ('<script src=\"%\"></script>', path));
});
}
@@ -406,7 +433,7 @@ module.exports = function (grunt)
output.push (head.data);
// Output a module declaration with no definitions.
output.push (sprintf ('angular.module (\'%\', %);%', module.name,
- toList (module.requires), options.moduleFooter)
+ toList (module.requires), options.moduleFooter)
);
}
// Enclose the module contents in a self-invoking function which receives the module instance as an argument.
@@ -485,7 +512,7 @@ module.exports = function (grunt)
var modInfo = result.data;
if (!options.renameModuleRefs) {
warn ('The module variable reference <cyan>%</cyan> doesn\'t match the preset name on the config setting ' +
- '<cyan>moduleVar=\'%\'</cyan>.%%%',
+ '<cyan>moduleVar=\'%\'</cyan>.%%%',
modInfo.moduleVar, options.moduleVar, NL, reportErrorLocation (path),
getExplanation ('Either rename the variable or enable <cyan>renameModuleRefs</cyan>.')
);
@@ -529,12 +556,12 @@ module.exports = function (grunt)
function warnAboutGlobalCode (sandbox, path)
{
var msg = csprintf ('yellow', 'Incompatible code found on the global scope!'.red + NL +
- reportErrorLocation (path) +
- getExplanation (
- 'This kind of code will behave differently between release and debug builds.' + NL +
- 'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
- 'directly to the window object.'
- )
+ reportErrorLocation (path) +
+ getExplanation (
+ 'This kind of code will behave differently between release and debug builds.' + NL +
+ 'You should wrap it in a self-invoking function and/or assign global variables/functions ' +
+ 'directly to the window object.'
+ )
);
if (verbose) {
var found = false;
diff --git a/tasks/lib/types.js b/tasks/lib/types.js
index <HASH>..<HASH> 100644
--- a/tasks/lib/types.js
+++ b/tasks/lib/types.js
@@ -140,13 +140,19 @@ var TASK_OPTIONS = {
* These stylesheets are those required by javascript files included in the build via build-directives.
* @type {string}
*/
- stylesheetsConfigProperty: 'angularStylesheets',
+ stylesheetsConfigProperty: 'requiredStylesheets',
/**
* The name of the Gruntfile config property to where the list of required template paths will be exported.
* These HTML templates are those required by javascript files included in the build via build-directives.
* @type {string}
*/
- templatesConfigProperty: 'angularTemplates'
+ templatesConfigProperty: 'requiredTemplates',
+ /**
+ * The name of the Gruntfile config property to where the list of required script paths will be exported.
+ * These scripts are all those that are actually required by your project, including forced includes.
+ * @type {string}
+ */
+ scriptsConfigProperty: 'requiredScripts'
};
/**
diff --git a/tasks/lib/util.js b/tasks/lib/util.js
index <HASH>..<HASH> 100644
--- a/tasks/lib/util.js
+++ b/tasks/lib/util.js
@@ -153,6 +153,16 @@ String.prototype.repeat = function( num )
};
/**
+ * Appends the second array into the first one, in-place.
+ * @param {Array} target
+ * @param {Array} src
+ * @returns {Number}
+ */
+exports.arrayAppend = function (target, src) {
+ return Array.prototype.push.apply (target, src);
+};
+
+/**
* OS dependent line terminator.
* @type {string}
*/
|
Required scripts paths export - for integration wih other Grunt plugins.
|
claudio-silva_grunt-angular-builder
|
train
|
7e31df39877d95446b48c8064e55ebef48d4e5c6
|
diff --git a/core/transaction_pool.go b/core/transaction_pool.go
index <HASH>..<HASH> 100644
--- a/core/transaction_pool.go
+++ b/core/transaction_pool.go
@@ -356,11 +356,12 @@ func (self *TxPool) RemoveTransactions(txs types.Transactions) {
self.mu.Lock()
defer self.mu.Unlock()
for _, tx := range txs {
- self.removeTx(tx.Hash())
+ self.RemoveTx(tx.Hash())
}
}
-func (pool *TxPool) removeTx(hash common.Hash) {
+// RemoveTx removes the transaction with the given hash from the pool.
+func (pool *TxPool) RemoveTx(hash common.Hash) {
// delete from pending pool
delete(pool.pending, hash)
// delete from queue
diff --git a/core/transaction_pool_test.go b/core/transaction_pool_test.go
index <HASH>..<HASH> 100644
--- a/core/transaction_pool_test.go
+++ b/core/transaction_pool_test.go
@@ -130,7 +130,7 @@ func TestRemoveTx(t *testing.T) {
t.Error("expected txs to be 1, got", len(pool.pending))
}
- pool.removeTx(tx.Hash())
+ pool.RemoveTx(tx.Hash())
if len(pool.queue) > 0 {
t.Error("expected queue to be 0, got", len(pool.queue))
diff --git a/rpc/api/eth.go b/rpc/api/eth.go
index <HASH>..<HASH> 100644
--- a/rpc/api/eth.go
+++ b/rpc/api/eth.go
@@ -21,8 +21,9 @@ import (
"encoding/json"
"math/big"
+ "fmt"
+
"github.com/ethereum/go-ethereum/common"
- "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/rpc/codec"
"github.com/ethereum/go-ethereum/rpc/shared"
@@ -578,14 +579,17 @@ func (self *ethApi) Resend(req *shared.Request) (interface{}, error) {
return nil, shared.NewDecodeParamError(err.Error())
}
- ret, err := self.xeth.Transact(args.Tx.From, args.Tx.To, args.Tx.Nonce, args.Tx.Value, args.GasLimit, args.GasPrice, args.Tx.Data)
- if err != nil {
- return nil, err
- }
+ from := common.HexToAddress(args.Tx.From)
- self.ethereum.TxPool().RemoveTransactions(types.Transactions{args.Tx.tx})
+ pending := self.ethereum.TxPool().GetTransactions()
+ for _, p := range pending {
+ if pFrom, err := p.From(); err == nil && pFrom == from && p.SigHash() == args.Tx.tx.SigHash() {
+ self.ethereum.TxPool().RemoveTx(common.HexToHash(args.Tx.Hash))
+ return self.xeth.Transact(args.Tx.From, args.Tx.To, args.Tx.Nonce, args.Tx.Value, args.GasLimit, args.GasPrice, args.Tx.Data)
+ }
+ }
- return ret, nil
+ return nil, fmt.Errorf("Transaction %s not found", args.Tx.Hash)
}
func (self *ethApi) PendingTransactions(req *shared.Request) (interface{}, error) {
diff --git a/rpc/api/eth_args.go b/rpc/api/eth_args.go
index <HASH>..<HASH> 100644
--- a/rpc/api/eth_args.go
+++ b/rpc/api/eth_args.go
@@ -888,6 +888,7 @@ type tx struct {
Data string
GasLimit string
GasPrice string
+ Hash string
}
func newTx(t *types.Transaction) *tx {
@@ -906,6 +907,7 @@ func newTx(t *types.Transaction) *tx {
Data: "0x" + common.Bytes2Hex(t.Data()),
GasLimit: t.Gas().String(),
GasPrice: t.GasPrice().String(),
+ Hash: t.Hash().Hex(),
}
}
@@ -931,6 +933,12 @@ func (tx *tx) UnmarshalJSON(b []byte) (err error) {
contractCreation = true
)
+ if val, found := fields["Hash"]; found {
+ if hashVal, ok := val.(string); ok {
+ tx.Hash = hashVal
+ }
+ }
+
if val, found := fields["To"]; found {
if strVal, ok := val.(string); ok && len(strVal) > 0 {
tx.To = strVal
|
bugfix, pending transaction was resend with new gas price/limit but not removed from transaction pool
|
ethereum_go-ethereum
|
train
|
29f658fd3cda71aec88e5eb3fb59b30b19be5508
|
diff --git a/bridge/xmpp/xmpp.go b/bridge/xmpp/xmpp.go
index <HASH>..<HASH> 100644
--- a/bridge/xmpp/xmpp.go
+++ b/bridge/xmpp/xmpp.go
@@ -114,6 +114,9 @@ func (b *Bxmpp) createXMPP() error {
ServerName: strings.Split(b.GetString("Jid"), "@")[1],
InsecureSkipVerify: b.GetBool("SkipTLSVerify"), // nolint: gosec
}
+
+ xmpp.DebugWriter = b.Log.Writer()
+
options := xmpp.Options{
Host: b.GetString("Server"),
User: b.GetString("Jid"),
@@ -122,7 +125,6 @@ func (b *Bxmpp) createXMPP() error {
StartTLS: true,
TLSConfig: tc,
Debug: b.GetBool("debug"),
- Logger: b.Log.Writer(),
Session: true,
Status: "",
StatusMessage: "",
|
Use DebugWriter after upstream changes (xmpp)
|
42wim_matterbridge
|
train
|
42e4c84c624e74f24a580cf802dabb8c9216fddb
|
diff --git a/lib/childprocess/unix/posix_spawn_process.rb b/lib/childprocess/unix/posix_spawn_process.rb
index <HASH>..<HASH> 100644
--- a/lib/childprocess/unix/posix_spawn_process.rb
+++ b/lib/childprocess/unix/posix_spawn_process.rb
@@ -37,7 +37,9 @@ module ChildProcess
attrs.flags = flags
- GC.disable # prevent GC of argv/env ptrs
+ # wrap in helper classes in order to avoid GC'ed pointers
+ argv = Argv.new(@args)
+ envp = Envp.new(ENV.to_hash.merge(@environment))
ret = Lib.posix_spawnp(
pid_ptr,
@@ -45,11 +47,9 @@ module ChildProcess
actions,
attrs,
argv,
- env
+ envp
)
- GC.enable
-
if duplex?
io._stdin = writer
reader.close
@@ -66,46 +66,57 @@ module ChildProcess
::Process.detach(@pid) if detach?
end
- def argv
- arg_ptrs = @args.map do |e|
- if e.include?("\0")
- raise ArgumentError, "argument cannot contain null bytes: #{e.inspect}"
- end
- FFI::MemoryPointer.from_string(e.to_s)
+ if ChildProcess.jruby?
+ def fileno_for(obj)
+ ChildProcess::JRuby.posix_fileno_for(obj)
+ end
+ else
+ def fileno_for(obj)
+ obj.fileno
end
- arg_ptrs << nil
-
- argv = FFI::MemoryPointer.new(:pointer, arg_ptrs.size)
- argv.put_array_of_pointer(0, arg_ptrs)
-
- argv
end
- def env
- env_ptrs = ENV.to_hash.merge(@environment).map do |key, val|
- if key =~ /=|\0/ || val.include?("\0")
- raise InvalidEnvironmentVariable, "#{key.inspect} => #{val.inspect}"
+ class Argv
+ def initialize(args)
+ @ptrs = args.map do |e|
+ if e.include?("\0")
+ raise ArgumentError, "argument cannot contain null bytes: #{e.inspect}"
+ end
+
+ FFI::MemoryPointer.from_string(e.to_s)
end
- FFI::MemoryPointer.from_string("#{key}=#{val}")
+ @ptrs << nil
end
- env_ptrs << nil
- env = FFI::MemoryPointer.new(:pointer, env_ptrs.size)
- env.put_array_of_pointer(0, env_ptrs)
+ def to_ptr
+ argv = FFI::MemoryPointer.new(:pointer, @ptrs.size)
+ argv.put_array_of_pointer(0, @ptrs)
- env
- end
+ argv
+ end
+ end # Argv
- if ChildProcess.jruby?
- def fileno_for(obj)
- ChildProcess::JRuby.posix_fileno_for(obj)
+ class Envp
+ def initialize(env)
+ @ptrs = env.map do |key, val|
+ if key =~ /=|\0/ || val.include?("\0")
+ raise InvalidEnvironmentVariable, "#{key.inspect} => #{val.inspect}"
+ end
+
+ FFI::MemoryPointer.from_string("#{key}=#{val}")
+ end
+
+ @ptrs << nil
end
- else
- def fileno_for(obj)
- obj.fileno
+
+ def to_ptr
+ env = FFI::MemoryPointer.new(:pointer, @ptrs.size)
+ env.put_array_of_pointer(0, @ptrs)
+
+ env
end
- end
+ end # Envp
end
end
|
JRuby doesn't support GC.{disable,enable}, so do this properly right away.
|
enkessler_childprocess
|
train
|
095fc79e628d6b6bf02d6852cf425356db4580c8
|
diff --git a/tests/log_parser/test_artifact_builder_collection.py b/tests/log_parser/test_artifact_builder_collection.py
index <HASH>..<HASH> 100644
--- a/tests/log_parser/test_artifact_builder_collection.py
+++ b/tests/log_parser/test_artifact_builder_collection.py
@@ -48,8 +48,7 @@ def test_all_builders_complete():
url,
)
for builder in lpc.builders:
- for parser in builder.parsers:
- parser.complete = True
+ builder.parser.complete = True
lpc.parse()
exp = {
diff --git a/treeherder/log_parser/artifactbuildercollection.py b/treeherder/log_parser/artifactbuildercollection.py
index <HASH>..<HASH> 100644
--- a/treeherder/log_parser/artifactbuildercollection.py
+++ b/treeherder/log_parser/artifactbuildercollection.py
@@ -38,8 +38,8 @@ ArtifactBuilderBase
* Manages:
* artifact
* line number
-* parsers
-* Passes lines into each ``Parser``
+* parser
+* Passes lines the ``Parser``
BuildbotLogViewArtifactBuilder
-------------
@@ -51,7 +51,6 @@ BuildbotJobArtifactBuilder
-------------
* Builds an artifact for the Treeherder job details panel
* Parsers:
-* ErrorParser
* TinderboxPrintParser
BuildbotPerformanceDataArtifactBuilder
diff --git a/treeherder/log_parser/artifactbuilders.py b/treeherder/log_parser/artifactbuilders.py
index <HASH>..<HASH> 100644
--- a/treeherder/log_parser/artifactbuilders.py
+++ b/treeherder/log_parser/artifactbuilders.py
@@ -39,40 +39,34 @@ class ArtifactBuilderBase(object):
"logurl": url
}
self.lineno = 0
- self.parsers = []
+ self.parser = None
self.name = "Generic Artifact"
def parse_line(self, line):
"""Parse a single line of the log."""
-
- """
- Talos data is stored in a json structure contained in
- a single line, if the MAX_LINE_LENGTH is applied the
- data structure could be truncated preventing it from
- being ingested.
- """
+ # Talos data is stored in a json structure contained in a single line,
+ # if the MAX_LINE_LENGTH is applied the data structure could be truncated,
+ # preventing it from being ingested.
if "TALOSDATA" not in line and 'TalosResult' not in line:
line = line[:self.MAX_LINE_LENGTH]
- for parser in self.parsers:
- # Some parsers only need to run until they've seen a specific line.
- # Once that's occurred, they mark themselves as complete, to save
- # being included in the set of parsers run against later log lines.
- if not parser.complete:
- parser.parse_line(line, self.lineno)
+ # The parser may only need to run until it has seen a specific line.
+ # Once that's occurred, it can mark itself as complete, to save
+ # being run against later log lines.
+ if not self.parser.complete:
+ self.parser.parse_line(line, self.lineno)
self.lineno += 1
def get_artifact(self):
- """Return the job artifact built from all parsers."""
- for sp in self.parsers:
- self.artifact[sp.name] = sp.get_artifact()
+ """Return the job artifact built by the parser."""
+ self.artifact[self.parser.name] = self.parser.get_artifact()
return self.artifact
class BuildbotJobArtifactBuilder(ArtifactBuilderBase):
"""
- Gather error and details for this job.
+ Gather properties for this job.
This parser gathers the data that shows in the job details panel.
"""
@@ -80,9 +74,7 @@ class BuildbotJobArtifactBuilder(ArtifactBuilderBase):
def __init__(self, url=None):
"""Construct a job artifact builder."""
super(BuildbotJobArtifactBuilder, self).__init__(url)
- self.parsers = [
- TinderboxPrintParser()
- ]
+ self.parser = TinderboxPrintParser()
self.name = "Job Info"
@@ -92,9 +84,7 @@ class BuildbotLogViewArtifactBuilder(ArtifactBuilderBase):
def __init__(self, url=None):
"""Construct artifact builder for the log viewer"""
super(BuildbotLogViewArtifactBuilder, self).__init__(url)
- self.parsers = [
- StepParser()
- ]
+ self.parser = StepParser()
self.name = "text_log_summary"
@@ -104,9 +94,7 @@ class BuildbotPerformanceDataArtifactBuilder(ArtifactBuilderBase):
def __init__(self, url=None):
"""Construct artifact builder for the log viewer"""
super(BuildbotPerformanceDataArtifactBuilder, self).__init__(url)
- self.parsers = [
- TalosParser()
- ]
+ self.parser = TalosParser()
self.name = "talos_data"
|
Bug <I> - Remove support for multiple parsers per ArtifactBuilder
Since we only have one parser per ArtifactBuilder currently, and are not
likely to ever have any more.
|
mozilla_treeherder
|
train
|
02d6ea06701e9f8c9835347c8ad389af3c4741f4
|
diff --git a/lenstronomy/Sampling/Samplers/nautilus.py b/lenstronomy/Sampling/Samplers/nautilus.py
index <HASH>..<HASH> 100644
--- a/lenstronomy/Sampling/Samplers/nautilus.py
+++ b/lenstronomy/Sampling/Samplers/nautilus.py
@@ -44,6 +44,7 @@ class Nautilus(object):
if prior_type == 'uniform':
for i in range(self._num_param):
prior.add_parameter(dist=(self._lower_limit[i], self._upper_limit[i]))
+ assert self._num_param == prior.dimensionality()
print(self._num_param, prior.dimensionality(), 'number of param, dimensionality')
else:
raise ValueError('prior_type %s is not supported for Nautilus wrapper.' % prior_type)
diff --git a/test/test_Sampling/test_Samplers/test_nautilus.py b/test/test_Sampling/test_Samplers/test_nautilus.py
index <HASH>..<HASH> 100644
--- a/test/test_Sampling/test_Samplers/test_nautilus.py
+++ b/test/test_Sampling/test_Samplers/test_nautilus.py
@@ -11,7 +11,7 @@ from lenstronomy.Sampling.Samplers.nautilus import Nautilus
def import_fixture(simple_einstein_ring_likelihood_2d):
"""
- :param simple_einstein_ring_likelihood: fixture
+ :param simple_einstein_ring_likelihood_2d: fixture
:return:
"""
likelihood, kwargs_truths = simple_einstein_ring_likelihood_2d
@@ -46,6 +46,16 @@ class TestNautilusSampler(object):
kwargs_run_fail['prior_type'] = 'wrong'
assert_raises(ValueError, sampler.nautilus_sampling, **kwargs_run_fail)
+ def test_prior(self):
+
+ num_param = 10
+ from nautilus import Prior
+ prior = Prior()
+
+ for i in range(num_param):
+ prior.add_parameter(dist=(0, 1))
+ assert num_param == prior.dimensionality()
+
if __name__ == '__main__':
pytest.main()
|
specific test for nautilus prior
|
sibirrer_lenstronomy
|
train
|
06e280843f9053677371534e6eff6eac8f11ee39
|
diff --git a/doc/source/v0.14.1.txt b/doc/source/v0.14.1.txt
index <HASH>..<HASH> 100644
--- a/doc/source/v0.14.1.txt
+++ b/doc/source/v0.14.1.txt
@@ -24,11 +24,6 @@ users upgrade to this version.
API changes
~~~~~~~~~~~
-
-
-
-
-
- All ``offsets`` suppports ``normalize`` keyword to specify whether ``offsets.apply``, ``rollforward`` and ``rollback`` resets time (hour, minute, etc) or not (default ``False``, preserves time) (:issue:`7156`)
@@ -60,6 +55,8 @@ API changes
- Bug in ``.loc`` performing fallback integer indexing with ``object`` dtype indices (:issue:`7496`)
- Add back ``#N/A N/A`` as a default NA value in text parsing, (regresion from 0.12) (:issue:`5521`)
+- Raise a ``TypeError`` on inplace-setting with a ``.where`` and a non ``np.nan`` value as this is inconsistent
+ with a set-item expression like ``df[mask] = None`` (:issue:`7656`)
.. _whatsnew_0141.prior_deprecations:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index <HASH>..<HASH> 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -679,8 +679,8 @@ class DataFrame(NDFrame):
the defined table schema and column types. For simplicity, this method
uses the Google BigQuery streaming API. The to_gbq method chunks data
into a default chunk size of 10,000. Failures return the complete error
- response which can be quite long depending on the size of the insert.
- There are several important limitations of the Google streaming API
+ response which can be quite long depending on the size of the insert.
+ There are several important limitations of the Google streaming API
which are detailed at:
https://developers.google.com/bigquery/streaming-data-into-bigquery.
@@ -1925,11 +1925,7 @@ class DataFrame(NDFrame):
if key.values.dtype != np.bool_:
raise TypeError('Must pass DataFrame with boolean values only')
- if self._is_mixed_type:
- if not self._is_numeric_mixed_type:
- raise TypeError(
- 'Cannot do boolean setting on mixed-type frame')
-
+ self._check_inplace_setting(value)
self._check_setitem_copy()
self.where(-key, value, inplace=True)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index <HASH>..<HASH> 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1910,6 +1910,24 @@ class NDFrame(PandasObject):
f = lambda: self._data.is_datelike_mixed_type
return self._protect_consolidate(f)
+ def _check_inplace_setting(self, value):
+ """ check whether we allow in-place setting with this type of value """
+
+ if self._is_mixed_type:
+ if not self._is_numeric_mixed_type:
+
+ # allow an actual np.nan thru
+ try:
+ if np.isnan(value):
+ return True
+ except:
+ pass
+
+ raise TypeError(
+ 'Cannot do inplace boolean setting on mixed-types with a non np.nan value')
+
+ return True
+
def _protect_consolidate(self, f):
blocks_before = len(self._data.blocks)
result = f()
@@ -3214,6 +3232,8 @@ class NDFrame(PandasObject):
if inplace:
# we may have different type blocks come out of putmask, so
# reconstruct the block manager
+
+ self._check_inplace_setting(other)
new_data = self._data.putmask(mask=cond, new=other, align=axis is None,
inplace=True)
self._update_inplace(new_data)
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -9242,6 +9242,12 @@ class TestDataFrame(tm.TestCase, CheckIndexing,
expected = DataFrame({'series': Series([0,1,2,3,4,5,6,7,np.nan,np.nan]) })
assert_frame_equal(df, expected)
+ # GH 7656
+ df = DataFrame([{'A': 1, 'B': np.nan, 'C': 'Test'}, {'A': np.nan, 'B': 'Test', 'C': np.nan}])
+ expected = df.where(~isnull(df), None)
+ with tm.assertRaisesRegexp(TypeError, 'boolean setting on mixed-type'):
+ df.where(~isnull(df), None, inplace=True)
+
def test_where_align(self):
def create():
|
API: disallow inplace setting with where and a non-np.nan value (GH<I>)
|
pandas-dev_pandas
|
train
|
eb4c42aa1fa888dd44c0e325d5d70a9337b5f209
|
diff --git a/test/extended/util/test.go b/test/extended/util/test.go
index <HASH>..<HASH> 100644
--- a/test/extended/util/test.go
+++ b/test/extended/util/test.go
@@ -470,6 +470,9 @@ var (
"[Flaky]": {
`Job should run a job to completion when tasks sometimes fail and are not locally restarted`, // seems flaky, also may require too many resources
`openshift mongodb replication creating from a template`, // flaking on deployment
+
+ // TODO(node): test works when run alone, but not in the suite in CI
+ `\[Feature:HPA\] Horizontal pod autoscaling \(scale resource: CPU\) \[sig-autoscaling\] ReplicationController light Should scale from 1 pod to 2 pods`,
},
// tests that must be run without competition
"[Serial]": {
@@ -485,6 +488,7 @@ var (
`Should be able to support the 1\.7 Sample API Server using the current Aggregator`, // down apiservices break other clients today https://bugzilla.redhat.com/show_bug.cgi?id=1623195
+ `\[Feature:HPA\] Horizontal pod autoscaling \(scale resource: CPU\) \[sig-autoscaling\] ReplicationController light Should scale from 1 pod to 2 pods`,
},
"[Skipped:azure]": {
"Networking should provide Internet connection for containers", // Azure does not allow ICMP traffic to internet.
|
CHECK(cesarwong): extended: make HPA RC test serial, but disabled
Test runs fine when launched separately, but not in the CI test, neither in serial nor in the normal suite.
|
openshift_origin
|
train
|
766ba0593dc4291fe8a2804b064e753dabee9bea
|
diff --git a/lib/rfs.js b/lib/rfs.js
index <HASH>..<HASH> 100644
--- a/lib/rfs.js
+++ b/lib/rfs.js
@@ -90,7 +90,7 @@ module.exports = class {
return match;
}
- // Multiply by remValue if value is in rem
+ // Convert to px if in rem
if (unit === 'rem') {
value *= this.opts.remValue;
}
|
Turn code-repeating comment into an intent comment (#<I>)
The current comment just repeats what the code does and is not useful. My think, it will be better to specify the intent as suggested.
|
twbs_rfs
|
train
|
a1689c394a9c365adf9d26c79cfac84036162310
|
diff --git a/tests/nipaptest.py b/tests/nipaptest.py
index <HASH>..<HASH> 100755
--- a/tests/nipaptest.py
+++ b/tests/nipaptest.py
@@ -34,7 +34,6 @@ o = AuthOptions({
# disable caching of objects in Pynipap
pynipap.CACHE = False
-
class TestHelper:
@classmethod
@@ -3157,17 +3156,17 @@ class TestDatabaseConstraints(unittest.TestCase):
th.add_prefix('1.3.3.0/32', 'host', d)
th.add_prefix('1.3.3.1/32', 'host', d)
with self.assertRaisesRegexp(NipapValueError, "Prefix of type host must have all bits set in netmask"):
- # do not allow /31 as type 'host'
- th.add_prefix('1.3.3.2/31', 'host', d)
+ # do not allow /31 as type 'host'
+ th.add_prefix('1.3.3.2/31', 'host', d)
with self.assertRaisesRegexp(NipapValueError, "Parent prefix .* is of type assignment"):
- # unable to create assignment within assignment
- th.add_prefix('1.3.3.3/32', 'assignment', d)
+ # unable to create assignment within assignment
+ th.add_prefix('1.3.3.3/32', 'assignment', d)
with self.assertRaisesRegexp(NipapValueError, "contains hosts"):
- # unable to remove assignment containing hosts
- p3.remove()
+ # unable to remove assignment containing hosts
+ p3.remove()
with self.assertRaisesRegexp(NipapValueError, "'assignment' must not have any subnets other than of type 'host'"):
- p2.type = 'assignment'
- p2.save()
+ p2.type = 'assignment'
+ p2.save()
if __name__ == '__main__':
|
fix indentation to be a multiple of four
|
SpriteLink_NIPAP
|
train
|
36a9b73f53b7251483c606f3a773fac50b8452d9
|
diff --git a/src/main/java/org/thymeleaf/dom/DOMSelector.java b/src/main/java/org/thymeleaf/dom/DOMSelector.java
index <HASH>..<HASH> 100755
--- a/src/main/java/org/thymeleaf/dom/DOMSelector.java
+++ b/src/main/java/org/thymeleaf/dom/DOMSelector.java
@@ -149,7 +149,8 @@ public final class DOMSelector implements Serializable {
private final String selectorExpression;
private final boolean descendMoreThanOneLevel;
- private final String selectorPath;
+ private final String selectorPath; // This will not be normalized in case it is a reference
+ private final String normalizedSelectorPath; // We keep a normalized version in case it refers to a tag name
private final String selectorPathIdModifier;
private final String selectorPathClassModifier;
private final String selectorPathReferenceModifier;
@@ -254,7 +255,7 @@ public final class DOMSelector implements Serializable {
* Process path: extract id, class, reference modifiers...
*/
- String path = Node.normalizeName(selectorNameGroup);
+ String path = selectorNameGroup;
final int idModifierPos = path.indexOf(ID_MODIFIER_SEPARATOR);
final int classModifierPos = path.indexOf(CLASS_MODIFIER_SEPARATOR);
@@ -312,7 +313,8 @@ public final class DOMSelector implements Serializable {
}
this.selectorPath = path;
- this.text = TEXT_SELECTOR.equals(this.selectorPath);
+ this.normalizedSelectorPath = Node.normalizeName(this.selectorPath);
+ this.text = TEXT_SELECTOR.equals(this.normalizedSelectorPath);
/*
@@ -794,8 +796,8 @@ public final class DOMSelector implements Serializable {
final String elementName = element.getNormalizedName();
- if (!StringUtils.isEmptyOrWhitespace(this.selectorPath)) {
- if (!this.selectorPath.equals(elementName)) {
+ if (!StringUtils.isEmptyOrWhitespace(this.normalizedSelectorPath)) {
+ if (!this.normalizedSelectorPath.equals(elementName)) {
return false;
}
@@ -814,8 +816,8 @@ public final class DOMSelector implements Serializable {
final String elementName = element.getNormalizedName();
- if (!StringUtils.isEmptyOrWhitespace(this.selectorPath)) {
- if (!this.selectorPath.equals(elementName)) {
+ if (!StringUtils.isEmptyOrWhitespace(this.normalizedSelectorPath)) {
+ if (!this.normalizedSelectorPath.equals(elementName)) {
return false;
}
@@ -835,8 +837,8 @@ public final class DOMSelector implements Serializable {
final String elementName = element.getNormalizedName();
- if (!StringUtils.isEmptyOrWhitespace(this.selectorPath)) {
- if (!this.selectorPath.equals(elementName)) {
+ if (!StringUtils.isEmptyOrWhitespace(this.normalizedSelectorPath)) {
+ if (!this.normalizedSelectorPath.equals(elementName)) {
return false;
}
@@ -851,11 +853,11 @@ public final class DOMSelector implements Serializable {
final String elementName = element.getNormalizedName();
if (!StringUtils.isEmptyOrWhitespace(this.selectorPath)) {
- if (!this.selectorPath.equals(elementName)) {
+ if (!this.normalizedSelectorPath.equals(elementName)) {
if (referenceChecker == null) {
return false;
}
- return referenceChecker.checkReference(element, this.selectorPath);
+ return referenceChecker.checkReference(element, this.selectorPath); // This is the NOT normalized one!
}
}
// We don't have any reasons to deny it matches
|
Fixed DOM Selector: wrong matching of non-normalized names
|
thymeleaf_thymeleaf
|
train
|
3025b171647f80795282c7d6259cb209eec048c5
|
diff --git a/tests/function/test_mark_assert.py b/tests/function/test_mark_assert.py
index <HASH>..<HASH> 100644
--- a/tests/function/test_mark_assert.py
+++ b/tests/function/test_mark_assert.py
@@ -43,3 +43,64 @@ def test_simple(function_marked_bl_def_act_arr):
LineType.blank_line,
LineType._assert,
]
+
+
+# NOTE temporary tests to keep arrange blocks built the same with comments
+# until #148 is done
+
+@pytest.mark.parametrize('code_str', ['''
+def test_comment_after_act():
+ x = 1
+ y = 2
+
+ result = x + y
+ # Sum x and y
+
+ assert result == 2
+'''])
+def test_comment_after_act(function_marked_bl_def_act_arr):
+ """
+ Act block with trailing comment, comment is not marked as Assert
+ """
+ result = function_marked_bl_def_act_arr.mark_assert()
+
+ assert result == 1
+ assert function_marked_bl_def_act_arr.line_markers.types == [
+ LineType.func_def,
+ LineType.arrange,
+ LineType.arrange,
+ LineType.blank_line,
+ LineType.act,
+ LineType.act,
+ LineType.blank_line,
+ LineType._assert,
+ ]
+
+
+@pytest.mark.parametrize('code_str', ['''
+def test_comment_before_assert():
+ x = 1
+ y = 2
+
+ result = x + y
+
+ # Always 2
+ assert result == 2
+'''])
+def test_comment_start_assert(function_marked_bl_def_act_arr):
+ """
+ Comment at start of Assert is marked as part of that block
+ """
+ result = function_marked_bl_def_act_arr.mark_assert()
+
+ assert result == 2
+ assert function_marked_bl_def_act_arr.line_markers.types == [
+ LineType.func_def,
+ LineType.arrange,
+ LineType.arrange,
+ LineType.blank_line,
+ LineType.act,
+ LineType.blank_line,
+ LineType._assert,
+ LineType._assert,
+ ]
|
Add failing test for marking assert with comment in Act
|
jamescooke_flake8-aaa
|
train
|
3b95d349e0564593b234bc981daf232f405df9ce
|
diff --git a/wordfreq_builder/wordfreq_builder/config.py b/wordfreq_builder/wordfreq_builder/config.py
index <HASH>..<HASH> 100644
--- a/wordfreq_builder/wordfreq_builder/config.py
+++ b/wordfreq_builder/wordfreq_builder/config.py
@@ -60,7 +60,8 @@ CONFIG = {
'twitter-dist': 'dist/twitter_{lang}.{ext}',
'jieba-dist': 'dist/jieba_{lang}.{ext}'
},
- 'min_sources': 2
+ 'min_sources': 2,
+ 'big-lists': ['en', 'fr', 'es', 'pt']
}
diff --git a/wordfreq_builder/wordfreq_builder/ninja.py b/wordfreq_builder/wordfreq_builder/ninja.py
index <HASH>..<HASH> 100644
--- a/wordfreq_builder/wordfreq_builder/ninja.py
+++ b/wordfreq_builder/wordfreq_builder/ninja.py
@@ -353,9 +353,11 @@ def combine_lists(languages):
params={'lang': language, 'buckets': 600})
add_dep(lines, 'freqs2cB', output_file, output_cBpack_big,
extra='wordfreq_builder/word_counts.py',
- params={'lang': language, 'buckets': 900})
+ params={'lang': language, 'buckets': 800})
lines.append('default {}'.format(output_cBpack))
+ if language in CONFIG['big-lists']:
+ lines.append('default {}'.format(output_cBpack_big))
# Write standalone lists for Twitter frequency
if language in CONFIG['sources']['twitter']:
|
configuration that builds some larger lists
Former-commit-id: c1a<I>cebec4ed<I>d<I>c<I>a<I>a<I>e<I>bc
|
LuminosoInsight_wordfreq
|
train
|
96787db6efc26443897c10ed8eecd96d4022a2c2
|
diff --git a/restygwt/src/it/restygwt-overlay-example/src/main/java/org/fusesource/restygwt/examples/server/GreetingServlet.java b/restygwt/src/it/restygwt-overlay-example/src/main/java/org/fusesource/restygwt/examples/server/GreetingServlet.java
index <HASH>..<HASH> 100644
--- a/restygwt/src/it/restygwt-overlay-example/src/main/java/org/fusesource/restygwt/examples/server/GreetingServlet.java
+++ b/restygwt/src/it/restygwt-overlay-example/src/main/java/org/fusesource/restygwt/examples/server/GreetingServlet.java
@@ -26,10 +26,10 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.codehaus.jackson.JsonNode;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import org.codehaus.jackson.node.JsonNodeFactory;
-import org.codehaus.jackson.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
import org.fusesource.restygwt.client.Resource;
@@ -66,7 +66,7 @@ public class GreetingServlet extends HttpServlet {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode nameObject = mapper.readValue(req.getInputStream(), ObjectNode.class);
- String name = nameObject.get("name").getTextValue();
+ String name = nameObject.get("name").asText();
String greeting = "Hello " + name;
ObjectNode resultObject = new ObjectNode(JsonNodeFactory.instance);
|
fixed overlay example with jackson2
|
resty-gwt_resty-gwt
|
train
|
54d40a6673dd13bf8500f0c186f47d111693ce2a
|
diff --git a/src/main/java/org/efaps/ui/wicket/components/table/header/AjaxFilterLink.java b/src/main/java/org/efaps/ui/wicket/components/table/header/AjaxFilterLink.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/efaps/ui/wicket/components/table/header/AjaxFilterLink.java
+++ b/src/main/java/org/efaps/ui/wicket/components/table/header/AjaxFilterLink.java
@@ -68,7 +68,7 @@ public class AjaxFilterLink
(UITableHeader) getDefaultModelObject());
modal.setPageCreator(pagecreator);
modal.setInitialWidth(300);
- modal.setTitle(DBProperties.getProperty("FilterPage.Title") + getModelObject().getLabel());
+ modal.setTitle(DBProperties.getProperty("FilterPage.Title") + " " + getModelObject().getLabel());
modal.show(_target);
}
|
- Issue #<I>: The title for modal windows is noe escaped with wicket <I>
closes #<I>
|
eFaps_eFaps-WebApp
|
train
|
4488979ad394306011be42cec0e47936e08075b1
|
diff --git a/src/Orders/OrdersAWBInfo.php b/src/Orders/OrdersAWBInfo.php
index <HASH>..<HASH> 100644
--- a/src/Orders/OrdersAWBInfo.php
+++ b/src/Orders/OrdersAWBInfo.php
@@ -17,7 +17,7 @@ class OrdersAWBInfo {
* @return \Psr\Http\Message\ResponseInterface
* @throws \Exception
*/
- public function setAwbInfo($cmd, $courier, $plic = null, $packages = null, $kg = null){
+ public function setAwbInfo($cmd, $courier, $plic = null, $packages = null, $kg = null, $sambata = 0){
// Sanity check
if(!isset($cmd) || !is_int($cmd)) throw new \Exception('Specificati comanda');
if(!isset($courier) || trim($courier) == '') throw new \Exception('Specificati curierul');
@@ -41,6 +41,7 @@ class OrdersAWBInfo {
$data['packages'] = $packages;
$data['kg'] = $kg;
}
+ $data['sambata'] = $sambata;
// Send request and retrieve response
$result = Dispatcher::send($method, $action, $data);
|
Added parameter for Saturday delivery
modified: src/Orders/OrdersAWBInfo.php
|
celdotro_marketplace
|
train
|
bd6e0d0977cf0e6ad1a04c6f0809b6cfdb266b77
|
diff --git a/.bumpversion.cfg b/.bumpversion.cfg
index <HASH>..<HASH> 100644
--- a/.bumpversion.cfg
+++ b/.bumpversion.cfg
@@ -1,5 +1,5 @@
[bumpversion]
-current_version = 1.1.0
+current_version = 1.1.1
part = patch
commit = False
tag = False
diff --git a/README.rst b/README.rst
index <HASH>..<HASH> 100644
--- a/README.rst
+++ b/README.rst
@@ -71,7 +71,7 @@ uses yaml to define a directory structure, like in the tests)::
- b.py: |
from . import a
-``pydeps relimp --show-cycles`` displays::
+``pydeps relimp --show-cycles`` displays:
.. image:: https://dl.dropboxusercontent.com/u/94882440/pydeps-cycle.svg
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -48,9 +48,9 @@ copyright = u'2014 Bjorn Pettersen'
# built documents.
#
# The short X.Y version.
-version = '1.1.0'
+version = '1.1.1'
# The full version, including alpha/beta/rc tags.
-release = '1.1.0'
+release = '1.1.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/pydeps/__init__.py b/pydeps/__init__.py
index <HASH>..<HASH> 100644
--- a/pydeps/__init__.py
+++ b/pydeps/__init__.py
@@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
-__version__ = "1.1.0"
+__version__ = "1.1.1"
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ from distutils.core import setup
setup(
name='pydeps',
- version='1.1.0',
+ version='1.1.1',
packages=['pydeps'],
install_requires=[
'enum34'
|
Image didn't display in README.rst
|
thebjorn_pydeps
|
train
|
c78b2c1b62601a460b8fe2eeb3bbb178e0e73549
|
diff --git a/armstrong/hatband/tests/sites.py b/armstrong/hatband/tests/sites.py
index <HASH>..<HASH> 100644
--- a/armstrong/hatband/tests/sites.py
+++ b/armstrong/hatband/tests/sites.py
@@ -1,3 +1,5 @@
+import json
+
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
@@ -14,6 +16,14 @@ __all__ = [
"RenderModelPreviewTestCase",
]
+
+def staff_login(func):
+ def inner(self, *args, **kwargs):
+ self.client.login(username=self.staff.username, password=PASSWORD)
+ return func(self, *args, **kwargs)
+ return inner
+
+
class HatbandViewTestCase(TestCase):
def setUp(self):
super(HatbandViewTestCase, self).setUp()
@@ -79,9 +89,51 @@ class TypeAndModelToQueryViewTestCase(HatbandViewTestCase):
"content_type_id": content_type.pk,
"object_id": obj.pk})
+ @staff_login
+ def test_query_is_inside_response(self):
+ response = self.get_response()
+ data = json.loads(response.content)
+ self.assertTrue("query" in data)
+
+ @staff_login
+ def test_bad_response_on_unknown_content_type(self):
+ response = self.client.get(self.url, {"content_type_id": -1})
+ self.assertEqual(400, response.status_code)
+
+ @staff_login
+ def test_bad_response_on_no_object_id(self):
+ content_type = ContentType.objects.all()[0]
+ response = self.client.get(self.url,
+ {"content_type_id": content_type.pk})
+ self.assertEqual(400, response.status_code)
+
+ @staff_login
+ def test_returns_empty_query_on_unknown_object_id(self):
+ content_type = ContentType.objects.all()[0]
+ response = self.client.get(self.url,
+ {"content_type_id": content_type.pk, "object_id": -1})
+ self.assertEqual(200, response.status_code)
+
+ data = json.loads(response.content)
+ self.assertTrue("query" in data)
+ self.assertEqual("", data["query"])
+
+ @staff_login
+ def test_returns_string_suitable_for_display_in_gfk_widget(self):
+ content_type = ContentType.objects.all()[0]
+ obj = content_type.model_class().objects.all()[0]
+ response = self.client.get(self.url, {
+ "content_type_id": content_type.pk,
+ "object_id": obj.pk})
+ data = json.loads(response.content)
+ query = data["query"]
+ self.assertEqual('%s: "%d: %s"' % (content_type.model, obj.pk, obj, ),
+ query)
+
class RenderModelPreviewTestCase(HatbandViewTestCase):
view_name = "admin:render_model_preview"
+
def get_response(self):
cat = TestCategory.objects.create(name="cat")
TestArticle.objects.create(text="Hooray", category=cat)
diff --git a/armstrong/hatband/views/search.py b/armstrong/hatband/views/search.py
index <HASH>..<HASH> 100644
--- a/armstrong/hatband/views/search.py
+++ b/armstrong/hatband/views/search.py
@@ -118,11 +118,12 @@ class ModelPreviewMixin(ArmstrongBaseMixin):
class TypeAndModelQueryMixin(ArmstrongBaseMixin):
- url = "search/type_and_model_to_query/"
+ type_and_model_to_query_url = "search/type_and_model_to_query/"
def get_urls(self):
urlpatterns = patterns('',
- url(r"^%s/%s$" % (self.url_prefix, self.url),
+ url(r"^%s/%s$" % (self.url_prefix,
+ self.type_and_model_to_query_url),
self.admin_view(self.type_and_model_to_query),
name="type_and_model_to_query",
)
|
Fix issue where type_and_model_to_query just wouldn't work
|
armstrong_armstrong.hatband
|
train
|
0edbbd3feaaf1fa852dd4b92c1004f7d383c23b1
|
diff --git a/src/Symfony/Component/Validator/Constraints/FileValidator.php b/src/Symfony/Component/Validator/Constraints/FileValidator.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Validator/Constraints/FileValidator.php
+++ b/src/Symfony/Component/Validator/Constraints/FileValidator.php
@@ -58,7 +58,7 @@ class FileValidator extends ConstraintValidator
$binaryFormat = $constraint->binaryFormat;
} else {
$limitInBytes = $iniLimitSize;
- $binaryFormat = true;
+ $binaryFormat = null === $constraint->binaryFormat ? true : $constraint->binaryFormat;
}
list($sizeAsString, $limitAsString, $suffix) = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php
+++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php
@@ -455,11 +455,17 @@ abstract class FileValidatorTest extends AbstractConstraintValidatorTest
'{{ suffix }}' => 'bytes',
), '1');
+ // access FileValidator::factorizeSizes() private method to format max file size
+ $reflection = new \ReflectionClass(\get_class(new FileValidator()));
+ $method = $reflection->getMethod('factorizeSizes');
+ $method->setAccessible(true);
+ list($sizeAsString, $limit, $suffix) = $method->invokeArgs(new FileValidator(), array(0, UploadedFile::getMaxFilesize(), false));
+
// it correctly parses the maxSize option and not only uses simple string comparison
// 1000M should be bigger than the ini value
$tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
- '{{ limit }}' => UploadedFile::getMaxFilesize() / 1048576,
- '{{ suffix }}' => 'MiB',
+ '{{ limit }}' => $limit,
+ '{{ suffix }}' => $suffix,
), '1000M');
// it correctly parses the maxSize option and not only uses simple string comparison
|
Format file size in validation message according to binaryFormat option
|
symfony_symfony
|
train
|
87df27e0533c988e11ea5d318fe80c840e73d515
|
diff --git a/ice_js/lib/path_helper.js b/ice_js/lib/path_helper.js
index <HASH>..<HASH> 100644
--- a/ice_js/lib/path_helper.js
+++ b/ice_js/lib/path_helper.js
@@ -1,9 +1,8 @@
-function link_to(location, default_label, opts) {
- if (! default_label) {
- default_label = location
+function link_to(default_label, location, opts) {
+ if (! location) {
+ location = default_label
}
- label = (opts && opts.label) || default_label
- return "<a href=\"" + location + "\">" + label + "</a>"
+ return "<a href=\"" + location + "\">" + default_label + "</a>"
}
var NavBar = function (options) {
@@ -21,13 +20,13 @@ var NavBar = function (options) {
}
}
-NavBar.prototype.link_to = function (link, default_label) {
- link_code = link_to(link, default_label)
+NavBar.prototype.link_to = function (label, link) {
+ link_code = link_to(label, link)
if (this.link_wrapper) {
link_data = this.link_wrapper(link_code)
} else {
- link_data = "<li>" + link_to(link, default_label) + "</li>"
+ link_data = "<li>" + link_code + "</li>"
}
if (this.link_data && this.separator) {
link_data = this.separator + link_data
diff --git a/ice_js/spec/unit/spec.js b/ice_js/spec/unit/spec.js
index <HASH>..<HASH> 100644
--- a/ice_js/spec/unit/spec.js
+++ b/ice_js/spec/unit/spec.js
@@ -21,7 +21,7 @@ describe "NavBar"
links = (bar.open() + bar.link_to("ff", "aa") + bar.close())
- links.should.eql "<ul class=\"linkBar\"><li><a href=\"ff\">aa</a></li></ul>"
+ links.should.eql "<ul class=\"linkBar\"><li><a href=\"aa\">ff</a></li></ul>"
end
end
|
reversed link_to params to match rails
|
ludicast_ice
|
train
|
7e538da8ee9bf5362bb9eda20d69a3f43d7e057d
|
diff --git a/client/src/js/ng-django-forms.js b/client/src/js/ng-django-forms.js
index <HASH>..<HASH> 100644
--- a/client/src/js/ng-django-forms.js
+++ b/client/src/js/ng-django-forms.js
@@ -137,60 +137,54 @@ djng_forms_module.directive('ngModel', function() {
});
-djng_forms_module.directive('validateMultipleFields', function($timeout) {
+djng_forms_module.directive('validateMultipleFields', function($compile) {
return {
restrict: 'A',
require: '^?form',
- link: function(scope, element, attrs, controller) {
- var formCtrl, subFields, checkboxElems = [];
-
- function validate(event) {
- // $timeout(function(){
- console.log('change')
- console.log(formCtrl)
- var valid = false;
- angular.forEach(checkboxElems, function(checkbox) {
- console.log(checkbox)
- valid = valid || checkbox.checked;
- });
- console.log(valid)
- formCtrl.$setValidity('required', valid);
- if (event && angular.isString(subFields)) {
- formCtrl[subFields].$dirty = true;
- formCtrl[subFields].$pristine = false;
- }
- //})
- }
-
- function click(event) {
- console.log('click')
- var valid = false;
- angular.forEach(checkboxElems, function(checkbox) {
- valid = valid || checkbox.checked;
- });
- console.log(valid)
- }
-
- if (!controller)
- return;
- formCtrl = controller;
- try {
- subFields = angular.fromJson(attrs.validateMultipleFields);
- } catch (SyntaxError) {
- subFields = attrs.validateMultipleFields;
- }
+ compile: function(element, attrs) {
angular.forEach(element.find('input'), function(elem) {
- if (subFields.indexOf(elem.name) >= 0) {
- //elem.on('change', validate)
- console.log(elem)
- checkboxElems.push(elem);
- }
+ elem = angular.element(elem)
+ elem.attr('ng-change', 'changed()');
});
- element.find('input').on('change', validate);
- //element.on('change', validate);
- //element.on('click', click);
- validate();
+ return {
+
+ post: function(scope, element, attrs, controller) {
+ var formCtrl, subFields, checkboxElems = [];
+
+ scope.changed = function() {
+ validate(true)
+ }
+
+ function validate(trigger) {
+ var valid = false;
+ angular.forEach(checkboxElems, function(checkbox) {
+ valid = valid || checkbox.checked;
+ });
+ formCtrl.$setValidity('required', valid);
+ if (trigger && angular.isString(subFields)) {
+ formCtrl[subFields].$dirty = true;
+ formCtrl[subFields].$pristine = false;
+ }
+ }
+
+ if (!controller)
+ return;
+ formCtrl = controller;
+ try {
+ subFields = angular.fromJson(attrs.validateMultipleFields);
+ } catch (SyntaxError) {
+ subFields = attrs.validateMultipleFields;
+ }
+ angular.forEach(element.find('input'), function(elem) {
+ if (subFields.indexOf(elem.name) >= 0) {
+ checkboxElems.push(elem);
+ }
+ });
+
+ validate();
+ }
+ }
}
};
});
|
fix for FF checkbox change validate-multiple-fields issue
|
jrief_django-angular
|
train
|
6222518cd018a78710dcf8047eb16e937fc63363
|
diff --git a/lib/virtualbox/ext/glob_loader.rb b/lib/virtualbox/ext/glob_loader.rb
index <HASH>..<HASH> 100644
--- a/lib/virtualbox/ext/glob_loader.rb
+++ b/lib/virtualbox/ext/glob_loader.rb
@@ -9,14 +9,18 @@ module VirtualBox
# @param [Array<String>] initial_files Initial files (relative to `dir`)
# to load
def self.glob_require(dir, initial_files=[])
+ # Note: The paths below both are "downcased" because on Windows, some
+ # expand to "c:\" and some expand to "C:\" and cause the same file to
+ # be loaded twice. Uck.
+
initial_files.each do |file|
- require File.expand_path(file, dir)
+ require File.expand_path(file, dir).downcase
end
# Glob require the rest
Dir[File.join(dir, "**", "*.rb")].each do |f|
- require File.expand_path(f)
+ require File.expand_path(f).downcase
end
end
end
-end
\ No newline at end of file
+end
|
Downcase loaded files. Fixes oddest bug ever on Windows.
|
mitchellh_virtualbox
|
train
|
6f376193331a1810903a1e11a262a8c06726c744
|
diff --git a/lib/Facebook.js b/lib/Facebook.js
index <HASH>..<HASH> 100644
--- a/lib/Facebook.js
+++ b/lib/Facebook.js
@@ -63,8 +63,11 @@ function Facebookbot(configuration) {
facebook_message.sender_action = message.sender_action;
}
- //Add Access Token to outgoing request
+ if (message.notification_type) {
+ facebook_message.notification_type = message.notification_type
+ }
+ //Add Access Token to outgoing request
facebook_message.access_token = configuration.access_token;
request({
|
Add notification type field for message for Facebook integration
|
howdyai_botkit
|
train
|
b91dd8defdcd7ebf761460b1d9b494fee3b96657
|
diff --git a/source/org/jivesoftware/smackx/packet/LastActivity.java b/source/org/jivesoftware/smackx/packet/LastActivity.java
index <HASH>..<HASH> 100644
--- a/source/org/jivesoftware/smackx/packet/LastActivity.java
+++ b/source/org/jivesoftware/smackx/packet/LastActivity.java
@@ -113,7 +113,8 @@ public class LastActivity extends IQ {
String seconds = parser.getAttributeValue("", "seconds");
String message = parser.nextText();
if (seconds != null) {
- lastActivity.setLastActivity(Long.parseLong(seconds));
+ long xmlSeconds = new Double(seconds).longValue();
+ lastActivity.setLastActivity((int)xmlSeconds);
}
if (message != null) {
|
SMACK <I> - LastActivtity throws numberformat exception in certain cases. This has been resolved.
git-svn-id: <URL>
|
igniterealtime_Smack
|
train
|
143fb4d7f4b2bfed94f6d6e576e2d5b340e3463d
|
diff --git a/tests/classifiers.py b/tests/classifiers.py
index <HASH>..<HASH> 100644
--- a/tests/classifiers.py
+++ b/tests/classifiers.py
@@ -44,6 +44,8 @@ def optimize_final_model_classification(model_name=None):
lower_bound = -0.235
if model_name == 'LGBMClassifier':
lower_bound = -0.221
+ if model_name == 'GradientBoostingClassifier':
+ lower_bound = -0.225
assert lower_bound < test_score < -0.17
|
adjusts test bound for gradientboosting after bumping up learning rate
|
ClimbsRocks_auto_ml
|
train
|
a3335e58367ba777101a0c0c568e4a730ef78ebf
|
diff --git a/parse.go b/parse.go
index <HASH>..<HASH> 100644
--- a/parse.go
+++ b/parse.go
@@ -40,8 +40,6 @@ type parser struct {
spaced, newLine bool
- gotEnd bool
-
ltok, tok Token
lval, val string
@@ -401,7 +399,7 @@ func (p *parser) wantFollow(lpos Pos, left string, tok Token) {
}
func (p *parser) wantFollowStmt(lpos Pos, left string, s *Stmt) {
- if !p.gotStmt(s) {
+ if !p.gotStmt(s, false) {
p.followErr(lpos, left, "a statement")
}
}
@@ -482,13 +480,10 @@ func (p *parser) curErr(format string, v ...interface{}) {
func (p *parser) stmts(sts *[]Stmt, stops ...Token) {
for !p.eof() && !p.peekAny(stops...) {
var s Stmt
- if !p.gotStmt(&s) {
+ if !p.gotStmt(&s, true) {
p.invalidStmtStart()
}
*sts = append(*sts, s)
- if !p.gotEnd && !p.newLine {
- p.curErr("statements must be separated by &, ; or a newline")
- }
}
}
@@ -736,7 +731,7 @@ func (p *parser) assignSplit() int {
return i
}
-func (p *parser) gotStmt(s *Stmt) bool {
+func (p *parser) gotStmt(s *Stmt, wantStop bool) bool {
if p.peek(RBRACE) {
// don't let it be a LIT
return false
@@ -789,7 +784,9 @@ func (p *parser) gotStmt(s *Stmt) bool {
if _, ok := s.Node.(FuncDecl); ok {
return true
}
- p.gotEnd = p.peekStop()
+ if wantStop && !p.peekStop() {
+ p.curErr("statements must be separated by &, ; or a newline")
+ }
switch {
case p.got(LAND), p.got(LOR):
*s = p.binaryStmt(*s, addRedir)
|
Completely remove p.gotEnd
|
mvdan_sh
|
train
|
b4690b00f22336c1ea2d07b2a5d8616ace680fd4
|
diff --git a/expand/expand.go b/expand/expand.go
index <HASH>..<HASH> 100644
--- a/expand/expand.go
+++ b/expand/expand.go
@@ -194,6 +194,24 @@ func Format(cfg *Config, format string, args []string) (string, int, error) {
initialArgs := len(args)
for i := 0; i < len(format); i++ {
+ // readDigits reads from 0 to max digits, either octal or
+ // hexadecimal.
+ readDigits := func(max int, hex bool) string {
+ j := 0
+ for ; j < max; j++ {
+ c := format[i+j]
+ if (c >= '0' && c <= '9') ||
+ (hex && c >= 'a' && c <= 'f') ||
+ (hex && c >= 'A' && c <= 'F') {
+ // valid octal or hex char
+ } else {
+ break
+ }
+ }
+ digits := format[i : i+j]
+ i += j - 1 // -1 since the outer loop does i++
+ return digits
+ }
c := format[i]
switch {
case c == '\\': // escaped
@@ -217,6 +235,32 @@ func Format(cfg *Config, format string, args []string) (string, int, error) {
buf.WriteByte('\v')
case '\\', '\'', '"', '?': // just the character
buf.WriteByte(c)
+ case '0', '1', '2', '3', '4', '5', '6', '7':
+ digits := readDigits(3, false)
+ // if digits don't fit in 8 bits, 0xff via strconv
+ n, _ := strconv.ParseUint(digits, 8, 8)
+ buf.WriteByte(byte(n))
+ case 'x', 'u', 'U':
+ i++
+ max := 2
+ if c == 'u' {
+ max = 4
+ } else if c == 'U' {
+ max = 8
+ }
+ digits := readDigits(max, true)
+ if len(digits) > 0 {
+ // can't error
+ n, _ := strconv.ParseUint(digits, 16, 32)
+ if c == 'x' {
+ // always as a single byte
+ buf.WriteByte(byte(n))
+ } else {
+ buf.WriteRune(rune(n))
+ }
+ break
+ }
+ fallthrough
default: // no escape sequence
buf.WriteByte('\\')
buf.WriteByte(c)
diff --git a/interp/interp_test.go b/interp/interp_test.go
index <HASH>..<HASH> 100644
--- a/interp/interp_test.go
+++ b/interp/interp_test.go
@@ -233,6 +233,10 @@ var fileCases = []struct {
{`a=$"foo\nbar"; echo "$a"`, "foo\\nbar\n"},
{`echo $'\a\b\e\E\f\v'`, "\a\b\x1b\x1b\f\v\n"},
{`echo $'\\\'\"\?'`, "\\'\"?\n"},
+ {`echo $'\1\45\12345\777\9'`, "\x01%S45\xff\\9\n"},
+ {`echo $'\x\xf\x09\xAB'`, "\\x\x0f\x09\xab\n"},
+ {`echo $'\u\uf\u09\uABCD\u00051234'`, "\\u\u000f\u0009\uabcd\u00051234\n"},
+ {`echo $'\U\Uf\U09\UABCD\U00051234'`, "\\U\u000f\u0009\uabcd\U00051234\n"},
// escaped chars
{"echo a\\b", "ab\n"},
|
expand: support character escapes in Format
Fixes #<I>.
|
mvdan_sh
|
train
|
69c40103e50d1cdea2af0d6074cec0da809abbcd
|
diff --git a/server.go b/server.go
index <HASH>..<HASH> 100644
--- a/server.go
+++ b/server.go
@@ -2,6 +2,7 @@ package tbot
import (
"log"
+ "strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
@@ -72,6 +73,7 @@ func (s *Server) HandleDefault(handler HandlerFunction, description ...string) {
func (s *Server) processMessage(message *tgbotapi.Message) {
log.Printf("[TBot] %s %s: %s", message.From.FirstName, message.From.LastName, message.Text)
+ message.Text = s.trimBotName(message.Text)
handler, data := s.mux.Mux(message.Text)
if handler == nil {
return
@@ -90,7 +92,7 @@ func (s *Server) processMessage(message *tgbotapi.Message) {
case reply := <-m.replies:
err := s.dispatchMessage(message.Chat, reply)
if err != nil {
- log.Println(err)
+ log.Printf("Error dispatching message: %q", err)
}
case <-m.close:
return
@@ -102,3 +104,12 @@ func (s *Server) dispatchMessage(chat *tgbotapi.Chat, reply *ReplyMessage) error
_, err := s.bot.Send(reply.msg)
return err
}
+
+func (s *Server) trimBotName(message string) string {
+ parts := strings.SplitN(message, " ", 2)
+ command := parts[0]
+ command = strings.TrimSuffix(command, "@"+s.bot.Self.UserName)
+ command = strings.TrimSuffix(command, "@"+s.bot.Self.FirstName)
+ parts[0] = command
+ return strings.Join(parts, " ")
+}
|
[Fix #2] Filter bot UserName and FirstName in commands.
|
yanzay_tbot
|
train
|
06cc552b8b1196ff833eb911eccf1c234d4b0d67
|
diff --git a/lib/puppet/module.rb b/lib/puppet/module.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/module.rb
+++ b/lib/puppet/module.rb
@@ -124,7 +124,7 @@ class Puppet::Module
# defaulting to 'init.{pp,rb}' for empty modules.
def match_manifests(rest)
pat = File.join(path, MANIFESTS, rest || 'init')
- Dir.
+ [manifest("init.pp"),manifest("init.rb")].compact + Dir.
glob(pat + (File.extname(pat).empty? ? '.{pp,rb}' : '')).
reject { |f| FileTest.directory?(f) }
end
|
Fix for #<I> -- modules not implicitly loading their init files
The module init loading was broken in <I>f1e..b<I>edf and then gradually
removed as dead code. This is a minimal (and mildly ugly) reinsertion os it
with the addition of .rb support.
|
puppetlabs_puppet
|
train
|
d71d966abc419c4c64baeec67ad0fc5845b30313
|
diff --git a/fathom-core/src/main/java/fathom/conf/Settings.java b/fathom-core/src/main/java/fathom/conf/Settings.java
index <HASH>..<HASH> 100644
--- a/fathom-core/src/main/java/fathom/conf/Settings.java
+++ b/fathom-core/src/main/java/fathom/conf/Settings.java
@@ -203,22 +203,39 @@ public class Settings {
}
}
+ /**
+ * Returns the preferred application url (https is favored over http).
+ *
+ * @return the preferred application url
+ */
public String getApplicationUrl() {
-
- if (getHttpPort() > 0) {
- return String.format("http://%s:%s%s", getApplicationHostname(), getHttpPort(), getContextPath());
+ if (getHttpsPort() > 0) {
+ int port = getHttpsPort();
+ if (port == 443) {
+ return String.format("https://%s%s", getApplicationHostname(), getContextPath());
+ }
+ return String.format("https://%s:%s%s", getApplicationHostname(), port, getContextPath());
} else if (getHttpPort() > 0) {
- return String.format("https://%s:%s%s", getApplicationHostname(), getHttpsPort(), getContextPath());
+ int port = getHttpPort();
+ if (port == 80) {
+ return String.format("http://%s%s", getApplicationHostname(), getContextPath());
+ }
+ return String.format("http://%s:%s%s", getApplicationHostname(), getHttpPort(), getContextPath());
}
return null;
}
-
+ /**
+ * Returns the preferred host url (http is favored over https).
+ * Generally this url is used for integration testing.
+ *
+ * @return the preferred host url
+ */
public String getUrl() {
if (getHttpPort() > 0) {
return String.format("http://%s:%s%s", getHost(), getHttpPort(), getContextPath());
- } else if (getHttpPort() > 0) {
+ } else if (getHttpsPort() > 0) {
return String.format("https://%s:%s%s", getHost(), getHttpsPort(), getContextPath());
}
return null;
|
Exclude port <I> and <I> from applicaiton urls
|
gitblit_fathom
|
train
|
a8dc5e1786b6abc050ff5cd6ca5c4f0d91c88ead
|
diff --git a/brightbox.go b/brightbox.go
index <HASH>..<HASH> 100644
--- a/brightbox.go
+++ b/brightbox.go
@@ -118,9 +118,7 @@ func NewClient(apiUrl string, accountId string, httpClient *http.Client) (*Clien
c := &Client{
client: httpClient,
BaseURL: au,
- }
- if accountId != "" {
- c.AccountId = accountId
+ AccountId: accountId,
}
return c, nil
}
|
brightbox.go: Remove redundant test
AccountId zero value is "" anyway.
|
brightbox_gobrightbox
|
train
|
dc180bfac1a16fa2dc5921455198f18458d3579c
|
diff --git a/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/helper.go b/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/helper.go
index <HASH>..<HASH> 100644
--- a/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/helper.go
+++ b/vendor/k8s.io/kubernetes/pkg/client/typed/discovery/helper.go
@@ -49,6 +49,9 @@ func MatchesServerVersion(client DiscoveryInterface) error {
// preference.
// - If version is provided and the server does not support it,
// return an error.
+// TODO negotiation should be reserved for cases where we need a version for a given group. In those cases, it should return an ordered list of
+// server preferences. From that list, a separate function can match from an ordered list of client versions.
+// This is not what the function has ever done before, but it makes more logical sense.
func NegotiateVersion(client DiscoveryInterface, requiredGV *unversioned.GroupVersion, clientRegisteredGVs []unversioned.GroupVersion) (*unversioned.GroupVersion, error) {
clientVersions := sets.String{}
for _, gv := range clientRegisteredGVs {
diff --git a/vendor/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go b/vendor/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go
index <HASH>..<HASH> 100644
--- a/vendor/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go
+++ b/vendor/k8s.io/kubernetes/pkg/kubectl/cmd/util/clientcache.go
@@ -47,6 +47,9 @@ type ClientCache struct {
fedClientSets map[unversioned.GroupVersion]fed_clientset.Interface
configs map[unversioned.GroupVersion]*restclient.Config
+ // noVersionConfig provides a cached config for the case of no required version specified
+ noVersionConfig *restclient.Config
+
matchVersion bool
defaultConfigLock sync.Mutex
@@ -103,8 +106,10 @@ func (c *ClientCache) ClientConfigForVersion(requiredVersion *unversioned.GroupV
// before looking up from the cache
if requiredVersion != nil {
if config, ok := c.configs[*requiredVersion]; ok {
- return config, nil
+ return copyConfig(config), nil
}
+ } else if c.noVersionConfig != nil {
+ return copyConfig(c.noVersionConfig), nil
}
negotiatedVersion, err := discovery.NegotiateVersion(discoveryClient, requiredVersion, registered.EnabledVersions())
@@ -117,15 +122,23 @@ func (c *ClientCache) ClientConfigForVersion(requiredVersion *unversioned.GroupV
oldclient.SetKubernetesDefaults(&config)
if requiredVersion != nil {
- c.configs[*requiredVersion] = &config
+ c.configs[*requiredVersion] = copyConfig(&config)
+ } else {
+ c.noVersionConfig = copyConfig(&config)
}
// `version` does not necessarily equal `config.Version`. However, we know that we call this method again with
// `config.Version`, we should get the config we've just built.
- configCopy := config
- c.configs[*config.GroupVersion] = &configCopy
+ c.configs[*config.GroupVersion] = copyConfig(&config)
+
+ return copyConfig(&config), nil
+}
- return &config, nil
+func copyConfig(in *restclient.Config) *restclient.Config {
+ configCopy := *in
+ copyGroupVersion := *configCopy.GroupVersion
+ configCopy.GroupVersion = ©GroupVersion
+ return &configCopy
}
// ClientSetForVersion initializes or reuses a clientset for the specified version, or returns an
|
UPSTREAM: <I>: stop senseless negotiation
|
openshift_origin
|
train
|
f7b364c76d0f19ea12406c8ea0b54096d6880acb
|
diff --git a/datajoint/relational_operand.py b/datajoint/relational_operand.py
index <HASH>..<HASH> 100644
--- a/datajoint/relational_operand.py
+++ b/datajoint/relational_operand.py
@@ -385,7 +385,8 @@ class RelationalOperand:
def make_sql(self, select_fields=None):
return 'SELECT {fields} FROM {from_}{where}'.format(
- fields=select_fields or (("DISTINCT " if self.distinct else "") + self.select_fields),
+ fields=select_fields or (
+ ("DISTINCT " if self.distinct and self.primary_key else "") + self.select_fields),
from_=self.from_clause,
where=self.where_clause)
@@ -394,7 +395,8 @@ class RelationalOperand:
number of tuples in the relation.
"""
return self.connection.query(self.make_sql('count(%s)' % (
- ("DISTINCT `%s`" % '`,`'.join(self.primary_key)) if self.distinct else "*"))).fetchone()[0]
+ "DISTINCT `%s`" % '`,`'.join(self.primary_key)
+ if self.distinct and self.primary_key else "*"))).fetchone()[0]
def __bool__(self):
"""
|
bugfix in aggregation queries
|
datajoint_datajoint-python
|
train
|
d1e86b5bbe421c889951f500633cdbb56ff713f7
|
diff --git a/Gemfile b/Gemfile
index <HASH>..<HASH> 100644
--- a/Gemfile
+++ b/Gemfile
@@ -51,3 +51,7 @@ end
gem 'mysql2', :require => nil, :platform => :mri, :group => :test
gem 'pg', :require => nil, :platform => :mri, :group => :test
gem 'sqlite3', :require => nil, :platform => :mri, :group => :test
+group :mssql do
+ gem 'tiny_tds', :require => nil, :platform => :mri, :group => :test
+ gem 'activerecord-sqlserver-adapter', :require => nil, :platform => :mri, :group => :test
+end
diff --git a/test/db/mssql/types_test.rb b/test/db/mssql/types_test.rb
index <HASH>..<HASH> 100644
--- a/test/db/mssql/types_test.rb
+++ b/test/db/mssql/types_test.rb
@@ -46,7 +46,7 @@ class MSSQLDateTimeTypesTest < Test::Unit::TestCase
Time.zone = time_zone unless time_zone == false
end if ar_version('3.0')
- if ActiveRecord::Base.connection.sqlserver_version >= '2008'
+ if defined? JRUBY_VERSION && ActiveRecord::Base.connection.sqlserver_version >= '2008'
# 2008 Date and Time: http://msdn.microsoft.com/en-us/library/ff848733.aspx
diff --git a/test/db/mssql/unit_test.rb b/test/db/mssql/unit_test.rb
index <HASH>..<HASH> 100644
--- a/test/db/mssql/unit_test.rb
+++ b/test/db/mssql/unit_test.rb
@@ -1,8 +1,9 @@
require 'test_helper'
-require 'arjdbc/mssql'
class MSSQLUnitTest < Test::Unit::TestCase
+ def self.startup; require 'arjdbc/mssql' end
+
# NOTE: lot of tests kindly borrowed from __activerecord-sqlserver-adapter__
test "get table name" do
@@ -42,14 +43,14 @@ class MSSQLUnitTest < Test::Unit::TestCase
test 'return clean table_name from Utils.unqualify_table_name' do
@qualifed_table_names.each do |qtn|
assert_equal @expected_table_name,
- ArJdbc::MSSQL::Utils.send(:unqualify_table_name, qtn),
+ ArJdbc::MSSQL::Utils.unqualify_table_name(qtn),
"This qualifed_table_name #{qtn} did not unqualify correctly."
end
end
test 'return nil from Utils.unqualify_db_name when table_name is less than 2 qualified' do
@first_second_table_names.each do |qtn|
- assert_equal nil, ArJdbc::MSSQL::Utils.send(:unqualify_db_name, qtn),
+ assert_equal nil, ArJdbc::MSSQL::Utils.unqualify_db_name(qtn),
"This qualifed_table_name #{qtn} did not return nil."
end
end
@@ -57,7 +58,7 @@ class MSSQLUnitTest < Test::Unit::TestCase
test 'return clean db_name from Utils.unqualify_db_name when table is thrid level qualified' do
@third_table_names.each do |qtn|
assert_equal @expected_db_name,
- ArJdbc::MSSQL::Utils.send(:unqualify_db_name, qtn),
+ ArJdbc::MSSQL::Utils.unqualify_db_name(qtn),
"This qualifed_table_name #{qtn} did not unqualify the db_name correctly."
end
end
@@ -132,11 +133,13 @@ class MSSQLUnitTest < Test::Unit::TestCase
adapter
end
-end
+end if defined? JRUBY_VERSION
# This tests ArJdbc::MSSQL#add_lock! without actually connecting to the database.
class MSSQLRowLockingUnitTest < Test::Unit::TestCase
+ def self.startup; require 'arjdbc/mssql' end
+
def test_find_all
add_lock_test "Appointment.find(:all)",
%q{SELECT * FROM appointments},
@@ -269,14 +272,14 @@ class MSSQLRowLockingUnitTest < Test::Unit::TestCase
}
end
- class Dummy
- include ::ArJdbc::MSSQL::LockMethods
- end
+ class Dummy; end
private
def add_lock!(sql, options={})
result = sql.dup
+ mod = ::ArJdbc::MSSQL::LockMethods
+ Dummy.send(:include, mod) unless Dummy.include?(mod)
Dummy.new.add_lock!(result, {:lock=>true}.merge(options))
result
end
diff --git a/test/db/mssql_config.rb b/test/db/mssql_config.rb
index <HASH>..<HASH> 100644
--- a/test/db/mssql_config.rb
+++ b/test/db/mssql_config.rb
@@ -8,4 +8,6 @@ MSSQL_CONFIG[:port] = ENV['SQLPORT'] if ENV['SQLPORT']
unless ( ps = ENV['PREPARED_STATEMENTS'] || ENV['PS'] ).nil?
MSSQL_CONFIG[:prepared_statements] = ps
-end
\ No newline at end of file
+end
+
+MSSQL_CONFIG[:adapter] = 'sqlserver' unless defined? JRUBY_VERSION
\ No newline at end of file
|
support running tests with activerecord-sqlserver-adapter for testing compatibility
|
jruby_activerecord-jdbc-adapter
|
train
|
5d01bb0de2b0457995f348861c455bc7638e4b3f
|
diff --git a/packages/ember-glimmer/tests/integration/components/local-lookup-test.js b/packages/ember-glimmer/tests/integration/components/local-lookup-test.js
index <HASH>..<HASH> 100644
--- a/packages/ember-glimmer/tests/integration/components/local-lookup-test.js
+++ b/packages/ember-glimmer/tests/integration/components/local-lookup-test.js
@@ -258,6 +258,10 @@ if (EMBER_MODULE_UNIFICATION) {
get resolver() {
return this.owner.__registry__.fallback.resolver;
}
+ set resolver(resolver) {
+ // `resolver` needs a setter because RenderingTestCase sets `resolver` in
+ // its constructor
+ }
getResolver() {
return new LocalLookupTestResolver();
|
Add a resolver setter to local lookup test case
Since RenderingTestCase is setting `resolver` in its constructor, a
setter is necessary, even if it doesn't do anything.
|
emberjs_ember.js
|
train
|
f543d4dbfd21a964a1ddbca134442aeb73e6e408
|
diff --git a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/ConditionType.qunit.js b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/ConditionType.qunit.js
index <HASH>..<HASH> 100644
--- a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/ConditionType.qunit.js
+++ b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/ConditionType.qunit.js
@@ -494,7 +494,7 @@ sap.ui.define([
}
assert.ok(oException, "exception fired");
- assert.equal(oException && oException.message, "Enter a date after 01.01.2000", "Pattern of original date used in message");
+ assert.ok(oException && oException.message.startsWith("Enter a date after 01.01.2000"), "Pattern of original date used in message");
assert.ok(oValueType.validateValue.calledWith(new Date(1900, 0, 1)), "validateValue of ValueType called with currentValue");
assert.ok(oOriginalType.validateValue.calledWith(new Date(1900, 0, 1)), "validateValue of originalDateType called with currentValue");
diff --git a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/FieldBase.qunit.js b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/FieldBase.qunit.js
index <HASH>..<HASH> 100644
--- a/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/FieldBase.qunit.js
+++ b/src/sap.ui.mdc/test/sap/ui/mdc/qunit/field/FieldBase.qunit.js
@@ -3952,12 +3952,12 @@ sap.ui.define([
fnDone();
}).catch(function(oException) {
assert.ok(true, "Promise must be rejected");
- assert.equal(oException.message, "Enter a valid value");
+ assert.ok(oException.message.startsWith("Enter a valid value"));
assert.notOk(oFieldHelp.onFieldChange.called, "onFieldChange not called on FieldHelp");
setTimeout(function() { // for model update
setTimeout(function() { // for ManagedObjectModel update
assert.equal(oContent.getValueState(), "Error", "ValueState set");
- assert.equal(oContent.getValueStateText(), "Enter a valid value", "ValueStateText");
+ assert.ok(oContent.getValueStateText().startsWith("Enter a valid value"), "ValueStateText");
aConditions = oCM.getConditions("Name");
assert.equal(aConditions.length, 3, "three conditions in Codition model");
aConditions = oFieldHelp.getConditions();
|
[INTERNAL] mdc qunit tests: adjust test because of translation changes
Change-Id: If<I>dc<I>f<I>acbc8b<I>dcf<I>a5a0fba<I>
|
SAP_openui5
|
train
|
1c76e994cf5bb408d9eb7ac5ffd738d68d7f4684
|
diff --git a/astrocats/catalog/model.py b/astrocats/catalog/model.py
index <HASH>..<HASH> 100644
--- a/astrocats/catalog/model.py
+++ b/astrocats/catalog/model.py
@@ -14,13 +14,13 @@ class MODEL(KeyCollection):
NAME = Key('name', KEY_TYPES.STRING)
VERSION = Key('version', KEY_TYPES.STRING)
DATE = Key('date', KEY_TYPES.STRING)
- DESC = Key('description', KEY_TYPES.STRING, compare=False)
+ DESCRIPTION = Key('description', KEY_TYPES.STRING, compare=False)
# Numbers
ALIAS = Key('alias', KEY_TYPES.NUMERIC, compare=False)
SCORE = Key('score', KEY_TYPES.NUMERIC, compare=False)
CONVERGENCE = Key('convergence', KEY_TYPES.NUMERIC, compare=False)
STEPS = Key('steps', KEY_TYPES.NUMERIC, compare=False)
- # Arrays
+ # Arrays/dictionaries
REALIZATIONS = Key('realizations', compare=False)
SETUP = Key('setup', compare=False)
diff --git a/astrocats/catalog/photometry.py b/astrocats/catalog/photometry.py
index <HASH>..<HASH> 100644
--- a/astrocats/catalog/photometry.py
+++ b/astrocats/catalog/photometry.py
@@ -62,7 +62,7 @@ class PHOTOMETRY(KeyCollection):
BAND_SET = Key('bandset', KEY_TYPES.STRING)
SYSTEM = Key('system', KEY_TYPES.STRING)
- DESC = Key('description', KEY_TYPES.STRING, compare=False)
+ DESCRIPTION = Key('description', KEY_TYPES.STRING, compare=False)
U_TIME = Key('u_time', KEY_TYPES.STRING)
U_FLUX = Key('u_flux', KEY_TYPES.STRING)
diff --git a/astrocats/catalog/quantity.py b/astrocats/catalog/quantity.py
index <HASH>..<HASH> 100644
--- a/astrocats/catalog/quantity.py
+++ b/astrocats/catalog/quantity.py
@@ -21,7 +21,7 @@ class QUANTITY(KeyCollection):
PROB : NUMERIC
UPPER_LIMIT : BOOL
If this value corresponds to a measured upper-limit.
- DESC : STRING
+ DESCRIPTION : STRING
Verbal description or notes on a quantity.
U_VALUE : STRING
Unit of measurement associated with this value.
@@ -46,7 +46,7 @@ class QUANTITY(KeyCollection):
LOWER_LIMIT = Key('lowerlimit', KEY_TYPES.BOOL)
DERIVED = Key('derived', KEY_TYPES.BOOL)
# Strings
- DESC = Key('description', KEY_TYPES.STRING, compare=False)
+ DESCRIPTION = Key('description', KEY_TYPES.STRING, compare=False)
U_VALUE = Key('u_value', KEY_TYPES.STRING)
KIND = Key('kind', KEY_TYPES.STRING, listable=True)
SOURCE = Key('source', KEY_TYPES.STRING, compare=False)
|
MAINT: renamed `DESC` to `DESCRIPTION`
|
astrocatalogs_astrocats
|
train
|
0961f4ef7cda113fbae43f5350773519485c4793
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -69,7 +69,7 @@ setup(
'dimod/include/',
],
install_requires=[
- 'numpy>=1.17.3,<2.0.0', # keep synced with circle-ci, pyproject.toml
+ 'numpy>=1.17.3,<2.0.0,!=1.21.0,!=1.21.1' # keep synced with circle-ci, pyproject.toml
],
extras_require=dict(preprocessing='dwave-preprocessing>=0.3,<0.4'),
)
|
Remove support for numpy <I> and <I> due to typing bug
|
dwavesystems_dimod
|
train
|
71a560303b58711eb148dfe6fa69d3e43d28289e
|
diff --git a/nanofilt/version.py b/nanofilt/version.py
index <HASH>..<HASH> 100644
--- a/nanofilt/version.py
+++ b/nanofilt/version.py
@@ -1 +1 @@
-__version__= "1.1.4"
+__version__= "1.2.0"
|
bumping version to <I>
|
wdecoster_nanofilt
|
train
|
4ff5e8497cc7c88cd28e6e65789830f67190e430
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -17,6 +17,7 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+import codecs
import os
import re
@@ -41,7 +42,8 @@ def get_version():
def get_long_description():
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
changes = os.path.join(os.path.dirname(__file__), 'CHANGES.rst')
- return open(readme).read() + '\n' + open(changes).read()
+ return codecs.open(readme, encoding='utf-8').read() + '\n' + \
+ codecs.open(changes, encoding='utf-8').read()
setup(
|
Fix UTF8 README decoding.
|
kdeldycke_maildir-deduplicate
|
train
|
0d49d731d49a81ca1ff3c08d3a1a0830b3c0c4ad
|
diff --git a/lib/classes/basket/adapter.class.php b/lib/classes/basket/adapter.class.php
index <HASH>..<HASH> 100644
--- a/lib/classes/basket/adapter.class.php
+++ b/lib/classes/basket/adapter.class.php
@@ -511,7 +511,6 @@ class basket_adapter implements cache_cacheableInterface
$this->desc = $row['descript'];
$this->created_on = new DateTime($row['date']);
$this->updated_on = new DateTime($row['updater']);
- $this->usr_id = (int) $row['owner'];
$this->noview = !!$row['noview'];
$this->is_mine = ($row['owner'] == $this->usr_id);
|
Fix #<I> : wrong string about the validation process
|
alchemy-fr_Phraseanet
|
train
|
1f17a142d0188645dd29782a490161202b5b070f
|
diff --git a/lib/jsftp.js b/lib/jsftp.js
index <HASH>..<HASH> 100644
--- a/lib/jsftp.js
+++ b/lib/jsftp.js
@@ -100,18 +100,20 @@ var Ftp = module.exports = function(cfg) {
COMMANDS.forEach(this._generateCmd.bind(this));
- var self = this;
if (DEBUG_MODE) {
+ var self = this;
["command", "response", "connect", "reconnect", "disconnect"].forEach(function(event) {
self.emitter.on(event, self.log);
});
}
this._createSocket(this.port, this.host);
+ this._createStreams.call(this, this.socket);
+};
- var createStreams;
- (createStreams = function(_socket) {
- var cmd;
+(function() {
+ this._createStreams = function(_socket) {
+ var self = this;
// Stream of incoming data from the FTP server.
var input = function(next, stop) {
_socket.on("connect", self.onConnect || function(){});
@@ -121,16 +123,16 @@ var Ftp = module.exports = function(cfg) {
_socket.on("close", stop);
};
- self.cmdQueue = queue();
- (self.nextCmd = function nextCmd() {
+ var cmd;
+ this.cmdQueue = queue();
+ (this.nextCmd = function nextCmd() {
S.head(self.cmdQueue)(function(obj) {
cmd(obj, self.nextCmd);
- self.push(obj[0], obj[1] || function(){});
+ self.push(obj[0]);
});
})();
- var parse = self.parse.bind(self);
- var emitter = self.emitter;
+ var parse = this.parse.bind(this);
// Zips (as in array zipping) commands with responses. This creates
// a stream that keeps yielding command/response pairs as soon as each pair
// becomes available.
@@ -143,14 +145,15 @@ var Ftp = module.exports = function(cfg) {
// Stream of FTP commands from the client.
S.append(S.list(null), function(next, stop) { cmd = next; })
)
- (parse, function() { emitter.emit("disconnect", "disconnect"); });
- })(this.socket);
+ (parse, function() { self.emitter.emit("disconnect", "disconnect"); });
};
-(function() {
- // Writes a new command to the server, but before that it pushes the
- // command into `cmds` list. This command will get paired with its response
- // once that one is received
+ /**
+ * Writes a new command to the server.
+ *
+ * @param {String} command Command to write in the FTP socket
+ * @returns void
+ */
this.push = function(command) {
if (!command || typeof command !== "string")
return;
|
Isolated `_createStreams` method
|
sergi_jsftp
|
train
|
c92ab0987450a57011b093798cc65cb670634dd5
|
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/detect/FindRefComparison.java b/findbugs/src/java/edu/umd/cs/findbugs/detect/FindRefComparison.java
index <HASH>..<HASH> 100644
--- a/findbugs/src/java/edu/umd/cs/findbugs/detect/FindRefComparison.java
+++ b/findbugs/src/java/edu/umd/cs/findbugs/detect/FindRefComparison.java
@@ -524,7 +524,7 @@ public class FindRefComparison implements Detector, ExtendedTypes {
// make it medium priority
try {
if (!Hierarchy.isSubtype(lhsType, rhsType) && !Hierarchy.isSubtype(rhsType, lhsType))
- priority = NORMAL_PRIORITY;
+ priority = HIGH_PRIORITY;
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
return;
|
Raise priority for comparing objects known to be incomparable.
git-svn-id: <URL>
|
spotbugs_spotbugs
|
train
|
d4bab11473a861bfdd05f9afb462953f96b14505
|
diff --git a/allauth/account/managers.py b/allauth/account/managers.py
index <HASH>..<HASH> 100644
--- a/allauth/account/managers.py
+++ b/allauth/account/managers.py
@@ -32,7 +32,7 @@ class EmailAddressManager(models.Manager):
# this is a list rather than a generator because we probably want to
# do a len() on it right away
return [address.user for address in self.filter(verified=True,
- email=email)]
+ email__iexact=email)]
def fill_cache_for_user(self, user, addresses):
"""
|
E-mail case insensitive (partly addresses #<I>)
|
pennersr_django-allauth
|
train
|
143c33485395a64b795da13ca1e74897666d5df4
|
diff --git a/src/main/java/org/junit/runner/JUnitCore.java b/src/main/java/org/junit/runner/JUnitCore.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/junit/runner/JUnitCore.java
+++ b/src/main/java/org/junit/runner/JUnitCore.java
@@ -25,14 +25,7 @@ import org.junit.runner.notification.RunNotifier;
* @see org.junit.runner.Request
*/
public class JUnitCore {
- private RunNotifier fNotifier;
-
- /**
- * Create a new <code>JUnitCore</code> to run tests.
- */
- public JUnitCore() {
- fNotifier= new RunNotifier();
- }
+ private final RunNotifier fNotifier= new RunNotifier();
/**
* Run the tests contained in the classes named in the <code>args</code>.
|
Removed explicit constructor of JUnitCore
The constructor was used to create the RunNotifier. Now the
initial value of the RunNotifier is provided in its declaration.
Additionally added the final modifiert to the RunNotifier in
order to make it clear, that it never changes.
|
junit-team_junit4
|
train
|
c3d4d3f7c15275e4f2712017ea18812fbf48b8be
|
diff --git a/lib/form/modgrade.php b/lib/form/modgrade.php
index <HASH>..<HASH> 100644
--- a/lib/form/modgrade.php
+++ b/lib/form/modgrade.php
@@ -266,7 +266,8 @@ class MoodleQuickForm_modgrade extends MoodleQuickForm_group {
$point = (isset($vals['modgrade_point'])) ? $vals['modgrade_point'] : null;
$scale = (isset($vals['modgrade_scale'])) ? $vals['modgrade_scale'] : null;
$rescalegrades = (isset($vals['modgrade_rescalegrades'])) ? $vals['modgrade_rescalegrades'] : null;
- $return = $this->process_value($type, $scale, $point);
+
+ $return = $this->process_value($type, $scale, $point, $rescalegrades);
return array($this->getName() => $return, $this->getName() . '_rescalegrades' => $rescalegrades);
}
@@ -276,11 +277,17 @@ class MoodleQuickForm_modgrade extends MoodleQuickForm_group {
* @param string $type The value of the grade type select box. Can be 'none', 'scale', or 'point'
* @param string|int $scale The value of the scale select box.
* @param string|int $point The value of the point grade textbox.
+ * @param string $rescalegrades The value of the rescalegrades select.
* @return int The resulting value
*/
- protected function process_value($type='none', $scale=null, $point=null) {
+ protected function process_value($type='none', $scale=null, $point=null, $rescalegrades=null) {
global $COURSE;
$val = 0;
+ if ($this->isupdate && $this->hasgrades && $this->canrescale && $this->currentgradetype == 'point' && empty($rescalegrades)) {
+ // If the maxgrade field is disabled with javascript, no value is sent with the form and mform assumes the default.
+ // If the user was forced to choose a rescale option - and they haven't - prevent any changes to the max grade.
+ return $this->currentgrade;
+ }
switch ($type) {
case 'point':
if ($this->validate_point($point) === true) {
|
MDL-<I> forms: Mod grade is changing values back to default
When a field is disabled in the page - no value is sent and modgrade is reverting
to the default. This change prevents the max grade from changing accidentally.
|
moodle_moodle
|
train
|
6c46024da7b8029b534579cbafc75d6e10f889e6
|
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -93,4 +93,6 @@ gulp.task("examples", [
"example3",
"example4",
"example5"
-]);
\ No newline at end of file
+]);
+
+gulp.task("default", ["examples", "test"]);
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -96,6 +96,38 @@ it('should work with size checking', function (done) {
});
+it('should resize with percentage options', function (done) {
+
+ var stream = gulpGm(function (gmfile, done) {
+
+ gmfile.size(function (err, features) {
+ assert.equal(features.width, 500);
+ assert.equal(features.height, 456);
+ done(null, gmfile.resize("50%", "50%"));
+ });
+
+ });
+
+ checkImageSize(stream, done, [ 250, 228 ]);
+
+});
+
+it('should crop with percentage options', function (done) {
+
+ var stream = gulpGm(function (gmfile, done) {
+
+ gmfile.size(function (err, features) {
+ assert.equal(features.width, 500);
+ assert.equal(features.height, 456);
+ done(null, gmfile.crop("50%", "50%", 0, 0));
+ });
+
+ });
+
+ checkImageSize(stream, done, [ 250, 228 ]);
+
+});
+
it('should convert png to jpg', function (done) {
var stream = gulpGm(function (gmfile) {
@@ -111,4 +143,4 @@ it('should convert png to jpg', function (done) {
stream.write(fixtureFile());
-});
\ No newline at end of file
+});
|
added test examples for percentage values #6
|
scalableminds_gulp-gm
|
train
|
669b83878d11c2164a5254f71c2f48406bbb127e
|
diff --git a/src/sad_spirit/pg_wrapper/converters/datetime/BaseDateTimeConverter.php b/src/sad_spirit/pg_wrapper/converters/datetime/BaseDateTimeConverter.php
index <HASH>..<HASH> 100644
--- a/src/sad_spirit/pg_wrapper/converters/datetime/BaseDateTimeConverter.php
+++ b/src/sad_spirit/pg_wrapper/converters/datetime/BaseDateTimeConverter.php
@@ -23,6 +23,7 @@ namespace sad_spirit\pg_wrapper\converters\datetime;
use sad_spirit\pg_wrapper\{
converters\BaseConverter,
converters\ConnectionAware,
+ exceptions\InvalidArgumentException,
exceptions\TypeConversionException
};
@@ -77,9 +78,36 @@ abstract class BaseDateTimeConverter extends BaseConverter implements Connection
*/
public function setConnectionResource($resource): void
{
+ if (!is_resource($resource) || 'pgsql link' !== get_resource_type($resource)) {
+ throw InvalidArgumentException::unexpectedType(
+ __METHOD__,
+ 'a database connection resource',
+ $resource
+ );
+ }
+
$this->connection = $resource;
- $this->setDateStyle(pg_parameter_status($resource, 'DateStyle'));
+ $this->updateDateStyleFromConnection();
+ }
+
+ /**
+ * Tries to update date style from current connection resource, if available
+ *
+ * @return bool Whether $style actually changed
+ */
+ private function updateDateStyleFromConnection(): bool
+ {
+ if (
+ !is_resource($this->connection)
+ || false === ($style = pg_parameter_status($this->connection, 'DateStyle'))
+ || $style === $this->style
+ ) {
+ return false;
+ }
+
+ $this->style = $style;
+ return true;
}
/**
@@ -109,11 +137,7 @@ abstract class BaseDateTimeConverter extends BaseConverter implements Connection
}
}
// check whether datestyle setting changed
- if (
- $this->connection
- && $this->style !== ($style = pg_parameter_status($this->connection, 'DateStyle'))
- ) {
- $this->style = $style;
+ if ($this->updateDateStyleFromConnection()) {
foreach ($this->getFormats($this->style) as $format) {
if ($value = \DateTimeImmutable::createFromFormat('!' . $format, $native)) {
return $value;
@@ -126,14 +150,16 @@ abstract class BaseDateTimeConverter extends BaseConverter implements Connection
/**
* Converts PHP variable not identical to null into native format
*
+ * Actually accepts strings, integers and instances of \DateTimeInterface
+ *
* Note: a passed string will be returned as-is without any attempts to parse it.
* PostgreSQL's date and time parser accepts a lot more possible formats than this
* class can handle. Integer will be handled using date() with an appropriate
* format specification.
*
- * @param string|integer|\DateTimeInterface $value
+ * @param mixed $value
* @return string
- * @throws TypeConversionException
+ * @throws TypeConversionException if given a $value of unexpected type
*/
protected function outputNotNull($value): string
{
diff --git a/tests/converters/DateTest.php b/tests/converters/DateTest.php
index <HASH>..<HASH> 100644
--- a/tests/converters/DateTest.php
+++ b/tests/converters/DateTest.php
@@ -21,7 +21,9 @@ declare(strict_types=1);
namespace sad_spirit\pg_wrapper\tests\converters;
use PHPUnit\Framework\TestCase;
+use sad_spirit\pg_wrapper\Connection;
use sad_spirit\pg_wrapper\converters\datetime\DateConverter;
+use sad_spirit\pg_wrapper\exceptions\InvalidArgumentException;
use sad_spirit\pg_wrapper\exceptions\TypeConversionException;
/**
@@ -40,6 +42,35 @@ class DateTest extends TestCase
}
/**
+ * We cannot type hint a resource, so check that the method does not accept anything but
+ *
+ * @param mixed $bogusResource
+ * @dataProvider bogusResourceProvider
+ */
+ public function testSetConnectionResourceAcceptsOnlyPostgreSQLConnections($bogusResource): void
+ {
+ $this::expectException(InvalidArgumentException::class);
+ $this->caster->setConnectionResource($bogusResource);
+ }
+
+ public function testIgnoresClosedConnection(): void
+ {
+ if (!TESTS_SAD_SPIRIT_PG_WRAPPER_CONNECTION_STRING) {
+ $this::markTestSkipped('Connection string is not configured');
+ }
+
+ $connection = new Connection(TESTS_SAD_SPIRIT_PG_WRAPPER_CONNECTION_STRING);
+ $connection->execute("set datestyle to 'German'");
+ $this->caster->setConnectionResource($connection->getResource());
+
+ $this::assertEquals('2021-02-11', $this->caster->input('11.02.2021')->format('Y-m-d'));
+ $connection->disconnect();
+
+ $this::expectException(TypeConversionException::class);
+ $this->caster->input('2021-02-11');
+ }
+
+ /**
* @dataProvider getValuesFrom
* @param string|null $style
* @param string|null $native
@@ -100,4 +131,12 @@ class DateTest extends TestCase
[new TypeConversionException(), new \stdClass()]
];
}
+
+ public function bogusResourceProvider(): array
+ {
+ return [
+ ['resource'],
+ [fopen(__DIR__ . '/../../phpstan.neon', 'r')]
+ ];
+ }
}
|
Fix working with connection resource in date and time converters
|
sad-spirit_pg-wrapper
|
train
|
9b59a069452eb2aae59b1b167cbbfee338439985
|
diff --git a/ansible/modules/hashivault/hashivault_read.py b/ansible/modules/hashivault/hashivault_read.py
index <HASH>..<HASH> 100755
--- a/ansible/modules/hashivault/hashivault_read.py
+++ b/ansible/modules/hashivault/hashivault_read.py
@@ -75,6 +75,7 @@ EXAMPLES = '''
def main():
argspec = hashivault_argspec()
+ argspec['mount_point'] = dict(required=False, type='str', default='secret')
argspec['secret'] = dict(required=True, type='str')
argspec['key'] = dict(required=False, type='str')
argspec['version'] = dict(required=False, type='int', default=1)
@@ -96,8 +97,10 @@ from ansible.module_utils.hashivault import *
def hashivault_read(params):
result = { "changed": False, "rc" : 0}
client = hashivault_auth_client(params)
+ mount_point = params.get('mount_point')
secret = params.get('secret')
version = params.get('version')
+
key = params.get('key')
default = params.get('default')
with warnings.catch_warnings():
@@ -107,9 +110,9 @@ def hashivault_read(params):
response = client.read(secret)
else:
if version == 2:
- response = client.read(u'secret/data/%s' % secret)
+ response = client.secrets.kv.v2.read_secret_version(secret, mount_point=mount_point)
else:
- response = client.read(u'secret/%s' % secret)
+ response = client.secrets.kv.v1.read_secret(secret, mount_point=mount_point)
if not response:
if default is not None:
result['value'] = default
@@ -118,10 +121,7 @@ def hashivault_read(params):
result['failed'] = True
result['msg'] = u"Secret %s is not in vault" % secret
return result
- if version == 2:
- data = response['data']['data']
- else:
- data = response['data']
+ data = response['data']
if key and key not in data:
if default is not None:
result['value'] = default
diff --git a/ansible/plugins/lookup/hashivault.py b/ansible/plugins/lookup/hashivault.py
index <HASH>..<HASH> 100755
--- a/ansible/plugins/lookup/hashivault.py
+++ b/ansible/plugins/lookup/hashivault.py
@@ -45,12 +45,15 @@ class LookupModule(LookupBase):
except IndexError:
key = None
default = kwargs.get('default', None)
+ version = kwargs.get('version')
params = {
'url': self._get_url(environments),
'verify': self._get_verify(environments),
'secret': path,
'key': key,
'default': default,
+ 'version': version,
+ 'mount_point': 'secret',
}
authtype = self._get_environment(environments, 'VAULT_AUTHTYPE', 'token')
params['authtype'] = authtype
@@ -70,7 +73,6 @@ class LookupModule(LookupBase):
params['password'] = self._get_environment(environments, 'VAULT_PASSWORD')
else:
params['token'] = self._get_environment(environments, 'VAULT_TOKEN', hashivault_default_token())
-
return params
def _get_verify(self, environments):
|
Use the hvac kv interface for read
|
TerryHowe_ansible-modules-hashivault
|
train
|
716375eef96e23dfb13538bd60c946e41b0d2301
|
diff --git a/wily/state.py b/wily/state.py
index <HASH>..<HASH> 100644
--- a/wily/state.py
+++ b/wily/state.py
@@ -65,7 +65,7 @@ class Index(object):
def __contains__(self, item):
if isinstance(item, Revision):
- return item.key in self.revisions
+ return item.key in self.revision_keys
else:
return item in self.revisions
|
correct __contains__ for state index
|
tonybaloney_wily
|
train
|
1d4aaeb8bedea96391e8e418b8aa6395a5ec8329
|
diff --git a/scripts/types.js b/scripts/types.js
index <HASH>..<HASH> 100644
--- a/scripts/types.js
+++ b/scripts/types.js
@@ -80,7 +80,7 @@ function addTemplateData(data) {
throw new Error('got status code ' + res.statusCode + ' from template ' + data.template)
var body = yield getTemplateBody(res)
- var mime = extractTemplateMime(body, ref)
+ var mime = extractTemplateMime(body)
// use extracted mime if it's almost the same
if (mime && mime.replace(symbolRegExp, '-') === data.mime.replace(symbolRegExp, '-')) {
@@ -91,7 +91,7 @@ function addTemplateData(data) {
}
}
-function extractTemplateMime(body, ref) {
+function extractTemplateMime(body) {
var type = mimeTypeLineRegExp.exec(body)
var subtype = mimeSubtypeLineRegExp.exec(body)
@@ -100,7 +100,6 @@ function extractTemplateMime(body, ref) {
}
if (!type || !subtype) {
- //console.dir([ref, type&&type[1], subtype&&subtype[1]])
return
}
|
build: remove debugging from types script
|
jshttp_mime-db
|
train
|
14727205907419dc0db3ab763c38298b68adbb3a
|
diff --git a/lib/db/mongodb/search/comparisons.js b/lib/db/mongodb/search/comparisons.js
index <HASH>..<HASH> 100644
--- a/lib/db/mongodb/search/comparisons.js
+++ b/lib/db/mongodb/search/comparisons.js
@@ -66,7 +66,7 @@
function notlike(value){
return {
- $not: value
+ $not: like(value)
};
}
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
"name": "Mike Mostachetti"
}
],
- "version": "0.19.0",
+ "version": "0.19.1",
"repository": {
"type": "git",
"url": "https://github.com/Solid-Interactive/grasshopper-core-nodejs.git"
diff --git a/test/content/query.js b/test/content/query.js
index <HASH>..<HASH> 100644
--- a/test/content/query.js
+++ b/test/content/query.js
@@ -515,6 +515,34 @@ describe('Grasshopper core - content', function(){
});
});
+ describe('notlike (!%) operator', function() {
+ it ('accepts a regular expression as a value', function (done) {
+ grasshopper.request(tokens.globalAdminToken).content.query({
+ filters: [{ key: 'fields.label', cmp: '!%', value: /search test7/ }]
+ }).then(function (results) {
+ results.should.be.ok;
+ results.total.should.equal(20);
+ done();
+ })
+ .fail(done)
+ .catch(done)
+ .done();
+ });
+
+ it ('should apply a case insensitive search when a string is supplied as a value', function (done) {
+ grasshopper.request(tokens.globalAdminToken).content.query({
+ filters : [{key : 'fields.label', cmp : '!%', value : 'search'}]
+ }).then(function (results) {
+ results.should.be.ok;
+ results.total.should.equal(13);
+ done();
+ })
+ .fail(done)
+ .catch(done)
+ .done();
+ });
+ });
+
describe('or query', function() {
});
|
Changed the not like (!%) operator to return a regular expression. Used the existing like() function that does that.
|
grasshopper-cms_grasshopper-core-nodejs
|
train
|
a29acdd9e375c235129827bf4712d18bf417bc13
|
diff --git a/flaskext/uploads.py b/flaskext/uploads.py
index <HASH>..<HASH> 100644
--- a/flaskext/uploads.py
+++ b/flaskext/uploads.py
@@ -68,6 +68,11 @@ def extension(filename):
return filename.rsplit('.', 1)[-1]
+def lowercase_ext(filename):
+ main, ext = filename.rsplit('.', 1)
+ return main + '.' + ext.lower()
+
+
def addslash(url):
if url.endswith('/'):
return url
@@ -287,16 +292,16 @@ class UploadSet(object):
dest = self.config.destination
return os.path.join(dest, filename)
- def file_allowed(self, storage):
+ def file_allowed(self, storage, basename):
"""
This tells whether a file is allowed. It should return `True` if the
- given `werkzeug.FileStorage` object can be saved, and `False` if it
- can't. The default implementation just checks the extension, so you
- can override this if you want.
+ given `werkzeug.FileStorage` object can be saved with the given
+ basename, and `False` if it can't. The default implementation just
+ checks the extension, so you can override this if you want.
:param storage: The `werkzeug.FileStorage` to check.
"""
- return self.extension_allowed(extension(storage.filename))
+ return self.extension_allowed(extension(basename))
def extension_allowed(self, ext):
"""
@@ -323,15 +328,17 @@ class UploadSet(object):
"""
if not isinstance(storage, FileStorage):
raise TypeError("storage must be a werkzeug.FileStorage")
- if not self.file_allowed(storage):
- raise UploadNotAllowed()
- basename = secure_filename(storage.filename)
+
+ basename = lowercase_ext(secure_filename(storage.filename))
if name:
if name.endswith('.'):
basename = name + extension(basename)
else:
basename = name
+ if not self.file_allowed(storage, basename):
+ raise UploadNotAllowed()
+
if folder:
target_folder = os.path.join(self.config.destination, folder)
else:
|
now lowercases all extensions by default
|
maxcountryman_flask-uploads
|
train
|
954e3d2e670aec4e323906e1032e48df251ecfbd
|
diff --git a/src/basis/data/index.js b/src/basis/data/index.js
index <HASH>..<HASH> 100644
--- a/src/basis/data/index.js
+++ b/src/basis/data/index.js
@@ -599,29 +599,10 @@
}
}
+
/**
- * Extend for basis.data.AbstractDataset
- * @namespace basis.data.AbstractDataset
+ * @class
*/
- AbstractDataset.extend({
- /**
- * @param {basis.data.index.IndexConstructor}
- */
- getIndex: function(indexConstructor){
- ;;;basis.dev.warn('basis.data.Dataset#getIndex is deprecated and will be removed soon, use basis.data.index.getDatasetIndex or basis.data.index.{indexName} functions instead');
- return getDatasetIndex(this, indexConstructor);
- },
-
- /**
- * @param {basis.data.index.Index}
- */
- deleteIndex: function(index){
- ;;;basis.dev.warn('basis.data.Dataset#deleteIndex is deprecated and will be removed soon, use basis.data.index.removeDatasetIndex fucntion instead');
- removeDatasetIndex(this, index);
- }
- });
-
-
var CalcIndexPreset = Class(null, {
extendConstructor_: true,
indexes: {},
|
don't extend basis.data.AbstractDataset by getIndex/deleteIndex
|
basisjs_basisjs
|
train
|
ae9e6da614007eb7e17c7c26cb08e7f99640abc3
|
diff --git a/app/Http/Controllers/ReportEngineController.php b/app/Http/Controllers/ReportEngineController.php
index <HASH>..<HASH> 100644
--- a/app/Http/Controllers/ReportEngineController.php
+++ b/app/Http/Controllers/ReportEngineController.php
@@ -257,7 +257,7 @@ class ReportEngineController extends AbstractBaseController
return response($pdf, StatusCodeInterface::STATUS_OK, [
'Content-Type' => 'application/pdf',
- 'Content-Disposition' => 'attachment; filename="' . addcslashes($report, '"') . '"',
+ 'Content-Disposition' => 'attachment; filename="' . addcslashes($report, '"') . '.pdf"',
]);
}
}
|
Fix: #<I> - missing .PDF extension in report downloads
|
fisharebest_webtrees
|
train
|
ffdfce481409049e249698b91aadcb9df4088cb7
|
diff --git a/lib/prey/actions.js b/lib/prey/actions.js
index <HASH>..<HASH> 100644
--- a/lib/prey/actions.js
+++ b/lib/prey/actions.js
@@ -57,7 +57,7 @@ var ActionsManager = function(){
if(err)
logger.error(err);
else {
- if(typeof module_opts == 'object') loaded_module.options = opts;
+ if(typeof module_opts == 'object') loaded_module.options = module_opts;
loaded_modules.push(loaded_module);
}
|
Fixed opts reference error in lib/actions.
|
prey_prey-node-client
|
train
|
b90e60d1da252128f64c0c36facf6a3fd4df247c
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -486,7 +486,7 @@ Not every item supports every method. For instance, no current version of Redmi
setup(
name = "pyredmine",
packages = ["redmine"],
- install_requires = ["dateutil"],
+ install_requires = ["python-dateutil"],
version = "0.2.4",
description = "Python Redmine Web Services Library",
long_description = readme(),
|
Require "python-dateutil" instead of "dateutil".
I find this necessary with Python<I> in a Windows environment.
|
ianepperson_pyredminews
|
train
|
07535a64ee284126cbb871387e046c3e63934636
|
diff --git a/dht.go b/dht.go
index <HASH>..<HASH> 100644
--- a/dht.go
+++ b/dht.go
@@ -2,6 +2,7 @@ package dht
import (
"bytes"
+ "crypto/rand"
"fmt"
"sync"
"time"
@@ -637,3 +638,10 @@ func (dht *IpfsDHT) peerFromInfo(pbp *PBDHTMessage_PBPeer) (*peer.Peer, error) {
return dht.network.GetConnection(peer.ID(pbp.GetId()), maddr)
}
+
+// Builds up list of peers by requesting random peer IDs
+func (dht *IpfsDHT) Bootstrap() {
+ id := make([]byte, 16)
+ rand.Read(id)
+ dht.FindPeer(peer.ID(id), time.Second*10)
+}
diff --git a/routing.go b/routing.go
index <HASH>..<HASH> 100644
--- a/routing.go
+++ b/routing.go
@@ -340,6 +340,56 @@ func (dht *IpfsDHT) FindPeer(id peer.ID, timeout time.Duration) (*peer.Peer, err
return nil, u.ErrNotFound
}
+func (dht *IpfsDHT) findPeerMultiple(id peer.ID, timeout time.Duration) (*peer.Peer, error) {
+ // Check if were already connected to them
+ p, _ := dht.Find(id)
+ if p != nil {
+ return p, nil
+ }
+
+ routeLevel := 0
+ peers := dht.routingTables[routeLevel].NearestPeers(kb.ConvertPeerID(id), AlphaValue)
+ if len(peers) == 0 {
+ return nil, kb.ErrLookupFailure
+ }
+
+ found := make(chan *peer.Peer)
+ after := time.After(timeout)
+
+ for _, p := range peers {
+ go func(p *peer.Peer) {
+ pmes, err := dht.findPeerSingle(p, id, timeout, routeLevel)
+ if err != nil {
+ u.DErr("getPeer error: %v\n", err)
+ return
+ }
+ plist := pmes.GetPeers()
+ if len(plist) == 0 {
+ routeLevel++
+ }
+ for _, fp := range plist {
+ nxtp, err := dht.peerFromInfo(fp)
+ if err != nil {
+ u.DErr("findPeer error: %v\n", err)
+ continue
+ }
+
+ if nxtp.ID.Equal(dht.self.ID) {
+ found <- nxtp
+ return
+ }
+ }
+ }(p)
+ }
+
+ select {
+ case p := <-found:
+ return p, nil
+ case <-after:
+ return nil, u.ErrTimeout
+ }
+}
+
// Ping a peer, log the time it took
func (dht *IpfsDHT) Ping(p *peer.Peer, timeout time.Duration) error {
// Thoughts: maybe this should accept an ID and do a peer lookup?
|
add pub/priv key code to identify, not complete yet
|
libp2p_go-libp2p-kad-dht
|
train
|
97fce881a5ad5e692fc78385d8644b789a2a57c4
|
diff --git a/pkg/authorization/registry/rolebinding/policybased/virtual_storage.go b/pkg/authorization/registry/rolebinding/policybased/virtual_storage.go
index <HASH>..<HASH> 100644
--- a/pkg/authorization/registry/rolebinding/policybased/virtual_storage.go
+++ b/pkg/authorization/registry/rolebinding/policybased/virtual_storage.go
@@ -3,6 +3,7 @@ package policybased
import (
"errors"
"fmt"
+ "sort"
kapi "k8s.io/kubernetes/pkg/api"
kapierrors "k8s.io/kubernetes/pkg/api/errors"
@@ -71,6 +72,7 @@ func (m *VirtualStorage) List(ctx kapi.Context, options *kapi.ListOptions) (runt
}
}
+ sort.Sort(byName(roleBindingList.Items))
return roleBindingList, nil
}
@@ -338,3 +340,9 @@ func (m *VirtualStorage) getPolicyBindingOwningRoleBinding(ctx kapi.Context, bin
return nil, kapierrors.NewNotFound(m.Resource, bindingName)
}
+
+type byName []authorizationapi.RoleBinding
+
+func (r byName) Len() int { return len(r) }
+func (r byName) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
+func (r byName) Less(i, j int) bool { return r[i].Name < r[j].Name }
|
Sort `List` for RoleBinding virtual storage
|
openshift_origin
|
train
|
a37e039692c579158cc7110b2197aeb40afba412
|
diff --git a/dpxdt/server/api.py b/dpxdt/server/api.py
index <HASH>..<HASH> 100644
--- a/dpxdt/server/api.py
+++ b/dpxdt/server/api.py
@@ -241,6 +241,7 @@ def _get_or_create_run(build):
run = (
models.Run.query
.filter_by(release_id=release.id, name=run_name)
+ .with_lockmode('update')
.first())
if not run:
# Ignore re-reports of the same run name for this release.
@@ -478,6 +479,7 @@ def runs_done():
release = (
models.Release.query
.filter_by(build_id=build.id, name=release_name, number=release_number)
+ .with_lockmode('update')
.first())
utils.jsonify_assert(release, 'Release does not exist')
|
Always properly lock rows that may be updated in place
|
bslatkin_dpxdt
|
train
|
0467ad2d065bd5fddadaf24e57a9856613988957
|
diff --git a/hazelcast-client/src/main/java/com/hazelcast/client/nearcache/ClientNearCache.java b/hazelcast-client/src/main/java/com/hazelcast/client/nearcache/ClientNearCache.java
index <HASH>..<HASH> 100644
--- a/hazelcast-client/src/main/java/com/hazelcast/client/nearcache/ClientNearCache.java
+++ b/hazelcast-client/src/main/java/com/hazelcast/client/nearcache/ClientNearCache.java
@@ -198,14 +198,12 @@ public class ClientNearCache<K> {
fireTtlCleanup();
CacheRecord<K> record = cache.get(key);
if (record != null) {
-
+ record.access();
if (record.expired()) {
cache.remove(key);
stats.incrementMisses();
return null;
}
- record.access();
-
if (record.value.equals(NULL_OBJECT)){
stats.incrementMisses();
return NULL_OBJECT;
diff --git a/hazelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java b/hazelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java
index <HASH>..<HASH> 100644
--- a/hazelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java
+++ b/hazelcast-client/src/test/java/com/hazelcast/client/ClientNearCacheTest.java
@@ -189,7 +189,7 @@ public class ClientNearCacheTest {
HazelcastTestSupport.assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
- final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
+ final NearCacheStats stats = map.getLocalMapStats().getNearCacheStats();
assertEquals(expetedSize, stats.getOwnedEntryCount());
}
});
@@ -253,6 +253,9 @@ public class ClientNearCacheTest {
//populate near cache
for (int i = 0; i < 100; i++) {
map.get(i);
+ }
+ //this will be from near cache
+ for (int i = 0; i < 100; i++) {
map.get(i);
}
@@ -261,12 +264,12 @@ public class ClientNearCacheTest {
sleepSeconds(2);
- for (int i = 0; i < 100; i++) {
+ for (int i = 0; i < 100; i++) {
map.get(i);
}
stats = map.getLocalMapStats().getNearCacheStats();
- assertEquals(0, stats.getHits());
+ assertEquals(100, stats.getHits());
}
|
Merge branch 'master' into findbugsMajor
Conflicts:
hazelcast/src/main/java/com/hazelcast/mapreduce/impl/AbstractJob.java
|
hazelcast_hazelcast
|
train
|
db38c345fdc119edd8a892a5b0ba2c2a4b1cbe1f
|
diff --git a/lib/model.rb b/lib/model.rb
index <HASH>..<HASH> 100644
--- a/lib/model.rb
+++ b/lib/model.rb
@@ -68,10 +68,6 @@ module OpenTox
:method => "fingerprint",
:type => "MP2D",
},
- :similarity => {
- :method => "Algorithm::Similarity.tanimoto",
- :min => 0.5,
- },
:feature_selection => nil
}
@@ -79,10 +75,18 @@ module OpenTox
model.algorithms[:prediction] = {
:method => "Algorithm::Classification.weighted_majority_vote",
}
+ model.algorithms[:similarity] = {
+ :method => "Algorithm::Similarity.tanimoto",
+ :min => 0.1,
+ }
elsif model.class == LazarRegression
model.algorithms[:prediction] = {
:method => "Algorithm::Caret.rf",
}
+ model.algorithms[:similarity] = {
+ :method => "Algorithm::Similarity.tanimoto",
+ :min => 0.5,
+ }
end
elsif substance_classes.first == "OpenTox::Nanoparticle"
diff --git a/test/model-classification.rb b/test/model-classification.rb
index <HASH>..<HASH> 100644
--- a/test/model-classification.rb
+++ b/test/model-classification.rb
@@ -10,35 +10,35 @@ class LazarClassificationTest < MiniTest::Test
},
:similarity => {
:method => "Algorithm::Similarity.tanimoto",
- :min => 0.5
+ :min => 0.1
},
- :feature_selection => nil,
:prediction => {
:method => "Algorithm::Classification.weighted_majority_vote",
},
+ :feature_selection => nil,
}
training_dataset = Dataset.from_csv_file File.join(DATA_DIR,"hamster_carcinogenicity.csv")
model = Model::Lazar.create training_dataset: training_dataset
assert_kind_of Model::LazarClassification, model
assert_equal algorithms, model.algorithms
- substance = training_dataset.substances[49]
+ substance = training_dataset.substances[10]
prediction = model.predict substance
assert_equal "false", prediction[:value]
[ {
- :compound => OpenTox::Compound.from_inchi("InChI=1S/C6H14N2O4/c1-5(10)2-8(7-12)3-6(11)4-9/h5-6,9-11H,2-4H2,1H3"),
+ :compound => OpenTox::Compound.from_inchi("InChI=1S/C6H6/c1-2-4-6-5-3-1/h1-6H"),
:prediction => "false",
},{
- :compound => OpenTox::Compound.from_smiles("OCC(CN(CC(O)C)N=O)O"),
+ :compound => OpenTox::Compound.from_smiles("c1ccccc1NN"),
:prediction => "false",
} ].each do |example|
prediction = model.predict example[:compound]
assert_equal example[:prediction], prediction[:value]
end
- compound = Compound.from_smiles "O=NN1CCC1"
+ compound = Compound.from_smiles "CCO"
prediction = model.predict compound
assert_equal "true", prediction[:value]
- #assert_equal ["false"], prediction[:measurements]
+ assert_equal ["false"], prediction[:measurements]
# make a dataset prediction
compound_dataset = OpenTox::Dataset.from_csv_file File.join(DATA_DIR,"EPAFHM.mini_log10.csv")
@@ -46,12 +46,12 @@ class LazarClassificationTest < MiniTest::Test
assert_equal compound_dataset.compounds, prediction_dataset.compounds
cid = prediction_dataset.compounds[7].id.to_s
- assert_equal "Could not find similar substances with experimental data in the training dataset.", prediction_dataset.predictions[cid][:warnings][0]
+ assert_equal "Could not find similar substances with experimental data in the training dataset.", prediction_dataset.predictions[cid][:warning]
prediction_dataset.predictions.each do |cid,pred|
- assert_equal "Could not find similar substances with experimental data in the training dataset.", pred[:warnings][0] if pred[:value].nil?
+ assert_equal "Could not find similar substances with experimental data in the training dataset.", pred[:warning] if pred[:value].nil?
end
cid = Compound.from_smiles("CCOC(=O)N").id.to_s
- assert_match "excluded", prediction_dataset.predictions[cid][:info]
+ assert_match "excluded", prediction_dataset.predictions[cid][:warning]
# cleanup
[training_dataset,model,compound_dataset,prediction_dataset].each{|o| o.delete}
end
@@ -85,7 +85,7 @@ class LazarClassificationTest < MiniTest::Test
model = Model::Lazar.create training_dataset: training_dataset
t = Time.now
2.times do
- compound = Compound.from_smiles("OCC(CN(CC(O)C)N=O)O")
+ compound = Compound.from_smiles("Clc1ccccc1NN")
prediction = model.predict compound
assert_equal "1", prediction[:value]
end
diff --git a/test/validation-classification.rb b/test/validation-classification.rb
index <HASH>..<HASH> 100644
--- a/test/validation-classification.rb
+++ b/test/validation-classification.rb
@@ -47,9 +47,9 @@ class ValidationClassificationTest < MiniTest::Test
dataset = Dataset.from_csv_file "#{DATA_DIR}/hamster_carcinogenicity.csv"
model = Model::Lazar.create training_dataset: dataset
loo = ClassificationLeaveOneOut.create model
- assert_equal 77, loo.nr_unpredicted
+ assert_equal 14, loo.nr_unpredicted
refute_empty loo.confusion_matrix
- assert loo.accuracy > 0.74
+ assert loo.accuracy > 0.77
assert loo.weighted_accuracy > loo.accuracy, "Weighted accuracy (#{loo.weighted_accuracy}) should be larger than accuracy (#{loo.accuracy})."
end
|
set default min sim to <I> for classification and <I> for regression
|
opentox_lazar
|
train
|
7f03a2277a9ee18d7442c9aa16ac9df7c01b580c
|
diff --git a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/QueryCardinalityUtil.java b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/QueryCardinalityUtil.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/QueryCardinalityUtil.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/QueryCardinalityUtil.java
@@ -134,6 +134,7 @@ public final class QueryCardinalityUtil
return Range.atLeast(0L);
}
+ @Override
public Range<Long> visitValues(ValuesNode node, Void context)
{
return Range.singleton((long) node.getRows().size());
diff --git a/presto-main/src/main/java/com/facebook/presto/util/MoreLists.java b/presto-main/src/main/java/com/facebook/presto/util/MoreLists.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/util/MoreLists.java
+++ b/presto-main/src/main/java/com/facebook/presto/util/MoreLists.java
@@ -17,8 +17,11 @@ import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.function.Function;
+import java.util.function.IntFunction;
import java.util.function.Predicate;
+import java.util.stream.IntStream;
+import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;
@@ -49,5 +52,14 @@ public class MoreLists
.collect(toImmutableList());
}
+ public static <T> List<T> nElements(int n, IntFunction<T> function)
+ {
+ checkArgument(n >= 0, "n must be greater than or equal to zero");
+ requireNonNull(function, "function is null");
+ return IntStream.range(0, n)
+ .mapToObj(function)
+ .collect(toImmutableList());
+ }
+
private MoreLists() {}
}
diff --git a/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/PlanBuilder.java b/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/PlanBuilder.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/PlanBuilder.java
+++ b/presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/PlanBuilder.java
@@ -92,6 +92,7 @@ import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION;
+import static com.facebook.presto.util.MoreLists.nElements;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
@@ -163,7 +164,15 @@ public class PlanBuilder
public ValuesNode values(PlanNodeId id, Symbol... columns)
{
- return values(id, ImmutableList.copyOf(columns), ImmutableList.of());
+ return values(id, 0, columns);
+ }
+
+ public ValuesNode values(PlanNodeId id, int rows, Symbol... columns)
+ {
+ return values(
+ id,
+ ImmutableList.copyOf(columns),
+ nElements(rows, row -> nElements(columns.length, cell -> (Expression) new NullLiteral())));
}
public ValuesNode values(List<Symbol> columns, List<List<Expression>> rows)
|
Create VALUES with row values
This is often necessary in tests to have VALUES filled with some data
rows, otherwise `QueryCardinalityUtil` will deem VALUES as scalar,
affecting testing conditions.
|
prestodb_presto
|
train
|
d5f13b3f8de5e81f43f7db74659de7ecbcc5343f
|
diff --git a/lib/bashcov/errors.rb b/lib/bashcov/errors.rb
index <HASH>..<HASH> 100644
--- a/lib/bashcov/errors.rb
+++ b/lib/bashcov/errors.rb
@@ -0,0 +1,14 @@
+module Bashcov
+ # Signals an error parsing Bash's debugging output.
+ class XtraceError < ::RuntimeError
+ # Will contain the coverages parsed prior to the error
+ attr_reader :files
+
+ # @param [#to_s] message An error message
+ # @param [Hash] files A hash containing coverage information
+ def initialize(message, files)
+ @files = files
+ super(message)
+ end
+ end
+end
|
Added error class for indicating failure to parse Xtrace output
|
infertux_bashcov
|
train
|
e21742ca11cd4d92de4db61f30953d1db8c5a0c5
|
diff --git a/lib/pipe.js b/lib/pipe.js
index <HASH>..<HASH> 100644
--- a/lib/pipe.js
+++ b/lib/pipe.js
@@ -83,6 +83,10 @@
}
function onResult() {
+ var justEnd = end && !isFsWrite,
+ justFinish = write && !isFsRead,
+ bothFinish = end && finish;
+
if (readError && finish) {
rm('error', write, onWriteError);
rm('end', read, onReadEnd);
@@ -98,7 +102,7 @@
rm('error', read, onReadError);
onEnd();
- } else if ((end && !isFsWrite) || (write && !isFsRead) || (write && end)) {
+ } else if (bothFinish || justEnd || justFinish) {
rm('error', read, onReadError);
rm('error', write, onWriteError);
|
fix(pipe) call callback twice
|
coderaiser_pipe-io
|
train
|
9267352071da1e1892efaf62f88d26ca8c1fe851
|
diff --git a/tools/gas_cost_measures.py b/tools/gas_cost_measures.py
index <HASH>..<HASH> 100644
--- a/tools/gas_cost_measures.py
+++ b/tools/gas_cost_measures.py
@@ -21,7 +21,6 @@ pyevm_main.GENESIS_GAS_LIMIT = 6 * 10 ** 6
class ContractTester:
def __init__(self, generate_keys=0):
self.tester = EthereumTester(PyEVMBackend())
- self.tester.set_fork_block('FORK_BYZANTIUM', 0)
self.web3 = Web3(EthereumTesterProvider(self.tester))
if generate_keys > 0:
generated_keys = [urandom(32) for _ in range(generate_keys)]
|
Adapt gas measuring tool to new version of eth-tester
|
raiden-network_raiden
|
train
|
7631308cd570cdb6c46edd8711e075ddb12726e9
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -60,8 +60,9 @@ setup(
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
'Natural Language :: English',
'Operating System :: OS Independent',
- 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
- 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
'Topic :: Scientific/Engineering']
)
|
chore: update supported python versions
|
NeuroML_pyNeuroML
|
train
|
1ad79b63bcb301578c406f9e4a4965f877e2362b
|
diff --git a/addon/authenticators/osf-cookie.js b/addon/authenticators/osf-cookie.js
index <HASH>..<HASH> 100644
--- a/addon/authenticators/osf-cookie.js
+++ b/addon/authenticators/osf-cookie.js
@@ -36,7 +36,11 @@ export default Base.extend({
// Push the result into the store for later use by the current-user service
// Note: we have to deepcopy res because pushPayload mutates our data
// and causes an infinite loop because reasons
- this.get('store').pushPayload(Ember.copy(res['meta']['current_user'], true));
+ if (res['meta']['current_user'] !== null ){
+ this.get('store').pushPayload(Ember.copy(res['meta']['current_user'], true));
+ } else {
+ return Ember.RSVP.reject();
+ }
return res.data;
});
},
|
reject the promise instead of pushing into the store when current_user is null
|
CenterForOpenScience_ember-osf
|
train
|
b8017acc36f06fa097eb5ecd11ae1648ee6d08b9
|
diff --git a/docker/scripts/scripts/httpsender/Alert_on_Unexpected_Content_Types.js b/docker/scripts/scripts/httpsender/Alert_on_Unexpected_Content_Types.js
index <HASH>..<HASH> 100644
--- a/docker/scripts/scripts/httpsender/Alert_on_Unexpected_Content_Types.js
+++ b/docker/scripts/scripts/httpsender/Alert_on_Unexpected_Content_Types.js
@@ -10,6 +10,8 @@ var extensionAlert = org.parosproxy.paros.control.Control.getSingleton().getExte
var expectedTypes = [
"application/json",
"application/octet-stream",
+ "application/problem+json",
+ "application/problem+xml",
"application/soap+xml",
"application/xml",
"application/x-yaml",
|
Added expected types application/problem+json/xml
|
zaproxy_zaproxy
|
train
|
80d2ef39ad8a09c880498ba05c8eaed3e3115cd3
|
diff --git a/public/js/jsbin.js b/public/js/jsbin.js
index <HASH>..<HASH> 100644
--- a/public/js/jsbin.js
+++ b/public/js/jsbin.js
@@ -44,7 +44,7 @@ if (storedSettings === "undefined") {
window.jsbin.settings = $.extend(JSON.parse(storedSettings || '{}'), jsbin.settings);
// if the above code isn't dodgy, this for hellz bells is:
-jsbin.mobile = /WebKit.*Mobile.*/.test(navigator.userAgent);
+jsbin.mobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent);
jsbin.tablet = /iPad/i.test(navigator.userAgent); // sue me.
// IE detect - sadly uglify is compressing the \v1 trick to death :(
// via @padolsey & @jdalton - https://gist.github.com/527683
|
Fixed the scrollbars missing on Android - using the same trick as I use on iOS - I disable CodeMirror. Fixes #<I>
|
jsbin_jsbin
|
train
|
df960186e0b00c65a430701cee9df38ee07fb089
|
diff --git a/spec/controllers/gpg_keys_controller_spec.rb b/spec/controllers/gpg_keys_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/gpg_keys_controller_spec.rb
+++ b/spec/controllers/gpg_keys_controller_spec.rb
@@ -327,7 +327,7 @@ describe GpgKeysController, :katello => true do
put :update, :id => @gpg_key.id, :gpg_key => GPGKeyControllerTest::GPGKEY_NAME_INVALID
# checking for bad response since we're not notifying in order to
# handle iframe
- response.code.to_s =~ /^4/
+ response.code.to_s.should match /^4/
end
it "should be unsuccessful" do
|
Fix missing should in gpg controller spec
|
Katello_katello
|
train
|
c2366b85b3e1692ed09bb142db148276f7e0e601
|
diff --git a/admin/settings/server.php b/admin/settings/server.php
index <HASH>..<HASH> 100644
--- a/admin/settings/server.php
+++ b/admin/settings/server.php
@@ -95,6 +95,7 @@ $options = array(
$temp->add(new admin_setting_configselect('getremoteaddrconf', new lang_string('getremoteaddrconf', 'admin'),
new lang_string('configgetremoteaddrconf', 'admin'),
GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP, $options));
+$temp->add(new admin_setting_configtext('reverseproxyignore', new lang_string('reverseproxyignore', 'admin'), new lang_string('configreverseproxyignore', 'admin'), ''));
$temp->add(new admin_setting_heading('webproxy', new lang_string('webproxy', 'admin'), new lang_string('webproxyinfo', 'admin')));
$temp->add(new admin_setting_configtext('proxyhost', new lang_string('proxyhost', 'admin'), new lang_string('configproxyhost', 'admin'), '', PARAM_HOST));
diff --git a/lang/en/admin.php b/lang/en/admin.php
index <HASH>..<HASH> 100644
--- a/lang/en/admin.php
+++ b/lang/en/admin.php
@@ -329,6 +329,7 @@ $string['configrequestedstudentname'] = 'Word for student used in requested cour
$string['configrequestedstudentsname'] = 'Word for students used in requested courses';
$string['configrequestedteachername'] = 'Word for teacher used in requested courses';
$string['configrequestedteachersname'] = 'Word for teachers used in requested courses';
+$string['configreverseproxyignore'] = 'If your server is behind multiple reverse proxies that append to the X-Forwarded-For header then you will need to specify a comma separated list of ip addresses or subnets of the reverse proxies to be ignored in order to find the users correct IP address.';
$string['configsectioninterface'] = 'Interface';
$string['configsectionmail'] = 'Mail';
$string['configsectionmaintenance'] = 'Maintenance';
@@ -1064,6 +1065,7 @@ $string['restorernewroleid'] = 'Restorers\' role in courses';
$string['restorernewroleid_help'] = 'If the user does not already have the permission to manage the newly restored course, the user is automatically assigned this role and enrolled if necessary. Select "None" if you do not want restorers to be able to manage every restored course.';
$string['resultfilter'] = 'Filter by result';
$string['reverseproxy'] = 'Reverse proxy';
+$string['reverseproxyignore'] = 'Ignore reverse proxies';
$string['riskconfig'] = 'Users could change site configuration and behaviour';
$string['riskconfigshort'] = 'Configuration risk';
$string['riskdataloss'] = 'Users could destroy large amounts of content or information';
diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index <HASH>..<HASH> 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -9205,6 +9205,11 @@ function getremoteaddr($default='0.0.0.0') {
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
+ $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
+ global $CFG;
+ return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore, ',');
+ });
+
// Multiple proxies can append values to this header including an
// untrusted original request header so we must only trust the last ip.
$address = end($forwardedaddresses);
|
MDL-<I> core: Added $CFG->reverseproxyignore IP subnet list
If your server is behind multiple reverse proxies that append to the
X-Forwarded-For header then you will need to specify a comma separated
list of ip addresses or subnets of the reverse proxies to be ignored
in order to find the users correct IP address.
|
moodle_moodle
|
train
|
7f5a3ca2f77b9012787d272d2a06089f7871b705
|
diff --git a/app/models/renalware/letters/letter.rb b/app/models/renalware/letters/letter.rb
index <HASH>..<HASH> 100644
--- a/app/models/renalware/letters/letter.rb
+++ b/app/models/renalware/letters/letter.rb
@@ -41,14 +41,13 @@ module Renalware
where(event: event).first
end
+ EVENTS_MAP = {
+ Clinics::ClinicVisit => Event::ClinicVisit,
+ NilClass => Event::Unknown
+ }
+
def letter_event
- @letter_event ||=
- case event
- when Clinics::ClinicVisit
- Event::ClinicVisit.new(event)
- else
- Event::Unknown.new(nil)
- end
+ @letter_event ||= EVENTS_MAP.fetch(event.class).new(event)
end
def doctor
|
Define a mapping of letter events
|
airslie_renalware-core
|
train
|
2684420fb3748b09a03f5ad67cdff4bb45102763
|
diff --git a/tests/test_core.py b/tests/test_core.py
index <HASH>..<HASH> 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -1663,3 +1663,11 @@ def test_griffinlim_momentum_warn():
librosa.griffinlim(x, momentum=2)
+@pytest.mark.parametrize('ext', ['wav', 'mp3'])
+def test_get_samplerate(ext):
+
+ path = os.path.join('tests', 'data',
+ os.path.extsep.join(['test1_22050', ext]))
+
+ sr = librosa.get_samplerate(path)
+ assert sr == 22050
|
added test coverage for get_samplerate
|
librosa_librosa
|
train
|
41beeed04c172a67640e744482fe6cc137b383c9
|
diff --git a/angr/procedures/stubs/UserHook.py b/angr/procedures/stubs/UserHook.py
index <HASH>..<HASH> 100644
--- a/angr/procedures/stubs/UserHook.py
+++ b/angr/procedures/stubs/UserHook.py
@@ -7,7 +7,7 @@ class UserHook(angr.SimProcedure):
def run(self, user_func=None, length=None):
result = user_func(self.state)
if result is None:
- self.successors.add_successor(self.state, self.addr+length, self.state.se.true, 'Ijk_NoHook')
+ self.successors.add_successor(self.state, self.state.addr+length, self.state.se.true, 'Ijk_NoHook')
else:
for state in result:
- self.successors.add_successor(state, state.ip, state.scratch.guard, state.history.jumpkind)
+ self.successors.add_successor(state, state.addr, state.scratch.guard, state.history.jumpkind)
diff --git a/angr/state_plugins/solver.py b/angr/state_plugins/solver.py
index <HASH>..<HASH> 100644
--- a/angr/state_plugins/solver.py
+++ b/angr/state_plugins/solver.py
@@ -472,6 +472,8 @@ class SimSolver(SimStatePlugin):
:return: The value of `solution` cast to type `cast_to`
"""
if cast_to is str:
+ if len(e) == 0:
+ return ""
return '{:x}'.format(solution).zfill(len(e)/4).decode('hex')
if cast_to is not int:
diff --git a/tests/test_inspect.py b/tests/test_inspect.py
index <HASH>..<HASH> 100644
--- a/tests/test_inspect.py
+++ b/tests/test_inspect.py
@@ -229,7 +229,7 @@ def test_inspect_concretization():
s.add_constraints(y == 10)
s.inspect.b('address_concretization', BP_AFTER, action=abort_unconstrained)
s.memory.store(y, 'A')
- assert list(s.se.eval(s.memory.load(y, 1), 10)) == [ 0x41 ]
+ assert list(s.se.eval_upto(s.memory.load(y, 1), 10)) == [ 0x41 ]
try:
s.memory.store(x, 'A')
|
fixes for empty BVs, testcases and UserHooks
|
angr_angr
|
train
|
725df98a85c438d1af6a66403ea61ac08131ce52
|
diff --git a/deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/DeploymentScannerRemove.java b/deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/DeploymentScannerRemove.java
index <HASH>..<HASH> 100644
--- a/deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/DeploymentScannerRemove.java
+++ b/deployment-scanner/src/main/java/org/jboss/as/server/deployment/scanner/DeploymentScannerRemove.java
@@ -31,6 +31,7 @@ import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import org.jboss.dmr.ModelNode;
+import org.jboss.msc.service.ServiceName;
/**
* Operation removing a {@link DeploymentScannerService}.
@@ -50,7 +51,11 @@ class DeploymentScannerRemove extends AbstractRemoveStepHandler implements Descr
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) {
final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
final String name = address.getLastElement().getValue();
- context.removeService(DeploymentScannerService.getServiceName(name));
+ final ServiceName serviceName = DeploymentScannerService.getServiceName(name);
+ final ServiceName pathServiceName = serviceName.append("path");
+
+ context.removeService(serviceName);
+ context.removeService(pathServiceName);
}
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) {
|
[AS7-<I>] Removal of the deployment scanner is not complete and was preventing installation of scanner with name used previously.
was: <I>a<I>e5c<I>b<I>ef8a6e3d<I>c0e<I>abf
|
wildfly_wildfly-core
|
train
|
bde5b334cf28855359c36fb451795675055502c0
|
diff --git a/lib/Cache.js b/lib/Cache.js
index <HASH>..<HASH> 100644
--- a/lib/Cache.js
+++ b/lib/Cache.js
@@ -25,6 +25,7 @@ var Cache = function Cache(filename, ttl) {
if (!this.cache) {
this.cache = Object.create(null);
+ this.write();
}
};
@@ -78,14 +79,22 @@ Cache.prototype.set = function set(filename, entry) {
// watcher to take over once it has run
this.updated[filename] = true;
+ this.write();
+};
+
+Cache.prototype.write = function write() {
var json = JSON.stringify(this.cache);
try {
- // Sync writes to avoid any async collisions
mkdirp.sync(path.dirname(this.filename));
+ } catch(err) {
+ throw new Error('Failed to create path to webpack cache file: ' + this.filename);
+ }
+
+ try {
fs.writeFileSync(this.filename, json);
} catch(err) {
- console.error('Failed to write webpack cache file ' + this.filename, err.stack);
+ throw new Error('Failed to write webpack cache file: ' + this.filename);
}
};
diff --git a/test/Cache.js b/test/Cache.js
index <HASH>..<HASH> 100644
--- a/test/Cache.js
+++ b/test/Cache.js
@@ -23,9 +23,11 @@ describe('Cache', function() {
assert.isFunction(Cache);
});
it('should accept a filename argument', function() {
- var cache = new Cache('foo.bar');
- assert.equal(cache.filename, 'foo.bar');
+ var filename = path.join(TEST_OUTPUT_DIR, 'cache_init_test.json');
+ var cache = new Cache(filename);
+ assert.equal(cache.filename, filename);
assert.deepEqual(cache.cache, {});
+ assert.equal(fs.readFileSync(filename).toString(), '{}');
});
it('should be able to persist an entry to a file', function() {
var cache = new Cache(path.join(TEST_OUTPUT_DIR, 'cache_persist.json'));
@@ -70,7 +72,7 @@ describe('Cache', function() {
fs.writeFileSync(filename, '{}');
fs.writeFileSync(testFile, '{}');
- var cache = new Cache('test');
+ var cache = new Cache(filename);
cache.get(testFile, function(err, entry) {
assert.isNull(err);
diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -194,8 +194,7 @@ describe('webpack-wrapper', function() {
mkdirp.sync(path.dirname(cacheFile));
- var obj = {
- };
+ var obj = {};
obj[configFile] = {
startTime: +new Date() + 2000,
fileDependencies: [],
|
Caches now try to write on startup.
This enables permission errors to be detected during startup, rather than as an async event.
|
markfinger_webpack-build
|
train
|
2c5474ee93f402fdbaa24fd22cba1f4379004897
|
diff --git a/autofit/mapper/model.py b/autofit/mapper/model.py
index <HASH>..<HASH> 100644
--- a/autofit/mapper/model.py
+++ b/autofit/mapper/model.py
@@ -118,7 +118,7 @@ def populate(obj, collection: ResultsCollection):
@DynamicRecursionCache()
def path_instances_of_class(
- obj, cls: type, ignore_class: Optional[Union[type, Tuple[type]]] = None
+ obj, cls: type, ignore_class: Optional[Union[type, Tuple[type]]] = None
):
"""
Recursively search the object for instances of a given class
@@ -144,7 +144,12 @@ def path_instances_of_class(
try:
from autofit.mapper.prior_model.annotation import AnnotationPriorModel
- for key, value in obj.__dict__.items():
+ if isinstance(obj, dict):
+ d = obj
+ else:
+ d = obj.__dict__
+
+ for key, value in d.items():
for item in path_instances_of_class(value, cls, ignore_class=ignore_class):
if isinstance(value, AnnotationPriorModel):
path = (key,)
|
accounting for dictionaries in recursiona
|
rhayes777_PyAutoFit
|
train
|
fc4a6a54ae63892cb9f7d34b3f8cf29fb24736a6
|
diff --git a/lib/amq/protocol/table.rb b/lib/amq/protocol/table.rb
index <HASH>..<HASH> 100644
--- a/lib/amq/protocol/table.rb
+++ b/lib/amq/protocol/table.rb
@@ -45,8 +45,8 @@ module AMQ
buffer << TYPE_INTEGER
buffer << [value].pack(PACK_UINT32)
when Float then
- buffer << TYPE_32BIT_FLOAT
- buffer << [value].pack(PACK_32BIT_FLOAT)
+ buffer << TYPE_64BIT_FLOAT
+ buffer << [value].pack(PACK_64BIT_FLOAT)
when TrueClass, FalseClass then
value = value ? 1 : 0
buffer << TYPE_INTEGER
diff --git a/spec/amq/protocol/table_spec.rb b/spec/amq/protocol/table_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/amq/protocol/table_spec.rb
+++ b/spec/amq/protocol/table_spec.rb
@@ -17,7 +17,7 @@ module AMQ
{
{} => "\000\000\000\000",
{"test" => 1} => "\000\000\000\n\004testI\000\000\000\001",
- {"float" => 1.0} => "\000\000\000\v\005floatf\000\000\200?",
+ {"float" => 1.87} => "\000\000\000\017\005floatd\354Q\270\036\205\353\375?",
{"test" => "string"} => "\000\000\000\020\004testS\000\000\000\006string",
{"test" => {}} => "\000\000\000\n\004testF\000\000\000\000",
{"test" => bigdecimal_1} => "\000\000\000\v\004testD\000\000\000\000\001",
@@ -28,7 +28,7 @@ module AMQ
{
{} => "\x00\x00\x00\x00",
{"test" => 1} => "\x00\x00\x00\n\x04testI\x00\x00\x00\x01",
- {"float" => 1.0} => "\000\000\000\v\005floatf\000\000\200?",
+ {"float" => 1.92} => "\x00\x00\x00\x0F\x05floatd\xB8\x1E\x85\xEBQ\xB8\xFE?",
{"test" => "string"} => "\x00\x00\x00\x10\x04testS\x00\x00\x00\x06string",
{"test" => {}} => "\x00\x00\x00\n\x04testF\x00\x00\x00\x00",
{"test" => bigdecimal_1} => "\x00\x00\x00\v\x04testD\x00\x00\x00\x00\x01",
@@ -53,7 +53,7 @@ module AMQ
end
it "should return \"\x00\x00\x00\n\x04testI\x00\x00\x00\x01\" for { :coordinates => { :latitude => 59.35, :longitude => 18.066667 } }" do
- Table.encode(:coordinates => { :latitude => 59.35, :longitude => 18.066667 }).should eql("\x00\x00\x00.\vcoordinatesF\x00\x00\x00\x1D\blatitudefffmB\tlongitudef\x89\x88\x90A")
+ Table.encode(:coordinates => { :latitude => 59.35, :longitude => 18.066667 }).should eql("\000\000\0006\vcoordinatesF\000\000\000%\blatituded\315\314\314\314\314\254M@\tlongituded\361\270\250\026\021\0212@")
end
DATA.each do |data, encoded|
@@ -68,6 +68,10 @@ module AMQ
it "should return #{data.inspect} for #{encoded.inspect}" do
Table.decode(encoded).should eql(data)
end
+
+ it "is capable of decoding what it encodes" do
+ Table.decode(Table.encode(data)).should == data
+ end
end
end
end
|
Ruby floats are actually double-precision
|
ruby-amqp_amq-protocol
|
train
|
5cd759c8975ed2743dabcc573e63fe9d321aee6a
|
diff --git a/doc.go b/doc.go
index <HASH>..<HASH> 100644
--- a/doc.go
+++ b/doc.go
@@ -12,11 +12,14 @@
// source file.
//
// On top of filesystem watchers notify maintains a watchpoint tree, which provides
-// strategy for creating and closing filesystem watches and dispatching filesystem
+// a strategy for creating and closing filesystem watches and dispatching filesystem
// events to user channels.
//
// An event set is just an event list joint using bitwise OR operator
// into a single event value.
+// Both the platform-independent (see Constants) and specific events can be used.
+// Refer to the event_*.go source files for information about the available
+// events.
//
// A filesystem watch or just a watch is platform-specific entity which represents
// a single path registered for notifications for specific event set. Setting a watch
@@ -35,6 +38,6 @@
// A watchpoint is a list of user channel and event set pairs for particular
// path (watchpoint tree's node). A single watchpoint can contain multiple
// different user channels registered to listen for one or more events. A single
-// user channel can be registered in one or more watchpoints, recurisve and
+// user channel can be registered in one or more watchpoints, recursive and
// non-recursive ones as well.
package notify
diff --git a/event_readdcw.go b/event_readdcw.go
index <HASH>..<HASH> 100644
--- a/event_readdcw.go
+++ b/event_readdcw.go
@@ -27,7 +27,11 @@ const (
dirmarker
)
-// ReadDirectoryChangesW filters.
+// ReadDirectoryChangesW filters
+// On Windows the following events can be passed to Watch. A different set of
+// events (see actions below) are received on the channel passed to Watch.
+// For more information refer to
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465(v=vs.85).aspx
const (
FileNotifyChangeFileName = Event(syscall.FILE_NOTIFY_CHANGE_FILE_NAME)
FileNotifyChangeDirName = Event(syscall.FILE_NOTIFY_CHANGE_DIR_NAME)
@@ -48,7 +52,13 @@ const (
// this flag should be declared in: http://golang.org/src/pkg/syscall/ztypes_windows.go
const syscallFileNotifyChangeSecurity = 0x00000100
-// ReadDirectoryChangesW actions.
+// ReadDirectoryChangesW actions
+// The following events are returned on the channel passed to Watch, but cannot
+// be passed to Watch itself (see filters above). You can find a table showing
+// the relation between actions and filteres at
+// https://github.com/rjeczalik/notify/issues/10#issuecomment-66179535
+// The msdn documentation on actions is part of
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364391(v=vs.85).aspx
const (
FileActionAdded = Event(syscall.FILE_ACTION_ADDED) << 12
FileActionRemoved = Event(syscall.FILE_ACTION_REMOVED) << 12
|
Improve documentation (comments) about events and polish
|
rjeczalik_notify
|
train
|
a52e812b5b0c598ebc1a6309996376887971829d
|
diff --git a/wisdom-engine/src/main/java/org/wisdom/engine/ssl/FakeKeyStore.java b/wisdom-engine/src/main/java/org/wisdom/engine/ssl/FakeKeyStore.java
index <HASH>..<HASH> 100644
--- a/wisdom-engine/src/main/java/org/wisdom/engine/ssl/FakeKeyStore.java
+++ b/wisdom-engine/src/main/java/org/wisdom/engine/ssl/FakeKeyStore.java
@@ -22,6 +22,7 @@ public class FakeKeyStore {
public static final String KEYSTORE_PATH = "conf/fake.keystore";
public static final String DN_NAME = "CN=localhost, OU=Testing, O=Mavericks, L=Moon Base 1, ST=Cyberspace, " +
"C=CY";
+ private static final String SHA1WITHRSA = "SHA1withRSA";
private static final Logger LOGGER = LoggerFactory.getLogger("wisdom-engine");
private FakeKeyStore(){}
@@ -109,14 +110,14 @@ public class FakeKeyStore {
// Create a new certificate and sign it
X509CertImpl cert = new X509CertImpl(certInfo);
- cert.sign(keyPair.getPrivate(), "SHA1withRSA");
+ cert.sign(keyPair.getPrivate(), SHA1WITHRSA);
// Since the SHA1withRSA provider may have a different algorithm ID to what we think it should be,
// we need to reset the algorithm ID, and resign the certificate
AlgorithmId actualAlgorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, actualAlgorithm);
X509CertImpl newCert = new X509CertImpl(certInfo);
- newCert.sign(keyPair.getPrivate(), "SHA1withRSA");
+ newCert.sign(keyPair.getPrivate(), SHA1WITHRSA);
return newCert;
}
|
[minor] Define a constant instead of duplicating this literal "SHA1withRSA" 2 times.
|
wisdom-framework_wisdom
|
train
|
359682fc835be1f79e12e173439d9421a352cabb
|
diff --git a/lib/gremlin/address.rb b/lib/gremlin/address.rb
index <HASH>..<HASH> 100644
--- a/lib/gremlin/address.rb
+++ b/lib/gremlin/address.rb
@@ -1,6 +1,7 @@
module Gremlin
module Address
-
+ extend self
+
def zip_code
Gremlin.numerify ZIP_FORMATS.rand
end
@@ -37,6 +38,8 @@ module Gremlin
def neighborhood
NEIGHBORHOOD.rand
end
+
+ private
ZIP_FORMATS = ['#####', '#####-####']
diff --git a/lib/gremlin/geolocation.rb b/lib/gremlin/geolocation.rb
index <HASH>..<HASH> 100644
--- a/lib/gremlin/geolocation.rb
+++ b/lib/gremlin/geolocation.rb
@@ -1,5 +1,6 @@
module Gremlin
module Geolocation
+ extend self
def lat
(rand(1.8e11)-9e10)/1e9 # precision 9
diff --git a/lib/gremlin/internet.rb b/lib/gremlin/internet.rb
index <HASH>..<HASH> 100644
--- a/lib/gremlin/internet.rb
+++ b/lib/gremlin/internet.rb
@@ -1,12 +1,9 @@
module Gremlin
module Internet
-
+ extend self
+
def email
- [ user_name(name), domain_name ].join('@')
- end
-
- def free_email
- "#{user_name(name)}@#{HOSTS.rand}"
+ "#{user_name}@#{HOSTS.rand}"
end
def user_name
@@ -20,6 +17,8 @@ module Gremlin
parts
end
end
+
+ private
def domain_name
"#{domain_word}.#{domain_suffix}"
diff --git a/lib/gremlin/lorem.rb b/lib/gremlin/lorem.rb
index <HASH>..<HASH> 100644
--- a/lib/gremlin/lorem.rb
+++ b/lib/gremlin/lorem.rb
@@ -1,6 +1,7 @@
module Gremlin
# Based on Perl's Text::Lorem
module Lorem
+ extend self
def words
WORDS.random_pick(5)
diff --git a/lib/gremlin/name.rb b/lib/gremlin/name.rb
index <HASH>..<HASH> 100644
--- a/lib/gremlin/name.rb
+++ b/lib/gremlin/name.rb
@@ -1,5 +1,6 @@
module Gremlin
module Name
+ extend self
def name
case rand(10)
@@ -8,8 +9,6 @@ module Gremlin
else "#{first_name} #{last_name}"
end
end
-
- private
def first_name
FIRST_NAMES.rand
@@ -18,6 +17,8 @@ module Gremlin
def last_name
LAST_NAMES.rand
end
+
+ private
def prefix
PREFIXES.rand
diff --git a/lib/gremlin/phone_number.rb b/lib/gremlin/phone_number.rb
index <HASH>..<HASH> 100644
--- a/lib/gremlin/phone_number.rb
+++ b/lib/gremlin/phone_number.rb
@@ -1,5 +1,6 @@
module Gremlin
module PhoneNumber
+ extend self
def phone_number
Gremlin.numerify case rand(20)
@@ -22,9 +23,8 @@ module Gremlin
end
end
- def self.short_phone_number
+ def short_phone_number
Faker.numerify('###-###-####')
end
-
end
end
|
"extend self" and minor fixes
|
goncalossilva_dummy
|
train
|
303a340b591c3092248166f0aaacd4e11d1cf06d
|
diff --git a/src/vml/Painter.js b/src/vml/Painter.js
index <HASH>..<HASH> 100644
--- a/src/vml/Painter.js
+++ b/src/vml/Painter.js
@@ -12,7 +12,10 @@ define(function (require) {
function parseInt10(val) {
return parseInt(val, 10);
}
-
+
+ /**
+ * @alias module:zrender/vml/Painter
+ */
var VMLPainter = function (root, storage) {
vmlCore.initVML();
@@ -46,16 +49,13 @@ define(function (require) {
oldDelFromMap.call(storage, elId);
if (el) {
- el.dispose && el.dispose(vmlRoot);
+ el.onRemoveFromStorage && el.onRemoveFromStorage(vmlRoot);
}
}
storage.addToMap = function (el) {
// Displayable already has a vml node
- var vmlEl = el.__vmlEl;
- if (vmlEl) {
- vmlRoot.appendChild(vmlEl);
- }
+ el.onAddToStorage && el.onAddToStorage(vmlRoot);
oldAddToMap.call(storage, el);
}
@@ -129,10 +129,6 @@ define(function (require) {
return this._vmlRoot;
},
- _getHeight: function () {
- return this._height;
- },
-
_getWidth: function () {
var root = this.root;
var stl = root.currentStyle;
diff --git a/src/vml/graphic.js b/src/vml/graphic.js
index <HASH>..<HASH> 100644
--- a/src/vml/graphic.js
+++ b/src/vml/graphic.js
@@ -310,10 +310,16 @@ define(function (require) {
}
};
- Path.prototype.dispose = function (vmlRoot) {
+ Path.prototype.onRemoveFromStorage = function (vmlRoot) {
remove(vmlRoot, this._vmlEl);
- this.disposeRectText(vmlRoot);
- }
+ this.removeRectText(vmlRoot);
+ };
+
+
+ Path.prototype.onAddToStorage = function (vmlRoot) {
+ append(vmlRoot, this._vmlEl);
+ this.appendRectText(vmlRoot);
+ };
/***************************************************
* IMAGE
@@ -531,14 +537,19 @@ define(function (require) {
}
};
- ZImage.prototype.dispose = function (vmlRoot) {
+ ZImage.prototype.onRemoveFromStorage = function (vmlRoot) {
remove(vmlRoot, this._vmlEl);
this._vmlEl = null;
this._cropEl = null;
this._imageEl = null;
- this.disposeRectText(vmlRoot);
+ this.removeRectText(vmlRoot);
+ };
+
+ ZImage.prototype.onAddToStorage = function (vmlRoot) {
+ append(vmlRoot, this._vmlEl);
+ this.appendRectText(vmlRoot);
};
@@ -758,10 +769,14 @@ define(function (require) {
append(vmlRoot, textVmlEl);
};
- function disposeRectText(vmlRoot) {
+ function removeRectText(vmlRoot) {
remove(vmlRoot, this._textVmlEl);
this._textVmlEl = null;
}
+
+ function appendRectText(vmlRoot) {
+ append(vmlRoot, this._textVmlEl);
+ }
var list = [RectText, Displayable, ZImage, Path, Text];
@@ -769,7 +784,8 @@ define(function (require) {
for (var i = 0; i < list.length; i++) {
var proto = list[i].prototype;
proto.drawRectText = drawRectText;
- proto.disposeRectText = disposeRectText;
+ proto.removeRectText = removeRectText;
+ proto.appendRectText = appendRectText;
}
Text.prototype.brush = function (root) {
@@ -780,9 +796,13 @@ define(function (require) {
width: 0, height: 0
}, this.getBoundingRect());
}
- }
+ };
- Text.prototype.dispose = function (vmlRoot) {
- this.disposeRectText(vmlRoot);
- }
+ Text.prototype.onRemoveFromStorage = function (vmlRoot) {
+ this.removeRectText(vmlRoot);
+ };
+
+ Text.prototype.onAddToStorage = function (vmlRoot) {
+ this.appendRectText(vmlRoot);
+ };
});
\ No newline at end of file
|
VML graphic element onAddToStorage and onRemoveStorage hook
|
ecomfe_zrender
|
train
|
e76a3d407f6a1071054e2cd59a14de749ac0e71b
|
diff --git a/abydos/distance/_token_distance.py b/abydos/distance/_token_distance.py
index <HASH>..<HASH> 100644
--- a/abydos/distance/_token_distance.py
+++ b/abydos/distance/_token_distance.py
@@ -272,7 +272,7 @@ class _TokenDistance(_Distance):
def _src_card(self):
r"""Return the cardinality of the tokens in the source set."""
- return self.normalizer(sum(self._src_tokens.values()), 2)
+ return self.normalizer(sum(abs(val) for val in self._src_tokens.values()), 2)
def _src_only(self):
r"""Return the src tokens minus the tar tokens.
@@ -283,11 +283,11 @@ class _TokenDistance(_Distance):
def _src_only_card(self):
"""Return the cardinality of the tokens only in the source set."""
- return self.normalizer(sum(self._src_only().values()), 1)
+ return self.normalizer(sum(abs(val) for val in self._src_only().values()), 1)
def _tar_card(self):
r"""Return the cardinality of the tokens in the target set."""
- return self.normalizer(sum(self._tar_tokens.values()), 2)
+ return self.normalizer(sum(abs(val) for val in self._tar_tokens.values()), 2)
def _tar_only(self):
r"""Return the tar tokens minus the src tokens.
@@ -298,7 +298,7 @@ class _TokenDistance(_Distance):
def _tar_only_card(self):
"""Return the cardinality of the tokens only in the target set."""
- return self.normalizer(sum(self._tar_only().values()), 1)
+ return self.normalizer(sum(abs(val) for val in self._tar_only().values()), 1)
def _symmetric_difference(self):
r"""Return the symmetric difference of tokens from src and tar.
@@ -309,7 +309,7 @@ class _TokenDistance(_Distance):
def _symmetric_difference_card(self):
"""Return the cardinality of the symmetric difference."""
- return self.normalizer(sum(self._symmetric_difference().values()), 2)
+ return self.normalizer(sum(abs(val) for val in self._symmetric_difference().values()), 2)
def _total(self):
"""Return the sum of the sets.
@@ -323,7 +323,7 @@ class _TokenDistance(_Distance):
def _total_card(self):
"""Return the cardinality of the complement of the total."""
- return self.normalizer(sum(self._total().values()), 3)
+ return self.normalizer(sum(abs(val) for val in self._total().values()), 3)
def _total_complement_card(self):
"""Return the cardinality of the complement of the total."""
@@ -331,7 +331,7 @@ class _TokenDistance(_Distance):
return self.normalizer(0, 1)
elif isinstance(self.params['alphabet'], Counter):
return self.normalizer(
- sum((self.params['alphabet']).values() - self._total()), 1
+ sum(abs(val) for val in (self.params['alphabet']).values() - self._total()), 1
)
return self.normalizer(
self.params['alphabet'] - len(self._total().values()), 1
@@ -354,7 +354,7 @@ class _TokenDistance(_Distance):
def _union_card(self):
"""Return the cardinality of the union."""
- return self.normalizer(sum(self._union().values()), 3)
+ return self.normalizer(abs(val) for val in sum(self._union().values()), 3)
def _difference(self):
"""Return the difference of the tokens, supporting negative values."""
@@ -443,7 +443,7 @@ class _TokenDistance(_Distance):
def _intersection_card(self):
"""Return the cardinality of the intersection."""
- return self.normalizer(sum(self.intersection().values()), 1)
+ return self.normalizer(sum(abs(val) for val in self.intersection().values()), 1)
def _get_confusion_table(self):
"""Return the token counts as a ConfusionTable object."""
|
made token distance base a little more robust (to negative values)
|
chrislit_abydos
|
train
|
150c44b839d123a1ce9383043f8151f1fa219623
|
diff --git a/base.php b/base.php
index <HASH>..<HASH> 100644
--- a/base.php
+++ b/base.php
@@ -211,8 +211,11 @@ final class Base {
$this->set('REQUEST'.$expr[2],$val);
if ($expr[1]=='COOKIE') {
$parts=$this->cut($key);
+ $jar=$this->hive['JAR'];
+ if ($ttl)
+ $jar['expire']=$ttl;
call_user_func_array('setcookie',
- array_merge(array($parts[1],$val),$this->hive['JAR']));
+ array_merge(array($parts[1],$val),$jar));
}
}
else switch ($key) {
|
Use $ttl for cookie expiration (Issue #<I>)
|
bcosca_fatfree-core
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.