hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
ddeffafdb4b0f9440b2099ca88ae00349a828dfd
|
diff --git a/src/Handlers/ImageHandler.php b/src/Handlers/ImageHandler.php
index <HASH>..<HASH> 100644
--- a/src/Handlers/ImageHandler.php
+++ b/src/Handlers/ImageHandler.php
@@ -123,7 +123,13 @@ class ImageHandler extends ImageModifier
}
// var_dump( $path );
- parent::save( $path );
+ $returnValue = parent::save( $path );
+
+ // Reset
+ $this->resetImageObject();
+
+ // Return $this-> from parent
+ return $returnValue;
}
/**
@@ -136,9 +142,9 @@ class ImageHandler extends ImageModifier
{
// Modify values
- $width = $this->setWidth ? $this->getWidth() : '_';
- $height = $this->setHeight ? $this->getHeight() : '_';
- $resize = $this->isResized && ( $width != '_' || $width != '_' ) ? '-resize' : '';
+ $width = $this->setWidth ?: '_';
+ $height = $this->setHeight ?: '_';
+ $resize = $this->isResized && !( $width == '_' || $height == '_' ) ? '-resize' : '';
$replaceString = sprintf( '$1-%sx%s%s$2', $width, $height, $resize ); // $1 = filename and $2 = extension
// var_dump( $replaceString );
@@ -146,4 +152,20 @@ class ImageHandler extends ImageModifier
// return $this->cropsFolder
}
+ /**
+ * Set $setWidth and $setHeight before resizing the GD
+ *
+ * @return static
+ */
+ public function resize($width = null, $height = null)
+ {
+
+ $this->setWidth = $width;
+ $this->setHeight = $height;
+ $this->isResized = true;
+
+ return parent::resize( $width, $height );
+ }
+
+
}
diff --git a/src/Modifiers/ImageModifier.php b/src/Modifiers/ImageModifier.php
index <HASH>..<HASH> 100644
--- a/src/Modifiers/ImageModifier.php
+++ b/src/Modifiers/ImageModifier.php
@@ -39,6 +39,22 @@ class ImageModifier
}
/**
+ * Reset image object to originalImagePath
+ *
+ * @return static
+ */
+ public function resetImageObject()
+ {
+
+ $this->destroy();
+
+ $this->createImageObject();
+
+ return $this;
+ }
+
+
+ /**
* Get the mime type of the working image
*
* @return String
@@ -237,7 +253,7 @@ class ImageModifier
*
* @return $this
*/
- public function resize( $width, $height )
+ public function resize( $width = null, $height = null )
{
// Get the source width and height
diff --git a/tests/ImageHandlerTest.php b/tests/ImageHandlerTest.php
index <HASH>..<HASH> 100644
--- a/tests/ImageHandlerTest.php
+++ b/tests/ImageHandlerTest.php
@@ -62,13 +62,21 @@ class ImageHandlerTest extends PHPUnit_Framework_TestCase
}
/*
- * Add custom filename on save
+ * Add custom filename on resize save
*/
- public function test_custom_filename_on_save()
+ public function test_custom_filename_on_resize()
{
- // $this->modifier->setCropsFolder( __DIR__ . '/../images/tests' );
- // $this->modifier->cropToFit( 100, 100 )
- // ->save();
+ $this->modifier->resize( 100, 100 )
+ ->save();
+ $this->assertFileExists( $this->modifier->getCropsFolder() . '/test-image-100x100-resize.jpg' );
+
+ $this->modifier->resize( null, 100 )
+ ->save();
+ $this->assertFileExists( $this->modifier->getCropsFolder() . '/test-image-_x100.jpg' );
+
+ $this->modifier->resize( 100, null )
+ ->save();
+ $this->assertFileExists( $this->modifier->getCropsFolder() . '/test-image-100x_.jpg' );
}
/*
diff --git a/tests/ImageModifierTest.php b/tests/ImageModifierTest.php
index <HASH>..<HASH> 100644
--- a/tests/ImageModifierTest.php
+++ b/tests/ImageModifierTest.php
@@ -18,6 +18,7 @@ class ImageModifierTest extends PHPUnit_Framework_TestCase
*/
public function setup()
{
+ // Throw error if originalFilePath does not exist
$this->imagePath = __DIR__ . '/../images/test-image.jpg';
$this->modifier = ImageModifier::create( $this->imagePath );
}
|
Created resize filename tests
|
LasseHaslev_image-handler
|
train
|
1e1cd4dfbb95642ac3ecd58821c6c2147ea6e619
|
diff --git a/package/domino/game.py b/package/domino/game.py
index <HASH>..<HASH> 100644
--- a/package/domino/game.py
+++ b/package/domino/game.py
@@ -8,12 +8,8 @@ def randomized_hands():
class Game:
- def __init__(self, starting_player=0,
- starting_domino=None, skinny_board=False):
- if skinny_board:
- self.board = domino.SkinnyBoard()
- else:
- self.board = domino.Board()
+ def __init__(self, starting_player=0, starting_domino=None):
+ self.board = domino.Board()
self.hands = randomized_hands()
|
initializing all Games with a full Board
|
abw333_dominoes
|
train
|
34a8572d8e7848865df74edf845d99cfe0b8530d
|
diff --git a/ntp_test.go b/ntp_test.go
index <HASH>..<HASH> 100644
--- a/ntp_test.go
+++ b/ntp_test.go
@@ -38,13 +38,15 @@ func isNil(t *testing.T, err error) bool {
func assertValid(t *testing.T, r *Response) {
err := r.Validate()
if err != nil {
- t.Errorf("[%s] Query invalid: %s\n", host, err)
+ t.Errorf("[%s] Response invalid: %s\n", host, err)
}
}
func assertInvalid(t *testing.T, r *Response) {
err := r.Validate()
- assert.NotNil(t, err)
+ if err == nil {
+ t.Errorf("[%s] Response unexpectedly valid\n", host)
+ }
}
func TestTime(t *testing.T) {
|
Unit tests output better messages.
When asserting a valid or invalid NTP Response, output
messages that are less generic.
|
beevik_ntp
|
train
|
b6759489e354ab314867c92436ce151d4fae9a77
|
diff --git a/lib/Surku.js b/lib/Surku.js
index <HASH>..<HASH> 100755
--- a/lib/Surku.js
+++ b/lib/Surku.js
@@ -181,64 +181,4 @@ var Surku = function (user_config){
return this
}
-/*if(require.main===module){
- var config=require('./cmd.js')
- debugPrint= function(message,level){
- if(config.hasOwnProperty('verbose') && config.verbose>=level){
- process.stderr.write(message)
- }
- }
- debugPrint('Initializing Surku with config:\n',5)
- if(config.verbose>=5)
- console.log(config)
- var S=new Surku(config)
-
-
- var sampleSelectorRandom=S.m.newMersenneTwister(S.seedBase.genrand_int31())
- var output={}
- var fileName=''
- var failCount=0;
- if(config.outputName!==undefined){
- fileName=config.outputName.split('%n')
- }
- if(config.inputPath){
- var samples=fs.readdirSync(config.inputPath);
- for(var x=0; x<config.count;x++){
- var index=Math.floor(sampleSelectorRandom.genrand_real1()*samples.length)
- var sample=samples[index]
- debugPrint('Input file: '+config.inputPath+'/'+sample+'\n',5)
- if(fs.statSync(config.inputPath+'/'+sample).isDirectory()){
- x--
- samples.splice(index,1)
- if(samples.length==0){
- console.log("Input folder doesn't contain any files")
- process.exit(2)
- }
- }
- else{
- output=S.generateTestCase(fs.readFileSync(config.inputPath+'/'+sample))
- if(fileName=='')
- console.log(output.toString())
- else{
- debugPrint('Output file: '+fileName.join(x)+'\n')
- fs.writeFileSync(fileName.join(x))
- }
- }
-
- }
- }
- else{
- var input=fs.readFileSync(config.inputFile)
- for(var x=0; x<config.count;x++){
- output=S.generateTestCase(input)
- if(fileName=='')
- console.log(output.toString())
- else{
- debugPrint('Output file: '+fileName.join(x)+'\n')
- fs.writeFileSync(fileName.join(x))
- }
- }
- }
-}
-else{*/
module.exports=Surku
diff --git a/lib/objectMutator.js b/lib/objectMutator.js
index <HASH>..<HASH> 100644
--- a/lib/objectMutator.js
+++ b/lib/objectMutator.js
@@ -1,4 +1,4 @@
-var sorrow = require('./index.js');
+var sorrow = require('../index.js');
function objectMutator(o, immutableProperties){
@@ -22,6 +22,7 @@ function objectMutator(o, immutableProperties){
};
type = types[type];
// Set it on the result using the destination key
+ console.log(sorrow)
build[key] = sorrow.async[type](o[key]);
}
}
@@ -29,4 +30,5 @@ function objectMutator(o, immutableProperties){
return build;
}
+
module.exports = objectMutator;
\ No newline at end of file
diff --git a/lib/otuMapArray.js b/lib/otuMapArray.js
index <HASH>..<HASH> 100644
--- a/lib/otuMapArray.js
+++ b/lib/otuMapArray.js
@@ -5,13 +5,11 @@
var data=data;
var map = map;
var len = data.length;
- console.log(Object.keys(data))
_this.rb = require('crypto').randomBytes;
var map=[];
for (var i = 0; i < len; i++) {
map.push(i)
- }
- //console.log(map)
+ }
_this.reset = function(){
if(!map) {
map=[];
diff --git a/lib/vectorator.js b/lib/vectorator.js
index <HASH>..<HASH> 100644
--- a/lib/vectorator.js
+++ b/lib/vectorator.js
@@ -28,7 +28,6 @@ _this.extend = function(name, vectorSet, customGenerator) {
} else {
_this.methods[name] = _this.tContexts[name].pop;
}
- console.log('loaded ' + name)
};
diff --git a/lib/vectors.js b/lib/vectors.js
index <HASH>..<HASH> 100644
--- a/lib/vectors.js
+++ b/lib/vectors.js
@@ -342,6 +342,9 @@ module.exports = [{
for (var i = 0; i < 500; i++) {
arr.push(newVector());
}
+ arr=arr.filter(function(el){
+ return el !== undefined && el !== 'undefined'
+ })
return arr;
})(),
}]
\ No newline at end of file
|
Fixed a bug caused by coercing types incorrectly, removed some unnecessary debug logs.
|
jlamendo_sorrow
|
train
|
30b668cba5a8ca5c54e01453e0b344a0edc1f237
|
diff --git a/core/API/ResponseBuilder.php b/core/API/ResponseBuilder.php
index <HASH>..<HASH> 100644
--- a/core/API/ResponseBuilder.php
+++ b/core/API/ResponseBuilder.php
@@ -86,7 +86,7 @@ class ResponseBuilder
// If the returned value is an object DataTable we
// apply the set of generic filters if asked in the URL
// and we render the DataTable according to the format specified in the URL
- if ($value instanceof DataTableInterface) {
+ if ($value instanceof DataTable || $value instanceof DataTable\Map) {
return $this->handleDataTable($value);
}
@@ -224,7 +224,6 @@ class ResponseBuilder
if ($isAssoc) {
$dataTable = DataTable::makeFromSimpleArray($array);
-
return $this->handleDataTable($dataTable);
}
diff --git a/core/DataTable/Renderer.php b/core/DataTable/Renderer.php
index <HASH>..<HASH> 100644
--- a/core/DataTable/Renderer.php
+++ b/core/DataTable/Renderer.php
@@ -128,7 +128,8 @@ abstract class Renderer
public function setTable($table)
{
if (!is_array($table)
- && !($table instanceof DataTableInterface)
+ && !($table instanceof DataTable)
+ && !($table instanceof DataTable\Map)
) {
throw new Exception("DataTable renderers renderer accepts only DataTable, Simple and Map instances, and arrays.");
}
|
refs #<I> DataTableInterface includes SimpleDataTable which is apparently not supposed to render anything. This should fix many tests
|
matomo-org_matomo
|
train
|
eb3a53efa28e7bd8890c438c33678e3d2c175c97
|
diff --git a/client/fingerprint_manager.go b/client/fingerprint_manager.go
index <HASH>..<HASH> 100644
--- a/client/fingerprint_manager.go
+++ b/client/fingerprint_manager.go
@@ -174,20 +174,17 @@ func (fm *FingerprintManager) setupDrivers(drivers []string) error {
return err
}
- // For all drivers without health checking enabled , create a driver
- // info which matches its fingerprint status. Later, for drivers that
- // have the health check interface implemented, a periodic health check
- // will be run
- if _, isHealthCheck := d.(fingerprint.HealthCheck); !isHealthCheck {
- healthInfo := &structs.DriverInfo{
- Healthy: detected,
- UpdateTime: time.Now(),
- }
- if node := fm.updateNodeFromDriver(name, nil, healthInfo); node != nil {
- fm.nodeLock.Lock()
- fm.node = node
- fm.nodeLock.Unlock()
- }
+ // Set the initial health check status to be the driver detected status.
+ // Later, the periodic health checker will update this value for drivers
+ // where health checks are enabled.
+ healthInfo := &structs.DriverInfo{
+ Healthy: detected,
+ UpdateTime: time.Now(),
+ }
+ if node := fm.updateNodeFromDriver(name, nil, healthInfo); node != nil {
+ fm.nodeLock.Lock()
+ fm.node = node
+ fm.nodeLock.Unlock()
}
// Start a periodic watcher to detect changes to a drivers health and
|
always set initial health status for every driver
|
hashicorp_nomad
|
train
|
37d743e738eba0e0ddfb7cbeedc25183100350a7
|
diff --git a/zappa/core.py b/zappa/core.py
index <HASH>..<HASH> 100644
--- a/zappa/core.py
+++ b/zappa/core.py
@@ -762,7 +762,7 @@ class Zappa(object):
installed_packages = {package.project_name.lower(): package.version for package in
pip.get_installed_distributions()
if package.project_name.lower() in package_to_keep
- or package.location in [site_packages, site_packages_64]}
+ or package.location.lower() in [site_packages.lower(), site_packages_64.lower()]}
return installed_packages
|
fix case sensitivity problem for comparing package location
|
Miserlou_Zappa
|
train
|
92b5c424fbad2d54cf9bb0770bdc94f2e83ae0c1
|
diff --git a/tests/unit/modules/test_win_pkg.py b/tests/unit/modules/test_win_pkg.py
index <HASH>..<HASH> 100644
--- a/tests/unit/modules/test_win_pkg.py
+++ b/tests/unit/modules/test_win_pkg.py
@@ -9,14 +9,16 @@ from __future__ import absolute_import, unicode_literals, print_function
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
-from tests.support.unit import TestCase
+from tests.support.unit import TestCase, skipIf
# Import Salt Libs
import salt.modules.pkg_resource as pkg_resource
import salt.modules.win_pkg as win_pkg
import salt.utils.data
+import salt.utils.platform
+@skipIf(not salt.utils.platform.is_windows(), "Must be on Windows")
class WinPkgInstallTestCase(TestCase, LoaderModuleMockMixin):
'''
Test cases for salt.modules.win_pkg
|
listen to extra_install_flag fix and test
|
saltstack_salt
|
train
|
1b797a103aca85c2958c359b4ba1d82c22de7540
|
diff --git a/lib/streams.js b/lib/streams.js
index <HASH>..<HASH> 100644
--- a/lib/streams.js
+++ b/lib/streams.js
@@ -375,7 +375,7 @@ var objectFeed = function(relmaker, titlemaker, streammaker, finisher) {
if (!principal) {
// XXX: keep a separate stream instead of filtering
str = new FilteredStream(results, objectPublicOnly);
- } else if (context.user && context.user.profile.id == principal.id) {
+ } else if (context.author && context.author.id == principal.id) {
str = results;
} else {
str = new FilteredStream(results, objectRecipientsOnly(principal));
@@ -850,6 +850,10 @@ var collectionMembers = objectFeed(
if (collection.items.length > 0) {
+ if (!collection.links) {
+ collection.links = {};
+ }
+
prevParams = {since: collection.items[0].id};
if (!collection.objectTypes ||
@@ -903,6 +907,7 @@ var collectionMembers = objectFeed(
addFollowed(principal, followable, this.parallel());
+ // Add the followed flag to applicable objects
addProxyObjects(principal, collection.items, this.parallel());
},
callback
diff --git a/routes/api.js b/routes/api.js
index <HASH>..<HASH> 100644
--- a/routes/api.js
+++ b/routes/api.js
@@ -358,7 +358,7 @@ var contextEndpoint = function(contextifier, streamCreator) {
streamCreator(contextifier(req), req.principal, args, function(err, collection) {
if (err) {
- // next(err);
+ next(err);
} else {
res.json(collection);
}
@@ -1171,7 +1171,7 @@ var userFollowing = streamEndpoint(streams.userFollowing);
var userFavorites = contextEndpoint(
function(req) {
- return {user: req.user};
+ return {user: req.user, author: req.person};
},
streams.userFavorites
);
@@ -1266,7 +1266,7 @@ var newUpload = function(req, res, next) {
var collectionMembers = contextEndpoint(
function(req) {
- var context = {collection: req.collection, user: req.collection.author};
+ var context = {collection: req.collection, author: req.collection.author};
if (req.query.type) {
context.type = req.query.type;
} else if (req.collection.objectTypes && req.collection.objectTypes.length > 0) {
|
Use author context to determine which filter to use
|
pump-io_pump.io
|
train
|
e19ab09db60aa503826276a0061697e70fc0300c
|
diff --git a/foolbox/attacks/boundary_attack.py b/foolbox/attacks/boundary_attack.py
index <HASH>..<HASH> 100644
--- a/foolbox/attacks/boundary_attack.py
+++ b/foolbox/attacks/boundary_attack.py
@@ -23,7 +23,8 @@ from .base import Attack
# TODO: use blended noise once noise attacks have been updated
# from .blended_noise import LinearSearchBlendedUniformNoiseAttack
-from .contrast_min import BinarySearchContrastReductionAttack
+# from .contrast_min import BinarySearchContrastReductionAttack
+from .deepfool import L2DeepFoolAttack
class BoundaryAttack(MinimizationAttack):
@@ -88,7 +89,8 @@ class BoundaryAttack(MinimizationAttack):
if self.init_attack is None:
# TODO: use blended noise once noise attacks have been updated
# init_attack = LinearSearchBlendedUniformNoiseAttack()
- init_attack = BinarySearchContrastReductionAttack()
+ # init_attack = BinarySearchContrastReductionAttack()
+ init_attack = L2DeepFoolAttack()
logging.info(
f"Neither starting_points nor init_attack given. Falling"
f" back to {init_attack!r} for initialization."
|
use DeepFool as the initialization attack
|
bethgelab_foolbox
|
train
|
835310ccd4cb63c83ae3776e33b63684ef968a22
|
diff --git a/lib/dcell.rb b/lib/dcell.rb
index <HASH>..<HASH> 100644
--- a/lib/dcell.rb
+++ b/lib/dcell.rb
@@ -81,7 +81,10 @@ module DCell
def addr; @configuration['addr']; end
alias_method :address, :addr
- def addr=(addr); @configuration['addr'] = addr; end
+ def addr=(addr)
+ @configuration['addr'] = addr
+ @me.update_server_address addr
+ end
alias_method :address=, :addr=
# Attempt to generate a unique node ID for this machine
diff --git a/lib/dcell/node.rb b/lib/dcell/node.rb
index <HASH>..<HASH> 100644
--- a/lib/dcell/node.rb
+++ b/lib/dcell/node.rb
@@ -44,11 +44,15 @@ module DCell
attach self
end
- def update_address( addr )
+ def update_client_address( addr )
@addr = addr
send_heartbeat
end
+ def update_server_address(addr)
+ @addr = addr
+ end
+
def shutdown
transition :shutdown
@socket.close if @socket
diff --git a/lib/dcell/node_manager.rb b/lib/dcell/node_manager.rb
index <HASH>..<HASH> 100644
--- a/lib/dcell/node_manager.rb
+++ b/lib/dcell/node_manager.rb
@@ -63,7 +63,7 @@ module DCell
addr = Directory[id]
return unless addr
if ( node = @nodes[id] ) and node.alive?
- node.update_address( addr )
+ node.update_client_address( addr )
else
@nodes[id] = Node.new( id, addr )
end
diff --git a/spec/dcell/explorer_spec.rb b/spec/dcell/explorer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/dcell/explorer_spec.rb
+++ b/spec/dcell/explorer_spec.rb
@@ -12,6 +12,6 @@ describe DCell::Explorer do
it "reports the current node's status" do
response = Net::HTTP.get URI(EXPLORER_BASE)
- response[%r{<h1><.*?> ([\w\.\-]+)<\/h1>}, 1].should == DCell.id
+ response[%r{<a href="/nodes/(.*?)">}, 1].should == DCell.id
end
end
|
update node self address when it is ready
|
celluloid_dcell
|
train
|
77857d4086c01dfe90e7eb9b6619fe87a1f37d38
|
diff --git a/test/move.test.js b/test/move.test.js
index <HASH>..<HASH> 100644
--- a/test/move.test.js
+++ b/test/move.test.js
@@ -176,6 +176,13 @@ describe("move", function() {
if (!fs.existsSync(differentDevice))
return console.log('Skipping cross-device move test')
+ // make sure we have permission on device
+ try {
+ fs.writeFileSync(path.join(differentDevice, 'file'), 'hi')
+ } catch (err) {
+ console.log("Can't write to device. Skipping test.")
+ }
+
var src = '/mnt/some/weird/dir-really-weird'
var dest = path.join(TEST_DIR, 'device-weird')
|
test/move: check if we can write to device
|
jprichardson_node-fs-extra
|
train
|
9333b632eb14af6eaa3c27cd3d137e47ac8972e3
|
diff --git a/src/tools/annotation/LengthTool.js b/src/tools/annotation/LengthTool.js
index <HASH>..<HASH> 100644
--- a/src/tools/annotation/LengthTool.js
+++ b/src/tools/annotation/LengthTool.js
@@ -39,6 +39,7 @@ export default class LengthTool extends BaseAnnotationTool {
drawHandlesOnHover: false,
hideHandlesIfMoving: false,
renderDashed: false,
+ digits: 2,
},
};
@@ -146,6 +147,7 @@ export default class LengthTool extends BaseAnnotationTool {
drawHandlesOnHover,
hideHandlesIfMoving,
renderDashed,
+ digits,
} = this.configuration;
const toolData = getToolState(evt.currentTarget, this.name);
@@ -252,7 +254,7 @@ export default class LengthTool extends BaseAnnotationTool {
function textBoxText(annotation, rowPixelSpacing, colPixelSpacing) {
const measuredValue = _sanitizeMeasuredValue(annotation.length);
- // measured value is not defined, return empty string
+ // Measured value is not defined, return empty string
if (!measuredValue) {
return '';
}
@@ -266,7 +268,7 @@ export default class LengthTool extends BaseAnnotationTool {
annotation.unit = suffix;
- return `${measuredValue.toFixed(2)} ${suffix}`;
+ return `${measuredValue.toFixed(digits)} ${suffix}`;
}
function textBoxAnchorPoints(handles) {
|
feat: Adding digits configuration for Length tool (#<I>)
|
cornerstonejs_cornerstoneTools
|
train
|
c41e5377ae3abe097feda9a9fb328423d8153eb9
|
diff --git a/spec/request_spec.rb b/spec/request_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/request_spec.rb
+++ b/spec/request_spec.rb
@@ -59,6 +59,30 @@ describe MaZMQ::Request do
}
end
end
+
+ context ".send_string" do
+ it "should return false when trying to send before receiving a response" do
+ EM.run do
+ @reply = MaZMQ::Reply.new
+ @request = MaZMQ::Request.new
+
+ @reply.bind :tcp, '127.0.0.1', 5235
+ @request.connect :tcp, '127.0.0.1', 5235
+
+ @request.send_string("request").should == :sending
+ @request.send_string("request").should == false
+
+ @reply.on_read { |msg|
+ @reply.send_string("response")
+ }
+ @request.on_read { |msg|
+ @reply.close
+ @request.close
+ EM.stop
+ }
+ end
+ end
+ end
end
end
|
Added Request specs: doing more than one send_string spec
|
al-nattahnam_ma-zmq
|
train
|
d7903bd1492ef2080d8f140fe67878d70f24315c
|
diff --git a/bindings/ruby/openwsman/xmldoc.rb b/bindings/ruby/openwsman/xmldoc.rb
index <HASH>..<HASH> 100644
--- a/bindings/ruby/openwsman/xmldoc.rb
+++ b/bindings/ruby/openwsman/xmldoc.rb
@@ -3,7 +3,7 @@ module Openwsman
#
# Assume XmlDoc.foo means XmlDoc.body.foo
#
- def method_missing method, *args
+ def method_missing method, *args :nodoc:
self.body.send method,*args
end
end
diff --git a/bindings/ruby/openwsman/xmlnode.rb b/bindings/ruby/openwsman/xmlnode.rb
index <HASH>..<HASH> 100644
--- a/bindings/ruby/openwsman/xmlnode.rb
+++ b/bindings/ruby/openwsman/xmlnode.rb
@@ -1,6 +1,6 @@
module Openwsman
class XmlNode
- def method_missing method, *args
+ def method_missing method, *args # :nodoc:
find(nil, method.to_s)
end
end
|
Bindings: don't document method_missing
|
Openwsman_openwsman
|
train
|
21bfe52694743a3def98706a9c2e1c784801eb0b
|
diff --git a/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java b/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java
index <HASH>..<HASH> 100644
--- a/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java
+++ b/spring-boot-samples/spring-boot-sample-devtools/src/test/java/sample/devtools/SampleDevToolsApplicationIntegrationTests.java
@@ -60,4 +60,11 @@ public class SampleDevToolsApplicationIntegrationTests {
assertThat(entity.getBody()).contains("public file");
}
+ @Test
+ public void testClassResource() throws Exception {
+ ResponseEntity<String> entity = this.restTemplate
+ .getForEntity("/application.properties", String.class);
+ assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
+ }
+
}
|
Add test to check class resources aren't exposed
Closes gh-<I>
|
spring-projects_spring-boot
|
train
|
b81ad3ab7d3f2b40108362e9eea2fea0b903bf14
|
diff --git a/omrdatasettools/downloaders/DatasetDownloader.py b/omrdatasettools/downloaders/DatasetDownloader.py
index <HASH>..<HASH> 100644
--- a/omrdatasettools/downloaders/DatasetDownloader.py
+++ b/omrdatasettools/downloaders/DatasetDownloader.py
@@ -27,9 +27,12 @@ class DatasetDownloader(ABC):
""" Returns the filename for the ZIP-file that will be downloaded for this dataset """
pass
- def extract_dataset(self, absolute_path_to_temp_folder: str):
- archive = ZipFile(self.get_dataset_filename(), "r")
- archive.extractall(absolute_path_to_temp_folder)
+ def extract_dataset(self, absolute_path_to_folder: str, dataset_filename: str = None):
+ if dataset_filename is None:
+ dataset_filename = self.get_dataset_filename()
+
+ archive = ZipFile(dataset_filename, "r")
+ archive.extractall(absolute_path_to_folder)
archive.close()
def clean_up_temp_directory(self, temp_directory):
diff --git a/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py b/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py
index <HASH>..<HASH> 100644
--- a/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py
+++ b/omrdatasettools/downloaders/MuscimaPlusPlusDatasetDownloader.py
@@ -1,5 +1,6 @@
import argparse
import os
+from distutils import dir_util
from omrdatasettools.downloaders.DatasetDownloader import DatasetDownloader
@@ -16,14 +17,31 @@ class MuscimaPlusPlusDatasetDownloader(DatasetDownloader):
def get_dataset_filename(self) -> str:
return "MUSCIMA-pp_v1.0.zip"
+ def get_images_download_url(self) -> str:
+ # This URL contains the images of the CVC-MUSCIMA dataset, that were annotated in the MUSCIMA++ dataset
+ return "https://owncloud.tuwien.ac.at/index.php/s/Xv91caXnPubL6Zk/download"
+
+ def get_imageset_filename(self) -> str:
+ return "CVC_MUSCIMA_PP_Annotated-Images.zip"
+
def download_and_extract_dataset(self, destination_directory: str):
if not os.path.exists(self.get_dataset_filename()):
print("Downloading MUSCIMA++ Dataset...")
self.download_file(self.get_dataset_download_url(), self.get_dataset_filename())
+ if not os.path.exists(self.get_imageset_filename()):
+ print("Downloading MUSCIMA++ Images...")
+ self.download_file(self.get_images_download_url(), self.get_imageset_filename())
+
print("Extracting MUSCIMA++ Dataset...")
self.extract_dataset(os.path.abspath(destination_directory))
+ absolute_path_to_temp_folder = os.path.abspath('MuscimaPpImages')
+ self.extract_dataset(absolute_path_to_temp_folder, self.get_imageset_filename())
+ dir_util.copy_tree(os.path.join(absolute_path_to_temp_folder, "fulls"),
+ os.path.join(os.path.abspath(destination_directory), "v1.0", "data", "images"))
+ self.clean_up_temp_directory(absolute_path_to_temp_folder)
+
if __name__ == "__main__":
parser = argparse.ArgumentParser()
diff --git a/omrdatasettools/tests/DatasetDownloaderTest.py b/omrdatasettools/tests/DatasetDownloaderTest.py
index <HASH>..<HASH> 100644
--- a/omrdatasettools/tests/DatasetDownloaderTest.py
+++ b/omrdatasettools/tests/DatasetDownloaderTest.py
@@ -123,6 +123,17 @@ class DatasetDownloaderTest(unittest.TestCase):
target_file_extension, zip_file,
downloader)
+ def test_download_and_extract_muscima_pp_dataset_expect_images_to_be_downloaded(self):
+ destination_directory = "MuscimaPlusPlus"
+ downloader = MuscimaPlusPlusDatasetDownloader()
+ zip_file = downloader.get_dataset_filename()
+ number_of_images = 140
+ target_file_extension = "*.png"
+
+ self.download_dataset_and_verify_correct_extraction(destination_directory, number_of_images,
+ target_file_extension, zip_file,
+ downloader)
+
def test_download_and_extract_openomr_dataset_expect_folder_to_be_created(self):
destination_directory = "OpenOMR"
downloader = OpenOmrDatasetDownloader()
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,13 +5,13 @@ from setuptools import find_packages
setup(
name='omrdatasettools',
packages=find_packages('.'),
- version='0.12',
+ version='0.13',
description='A collection of tools that simplify the downloading and handling of datasets used for Optical Music Recognition (OMR).',
author='Alexander Pacha',
author_email='alexander.pacha@tuwien.ac.at',
license='MIT',
url='https://github.com/apacha/omr-datasets', # use the URL to the github repo
- download_url='https://github.com/apacha/OMR-Datasets/archive/0.12.tar.gz',
+ download_url='https://github.com/apacha/OMR-Datasets/archive/0.13.tar.gz',
keywords=['optical music recognition', 'downloading', 'extracting', 'omr', 'generating', 'dataset', 'preprocessing'],
classifiers=[
# How mature is this project? Common values are
@@ -35,5 +35,6 @@ setup(
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
],
)
|
Updating MUSCIMA-pp downloader to also download the images, that were actually annotated (7MB), without needing to download the entire CVC-MUSCIMA dataset (2GB).
|
apacha_OMR-Datasets
|
train
|
b9aba211020252b17d2df3f681fab68df08278f2
|
diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringValidation.java b/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringValidation.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringValidation.java
+++ b/core/src/main/java/com/google/errorprone/bugpatterns/formatstring/FormatStringValidation.java
@@ -297,8 +297,9 @@ public final class FormatStringValidation {
private static String unknownFormatConversion(String conversion) {
if (conversion.equals("l")) {
- return "%l is not a valid format specifier; use %d for all integral types and %f for all "
- + "floating point types";
+ return "%l is not a valid format specifier; use %d to format integral types as a decimal "
+ + "integer, and %f, %g or %e to format floating point types (depending on your "
+ + "formatting needs)";
}
return String.format("unknown format conversion: '%s'", conversion);
}
diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringTest.java
+++ b/core/src/test/java/com/google/errorprone/bugpatterns/formatstring/FormatStringTest.java
@@ -101,27 +101,27 @@ public class FormatStringTest {
@Test
public void testCStyleLongConversion() throws Exception {
- testFormat("use %d for all integral types", "String.format(\"%l\", 42);");
+ testFormat("use %d to format integral types", "String.format(\"%l\", 42);");
}
@Test
public void testCStyleLongConversion2() throws Exception {
- testFormat("use %d for all integral types", "String.format(\"%ld\", 42);");
+ testFormat("use %d to format integral types", "String.format(\"%ld\", 42);");
}
@Test
public void testCStyleLongConversion3() throws Exception {
- testFormat("use %d for all integral types", "String.format(\"%lld\", 42);");
+ testFormat("use %d to format integral types", "String.format(\"%lld\", 42);");
}
@Test
public void testCStyleLongConversion4() throws Exception {
- testFormat("%f for all floating point ", "String.format(\"%lf\", 42);");
+ testFormat("%f, %g or %e to format floating point types", "String.format(\"%lf\", 42);");
}
@Test
public void testCStyleLongConversion5() throws Exception {
- testFormat("%f for all floating point ", "String.format(\"%llf\", 42);");
+ testFormat("%f, %g or %e to format floating point types", "String.format(\"%llf\", 42);");
}
@Test
|
Clarify that `%f` is not the only floating point specifier
In fact `%g` is what produces the same result as "toString()" on the boxed type.
`%e` is rarer, but probably still worth reminding people of.
PiperOrigin-RevId: <I>
|
google_error-prone
|
train
|
71129b3bfa66377d3e8586ea94e8fc23306b90ce
|
diff --git a/src/scs_core/aws/monitor/device_monitor.py b/src/scs_core/aws/monitor/device_monitor.py
index <HASH>..<HASH> 100644
--- a/src/scs_core/aws/monitor/device_monitor.py
+++ b/src/scs_core/aws/monitor/device_monitor.py
@@ -84,13 +84,21 @@ class DeviceMonitor(object):
# see if all topics are published on recently
device_tester.get_byline_activity()
- if not this_dev.email_sent and this_dev.is_active:
- inactive, topic = device_tester.has_byline_status_changed(device_byline_list)
- if inactive:
- logging.info('Device %s: ByLine %s: has become inactive. ' % (this_dev.device_tag, topic))
- this_dev.dm_status = "byline"
- self.generate_email(this_dev, topic)
- this_dev.email_sent = True
+ if this_dev.is_active:
+ changed, inactive, topic = device_tester.has_byline_status_changed(device_byline_list)
+ if changed:
+ if inactive:
+ logging.info('Device %s: ByLine %s: has become inactive. ' % (this_dev.device_tag, topic))
+ this_dev.dm_status = "byline_inactive"
+ if not this_dev.email_sent:
+ self.generate_email(this_dev, topic)
+ this_dev.email_sent = True
+ else:
+ logging.info('Device %s: ByLine %s: has become active. ' % (this_dev.device_tag, topic))
+ this_dev.dm_status = "byline_active"
+ if not this_dev.email_sent:
+ self.generate_email(this_dev, topic)
+ this_dev.email_sent = True
# check for weird (null) values
if not this_dev.email_sent and this_dev.is_active:
@@ -194,8 +202,10 @@ class DeviceMonitor(object):
template = "status_offline.txt"
else:
template = "status_online.txt"
- elif device.dm_status == "byline":
+ elif device.dm_status == "byline_inactive":
template = "topic_inactive.txt"
+ elif device.dm_status == "byline_active":
+ template = "topic_active.txt"
elif device.dm_status == "reboot":
template = "uptime.txt"
elif device.dm_status == "values":
diff --git a/src/scs_core/aws/monitor/device_tester.py b/src/scs_core/aws/monitor/device_tester.py
index <HASH>..<HASH> 100644
--- a/src/scs_core/aws/monitor/device_tester.py
+++ b/src/scs_core/aws/monitor/device_tester.py
@@ -71,17 +71,19 @@ class DeviceTester(object):
if device_tag in s3_byline_status_list:
old_byline_status_list = s3_byline_status_list[device_tag]
if old_byline_status_list is None:
- return False, False
+ return False, False, ""
for line in device_bylines:
active = self.is_byline_active(line)
- if not active:
- topic = line.topic
- for key, value in old_byline_status_list.items():
- if key == topic:
- if value is not active:
- return True, topic
-
- return False, None
+ topic = line.topic
+ for key, value in old_byline_status_list.items():
+ if key == topic:
+ if value is not active:
+ if value is True:
+ return False, True, topic
+ if value is False:
+ return True, True, topic
+
+ return False, False, None
def check_values(self):
|
Now reports when byline becomes active if it was inactive
|
south-coast-science_scs_core
|
train
|
dc45cb27917b916c17ba14ab4d7627402c619a62
|
diff --git a/src/CommandMediatorInterface.php b/src/CommandMediatorInterface.php
index <HASH>..<HASH> 100644
--- a/src/CommandMediatorInterface.php
+++ b/src/CommandMediatorInterface.php
@@ -19,11 +19,11 @@ namespace Demander;
interface CommandMediatorInterface
{
/**
- * Dispatch a command
+ * Execute a command
*
* @param CommandInterface $command
*
* @return void
*/
- public function request(CommandInterface $command);
+ public function execute(CommandInterface $command);
}
|
Refactor `CommandMediatorInterface` due to conflicting method names
|
NigelGreenway_Demander
|
train
|
a1c65a5c5a93fe25898d690f00a4ac539601a73f
|
diff --git a/ipcalc.py b/ipcalc.py
index <HASH>..<HASH> 100644
--- a/ipcalc.py
+++ b/ipcalc.py
@@ -713,7 +713,8 @@ class Network(IP):
def __eq__(self, other):
"""Compare equal."""
- return self.size() == Network(other).size()
+ other = Network(other)
+ return int(self) == int(other) and self.size() == other.size()
def __getitem__(self, key):
"""Get the nth item or slice of the network."""
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -195,18 +195,18 @@ class TestNetwork(unittest.TestCase):
self.assertEqual(str(a), '192.168.0.100/28')
self.assertEqual(a.size(), 16)
self.assertEqual(a.size(), len(a))
- self.assertEqual(long(a), 0xC0A80064)
- for i in xrange(a.size()):
- self.assertEqual(long(a[i]), i + 0xC0A80064)
+ self.assertEqual(int(a), 0xC0A80064)
+ for i in range(a.size()):
+ self.assertEqual(int(a[i]), i + 0xC0A80064)
self.assertRaises(IndexError, lambda: a[a.size()])
def test_indexers(self):
- expected = range(long(0xC0A80B00), long(0xC0A80C00))
+ expected = range(int(0xC0A80B00), int(0xC0A80C00))
self.assertEqual(self.network.size(), len(expected))
- for i in xrange(self.network.size()):
- self.assertEqual(long(self.network[i]), expected[i])
- self.assertEqual(long(self.network[-1]), expected[-1])
+ for i in range(self.network.size()):
+ self.assertEqual(int(self.network[i]), expected[i])
+ self.assertEqual(int(self.network[-1]), expected[-1])
def test_contains(self):
self.assertTrue(IP('192.168.11.0') in self.network)
|
Fixed bug in __eq__
When doing __eq__ we actually have to compare the size *and* the actual
network address.
|
tehmaze_ipcalc
|
train
|
1118f0bd693cbd018f45ac8ea25690755239d806
|
diff --git a/tests/frontend/org/voltdb/regressionsuites/TestStatisticsSuite.java b/tests/frontend/org/voltdb/regressionsuites/TestStatisticsSuite.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/regressionsuites/TestStatisticsSuite.java
+++ b/tests/frontend/org/voltdb/regressionsuites/TestStatisticsSuite.java
@@ -33,6 +33,7 @@ import java.util.concurrent.TimeUnit;
import junit.framework.Test;
+import org.HdrHistogram_voltpatches.AbstractHistogram;
import org.voltdb.BackendTarget;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
@@ -174,14 +175,12 @@ public class TestStatisticsSuite extends SaveRestoreBase {
System.out.println("\n\nTESTING LATENCY STATS\n\n\n");
Client client = getFullyConnectedClient();
- ColumnInfo[] expectedSchema = new ColumnInfo[7];
+ ColumnInfo[] expectedSchema = new ColumnInfo[5];
expectedSchema[0] = new ColumnInfo("TIMESTAMP", VoltType.BIGINT);
expectedSchema[1] = new ColumnInfo("HOST_ID", VoltType.INTEGER);
expectedSchema[2] = new ColumnInfo("HOSTNAME", VoltType.STRING);
expectedSchema[3] = new ColumnInfo("SITE_ID", VoltType.INTEGER);
- expectedSchema[4] = new ColumnInfo("BUCKET_MIN", VoltType.INTEGER);
- expectedSchema[5] = new ColumnInfo("BUCKET_MAX", VoltType.INTEGER);
- expectedSchema[6] = new ColumnInfo("INVOCATIONS", VoltType.BIGINT);
+ expectedSchema[4] = new ColumnInfo("HISTOGRAM", VoltType.VARBINARY);
VoltTable expectedTable = new VoltTable(expectedSchema);
VoltTable[] results = null;
@@ -200,12 +199,12 @@ public class TestStatisticsSuite extends SaveRestoreBase {
results[0].advanceRow();
validateRowSeenAtAllHosts(results[0], "HOSTNAME", results[0].getString("HOSTNAME"), false);
// actually, there are 26 rows per host so:
- assertEquals(26 * HOSTS, results[0].getRowCount());
+ assertEquals(HOSTS, results[0].getRowCount());
// Check for non-zero invocations (ENG-4668)
long invocations = 0;
results[0].resetRowPosition();
while (results[0].advanceRow()) {
- invocations += results[0].getLong("INVOCATIONS");
+ invocations += AbstractHistogram.fromCompressedBytes(results[0].getVarbinary("HISTOGRAM")).getHistogramData().getTotalCount();
}
assertTrue(invocations > 0);
}
|
For ENG-<I>, fix test bugs for latency stats
|
VoltDB_voltdb
|
train
|
ba8c6c0e0bd3e2780dedb4488bf23601f752f726
|
diff --git a/django_extensions/management/commands/show_urls.py b/django_extensions/management/commands/show_urls.py
index <HASH>..<HASH> 100644
--- a/django_extensions/management/commands/show_urls.py
+++ b/django_extensions/management/commands/show_urls.py
@@ -13,8 +13,9 @@ from django_extensions.management.color import color_style
FMTR = {
- 'dense': "{url}\t{module}.{name}\t{url_name}\t{decorator}",
- 'verbose': "{url}\n\tController: {module}.{name}\n\tURL Name: {url_name}\n\tDecorators: {decorator}\n",
+ 'dense': "{url}\t{module}\t{url_name}\t{decorator}",
+ 'table': "{url},{module},{url_name},{decorator}",
+ 'verbose': "{url}\n\tController: {module}\n\tURL Name: {url_name}\n\tDecorators: {decorator}\n",
}
@@ -128,8 +129,7 @@ class Command(BaseCommand):
func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))
views.append(fmtr.format(
- name=style.MODULE_NAME(func_name),
- module=style.MODULE(func.__module__),
+ module='{0}.{1}'.format(style.MODULE(func.__module__), style.MODULE_NAME(func_name)),
url_name=style.URL_NAME(url_name or ''),
url=style.URL(simplify_regex(regex)),
decorator=', '.join(decorators),
@@ -138,4 +138,25 @@ class Command(BaseCommand):
if not options.get('unsorted', False):
views = sorted(views)
+ if format_style == 'table':
+ # Reformat all data and show in a table format
+
+ views = [row.split(',') for row in views]
+ widths = [ len(max(columns, key=len)) for columns in zip(*views) ]
+ table_views = []
+
+ header = ('URL', 'Module', 'Name', 'Decorator')
+ table_views.append(
+ ' | '.join( '{0:{1}}'.format(title, width) for width, title in zip(widths, header) )
+ )
+ table_views.append( '-+-'.join( '-' * width for width in widths ) )
+
+ for row in views:
+ table_views.append(
+ ' | '.join( '{0:{1}}'.format(cdata, width) for width, cdata in zip(widths, row) )
+ )
+
+ # Replace original views so we can return the same object
+ views = table_views
+
return "\n".join([v for v in views]) + "\n"
|
Added table formatting to command output. Refs #<I>
|
django-extensions_django-extensions
|
train
|
bc3cf5590ae4e3a13a90708b83a91e0acdd196dd
|
diff --git a/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java b/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java
+++ b/src/test/java/org/sonar/plugins/groovy/GroovySensorTest.java
@@ -110,6 +110,8 @@ public class GroovySensorTest {
//5 times for comment because we register comment even when ignoring header comment
verify(fileLinesContext, Mockito.times(5)).setIntValue(Mockito.eq(CoreMetrics.COMMENT_LINES_DATA_KEY), Mockito.anyInt(), Mockito.eq(1));
verify(fileLinesContext, Mockito.times(17)).setIntValue(Mockito.eq(CoreMetrics.NCLOC_DATA_KEY), Mockito.anyInt(), Mockito.eq(1));
+ verify(fileLinesContext).setIntValue(CoreMetrics.COMMENT_LINES_DATA_KEY, 18, 1);
+ verify(fileLinesContext).setIntValue(CoreMetrics.NCLOC_DATA_KEY, 18, 1);
verify(fileLinesContext).save();
}
|
Add verification that trailing comment is both code and comment line
|
pmayweg_sonar-groovy
|
train
|
eadae0d2cdb80a0e599c4928acd5b839c87bb8ea
|
diff --git a/src/frontend/org/voltdb/dbmonitor/js/voltdb.graph.js b/src/frontend/org/voltdb/dbmonitor/js/voltdb.graph.js
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/dbmonitor/js/voltdb.graph.js
+++ b/src/frontend/org/voltdb/dbmonitor/js/voltdb.graph.js
@@ -1261,7 +1261,7 @@
d3.select('#visualisationCommandLog .nv-y')
.append('rect')
.attr('x', 2)
- .attr('width', 475)
+ .attr('width', 560)
.style('fill', 'white')
.style('opacity', 1)
.attr('y', 0)
@@ -1271,7 +1271,7 @@
var x1 = MonitorGraphUI.ChartCommandlog.xScale()(partitionValue.x);
var x2 = MonitorGraphUI.ChartCommandlog.xScale()(partitionValue.y);
var opacity = 1;
- if (x1 > 3 && x1 < 475 && (x2 - x1 > 0)) {
+ if (x1 > 3 && x1 < 560 && (x2 - x1 > 0)) {
opacity = ((x2 - x1) > 4) ? 0.2 : 1;
d3.select('#visualisationCommandLog .nv-y')
.append('rect')
|
Modified code to adjust width of overlay in command log graph.
|
VoltDB_voltdb
|
train
|
4e36ee365bb82408b49032c00a6d7eafcd6a7524
|
diff --git a/wpull/hook.py b/wpull/hook.py
index <HASH>..<HASH> 100644
--- a/wpull/hook.py
+++ b/wpull/hook.py
@@ -493,7 +493,8 @@ class HookEnvironment(object):
self.callbacks.engine_run()
def _exit_status(self, exit_status):
- return self.callbacks.exit_status(exit_status)
+ return self.callbacks.exit_status(
+ self.to_script_native_type(exit_status))
def _finishing_statistics(self, start_time, stop_time, files, size):
self.callbacks.finishing_statistics(
|
hook.py: Fixes lua type conversion on exit status callback.
|
ArchiveTeam_wpull
|
train
|
f1bc978ebdecf61c0d3475500e28cf45f18fc961
|
diff --git a/registry.go b/registry.go
index <HASH>..<HASH> 100644
--- a/registry.go
+++ b/registry.go
@@ -15,7 +15,6 @@
package vellum
import (
- "encoding/binary"
"hash"
"hash/fnv"
)
@@ -49,20 +48,23 @@ func (r *registry) entry(node *builderState) *builderState {
return rc.entry(node)
}
+const fnvPrime = 1099511628211
+
func (r *registry) hash(b *builderState) int {
- r.hasher.Reset()
var final uint64
if b.final {
final = 1
}
- _ = binary.Write(r.hasher, binary.LittleEndian, final)
- _ = binary.Write(r.hasher, binary.LittleEndian, b.finalVal)
+
+ var h uint64 = 14695981039346656037
+ h ^= (final * fnvPrime)
+ h ^= (b.finalVal * fnvPrime)
for _, t := range b.transitions {
- _ = binary.Write(r.hasher, binary.LittleEndian, t.key)
- _ = binary.Write(r.hasher, binary.LittleEndian, t.val)
- _ = binary.Write(r.hasher, binary.LittleEndian, t.dest)
+ h ^= (uint64(t.key) * fnvPrime)
+ h ^= (t.val * fnvPrime)
+ h ^= (uint64(t.dest.id) * fnvPrime)
}
- return int(uint(r.hasher.Sum64()) % r.tableSize)
+ return int(h % uint64(r.tableSize))
}
type registryCache []*builderState
|
manually compute hash
results in smaller FST (fewer registry collisions)
all tests pass
benchmarks show speedup and less garbage
|
couchbase_vellum
|
train
|
4230d53deab63eb8de77750abd7eae0b90e9e871
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -16,10 +16,10 @@ Then you have to include it in your HTML:
<script src="bower_components/angular-capitalize-filter/capitalize.js"></script>
```
-And inject the module `customFilters` in your application:
+And inject the module `angular-capitalize-filter` as a dependency in your application:
```js
-angular.module('webApp', ['customFilters']);
+angular.module('webApp', ['angular-capitalize-filter']);
```
## Usage
diff --git a/bower.json b/bower.json
index <HASH>..<HASH> 100644
--- a/bower.json
+++ b/bower.json
@@ -1,6 +1,6 @@
{
"name": "angular-capitalize-filter",
- "version": "1.2.1",
+ "version": "2.0.0",
"homepage": "https://github.com/Puigcerber/angular-capitalize-filter",
"repository": {
"type": "git",
diff --git a/capitalize.js b/capitalize.js
index <HASH>..<HASH> 100644
--- a/capitalize.js
+++ b/capitalize.js
@@ -12,7 +12,7 @@
* If not specified, 'all' is used.
* @returns {string} Formatted string.
*/
-angular.module('customFilters',[])
+angular.module('angular-capitalize-filter',[])
.filter('capitalize', function () {
return function (input, format) {
if (!input) {
diff --git a/capitalize.min.js b/capitalize.min.js
index <HASH>..<HASH> 100644
--- a/capitalize.min.js
+++ b/capitalize.min.js
@@ -1 +1 @@
-"use strict";angular.module("customFilters",[]).filter("capitalize",function(){return function(a,b){if(!a)return a;if(b=b||"all","first"===b)return a.charAt(0).toUpperCase()+a.slice(1).toLowerCase();var c=a.split(" "),d=[];return c.forEach(function(a){d.push(2===a.length&&"team"===b?a.toUpperCase():a.charAt(0).toUpperCase()+a.slice(1).toLowerCase())}),d.join(" ")}});
\ No newline at end of file
+"use strict";angular.module("angular-capitalize-filter",[]).filter("capitalize",function(){return function(a,b){if(!a)return a;if(b=b||"all","first"===b)return a.charAt(0).toUpperCase()+a.slice(1).toLowerCase();var c=a.split(" "),d=[];return c.forEach(function(a){d.push(2===a.length&&"team"===b?a.toUpperCase():a.charAt(0).toUpperCase()+a.slice(1).toLowerCase())}),d.join(" ")}});
\ No newline at end of file
diff --git a/lib/capitalize.js b/lib/capitalize.js
index <HASH>..<HASH> 100644
--- a/lib/capitalize.js
+++ b/lib/capitalize.js
@@ -12,7 +12,7 @@
* If not specified, 'all' is used.
* @returns {string} Formatted string.
*/
-angular.module('customFilters',[])
+angular.module('angular-capitalize-filter',[])
.filter('capitalize', function () {
return function (input, format) {
if (!input) {
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "angular-capitalize-filter",
- "version": "1.2.1",
+ "version": "2.0.0",
"repository": {
"type": "git",
"url": "http://github.com/Puigcerber/angular-capitalize-filter"
diff --git a/test/capitalize.js b/test/capitalize.js
index <HASH>..<HASH> 100644
--- a/test/capitalize.js
+++ b/test/capitalize.js
@@ -3,7 +3,7 @@
describe('Filter: capitalize', function () {
// load the filter's module
- beforeEach(module('customFilters'));
+ beforeEach(module('angular-capitalize-filter'));
// initialize a new instance of the filter before each test
var capitalize;
|
Change module name.
This changes breaks backwards compatibility so it's being released as a major version change. After checking some AngularJS projects seems better to name the module after the repository in order to avoid possible clashes with other custom modules.
|
Puigcerber_angular-capitalize-filter
|
train
|
b18da8615992fb2592695034b215a1f4b00ac89c
|
diff --git a/entity.go b/entity.go
index <HASH>..<HASH> 100644
--- a/entity.go
+++ b/entity.go
@@ -619,6 +619,7 @@ func deserializeStruct(dst interface{}, b []byte) error {
return err
}
} else {
+ sd.dec.Decode(nil) // Discard the value
notFoundField = fieldName
}
}
diff --git a/goon_test.go b/goon_test.go
index <HASH>..<HASH> 100644
--- a/goon_test.go
+++ b/goon_test.go
@@ -788,6 +788,7 @@ type MigrationA struct {
File []byte
DeprecatedField string `datastore:"depf,noindex"`
DeprecatedStruct MigrationSub `datastore:"deps,noindex"`
+ FinalField string `datastore:"final,noindex"` // This should always be last, to test deprecating middle properties
}
type MigrationSub struct {
@@ -852,6 +853,7 @@ type MigrationB struct {
ZZs ZigZags `datastore:"zigzag,noindex"`
Keys []*datastore.Key `datastore:"ZeroKey,noindex"`
Files [][]byte `datastore:"File,noindex"`
+ FinalField string `datastore:"final,noindex"`
}
const (
@@ -879,7 +881,7 @@ func TestMigration(t *testing.T) {
Parents: []MigrationPerson{{Name: "Sven", Age: 56}, {Name: "Sonya", Age: 49}},
DeepSlice: MigrationDeepA{Deep: MigrationDeepB{Deep: MigrationDeepC{Slice: []int{1, 2, 3}}}},
ZZs: []ZigZag{{Zig: 1}, {Zag: 1}}, File: []byte{0xF0, 0x0D},
- DeprecatedField: "dep", DeprecatedStruct: MigrationSub{Data: "dep"}}
+ DeprecatedField: "dep", DeprecatedStruct: MigrationSub{Data: "dep", Noise: []int{1, 2, 3}}, FinalField: "fin"}
if _, err := g.Put(migA); err != nil {
t.Errorf("Unexpected error on Put: %v", err)
}
@@ -1038,6 +1040,8 @@ func verifyMigration(t *testing.T, g *Goon, migA *MigrationA, method int, debugI
t.Errorf("%v > Expected 1 file, got %v", debugInfo, len(migB.Files))
} else if !reflect.DeepEqual(migA.File, migB.Files[0]) {
t.Errorf("%v > Files don't match: %v != %v", debugInfo, migA.File, migB.Files[0])
+ } else if migA.FinalField != migB.FinalField {
+ t.Errorf("%v > FinalField doesn't match: %v != %v", debugInfo, migA.FinalField, migB.FinalField)
}
}
|
Properly discard unused struct fields.
|
mjibson_goon
|
train
|
8096c55e0835b47f3856cdd8052eb8a3e7aea81d
|
diff --git a/src/notebook/actions/index.js b/src/notebook/actions/index.js
index <HASH>..<HASH> 100644
--- a/src/notebook/actions/index.js
+++ b/src/notebook/actions/index.js
@@ -358,3 +358,10 @@ export function changeCellType(id, to) {
to,
};
}
+
+export function setModified(value) {
+ return {
+ type: constants.SET_MODIFIED,
+ value,
+ };
+}
diff --git a/src/notebook/constants/index.js b/src/notebook/constants/index.js
index <HASH>..<HASH> 100644
--- a/src/notebook/constants/index.js
+++ b/src/notebook/constants/index.js
@@ -67,3 +67,5 @@ export const COPY_CELL = 'COPY_CELL';
export const PASTE_CELL = 'PASTE_CELL';
export const CHANGE_CELL_TYPE = 'CHANGE_CELL_TYPE';
+
+export const SET_MODIFIED = 'SET_MODIFIED';
diff --git a/src/notebook/records/index.js b/src/notebook/records/index.js
index <HASH>..<HASH> 100644
--- a/src/notebook/records/index.js
+++ b/src/notebook/records/index.js
@@ -9,6 +9,7 @@ export const AppRecord = new Immutable.Record({
notificationSystem: null,
kernelSpecName: null,
isSaving: false,
+ modified: false,
});
export const DocumentRecord = new Immutable.Record({
diff --git a/src/notebook/reducers/app.js b/src/notebook/reducers/app.js
index <HASH>..<HASH> 100644
--- a/src/notebook/reducers/app.js
+++ b/src/notebook/reducers/app.js
@@ -56,4 +56,8 @@ export default handleActions({
[constants.SET_NOTIFICATION_SYSTEM]: function setNotificationsSystem(state, action) {
return state.set('notificationSystem', action.notificationSystem);
},
+ [constants.SET_MODIFIED]: function setModified(state, action) {
+ const { value } = action;
+ return state.set('modified', value);
+ }
}, {});
|
Add setModified action/reducer
|
nteract_nteract
|
train
|
25c8aae1edd18ad11fa726922c5bca9e81818f5b
|
diff --git a/base.php b/base.php
index <HASH>..<HASH> 100644
--- a/base.php
+++ b/base.php
@@ -2564,6 +2564,8 @@ class Preview extends View {
function filter($key=NULL,$func=NULL) {
if (!$key)
return array_keys($this->filter);
+ if (!$func)
+ return $this->filter[$key];
$this->filter[$key]=$func;
}
@@ -2584,7 +2586,7 @@ class Preview extends View {
$str,$parts)) {
$str=$parts[1];
foreach (Base::instance()->split($parts[2]) as $func)
- $str=$this->filter[$func].'('.$str.')';
+ $str=$self->filter($func).'('.$str.')';
}
return '<?php echo '.$str.'; ?>'.
(isset($expr[3])?$expr[3]."\n":'');
|
fix php <I>.x issue, #<I>
1st, Using $this in closure
2nd, Fatal error: Cannot access protected property Preview::$filter
|
bcosca_fatfree-core
|
train
|
ca5a35aa151fc8ca9e2ffc5d4148bd1819662259
|
diff --git a/xod-client-browser/webpack/base.js b/xod-client-browser/webpack/base.js
index <HASH>..<HASH> 100644
--- a/xod-client-browser/webpack/base.js
+++ b/xod-client-browser/webpack/base.js
@@ -45,7 +45,7 @@ module.exports = {
{
test: /node_modules\/font-awesome\/.*\.(jpe?g|png|gif|svg|ttf|eot|svg|woff|woff2)(\?\S*)?$/,
loaders: [
- 'file?name=/assets/font-awesome/[name].[ext]?[hash:6]',
+ 'file?name=assets/font-awesome/[name].[ext]?[hash:6]',
],
},
{
diff --git a/xod-client-browser/webpack/web-dev.js b/xod-client-browser/webpack/web-dev.js
index <HASH>..<HASH> 100644
--- a/xod-client-browser/webpack/web-dev.js
+++ b/xod-client-browser/webpack/web-dev.js
@@ -10,7 +10,7 @@ const baseConfig = require('./base.js');
const config = merge.smart(baseConfig, {
output: {
path: path.join(__dirname, '../dist'),
- publicPath: 'http://localhost:8080/',
+ publicPath: './',
},
module: {
loaders: [
|
fix(font-awesome): fixed path to static by changing publicPath in webpack config from 'localhost:<I>' to './'
|
xodio_xod
|
train
|
99849998e09a3613367b790d5e12ff808bdaeada
|
diff --git a/lib/locomotive/steam/entities/editable_element.rb b/lib/locomotive/steam/entities/editable_element.rb
index <HASH>..<HASH> 100644
--- a/lib/locomotive/steam/entities/editable_element.rb
+++ b/lib/locomotive/steam/entities/editable_element.rb
@@ -9,7 +9,8 @@ module Locomotive::Steam
def initialize(attributes = {})
super({
content: nil,
- source: nil
+ source: nil,
+ inline_editing: true
}.merge(attributes))
end
diff --git a/lib/locomotive/steam/liquid/tags/editable/base.rb b/lib/locomotive/steam/liquid/tags/editable/base.rb
index <HASH>..<HASH> 100644
--- a/lib/locomotive/steam/liquid/tags/editable/base.rb
+++ b/lib/locomotive/steam/liquid/tags/editable/base.rb
@@ -12,7 +12,7 @@ module Locomotive
def initialize(tag_name, markup, options)
if markup =~ Syntax
@slug = $1.gsub(/[\"\']/, '')
- @element_options = { fixed: false }
+ @element_options = { fixed: false, inline_editing: true }
markup.scan(::Liquid::TagAttributes) { |key, value| @element_options[key.to_sym] = value.gsub(/^[\"\']/, '').gsub(/[\"\']$/, '') }
else
raise ::Liquid::SyntaxError.new("Valid syntax: #{tag_name} <slug>(, <options>)")
@@ -48,9 +48,9 @@ module Locomotive
slug: @slug,
hint: @element_options[:hint],
priority: @element_options[:priority] || 0,
- fixed: !!@element_options[:fixed],
+ fixed: [true, 'true'].include?(@element_options[:fixed]),
disabled: false,
- inline_editing: true,
+ inline_editing: [true, 'true'].include?(@element_options[:inline_editing]),
from_parent: false,
type: @tag_name.to_sym
}
diff --git a/lib/locomotive/steam/liquid/tags/editable/text.rb b/lib/locomotive/steam/liquid/tags/editable/text.rb
index <HASH>..<HASH> 100644
--- a/lib/locomotive/steam/liquid/tags/editable/text.rb
+++ b/lib/locomotive/steam/liquid/tags/editable/text.rb
@@ -26,7 +26,7 @@ module Locomotive
end
def editable?(context, element)
- !!context.registers[:live_editing]
+ !!context.registers[:live_editing] && element.inline_editing
end
def default_element_attributes
diff --git a/spec/unit/liquid/tags/editable/text_spec.rb b/spec/unit/liquid/tags/editable/text_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/liquid/tags/editable/text_spec.rb
+++ b/spec/unit/liquid/tags/editable/text_spec.rb
@@ -71,10 +71,11 @@ describe Locomotive::Steam::Liquid::Tags::Editable::Text do
describe 'rendering' do
- let(:live_editing) { false }
+ let(:live_editing) { false }
+ let(:element_editing) { true }
let(:page) { instance_double('Page', fullpath: 'hello-world') }
- let(:element) { instance_double('EditableText', _id: 42, id: 42, default_content?: true, inline_editing?: true) }
+ let(:element) { instance_double('EditableText', _id: 42, id: 42, default_content?: true, inline_editing?: element_editing, inline_editing: element_editing) }
let(:services) { Locomotive::Steam::Services.build_instance(nil) }
let(:context) { ::Liquid::Context.new({}, {}, { page: page, services: services, live_editing: live_editing }) }
@@ -119,6 +120,13 @@ describe Locomotive::Steam::Liquid::Tags::Editable::Text do
end
+ context 'editing disabled for the element' do
+
+ let(:element_editing) { false }
+ it { is_expected.to eq 'Hello world' }
+
+ end
+
end
describe 'deprecated elements' do
|
allow disabling the live editing (or inline editing) mode for a single editable_element
|
locomotivecms_steam
|
train
|
1668a188599fd307628332e560bac2881040f0f3
|
diff --git a/request-strategy/order.go b/request-strategy/order.go
index <HASH>..<HASH> 100644
--- a/request-strategy/order.go
+++ b/request-strategy/order.go
@@ -21,24 +21,19 @@ type (
ChunkSpec = types.ChunkSpec
)
-type pieceOrderInput struct {
- PieceRequestOrderState
- PieceRequestOrderKey
-}
-
-func pieceOrderLess(i, j pieceOrderInput) multiless.Computation {
+func pieceOrderLess(i, j *pieceRequestOrderItem) multiless.Computation {
return multiless.New().Int(
- int(j.Priority), int(i.Priority),
+ int(j.state.Priority), int(i.state.Priority),
).Bool(
- j.Partial, i.Partial,
+ j.state.Partial, i.state.Partial,
).Int64(
- i.Availability, j.Availability,
+ i.state.Availability, j.state.Availability,
).Int(
- i.Index, j.Index,
+ i.key.Index, j.key.Index,
).Lazy(func() multiless.Computation {
return multiless.New().Cmp(bytes.Compare(
- i.InfoHash[:],
- j.InfoHash[:],
+ i.key.InfoHash[:],
+ j.key.InfoHash[:],
))
})
}
diff --git a/request-strategy/piece-request-order.go b/request-strategy/piece-request-order.go
index <HASH>..<HASH> 100644
--- a/request-strategy/piece-request-order.go
+++ b/request-strategy/piece-request-order.go
@@ -37,16 +37,7 @@ type pieceRequestOrderItem struct {
func (me *pieceRequestOrderItem) Less(other btree.Item) bool {
otherConcrete := other.(*pieceRequestOrderItem)
- return pieceOrderLess(
- pieceOrderInput{
- PieceRequestOrderState: me.state,
- PieceRequestOrderKey: me.key,
- },
- pieceOrderInput{
- PieceRequestOrderState: otherConcrete.state,
- PieceRequestOrderKey: otherConcrete.key,
- },
- ).Less()
+ return pieceOrderLess(me, otherConcrete).Less()
}
func (me *PieceRequestOrder) Add(key PieceRequestOrderKey, state PieceRequestOrderState) {
@@ -63,10 +54,17 @@ func (me *PieceRequestOrder) Add(key PieceRequestOrderKey, state PieceRequestOrd
}
func (me *PieceRequestOrder) Update(key PieceRequestOrderKey, state PieceRequestOrderState) {
- item := me.existingItemForKey(key)
- if item.state == state {
+ oldState, ok := me.keys[key]
+ if !ok {
+ panic("key should have been added already")
+ }
+ if state == oldState {
return
}
+ item := pieceRequestOrderItem{
+ key: key,
+ state: oldState,
+ }
if me.tree.Delete(&item) == nil {
panic(fmt.Sprintf("%#v", key))
}
|
Some optimizations in PieceRequestOrder.Update and item comparisons
|
anacrolix_torrent
|
train
|
1113d93420907289f892cb6aa5b012e7d1c8ca08
|
diff --git a/lib/graphql/relay/mutation.rb b/lib/graphql/relay/mutation.rb
index <HASH>..<HASH> 100644
--- a/lib/graphql/relay/mutation.rb
+++ b/lib/graphql/relay/mutation.rb
@@ -148,6 +148,7 @@ module GraphQL
attr_reader :client_mutation_id
def initialize(client_mutation_id:, result:)
@client_mutation_id = client_mutation_id
+ raise result if result.is_a? GraphQL::ExecutionError
result.each do |key, value|
self.public_send("#{key}=", value)
end
diff --git a/spec/graphql/relay/mutation_spec.rb b/spec/graphql/relay/mutation_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/graphql/relay/mutation_spec.rb
+++ b/spec/graphql/relay/mutation_spec.rb
@@ -160,4 +160,22 @@ describe GraphQL::Relay::Mutation do
assert_equal "String", input.arguments['stringDefault'].default_value
end
end
+
+ describe "handling errors" do
+ it "supports returning an error in resolve" do
+ result = star_wars_query(query_string, "clientMutationId" => "5678", "shipName" => "Millennium Falcon")
+
+ expected = { "data" => {
+ "introduceShip" => nil
+ } , "errors" => [
+ { "message" => "Sorry, Millennium Falcon ship is reserved",
+ "locations" => [ { "line" => 3 , "column" => 7}],
+ "path" => ["introduceShip"]
+ }
+ ]
+ }
+
+ assert_equal(expected, result)
+ end
+ end
end
diff --git a/spec/support/star_wars_schema.rb b/spec/support/star_wars_schema.rb
index <HASH>..<HASH> 100644
--- a/spec/support/star_wars_schema.rb
+++ b/spec/support/star_wars_schema.rb
@@ -157,6 +157,7 @@ IntroduceShipMutation = GraphQL::Relay::Mutation.define do
# Here's the mutation operation:
resolve ->(root_obj, inputs, ctx) {
faction_id = inputs["factionId"]
+ return GraphQL::ExecutionError.new("Sorry, Millennium Falcon ship is reserved") if inputs["shipName"] == 'Millennium Falcon'
ship = STAR_WARS_DATA.create_ship(inputs["shipName"], faction_id)
faction = STAR_WARS_DATA["Faction"][faction_id]
connection_class = GraphQL::Relay::BaseConnection.connection_for_nodes(faction.ships)
|
Returning a GraphQL::ExecutionError in a mutation with return_fields works as expected.
|
rmosolgo_graphql-ruby
|
train
|
352abfc74afa6a3b1a079eb0916b64005463930b
|
diff --git a/examples/simple.py b/examples/simple.py
index <HASH>..<HASH> 100644
--- a/examples/simple.py
+++ b/examples/simple.py
@@ -16,6 +16,7 @@ from formlayout import fedit
datalist = [('Name', 'Paul'),
(None, None),
(None, 'Information:'),
+ ('Password', 'password'),
('Age', 30),
('Sex', [0, 'Male', 'Female']),
('Size', 12.1),
diff --git a/formlayout.py b/formlayout.py
index <HASH>..<HASH> 100644
--- a/formlayout.py
+++ b/formlayout.py
@@ -388,6 +388,9 @@ class FormWidget(QWidget):
elif is_text_string(value):
if value in ['file', 'dir'] or value.startswith('file:'):
field = FileLayout(value, self)
+ elif value == 'password':
+ field = QLineEdit(self)
+ field.setEchoMode(QLineEdit.Password)
elif '\n' in value:
for linesep in (os.linesep, '\n'):
if linesep in value:
|
Add a Password widget (when value is 'password')
|
PierreRaybaut_formlayout
|
train
|
d43b66a30aa6d96f24f1e2a2e59e54abcaa49851
|
diff --git a/pax-web-undertow/src/main/java/org/ops4j/pax/web/service/undertow/internal/Context.java b/pax-web-undertow/src/main/java/org/ops4j/pax/web/service/undertow/internal/Context.java
index <HASH>..<HASH> 100644
--- a/pax-web-undertow/src/main/java/org/ops4j/pax/web/service/undertow/internal/Context.java
+++ b/pax-web-undertow/src/main/java/org/ops4j/pax/web/service/undertow/internal/Context.java
@@ -395,7 +395,10 @@ public class Context implements LifeCycle, HttpHandler, ResourceManager {
// TODO: move to XML configuration
deployment.setIdentityManager(identityManager);
if (contextModel.getRealmName() != null && contextModel.getAuthMethod() != null) {
- deployment.getServletExtensions().add(getAuthenticator(contextModel.getAuthMethod()));
+ ServletExtension authenticator = getAuthenticator(contextModel.getAuthMethod());
+ if (authenticator != null) {
+ deployment.getServletExtensions().add(authenticator);
+ }
LoginConfig cfg = new LoginConfig(
contextModel.getAuthMethod(),
contextModel.getRealmName(),
|
[PAXWEB-<I>] Fix NPE when there's no Undertow authenticator extension
(cherry picked from commit <I>fef<I>a5c<I>f<I>a1f<I>d<I>c<I>)
|
ops4j_org.ops4j.pax.web
|
train
|
a917c5b5be8662e686554d7d89ed765ff7341971
|
diff --git a/ext_localconf.php b/ext_localconf.php
index <HASH>..<HASH> 100644
--- a/ext_localconf.php
+++ b/ext_localconf.php
@@ -1,5 +1,7 @@
<?php
+declare(strict_types=1);
+
defined('TYPO3') or die();
// Rebuild cache in DataHandler on changing / inserting / adding redirect records
|
[TASK] Declare strict types in ext_localconf.php files
Since #<I> it's possible to declare strict types
in ext_localconf.php files. This patch does this
through the core.
Resolves: #<I>
Related: #<I>
Releases: master
Change-Id: I<I>a<I>a<I>d5d<I>daccc<I>ca<I>a1ffd<I>f9d<I>
Reviewed-on: <URL>
|
TYPO3-CMS_redirects
|
train
|
0a60ad0d7bf7a4401a480f1d34dd335cca5f09a1
|
diff --git a/lib/mongo/util/bson.rb b/lib/mongo/util/bson.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/util/bson.rb
+++ b/lib/mongo/util/bson.rb
@@ -47,6 +47,7 @@ class BSON
CODE_W_SCOPE = 15
NUMBER_INT = 16
TIMESTAMP = 17
+ NUMBER_LONG = 18
MAXKEY = 127
if RUBY_VERSION >= '1.9'
@@ -180,6 +181,9 @@ class BSON
when NUMBER_INT
key = deserialize_cstr(@buf)
doc[key] = deserialize_number_int_data(@buf)
+ when NUMBER_LONG
+ key = deserialize_cstr(@buf)
+ doc[key] = deserialize_number_long_data(@buf)
when OID
key = deserialize_cstr(@buf)
doc[key] = deserialize_oid_data(@buf)
@@ -263,6 +267,12 @@ class BSON
unsigned >= 2**32 / 2 ? unsigned - 2**32 : unsigned
end
+ def deserialize_number_long_data(buf)
+ # same note as above applies here...
+ unsigned = buf.get_long
+ unsigned >= 2 ** 64 / 2 ? unsigned - 2**64 : unsigned
+ end
+
def deserialize_object_data(buf)
size = buf.get_int
buf.position -= 4
@@ -394,15 +404,23 @@ class BSON
end
def serialize_number_element(buf, key, val, type)
- buf.put(type)
- self.class.serialize_cstr(buf, key)
if type == NUMBER
+ buf.put(type)
+ self.class.serialize_cstr(buf, key)
buf.put_double(val)
else
+ if val > 2**64 / 2 - 1 or val < -2**64 / 2
+ raise RangeError.new("MongoDB can only handle 8-byte ints")
+ end
if val > 2**32 / 2 - 1 or val < -2**32 / 2
- raise RangeError.new("MongoDB can only handle 4-byte ints - try converting to a double before saving")
+ buf.put(NUMBER_LONG)
+ self.class.serialize_cstr(buf, key)
+ buf.put_long(val)
+ else
+ buf.put(type)
+ self.class.serialize_cstr(buf, key)
+ buf.put_int(val)
end
- buf.put_int(val)
end
end
diff --git a/tests/test_bson.rb b/tests/test_bson.rb
index <HASH>..<HASH> 100644
--- a/tests/test_bson.rb
+++ b/tests/test_bson.rb
@@ -215,18 +215,32 @@ class BSONTest < Test::Unit::TestCase
end
def test_overflow
- doc = {"x" => 2**45}
+ doc = {"x" => 2**75}
assert_raise RangeError do
@b.serialize(doc)
end
- doc = {"x" => 2147483647}
+ doc = {"x" => 9223372036854775}
+ assert_equal doc, @b.deserialize(@b.serialize(doc).to_a)
+
+ doc = {"x" => 9223372036854775807}
assert_equal doc, @b.deserialize(@b.serialize(doc).to_a)
doc["x"] = doc["x"] + 1
assert_raise RangeError do
@b.serialize(doc)
end
+
+ doc = {"x" => -9223372036854775}
+ assert_equal doc, @b.deserialize(@b.serialize(doc).to_a)
+
+ doc = {"x" => -9223372036854775808}
+ assert_equal doc, @b.deserialize(@b.serialize(doc).to_a)
+
+ doc["x"] = doc["x"] - 1
+ assert_raise RangeError do
+ @b.serialize(doc)
+ end
end
def test_do_not_change_original_object
diff --git a/tests/test_db_api.rb b/tests/test_db_api.rb
index <HASH>..<HASH> 100644
--- a/tests/test_db_api.rb
+++ b/tests/test_db_api.rb
@@ -639,6 +639,12 @@ class DBAPITest < Test::Unit::TestCase
assert_equal 2, @@coll.count
end
+ def test_save_long
+ @@coll.clear
+ @@coll.insert("x" => 9223372036854775807)
+ assert_equal 9223372036854775807, @@coll.find_first()["x"]
+ end
+
def test_find_by_oid
@@coll.clear
|
support for long type in pure ruby [enc|dec]oder
|
mongodb_mongo-ruby-driver
|
train
|
6a1eee9c2393f32b3270609433482a5668232cc7
|
diff --git a/src/main/java/com/rackspace/cloud/api/docs/PDFMojo.java b/src/main/java/com/rackspace/cloud/api/docs/PDFMojo.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/rackspace/cloud/api/docs/PDFMojo.java
+++ b/src/main/java/com/rackspace/cloud/api/docs/PDFMojo.java
@@ -180,6 +180,14 @@ public abstract class PDFMojo extends AbstractFoMojo {
private String security;
/**
+ *
+ * @parameter
+ * expression="${generate-pdf.strictImageValidation}"
+ * default-value=true
+ */
+ private boolean strictImageValidation;
+
+ /**
*
*
* @parameter expression="${generate-pdf.draft.status}" default-value=""
diff --git a/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java b/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java
+++ b/src/main/java/com/rackspace/cloud/api/docs/WebHelpMojo.java
@@ -606,7 +606,7 @@ public abstract class WebHelpMojo extends AbstractWebhelpMojo {
int index = inputFilename.lastIndexOf('.');
File targetDirForPdf = new File(getTargetDirectory().getAbsolutePath(),inputFilename.substring(0,index));
if(!targetDirForPdf.exists()) {
- FileUtils.mkdir(targetDirForPdf);
+ com.rackspace.cloud.api.docs.FileUtils.mkdir(targetDirForPdf);
}
boolean moved = pdfBuilder.movePdfToWebhelpDir(pdfFile, targetDirForPdf);
if(moved) {
|
Fixed more merge conflicts for PDF and Webhelp mojos
|
rackerlabs_clouddocs-maven-plugin
|
train
|
4ccf8319bb3b6e9f5df507b4e9b58c649a3adc34
|
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -28,12 +28,15 @@ module ActiveRecord
# It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
# +null+ determines if this column allows +NULL+ values.
def initialize(name, default, sql_type = nil, null = true)
- @name, @sql_type, @null = name, sql_type, null
- @limit, @precision, @scale = extract_limit(sql_type), extract_precision(sql_type), extract_scale(sql_type)
- @type = simplified_type(sql_type)
- @default = extract_default(default)
-
- @primary = nil
+ @name = name
+ @sql_type = sql_type
+ @null = null
+ @limit = extract_limit(sql_type)
+ @precision = extract_precision(sql_type)
+ @scale = extract_scale(sql_type)
+ @type = simplified_type(sql_type)
+ @default = extract_default(default)
+ @primary = nil
end
# Returns +true+ if the column is either of type string or text.
|
expand mulasgn for enhancing readability
|
rails_rails
|
train
|
4b1fa1fdf415549d369a4b76016283313573e547
|
diff --git a/htmresearch/frameworks/nlp/classification_model.py b/htmresearch/frameworks/nlp/classification_model.py
index <HASH>..<HASH> 100644
--- a/htmresearch/frameworks/nlp/classification_model.py
+++ b/htmresearch/frameworks/nlp/classification_model.py
@@ -136,12 +136,12 @@ class ClassificationModel(object):
tokenized (and preprocessed if specified).
@param dataDict (dict) Keys are data record IDs, values are
- two-tuples of text (str) and categories (numpy.array). If no labels,
- the categories array is empty. E.g.:
+ three-tuples of text (str), categories (numpy.array), and record number.
+ If no labels, the categories array is empty. E.g.:
dataDict = OrderedDict([
- ('0', ('Hello world!', array([3])),
- ('1', ('import this', array([0, 3]))
+ ('A', ('Hello world!', array([3]), '0'),
+ ('B', ('import this', array([0, 3]), '1')
])
"""
outDict = OrderedDict()
diff --git a/projects/nlp/imbu_runner.py b/projects/nlp/imbu_runner.py
index <HASH>..<HASH> 100644
--- a/projects/nlp/imbu_runner.py
+++ b/projects/nlp/imbu_runner.py
@@ -113,15 +113,18 @@ def _createModel(modelName, savePath, **htmArgs):
def trainModel(model, trainingData):
"""
- Train the given model on trainingData. Return the trained model instance.
+ Train the given model on trainingData.
"""
TP = TextPreprocess()
- for seqId, (text, _, uniqueID) in enumerate(trainingData.values()):
+ for text, _, uniqueID in trainingData.values():
textTokens = TP.tokenize(text)
+ lastToken = len(textTokens) - 1
for i, token in enumerate(textTokens):
- model.trainText(token, [seqId], sequenceId=seqId, reset=int(i==0))
-
- return model
+ # use the sequence's ID as the category label
+ model.trainText(token,
+ [int(uniqueID)],
+ sequenceId=int(uniqueID),
+ reset=int(i==lastToken))
@@ -150,7 +153,7 @@ def run(args):
model = _createModel(modelName=args.modelName, savePath=args.savePath)
print "Training the model (and encoding the data)..."
- model = trainModel(model, dataDict)
+ trainModel(model, dataDict)
if args.savePath:
|
Update Imbu runner model training method, and ClassificationModel documentation
|
numenta_htmresearch
|
train
|
87d7f6732524beeedf5e177fe6e192914954a542
|
diff --git a/lib/winston-telegram.js b/lib/winston-telegram.js
index <HASH>..<HASH> 100644
--- a/lib/winston-telegram.js
+++ b/lib/winston-telegram.js
@@ -25,6 +25,8 @@ var Telegram = exports.Telegram = function (options) {
this.level = options.level || 'info';
this.unique = options.unique || false;
this.silent = options.silent || false;
+ this.disable_notification = options.disable_notification || false;
+ this.name = options.name || this.name;
};
/** @extends winston.Transport */
@@ -37,6 +39,11 @@ util.inherits(Telegram, winston.Transport);
winston.transports.Telegram = Telegram;
/**
+ * Expose the name of this Transport on the prototype
+ */
+Telegram.prototype.name = 'telegram';
+
+/**
* Core logging method exposed to Winston.
* @function log
* @member Telegram
@@ -55,7 +62,8 @@ Telegram.prototype.log = function (level, msg, meta, callback) {
method : 'POST',
json : {
chat_id : this.chatid,
- text : '['+level+'] '+msg
+ text : '['+level+'] '+msg,
+ disable_notification : this.disable_notification
}
}, function(error, response, body){
if (error) {
|
Allow multiple transports, send messages silently
|
ivanmarban_winston-telegram
|
train
|
b2cb541c27411cd5d4efe3e778371a74b6cea0b2
|
diff --git a/lib/ohai/plugins/shard.rb b/lib/ohai/plugins/shard.rb
index <HASH>..<HASH> 100644
--- a/lib/ohai/plugins/shard.rb
+++ b/lib/ohai/plugins/shard.rb
@@ -22,10 +22,12 @@ Ohai.plugin(:ShardSeed) do
def get_dmi_property(dmi, thing)
%w{system base_board chassis}.each do |section|
- unless dmi[section][thing].strip.empty?
+ if dmi[section] && dmi[section][thing] && !dmi[section][thing].strip.empty?
return dmi[section][thing]
end
end
+ Ohai::Log.error("shard_seed: Failed to get dmi property #{thing}: is dmidecode installed?")
+ raise "Failed to generate shard_seed"
end
def default_sources
@@ -77,11 +79,16 @@ Ohai.plugin(:ShardSeed) do
yield(src)
end
end
+ if data.empty?
+ Ohai::Log.error("shard_seed: Unable to generate seed! Either ensure 'dmidecode' is installed, or use 'Ohai.config[:plugin][:shard_seed][:sources]' to set different sources.")
+ raise "Failed to generate shard_seed"
+ end
shard_seed digest_algorithm.hexdigest(data)[0...7].to_i(16)
end
collect_data do
create_seed do |src|
+ Ohai::Log.error("shard_seed: No such source #{src}")
raise "No such shard_seed source: #{src}"
end
end
@@ -99,6 +106,7 @@ Ohai.plugin(:ShardSeed) do
when :uuid
wmi.first_of("Win32_ComputerSystemProduct")["UUID"]
else
+ Ohai::Log.error("shard_seed: No such source #{src}")
raise "No such shard_seed source: #{src}"
end
end
@@ -112,6 +120,7 @@ Ohai.plugin(:ShardSeed) do
when :uuid
hardware["platform_UUID"]
else
+ Ohai::Log.error("shard_seed: No such source #{src}")
raise "No such shard_seed source: #{src}"
end
end
@@ -125,6 +134,7 @@ Ohai.plugin(:ShardSeed) do
when :uuid
get_dmi_property(dmi, :uuid)
else
+ Ohai::Log.error("shard_seed: No such source #{src}")
raise "No such shard_seed source: #{src}"
end
end
diff --git a/spec/unit/plugins/shard_spec.rb b/spec/unit/plugins/shard_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/plugins/shard_spec.rb
+++ b/spec/unit/plugins/shard_spec.rb
@@ -54,8 +54,9 @@ describe Ohai::System, "shard plugin" do
expect(subject).to eq(203669792)
end
- it "fails on an unrecognized source" do
+ it "logs and fails on an unrecognized source" do
Ohai.config[:plugin][:shard_seed][:sources] = [:GreatGooglyMoogly]
+ expect(Ohai::Log).to receive(:error).with(/No such source/)
expect { subject }.to raise_error(RuntimeError)
end
@@ -65,6 +66,20 @@ describe Ohai::System, "shard plugin" do
expect(subject).to eq(117055036)
end
+ it "logs and fails when dmidecode data is not available" do
+ plugin["dmi"] = {}
+ expect(Ohai::Log).to receive(:error).with(/Failed to get dmi/)
+ expect { subject }.to raise_error(RuntimeError)
+ end
+
+ it "logs and fails when no data sources were available" do
+ Ohai.config[:plugin][:shard_seed][:sources] = [:fqdn]
+ plugin["fqdn"] = ""
+ expect(Ohai::Log).to receive(:error).with(/Unable to generate seed/)
+ expect { subject }.to raise_error(RuntimeError)
+ end
+
+
context "with Darwin OS" do
let(:os) { "darwin" }
|
Make shard plugin more resilient and throw better errors
* Catch a variety of problems and Ohai::Log.error about them. Since this
is an optional plugin, if we're hitting these, someone specifically
requested this plugin, so an error is warranted.
* We raise anyway, so that you don't spew further errors
Fixes #<I>
|
chef_ohai
|
train
|
b0db9707c65c2158a6e8677b6abb6da3620efe53
|
diff --git a/middleware/mw.app.context.js b/middleware/mw.app.context.js
index <HASH>..<HASH> 100644
--- a/middleware/mw.app.context.js
+++ b/middleware/mw.app.context.js
@@ -121,7 +121,7 @@ module.exports = function (Q, _, appConfigs, config, cls, translations, routeHel
var appName = req.app.name;
var lang = req.app.lang;
- if (req .app.isLegacyMobile || appName === 'www' || req.app.domain === 'contact') {
+ if (req.app.isLegacyMobile || appName === 'www' || req.app.domain === 'contact') {
appName = appName === 'www' ? 'contact' : appName;
reply.redirect(routeHelper.getBaseUrl(appName, lang) + req.url.path).permanent(true);
return;
|
Formatting fix for req.app.isLegacyMobile
|
gethuman_pancakes-recipe
|
train
|
b89b1808e45986e2bf9f29fea09f4df8cf5e6c12
|
diff --git a/addon/store.js b/addon/store.js
index <HASH>..<HASH> 100644
--- a/addon/store.js
+++ b/addon/store.js
@@ -75,10 +75,6 @@ var Store = Ember.Object.extend({
}
return this._findByIdComputed(type, options);
},
- findOne: function(type) {
- var all = this._findAll(type);
- return all.length > 0 ? all.objectAt(0) : null;
- },
_findById: function(type, id) {
var identityMap = identityMapForType(type, this);
return identityMap[id] || null;
@@ -148,6 +144,32 @@ var Store = Ember.Object.extend({
};
}
});
+ },
+ findOne: function(type) {
+ var store = this;
+ return Ember.ObjectProxy.extend({
+ content: function() {
+ return this.get("source").objectAt(0);
+ }.property("source.[]")
+ }).create({
+ source: this._findAll(type),
+ init: function () {
+ var model = store.container.lookup("model:" + type);
+ for(var method in model) {
+ if(typeof model[method] === "function") {
+ if(!this[method]) {
+ this.proxyMethod(method);
+ }
+ }
+ }
+ },
+ proxyMethod: function(method) {
+ this[method] = function() {
+ var content = this.get("content");
+ return content[method].apply(content, arguments);
+ };
+ }
+ });
}
});
diff --git a/tests/unit/store-test.js b/tests/unit/store-test.js
index <HASH>..<HASH> 100644
--- a/tests/unit/store-test.js
+++ b/tests/unit/store-test.js
@@ -396,30 +396,34 @@ test("pushing a model that does not exist should raise clear exception", functio
});
test("findOne will return the first record", function(assert) {
- var first = store.push("person", {
+ var first = store.push("toran", {
id: 1,
- firstName: "Toran",
- lastName: "Billups"
+ firstName: "Jake",
+ lastName: "Good"
});
- var last = store.push("person", {
+ var last = store.push("toran", {
id: 2,
firstName: "Brandon",
lastName: "Williams"
});
- assert.equal(store.find("person").length, 2);
+ assert.equal(store.find("toran").length, 2);
- var toranb = store.findOne("person");
- assert.equal(toranb.get("firstName"), "Toran", "the firstName property is correct");
- assert.equal(toranb.get("lastName"), "Billups", "the lastName property is correct");
+ var toranb = store.findOne("toran");
+ assert.equal(toranb.get("firstName"), "Jake", "the firstName property is correct");
+ assert.equal(toranb.get("lastName"), "Good", "the lastName property is correct");
assert.equal(toranb.get("id"), "1", "the id property is correct");
+ assert.equal(toranb.get("content").fake(), "Jake 999");
+ assert.equal(toranb.get("content").demo(), "Jake 777");
+ assert.equal(toranb.fake(), "Jake 999");
+ assert.equal(toranb.demo(), "Jake 777");
});
test("findOne should return null when no objects exist in the cache for given type", function(assert) {
assert.equal(store.find("person").length, 0);
var person = store.findOne("person");
- assert.equal(person, null);
+ assert.equal(person.get("content"), null);
});
test("find with filter function will return bound array", function(assert) {
@@ -673,3 +677,30 @@ test("findById will proxy each method for the given type when already in the sto
assert.equal(toranb.fake(), "Toran 999");
assert.equal(toranb.demo(), "Toran 777");
});
+
+test("findOne result will be computed property that updates as records are pushed into the store", function(assert) {
+ var done = assert.async();
+ var toran = store.findOne("toran");
+ assert.equal(toran.get("id"), undefined);
+ assert.equal(toran.get("firstName"), undefined);
+ assert.equal(toran.get("lastName"), undefined);
+ setTimeout(function() {
+ store.push("toran", {
+ id: 123,
+ firstName: "Toran",
+ lastName: "Billups"
+ });
+
+ setTimeout(function() {
+ assert.equal(toran.get("id"), 123);
+ assert.equal(toran.get("firstName"), "Toran");
+ assert.equal(toran.get("lastName"), "Billups");
+ assert.equal(toran.get("content").fake(), "Toran 999");
+ assert.equal(toran.get("content").demo(), "Toran 777");
+ assert.equal(toran.fake(), "Toran 999");
+ assert.equal(toran.demo(), "Toran 777");
+
+ done();
+ }, 0);
+ }, 0);
+});
|
[FEATURE]: findOne is now computed (w/ proxy'd methods)
|
toranb_ember-cli-simple-store
|
train
|
cd4a37b3b81262de03445ad0dfc3bfdb7d791017
|
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100644
--- a/test.js
+++ b/test.js
@@ -102,7 +102,7 @@ describe('is a number', function() {
fixtures.forEach(function(num, idx) {
it(JSON.stringify(num) + ' should be a number', function() {
- assert(isNumber(num), `expected "${String(num)}" to be a number`);
+ assert(isNumber(num), 'expected "' + String(num) + '" to be a number');
});
});
});
@@ -148,7 +148,7 @@ describe('is not a number', function() {
fixtures.forEach(function(num) {
it(JSON.stringify(num) + ' should not be a number', function() {
- assert(!isNumber(num), `expected "${String(num)}" to not be a number`);
+ assert(!isNumber(num), 'expected "' + String(num) + '" to not be a number');
});
});
});
|
use quotes
so we can avoid a major bump
|
jonschlinkert_is-number
|
train
|
067c6516606f0cc318a7a586c7bba19dfc794860
|
diff --git a/src/asynqp/__init__.py b/src/asynqp/__init__.py
index <HASH>..<HASH> 100644
--- a/src/asynqp/__init__.py
+++ b/src/asynqp/__init__.py
@@ -49,7 +49,7 @@ def connect(host='localhost',
dispatcher = Dispatcher()
transport, protocol = yield from loop.create_connection(lambda: AMQP(dispatcher, loop), **kwargs)
- connection = yield from open_connection(loop, protocol, dispatcher, ConnectionInfo(username, password, virtual_host))
+ connection = yield from open_connection(loop, transport, protocol, dispatcher, ConnectionInfo(username, password, virtual_host))
return connection
diff --git a/src/asynqp/connection.py b/src/asynqp/connection.py
index <HASH>..<HASH> 100644
--- a/src/asynqp/connection.py
+++ b/src/asynqp/connection.py
@@ -30,8 +30,18 @@ class Connection(object):
.. attribute:: closed
a :class:`~asyncio.Future` which is done when the handshake to close the connection has finished
+
+ .. attribute:: transport
+
+ The :class:`~asyncio.BaseTransport` over which the connection is communicating with the server
+
+ .. attribute:: protocol
+
+ The :class:`~asyncio.Protocol` which is paired with the transport
"""
- def __init__(self, loop, protocol, synchroniser, sender, dispatcher, connection_info):
+ def __init__(self, loop, transport, protocol, synchroniser, sender, dispatcher, connection_info):
+ self.transport = transport
+ self.protocol = protocol
self.synchroniser = synchroniser
self.sender = sender
self.channel_factory = channel.ChannelFactory(loop, protocol, dispatcher, connection_info)
@@ -69,11 +79,11 @@ class Connection(object):
@asyncio.coroutine
-def open_connection(loop, protocol, dispatcher, connection_info):
+def open_connection(loop, transport, protocol, dispatcher, connection_info):
synchroniser = routing.Synchroniser()
sender = ConnectionMethodSender(protocol)
- connection = Connection(loop, protocol, synchroniser, sender, dispatcher, connection_info)
+ connection = Connection(loop, transport, protocol, synchroniser, sender, dispatcher, connection_info)
handler = ConnectionFrameHandler(synchroniser, sender, protocol, connection)
reader, writer = routing.create_reader_and_writer(handler)
diff --git a/test/base_contexts.py b/test/base_contexts.py
index <HASH>..<HASH> 100644
--- a/test/base_contexts.py
+++ b/test/base_contexts.py
@@ -43,7 +43,7 @@ class MockServerContext(LoopContext):
class OpenConnectionContext(MockServerContext):
def given_an_open_connection(self):
connection_info = ConnectionInfo('guest', 'guest', '/')
- task = asyncio.async(open_connection(self.loop, self.protocol, self.dispatcher, connection_info))
+ task = asyncio.async(open_connection(self.loop, self.transport, self.protocol, self.dispatcher, connection_info))
self.tick()
start_method = spec.ConnectionStart(0, 9, {}, 'PLAIN AMQPLAIN', 'en_US')
@@ -126,7 +126,7 @@ class LegacyConnectionContext(LoopContext):
class LegacyOpenConnectionContext(LegacyConnectionContext):
def given_an_open_connection(self):
- task = asyncio.async(open_connection(self.loop, self.protocol, self.dispatcher, self.connection_info))
+ task = asyncio.async(open_connection(self.loop, self.protocol.transport, self.protocol, self.dispatcher, self.connection_info))
self.tick()
start_frame = asynqp.frames.MethodFrame(0, spec.ConnectionStart(0, 9, {}, 'PLAIN AMQPLAIN', 'en_US'))
diff --git a/test/connection_tests.py b/test/connection_tests.py
index <HASH>..<HASH> 100644
--- a/test/connection_tests.py
+++ b/test/connection_tests.py
@@ -10,7 +10,7 @@ from .base_contexts import LegacyOpenConnectionContext, MockServerContext, OpenC
class WhenRespondingToConnectionStart(MockServerContext):
def given_I_wrote_the_protocol_header(self):
connection_info = ConnectionInfo('guest', 'guest', '/')
- self.async_partial(open_connection(self.loop, self.protocol, self.dispatcher, connection_info))
+ self.async_partial(open_connection(self.loop, self.transport, self.protocol, self.dispatcher, connection_info))
def when_ConnectionStart_arrives(self):
self.server.send_method(0, spec.ConnectionStart(0, 9, {}, 'PLAIN AMQPLAIN', 'en_US'))
@@ -28,7 +28,7 @@ class WhenRespondingToConnectionStart(MockServerContext):
class WhenRespondingToConnectionTune(MockServerContext):
def given_a_started_connection(self):
connection_info = ConnectionInfo('guest', 'guest', '/')
- self.async_partial(open_connection(self.loop, self.protocol, self.dispatcher, connection_info))
+ self.async_partial(open_connection(self.loop, self.transport, self.protocol, self.dispatcher, connection_info))
self.server.send_method(0, spec.ConnectionStart(0, 9, {}, 'PLAIN AMQPLAIN', 'en_US'))
def when_ConnectionTune_arrives(self):
|
Expose transport and protocol on Connection
|
benjamin-hodgson_asynqp
|
train
|
2f96c17ad59e4986b2db10c08be67e818bb4bf6a
|
diff --git a/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java b/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java
index <HASH>..<HASH> 100644
--- a/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java
+++ b/zuul-core/src/main/java/com/netflix/zuul/filters/endpoint/ProxyEndpoint.java
@@ -381,38 +381,37 @@ public class ProxyEndpoint extends SyncZuulFilterAdapter<HttpRequestMessage, Htt
// MUST run this within bindingcontext because RequestExpiryProcessor (and probably other things) depends on ThreadVariables.
try {
methodBinding.bind(() -> {
-
- // Invoke the ribbon execution listeners (including RequestExpiry).
- final ExecutionContext<?> executionContext = origin.getExecutionContext(zuulRequest, attemptNum);
- IClientConfig requestConfig = executionContext.getRequestConfig();
- final Object previousOverriddenReadTimeout = requestConfig.getProperty(ReadTimeout, null);
- Integer readTimeout;
- try {
- Server server = chosenServer.get();
- if (requestStat != null)
- requestStat.server(server);
-
- readTimeout = getReadTimeout(requestConfig, attemptNum);
- requestConfig.set(ReadTimeout, readTimeout);
-
- origin.onRequestStartWithServer(zuulRequest, server, attemptNum);
- }
- catch (Throwable e) {
- handleError(e);
- return;
- }
- finally {
- // Reset the timeout in overriddenConfig back to what it was before, otherwise it will take
- // preference on subsequent retry attempts in RequestExpiryProcessor.
- if (previousOverriddenReadTimeout == null) {
- requestConfig.setProperty(ReadTimeout, null);
- } else {
- requestConfig.setProperty(ReadTimeout, previousOverriddenReadTimeout);
- }
- }
-
// Handle the connection.
if (connectResult.isSuccess()) {
+ // Invoke the ribbon execution listeners (including RequestExpiry).
+ final ExecutionContext<?> executionContext = origin.getExecutionContext(zuulRequest, attemptNum);
+ IClientConfig requestConfig = executionContext.getRequestConfig();
+ final Object previousOverriddenReadTimeout = requestConfig.getProperty(ReadTimeout, null);
+ Integer readTimeout;
+ try {
+ Server server = chosenServer.get();
+ if (requestStat != null)
+ requestStat.server(server);
+
+ readTimeout = getReadTimeout(requestConfig, attemptNum);
+ requestConfig.set(ReadTimeout, readTimeout);
+
+ origin.onRequestStartWithServer(zuulRequest, server, attemptNum);
+ }
+ catch (Throwable e) {
+ handleError(e);
+ return;
+ }
+ finally {
+ // Reset the timeout in overriddenConfig back to what it was before, otherwise it will take
+ // preference on subsequent retry attempts in RequestExpiryProcessor.
+ if (previousOverriddenReadTimeout == null) {
+ requestConfig.setProperty(ReadTimeout, null);
+ } else {
+ requestConfig.setProperty(ReadTimeout, previousOverriddenReadTimeout);
+ }
+ }
+
onOriginConnectSucceeded(connectResult.getNow(), readTimeout);
} else {
onOriginConnectFailed(connectResult.cause());
|
Bugfix in ProxyEndpoint
In operationComplete(), the onRequestStartWithServer() call was being made even if there were no-available-servers, in which
case the chosenServer is null. This wasn't breaking the flow, but was causing stacktraces in logs from an ExecutionListener.
|
Netflix_zuul
|
train
|
21657ff3826ba5f14f68a8d338945a7459c98dce
|
diff --git a/synapse/common.py b/synapse/common.py
index <HASH>..<HASH> 100644
--- a/synapse/common.py
+++ b/synapse/common.py
@@ -3,6 +3,7 @@ import os
import sys
import json
import time
+import fcntl
import types
import base64
import fnmatch
@@ -12,6 +13,7 @@ import functools
import itertools
import threading
import traceback
+import contextlib
import collections
from binascii import hexlify
@@ -204,6 +206,18 @@ def genfile(*paths):
return io.open(path, 'w+b')
return io.open(path, 'r+b')
+@contextlib.contextmanager
+def lockfile(path):
+ '''
+ A file lock with-block helper.
+
+ Args:
+ path (str): A path to a lock file.
+ '''
+ with genfile(path) as fd:
+ fcntl.lockf(fd, fcntl.LOCK_EX)
+ yield
+
def listdir(*paths, glob=None):
'''
List the (optionally glob filtered) full paths from a dir.
|
Updates to synapse.common
|
vertexproject_synapse
|
train
|
2d0357a152bbb0326ce695866bf149399cdcd0a1
|
diff --git a/htmresearch/algorithms/union_temporal_pooler.py b/htmresearch/algorithms/union_temporal_pooler.py
index <HASH>..<HASH> 100644
--- a/htmresearch/algorithms/union_temporal_pooler.py
+++ b/htmresearch/algorithms/union_temporal_pooler.py
@@ -174,7 +174,6 @@ class UnionTemporalPooler(SpatialPooler):
self.setOverlapDutyCycles(numpy.zeros(self.getNumColumns(), dtype=REAL_DTYPE))
self.setActiveDutyCycles(numpy.zeros(self.getNumColumns(), dtype=REAL_DTYPE))
self.setMinOverlapDutyCycles(numpy.zeros(self.getNumColumns(), dtype=REAL_DTYPE))
- self.setMinActiveDutyCycles(numpy.zeros(self.getNumColumns(), dtype=REAL_DTYPE))
self.setBoostFactors(numpy.ones(self.getNumColumns(), dtype=REAL_DTYPE))
diff --git a/projects/relational_memory/pooling_test.py b/projects/relational_memory/pooling_test.py
index <HASH>..<HASH> 100644
--- a/projects/relational_memory/pooling_test.py
+++ b/projects/relational_memory/pooling_test.py
@@ -25,7 +25,7 @@ import collections
import numpy as np
-from htmresearch.algorithms.column_pooler import ColumnPooler
+from htmresearch.algorithms.union_temporal_pooler import UnionTemporalPooler
from nupic.algorithms.knn_classifier import KNNClassifier
@@ -36,12 +36,13 @@ def train(pooler, classifier, objs, numPasses):
for _ in xrange(numPasses):
np.random.shuffle(obj)
for feature in obj:
- sortedFeature = sorted(set(feature))
- pooler.compute(feedforwardInput=sortedFeature,
- learn=True,
- predictedInput=sortedFeature)
- poolerOutput = pooler.getActiveCells()
- classifierInput = np.zeros(4096, dtype=np.uint32)
+ denseFeature = np.zeros((1024,), dtype=np.uint32)
+ denseFeature[feature] = 1
+ poolerOutput = pooler.compute(denseFeature,
+ denseFeature,
+ learn=True)
+
+ classifierInput = np.zeros((1024,), dtype=np.uint32)
classifierInput[poolerOutput] = 1
classifier.learn(classifierInput, label)
@@ -55,13 +56,13 @@ def test(pooler, classifier, objs):
np.random.shuffle(obj)
classifierGuesses = collections.defaultdict(int)
for feature in obj:
- sortedFeature = sorted(set(feature))
- pooler.compute(feedforwardInput=sortedFeature,
- learn=False,
- predictedInput=sortedFeature)
- poolerOutput = pooler.getActiveCells()
+ denseFeature = np.zeros((1024,), dtype=np.uint32)
+ denseFeature[feature] = 1
+ poolerOutput = pooler.compute(denseFeature,
+ denseFeature,
+ learn=False)
- classifierInput = np.zeros(4096, dtype=np.uint32)
+ classifierInput = np.zeros((1024,), dtype=np.uint32)
classifierInput[poolerOutput] = 1
classifierResult = classifier.infer(classifierInput)
@@ -89,8 +90,15 @@ def run():
for label in xrange(numObjects)
]
- pooler = ColumnPooler(
- inputWidth=1024,
+ pooler = UnionTemporalPooler(
+ inputDimensions=(1024,),
+ columnDimensions=(1024,),
+ potentialRadius=1024,
+ potentialPct=0.8,
+ globalInhibition=True,
+ numActiveColumnsPerInhArea=20.0,
+ #boostStrength=10.0,
+ #dutyCyclePeriod=50,
)
classifier = KNNClassifier(k=1, distanceMethod="rawOverlap")
|
Fix bug in union pooler left from removal of min active duty cycles. Also switch relational memory experiment to use union pooler
|
numenta_htmresearch
|
train
|
8a6408831c1aae246b87029ba6803f7bb69b9059
|
diff --git a/py_linq/__init__.py b/py_linq/__init__.py
index <HASH>..<HASH> 100644
--- a/py_linq/__init__.py
+++ b/py_linq/__init__.py
@@ -1,6 +1,6 @@
""" Linq for Python """
-__version__ = '1.0.1'
+__version__ = '1.1.0'
try:
from py_linq import Enumerable # noqa
|
Upped version number to <I>
|
viralogic_py-enumerable
|
train
|
5281b5c332819b0567b70b092987b2945f0bd488
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@
- Updated method of merging default and user options from deep to shallow merge
to better accommodate SSR / virtual DOM environments.
+- Fixed parsing of variable functions that contain spaces, tabs, and new lines.
+
## 1.16.2
*2018-12-23*
@@ -24,8 +26,10 @@
*2018-12-14*
- Added `types` property to package.json.
+
- Updated `options.onlyVars` implementation resulting in a significant
performance increase.
+
- Fixed build status badge (now reflects only master branch status).
## 1.15.3
@@ -53,7 +57,7 @@
*2018-11-12*
-- Updated `options.onSuccess` callback to better handle falsey return values
+- Changed `options.onSuccess` callback to better handle falsey return values
(e.g. `false`, `null`, `0`, `""`).
## 1.14.0
@@ -77,7 +81,7 @@
*2018-11-06*
-- Updated `options.onComplete` callback to return a clone instead of a reference
+- Changed `options.onComplete` callback to return a clone instead of a reference
to the internal variable storage object as the `cssVariables` argument.
- Fixed bug that prevented `options.variables` values from persisting properly
@@ -139,8 +143,8 @@
- Added check for non-browser environments to support Node+SSR. (#16)
-- Updated keyframe animation fix to support legacy browsers that require vendor
- prefixes for `animation-name` and `@keyframes`.
+- Fixed keyframe animation fix by adding vendor prefixes for `animation-name`
+ and `@keyframes`.
- Fixed internal placeholder comments appearing in CSS output instead of
stylesheet content. (#15)
@@ -167,7 +171,7 @@
*2018-05-20*
-- Updated `options.onError` callback `url` argument so that it always returns an
+- Changed `options.onError` callback `url` argument so that it always returns an
absolute URL.
- Updated README with `options.onError` fixes and a few other minor tweaks.
@@ -213,12 +217,12 @@
- Updated `get-css-data` dependency to 1.2.0 to resolve a callback related bug.
-- Updated logic for inserting generated `<style>` element. Element is now
+- Changed logic for inserting generated `<style>` element. Element is now
inserted after the last `<style>` or `<link>` node processed. This
change, combined with the proceeding change, ensures that the original cascade
order is maintained after the transformed styles are appended to the DOM.
-- Updated `options.onlyVars` default value from `true` to `false`. This
+- Changed `options.onlyVars` default value from `true` to `false`. This
change, combined with the preceding change, ensures that the original cascade
order is maintained after the transformed styles are appended to the DOM.
@@ -268,10 +272,10 @@
- Fixed bug that prevented `options.onlyVars` from properly filtering
declarations that do not contain a custom property value or function.
-- Updated `options.preserve` default value from `true` to `false`. This aligns
+- Changed `options.preserve` default value from `true` to `false`. This aligns
with other default values which assume a "legacy-only" configuration.
-- Updated logic for inserting generated `<style>` element. Element is now
+- Changed logic for inserting generated `<style>` element. Element is now
inserted as first CSS source node rather than the last. This allows the
cascade order to be maintained when `options.onlyVars` is `true`.
diff --git a/src/transform-css.js b/src/transform-css.js
index <HASH>..<HASH> 100644
--- a/src/transform-css.js
+++ b/src/transform-css.js
@@ -276,7 +276,7 @@ function resolveValue(value, map, settings = {}, __recursiveFallback) {
* // => 'var(--fail)' when map['--fail'] does not exist
*/
function resolveFunc(value) {
- const name = value.split(',')[0];
+ const name = value.split(',')[0].replace(/[\s\n\t]/g, '');
const fallback = (value.match(/(?:\s*,\s*){1}(.*)?/) || [])[1];
const match = map.hasOwnProperty(name) ? String(map[name]) : undefined;
const replacement = match || (fallback ? String(fallback) : undefined);
diff --git a/tests/transform-css.test.js b/tests/transform-css.test.js
index <HASH>..<HASH> 100644
--- a/tests/transform-css.test.js
+++ b/tests/transform-css.test.js
@@ -83,6 +83,21 @@ describe('transform-css', function() {
expect(cssOut).to.equal(expectCss);
});
+ it('transforms variable function with spaces, tabs, and new lines', function() {
+ const cssIn = `
+ :root { --color: red; }
+ p {
+ color: var(
+ --color
+ );
+ }
+ `;
+ const cssOut = transformCss(cssIn);
+ const expectCss = 'p{color:red;}';
+
+ expect(cssOut).to.equal(expectCss);
+ });
+
it('transforms variable function in mixed property value', function() {
const cssIn = `
:root { --margin: 20px; }
|
Fixed var() with spaces, tabs, and new lines
|
jhildenbiddle_css-vars-ponyfill
|
train
|
0eda41e713b7c02fabe94ef2f9b988bce31469fb
|
diff --git a/auth_metadata.go b/auth_metadata.go
index <HASH>..<HASH> 100644
--- a/auth_metadata.go
+++ b/auth_metadata.go
@@ -53,8 +53,13 @@ func (mc *metadataCreds) ExpiringKeyForSigning(now time.Time) (*SigningKey, time
func retrieveAWSCredentials(role string) (map[string]string, error) {
var bodybytes []byte
+
+ client := http.Client{
+ Timeout: time.Duration(10 * time.Second),
+ }
+
// Retrieve the json for this role
- resp, err := http.Get(fmt.Sprintf("%s/%s", AWSIAMCredsURL, role))
+ resp, err := client.Get(fmt.Sprintf("%s/%s", AWSIAMCredsURL, role))
if err != nil || resp.StatusCode != http.StatusOK {
return nil, err
}
@@ -77,7 +82,11 @@ func retrieveAWSCredentials(role string) (map[string]string, error) {
func retrieveIAMRole() (string, error) {
var bodybytes []byte
- resp, err := http.Get(AWSIAMCredsURL)
+ client := http.Client{
+ Timeout: time.Duration(10 * time.Second),
+ }
+
+ resp, err := client.Get(AWSIAMCredsURL)
if err != nil || resp.StatusCode != http.StatusOK {
return "", err
}
|
Fix AWS authentication using metdata timeout. Default HTTP client has no timeout and results in infinite hang
|
sendgridlabs_go-kinesis
|
train
|
9eaf469e99fac47eda2c023d90b21e655145feee
|
diff --git a/lib/fog/rackspace/files.rb b/lib/fog/rackspace/files.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/rackspace/files.rb
+++ b/lib/fog/rackspace/files.rb
@@ -59,9 +59,10 @@ module Fog
},
:host => @cdn_host,
:method => params[:method],
- :path => "#{@cdn_path}/#{params[:path]}"
+ :path => "#{@cdn_path}/#{params[:path]}",
+ :query => params[:query]
})
- unless response.status == 204
+ unless response.body.empty?
response.body = JSON.parse(response.body)
end
response
@@ -76,9 +77,10 @@ module Fog
},
:host => @storage_host,
:method => params[:method],
- :path => "#{@storage_path}/#{params[:path]}"
+ :path => "#{@storage_path}/#{params[:path]}",
+ :query => params[:query]
})
- unless response.status == 204
+ unless response.body.empty?
response.body = JSON.parse(response.body)
end
response
diff --git a/lib/fog/rackspace/requests/files/get_containers.rb b/lib/fog/rackspace/requests/files/get_containers.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/rackspace/requests/files/get_containers.rb
+++ b/lib/fog/rackspace/requests/files/get_containers.rb
@@ -20,7 +20,7 @@ unless Fog.mocking?
# * 'name'<~String>: - Name of container
def get_containers(options = {})
options = { 'format' => 'json' }.merge!(options)
- query = []
+ query = ''
for key, value in options
query << "#{key}=#{CGI.escape(value)}&"
end
@@ -31,9 +31,6 @@ unless Fog.mocking?
:path => '',
:query => query
)
- if response.status == 204
- response.body = []
- end
response
end
diff --git a/lib/fog/rackspace/requests/files/put_container.rb b/lib/fog/rackspace/requests/files/put_container.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/rackspace/requests/files/put_container.rb
+++ b/lib/fog/rackspace/requests/files/put_container.rb
@@ -11,7 +11,7 @@ unless Fog.mocking?
#
def put_container(name)
response = storage_request(
- :expects => 201,
+ :expects => [201, 202],
:method => 'PUT',
:path => CGI.escape(name)
)
diff --git a/spec/rackspace/requests/files/delete_container_spec.rb b/spec/rackspace/requests/files/delete_container_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rackspace/requests/files/delete_container_spec.rb
+++ b/spec/rackspace/requests/files/delete_container_spec.rb
@@ -3,9 +3,12 @@ require File.dirname(__FILE__) + '/../../../spec_helper'
describe 'Rackspace::Files.delete_container' do
describe 'success' do
+ before(:each) do
+ files.put_container('container_name')
+ end
+
it "should return proper attributes" do
- pending
- p files.delete_container(container_name)
+ files.delete_container('container_name')
end
end
diff --git a/spec/rackspace/requests/files/get_container_spec.rb b/spec/rackspace/requests/files/get_container_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rackspace/requests/files/get_container_spec.rb
+++ b/spec/rackspace/requests/files/get_container_spec.rb
@@ -5,7 +5,7 @@ describe 'Rackspace::Files.get_container' do
it "should return proper attributes" do
pending
- p files.get_container(container_name)
+ files.get_container(container_name)
end
end
diff --git a/spec/rackspace/requests/files/get_containers_spec.rb b/spec/rackspace/requests/files/get_containers_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rackspace/requests/files/get_containers_spec.rb
+++ b/spec/rackspace/requests/files/get_containers_spec.rb
@@ -3,8 +3,19 @@ require File.dirname(__FILE__) + '/../../../spec_helper'
describe 'Rackspace::Files.get_containers' do
describe 'success' do
+ before(:each) do
+ files.put_container('container_name')
+ end
+
+ after(:each) do
+ files.delete_container('container_name')
+ end
+
it "should return proper attributes" do
- p files.get_containers
+ actual = files.get_containers.body
+ actual.first['bytes'].should be_an(Integer)
+ actual.first['count'].should be_an(Integer)
+ actual.first['name'].should be_a(String)
end
end
diff --git a/spec/rackspace/requests/files/put_container_spec.rb b/spec/rackspace/requests/files/put_container_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rackspace/requests/files/put_container_spec.rb
+++ b/spec/rackspace/requests/files/put_container_spec.rb
@@ -3,9 +3,12 @@ require File.dirname(__FILE__) + '/../../../spec_helper'
describe 'Rackspace::Files.put_container' do
describe 'success' do
+ after(:each) do
+ files.delete_container('container_name')
+ end
+
it "should return proper attributes" do
- pending
- p files.put_container(container_name)
+ files.put_container('container_name')
end
end
|
starting to fill in pending rackspace files tests
|
fog_fog
|
train
|
51b8886d70d1b3c1062ef75b41eaa7ace4c61437
|
diff --git a/lib/angle-bracket-invocation-polyfill.js b/lib/angle-bracket-invocation-polyfill.js
index <HASH>..<HASH> 100644
--- a/lib/angle-bracket-invocation-polyfill.js
+++ b/lib/angle-bracket-invocation-polyfill.js
@@ -91,7 +91,6 @@ class AngleBracketPolyfill {
arg.loc
)
));
- // AttrNode.value: TextNode | MustacheStatement | ConcatStatement;
if (invocation.kind === 'StaticComponent') {
if (invocation.selfClosing === true) {
|
Remove outdated comment from AST transform.
|
rwjblue_ember-angle-bracket-invocation-polyfill
|
train
|
ed8a27d716b4b111118eb4802276dd84b1450b98
|
diff --git a/src/Components/Expression.php b/src/Components/Expression.php
index <HASH>..<HASH> 100644
--- a/src/Components/Expression.php
+++ b/src/Components/Expression.php
@@ -261,7 +261,7 @@ class Expression extends Component
continue;
}
$isExpr = true;
- } elseif ($brackets === 0 && count($ret->expr) > 0 && ! $alias) {
+ } elseif ($brackets === 0 && strlen($ret->expr) > 0 && ! $alias) {
/* End of expression */
break;
}
diff --git a/src/Statements/DeleteStatement.php b/src/Statements/DeleteStatement.php
index <HASH>..<HASH> 100644
--- a/src/Statements/DeleteStatement.php
+++ b/src/Statements/DeleteStatement.php
@@ -154,7 +154,7 @@ class DeleteStatement extends Statement
if ($this->order != NULL && count($this->order) > 0) {
$ret .= ' ORDER BY ' . ExpressionArray::build($this->order);
}
- if ($this->limit != NULL && count($this->limit) > 0) {
+ if ($this->limit != NULL && strlen($this->limit) > 0) {
$ret .= ' LIMIT ' . Limit::build($this->limit);
}
diff --git a/src/Statements/InsertStatement.php b/src/Statements/InsertStatement.php
index <HASH>..<HASH> 100644
--- a/src/Statements/InsertStatement.php
+++ b/src/Statements/InsertStatement.php
@@ -121,7 +121,7 @@ class InsertStatement extends Statement
$ret .= ' VALUES ' . Array2d::build($this->values);
} elseif ($this->set != NULL && count($this->set) > 0) {
$ret .= ' SET ' . SetOperation::build($this->set);
- } elseif ($this->select != NULL && count($this->select) > 0) {
+ } elseif ($this->select != NULL && strlen($this->select) > 0) {
$ret .= ' ' . $this->select->build();
}
diff --git a/src/Statements/ReplaceStatement.php b/src/Statements/ReplaceStatement.php
index <HASH>..<HASH> 100644
--- a/src/Statements/ReplaceStatement.php
+++ b/src/Statements/ReplaceStatement.php
@@ -99,7 +99,7 @@ class ReplaceStatement extends Statement
$ret .= ' VALUES ' . Array2d::build($this->values);
} elseif ($this->set != NULL && count($this->set) > 0) {
$ret .= ' SET ' . SetOperation::build($this->set);
- } elseif ($this->select != NULL && count($this->select) > 0) {
+ } elseif ($this->select != NULL && strlen($this->select) > 0) {
$ret .= ' ' . $this->select->build();
}
|
Use strlen on strings instead of count
This fails in PHP <I>
|
phpmyadmin_sql-parser
|
train
|
afef21498b5d7b5dcf5af7f78464f4b247994e34
|
diff --git a/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java b/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java
index <HASH>..<HASH> 100644
--- a/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java
+++ b/src/com/opera/core/systems/scope/services/ums/DesktopWindowManager.java
@@ -13,6 +13,7 @@ import com.opera.core.systems.ScopeServices;
import com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowList;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo;
+import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo.QuickWidgetType;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfoList;
import com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowInfo;
//import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetSearch;
@@ -136,20 +137,24 @@ public class DesktopWindowManager extends AbstractService implements IDesktopWin
return null;
}
- public QuickWidget getQuickWidgetByPos(int id, int row, int column)
+ public QuickWidget getQuickWidgetByPos( int id, int row, int column)
{
return getQuickWidgetByPos(id, row, column, "");
}
// FIXME. TODO: ADD check type of widget too. Also to the other funcs to find widget!
- public QuickWidget getQuickWidgetByPos(int id, int row, int column, String parentName)
+ public QuickWidget getQuickWidgetByPos( int id, int row, int column, String parentName)
{
if (id < 0) {
id = getActiveWindowId();
}
List<QuickWidget> widgets = getQuickWidgetList(id);
for (QuickWidget widget : widgets) {
- if ((parentName.length() == 0 || widget.getParentName().equals(parentName)) &&
+ if ((parentName.length() == 0 || widget.getParentName().equals(parentName)) &&
+ // Position is only set on tabbuttons and treeitems
+ // so only look for these
+ (widget.getType() == QuickWidgetType.TABBUTTON ||
+ widget.getType() == QuickWidgetType.TREEITEM) &&
widget.getRow() == row && widget.getColumn() == column) {
return widget;
}
|
Hack to get tab with position 0 to work (all widget with no pos set has pos 0 so we got a clash)
|
operasoftware_operaprestodriver
|
train
|
b2eaa291f36fc8c050a10d6d940a5f88ff08aed4
|
diff --git a/lib/util/mixin.js b/lib/util/mixin.js
index <HASH>..<HASH> 100644
--- a/lib/util/mixin.js
+++ b/lib/util/mixin.js
@@ -1,5 +1,6 @@
'use strict';
+var _ = require('lodash');
var Class = require('./class');
/**
@@ -8,23 +9,40 @@ var Class = require('./class');
* @since 1.0
* @public
* @constructor Mixin
- * @param {...(Object|Mixin)} properties Properties to add to the mixin.
+ * @param {...(Object|Mixin)} properties Properties and/or mixins to add to the
+ * mixin.
*/
var Mixin = Class.extend({
- init: function(/*properties*/) {
+ init: function() {
var args = Array.prototype.slice.call(arguments);
- var combined = args.reduce(function(array, arg) {
- var isMixin = arg instanceof Mixin.__class__;
- var mixins = isMixin ? arg._all : [arg];
- return array.concat(mixins);
- }, []);
- this._all = combined;
+ return args.reduce(function(dependency, mixin) {
+ while (mixin) { // extend dependency chain to include existing mixins
+ dependency = Mixin._link(mixin, dependency);
+ mixin = mixin._dependency;
+ }
+ return dependency;
+ }, undefined);
}
});
Mixin.reopenClass({
extend: function() {
throw new Error('Cannot extend Mixin class');
+ },
+
+ /**
+ * Link objects together through a hidden `_dependency` property that
+ * basically creates a linked-list.
+ *
+ * @param {Object} mixin A mixin to link.
+ * @param {Object} next The next mixin in the chain.
+ * @return {Mixin} The linked mixin.
+ */
+ _link: function(mixin, next) {
+ var F = function() {};
+ F.prototype = Object.create(Mixin.__class__.prototype);
+ F.prototype._dependency = next;
+ return _.extend(new F(), mixin);
}
});
@@ -34,7 +52,13 @@ Class.__metaclass__.prototype.extend = (function(extend) {
var args = Array.prototype.slice.call(arguments);
var mixins = [];
while (args[0] instanceof Mixin.__class__) {
- mixins = mixins.concat(args.shift()._all);
+ var mixin = args.shift();
+ while(mixin) {
+ // mixins are linked to their dependencies, unshift each to get them in
+ // the proper order for adding them to the created class.
+ mixins.unshift(mixin);
+ mixin = mixin._dependency;
+ }
}
// pull out the properties from the arguments & replace with an empty
diff --git a/test/util/mixin_test.js b/test/util/mixin_test.js
index <HASH>..<HASH> 100644
--- a/test/util/mixin_test.js
+++ b/test/util/mixin_test.js
@@ -1,11 +1,26 @@
'use strict';
+var _ = require('lodash');
var chai = require('chai');
var expect = chai.expect;
var Class = require('../../lib/util/class');
var Mixin = require('../../lib/util/mixin');
describe('mixins', function() {
+ it('looks just like an object', function() {
+ var properties = {
+ first: 'first',
+ second: function() { return 'second'; }
+ };
+ var SimpleMixin = Mixin.create(properties);
+ expect(_.clone(SimpleMixin)).to.eql(properties);
+ });
+
+ it('is a mixin', function() {
+ var SimpleMixin = Mixin.create({});
+ expect(SimpleMixin).to.be.instanceOf(Mixin.__class__);
+ });
+
it('can specify mixins without instance properties', function() {
var BarkMixin = Mixin.create({
bark: function() { return 'bark'; }
|
Mixins now look more similar to standard objects.
|
wbyoung_azul
|
train
|
cf43663e85be35c0343cfde87e4fb9672614b28d
|
diff --git a/command/e2etest/init_test.go b/command/e2etest/init_test.go
index <HASH>..<HASH> 100644
--- a/command/e2etest/init_test.go
+++ b/command/e2etest/init_test.go
@@ -39,7 +39,7 @@ func TestInitProviders(t *testing.T) {
t.Errorf("success message is missing from output:\n%s", stdout)
}
- if !strings.Contains(stdout, "- Downloading plugin for provider \"template\" (terraform-providers/template)") {
+ if !strings.Contains(stdout, "- Downloading plugin for provider \"template\" (hashicorp/template)") {
t.Errorf("provider download message is missing from output:\n%s", stdout)
t.Logf("(this can happen if you have a copy of the plugin in one of the global plugin search dirs)")
}
|
command/e2etest: Fix TestInitProviders
The canonical location of the "template" provider is now in the hashicorp
namespace rather than the terraform-providers namespace, so the output
has changed to reflect that.
|
hashicorp_terraform
|
train
|
bb2633797652389314079e921c8ec05fa211ea3c
|
diff --git a/tornado/httpclient.py b/tornado/httpclient.py
index <HASH>..<HASH> 100644
--- a/tornado/httpclient.py
+++ b/tornado/httpclient.py
@@ -227,6 +227,13 @@ class AsyncHTTPClient(Configurable):
raise RuntimeError("fetch() called on closed AsyncHTTPClient")
if not isinstance(request, HTTPRequest):
request = HTTPRequest(url=request, **kwargs)
+ else:
+ for k, v in kwargs.items():
+ try:
+ getattr(request, k)
+ except Exception as e:
+ raise ValueError('HTTPRequest get an unexcept kwags %s' % k)
+ setattr(request, k, v)
# We may modify this (to add Host, Accept-Encoding, etc),
# so make sure we don't modify the caller's object. This is also
# where normal dicts get converted to HTTPHeaders objects.
|
make kwargs always work in AsyncHTTPClient.fetch()
|
tornadoweb_tornado
|
train
|
67fb1c7d0230187ec38e8c129b4948a042867579
|
diff --git a/environs/interface.go b/environs/interface.go
index <HASH>..<HASH> 100644
--- a/environs/interface.go
+++ b/environs/interface.go
@@ -12,7 +12,12 @@ type EnvironProvider interface {
// Open opens the environment and returns it.
Open(config *config.Config) (Environ, error)
- // TODO: add Validate
+ // Validate ensures that config is a valid configuration for this
+ // provider, applying changes to it if necessary, and returns the
+ // validated configuration.
+ // If old is not nil, it holds the previous environment configuration
+ // for consideration when validating changes.
+ // TODO: Validate(config, old *config.Config) (valid *config.Config, err error)
}
var ErrNoDNSName = errors.New("DNS name not allocated")
diff --git a/environs/open.go b/environs/open.go
index <HASH>..<HASH> 100644
--- a/environs/open.go
+++ b/environs/open.go
@@ -24,6 +24,17 @@ func (envs *Environs) Open(name string) (Environ, error) {
return New(e.config)
}
+// NewFromAttrs returns a new environment based on the provided configuration
+// attributes. The configuration is validated for the respective provider
+// before the environment is instantiated.
+func NewFromAttrs(attrs map[string]interface{}) (Environ, error) {
+ cfg, err := config.New(attrs)
+ if err != nil {
+ return nil, err
+ }
+ return New(cfg)
+}
+
// New returns a new environment based on the provided configuration.
// The configuration is validated for the respective provider before
// the environment is instantiated.
@@ -32,16 +43,6 @@ func New(config *config.Config) (Environ, error) {
if !ok {
return nil, fmt.Errorf("no registered provider for %q", config.Type())
}
+ // TODO: config, err := p.Validate(config, nil)
return p.Open(config)
}
-
-// New returns a new environment based on the provided configuration
-// attributes. The configuration is validated for the respective provider
-// before the environment is instantiated.
-func NewFromAttrs(attrs map[string]interface{}) (Environ, error) {
- cfg, err := config.New(attrs)
- if err != nil {
- return nil, err
- }
- return New(cfg)
-}
|
Clarified the call sites for Validate.
|
juju_juju
|
train
|
eece8e1588aca6c338306249c4934f9b424b2e1a
|
diff --git a/maven-repository-manager/src/test/java/org/jboss/pnc/mavenrepositorymanager/fixture/TestBuildExecution.java b/maven-repository-manager/src/test/java/org/jboss/pnc/mavenrepositorymanager/fixture/TestBuildExecution.java
index <HASH>..<HASH> 100644
--- a/maven-repository-manager/src/test/java/org/jboss/pnc/mavenrepositorymanager/fixture/TestBuildExecution.java
+++ b/maven-repository-manager/src/test/java/org/jboss/pnc/mavenrepositorymanager/fixture/TestBuildExecution.java
@@ -19,33 +19,18 @@ package org.jboss.pnc.mavenrepositorymanager.fixture;
import org.jboss.pnc.spi.repositorymanager.BuildExecution;
-import java.net.URI;
-
public class TestBuildExecution implements BuildExecution {
private int id = 1;
- private String topContentId;
-
- private String buildSetContentId;
-
private String buildContentId;
- private String projectName = "my project";
-
- private boolean isSetBuild;
-
- private URI logsWebSocketLink;
-
- public TestBuildExecution(String topId, String setId, String buildId, boolean isSetBuild) {
- this.topContentId = topId;
- this.buildSetContentId = setId;
+ public TestBuildExecution(String buildId) {
this.buildContentId = buildId;
- this.isSetBuild = isSetBuild;
}
public TestBuildExecution() {
- this("product+myproduct+1-0", null, "build+myproject+12345", false);
+ this("build+myproject+12345");
}
public int getId() {
@@ -56,21 +41,4 @@ public class TestBuildExecution implements BuildExecution {
public String getBuildContentId() {
return buildContentId;
}
-
- public void setTopContentId(String topContentId) {
- this.topContentId = topContentId;
- }
-
- public void setBuildSetContentId(String buildSetContentId) {
- this.buildSetContentId = buildSetContentId;
- }
-
- public void setBuildContentId(String buildContentId) {
- this.buildContentId = buildContentId;
- }
-
- public void setProjectName(String projectName) {
- this.projectName = projectName;
- }
-
}
|
Clean up maven repo manager fixture.
|
project-ncl_pnc
|
train
|
458bbda9cd161a71b9a97d55b581492f7ca3b696
|
diff --git a/tests/test_regular_solution.py b/tests/test_regular_solution.py
index <HASH>..<HASH> 100644
--- a/tests/test_regular_solution.py
+++ b/tests/test_regular_solution.py
@@ -51,6 +51,9 @@ def test_4_components():
GE = RegularSolution(T, xs, Vs, SPs, lambda_coeffs)
assert eval(str(GE)).GE() == GE.GE()
+ GE2 = RegularSolution.from_JSON(GE.as_JSON())
+ assert GE2.__dict__ == GE.__dict__
+
dT = 1e-7*T
gammas_expect = [1.1928784349228994, 1.3043087978251762, 3.2795596493820955, 197.92137114651274]
assert_close1d(GE.gammas(), gammas_expect, rtol=1e-12)
@@ -135,6 +138,10 @@ def test_4_components():
[7499.862362680743, 7807.307245181044, 7459.310988306651, 6343.066547716518]]]
assert_close3d(d3GE_dxixjxks_analytical, d3GE_dxixjxks_sympy, rtol=1e-12)
+ # Test with some stored results
+ GE2 = RegularSolution.from_JSON(GE.as_JSON())
+ assert GE2.__dict__ == GE.__dict__
+
def test_create_many_components_regular_solution():
# Just create it. This can be used for easy benchmarking.
N = 10
|
Add regular solution json export test
|
CalebBell_thermo
|
train
|
84bb35ebf4aa76addc360f6c0157152c949a9e72
|
diff --git a/floodsub_test.go b/floodsub_test.go
index <HASH>..<HASH> 100644
--- a/floodsub_test.go
+++ b/floodsub_test.go
@@ -986,7 +986,7 @@ func TestImproperlySignedMessageRejected(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- time.Sleep(time.Millisecond * 10)
+ time.Sleep(time.Millisecond * 50)
// First the adversary sends the correct message.
err = adversaryPubSub.Publish(topic, correctMessage)
|
Bump wait from <I> -> <I>ms
This matches the waits in the rest of the package.
|
libp2p_go-libp2p-pubsub
|
train
|
04e81daa1bddc6a5f2f28dc490d762f71b7546c8
|
diff --git a/functional/server_tests.js b/functional/server_tests.js
index <HASH>..<HASH> 100644
--- a/functional/server_tests.js
+++ b/functional/server_tests.js
@@ -688,3 +688,115 @@ exports['Should correctly connect execute 5 evals in parallel'] = {
server.connect();
}
}
+
+exports['Should correctly promoteValues when calling getMore on queries'] = {
+ metadata: {
+ requires: {
+ node: ">0.8.0",
+ topology: ['single', 'ssl', 'wiredtiger']
+ }
+ },
+
+ // The actual test we wish to run
+ test: function(configuration, test) {
+ var Server = require('../../../lib/topologies/server')
+ , bson = require('bson');
+
+ // Attempt to connect
+ var server = new Server({
+ host: configuration.host
+ , port: configuration.port
+ , size: 10
+ , bson: new bson()
+ });
+ // Namespace
+ var ns = 'integration_tests.remove_example';
+
+ // Add event listeners
+ server.on('connect', function(server) {
+ var docs = new Array(150).fill(0).map(function(_, i) {
+ return {
+ _id: 'needle_' + i,
+ is_even: i % 2,
+ long: bson.Long.fromString('1234567890'),
+ double: 0.23456,
+ int: 1234
+ };
+ });
+
+ server.insert(ns, docs, function(err, r) {
+ test.equal(null, err);
+ test.equal(true, r.result.ok);
+
+ // Execute find
+ var cursor = server.cursor(ns, {
+ find: ns
+ , query: {}
+ , limit: 102
+ }, {
+ promoteValues: false
+ });
+
+ function callNext(cursor) {
+ cursor.next(function(err, doc) {
+ if(!doc) {
+ return test.done();
+ }
+
+ test.equal(typeof doc.int, 'object');
+ test.equal(doc.int._bsontype, 'Int32');
+ test.equal(typeof doc.long, 'object');
+ test.equal(doc.long._bsontype, 'Long');
+ test.equal(typeof doc.double, 'object');
+ test.equal(doc.double._bsontype, 'Double');
+
+ // Call next
+ callNext(cursor);
+ });
+ }
+
+ callNext(cursor);
+ });
+ });
+
+ // Start connection
+ server.connect();
+
+ // var MongoClient = configuration.require.MongoClient;
+ // var Long = configuration.require.Long;
+
+ // MongoClient.connect(configuration.url(), function(err, db) {
+ // var docs = new Array(150).fill(0).map(function(_, i) {
+ // return {
+ // _id: 'needle_' + i,
+ // is_even: i % 2,
+ // long: Long.fromString('1234567890'),
+ // double: 0.23456,
+ // int: 1234
+ // };
+ // });
+
+ // db.collection('haystack').insert(docs, function(errInsert) {
+ // if (errInsert) throw errInsert;
+ // // change limit from 102 to 101 and this test passes.
+ // // seems to indicate that the promoteValues flag is used for the
+ // // initial find, but not for subsequent getMores
+ // db.collection('haystack').find({}, {limit: 102, promoteValues: false})
+ // .on('data', function(doc) {
+ // test.equal(typeof doc.int, 'object');
+ // test.equal(doc.int._bsontype, 'Int32');
+ // test.equal(typeof doc.long, 'object');
+ // test.equal(doc.long._bsontype, 'Long');
+ // test.equal(typeof doc.double, 'object');
+ // test.equal(doc.double._bsontype, 'Double');
+ // })
+ // .on('end', function() {
+ // db.dropCollection('haystack', function() {
+ // db.close();
+ // test.done();
+ // });
+ // });
+ // });
+ // });
+ }
+}
|
NODE-<I> promoteValues not being promoted correctly to getMore
|
mongodb_node-mongodb-native
|
train
|
40aaf6c459f2dbfe5617f12c0324871964780665
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -456,14 +456,18 @@ PageClass.prototype.importDocument = function(doc, noload) {
});
}
- var links = queryAll(mountHead, 'link[rel="none"]')
- .concat(queryAll(mountBody, 'link[rel="none"]'));
+ var parallels = [].concat(
+ queryAll(mountHead, 'link[rel="_stylesheet"]'),
+ queryAll(mountBody, 'link[rel="_stylesheet"]')
+ );
- var scripts = queryAll(mountHead, 'script[type="none"]')
- .concat(queryAll(mountBody, 'script[type="none"]'));
+ var serials = [].concat(
+ queryAll(mountHead, 'script[type="none"],link[rel="_import"]'),
+ queryAll(mountBody, 'script[type="none"],link[rel="_import"]'),
+ );
// links can be loaded all at once
- return Promise.all(links.map(loadNode)).then(function() {
+ return Promise.all(parallels.map(loadNode)).then(function() {
// replace document
var root = document.documentElement;
while (root.attributes.length > 0) {
@@ -478,7 +482,7 @@ PageClass.prototype.importDocument = function(doc, noload) {
// scripts must be run in order
var p = Promise.resolve();
- scripts.forEach(function(node) {
+ serials.forEach(function(node) {
p = p.then(function() {
return loadNode(node);
});
|
Use simpler rel handling to keep script/import order
|
kapouer_window-page
|
train
|
16e8502d78b1764ad122bf8d56cd381e4958ef43
|
diff --git a/plugins/deck.js b/plugins/deck.js
index <HASH>..<HASH> 100644
--- a/plugins/deck.js
+++ b/plugins/deck.js
@@ -8,7 +8,7 @@ Deck.prototype = {
},
isActive : function() {
- return typeof $.deck === "function";
+ return typeof $ === "function" && typeof $.deck === "function";
},
slideCount : function() {
|
Avoid 'Can't find variable: $' message in deck.js detection
|
astefanutti_decktape
|
train
|
7c4ce9e36e61f979d5b7cdeeda1845f5bee847f7
|
diff --git a/src/compile.php b/src/compile.php
index <HASH>..<HASH> 100644
--- a/src/compile.php
+++ b/src/compile.php
@@ -48,6 +48,7 @@ return [
'orchestra/foundation' => [
'src/Providers/SupportServiceProvider',
'src/Support/Providers/Traits/RouteProviderTrait',
+ 'src/Support/Providers/ModuleServiceProvider',
'src/Support/Providers/ExtensionServiceProvider',
'src/Support/Providers/ExtensionRouteServiceProvider',
'src/Support/Providers/RouteServiceProvider',
|
Add ModuleServiceProvider to compiled list.
|
orchestral_optimize
|
train
|
b2391691e2789589494f77f1cc0e8b1da73ba599
|
diff --git a/Gruntfile.js b/Gruntfile.js
index <HASH>..<HASH> 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -103,11 +103,10 @@ module.exports = function(grunt) {
banner: ''
},
files: {
- '<%=dirs.dist%>/jquery.qtip.js': [
- '<%=dirs.dist%>/jquery.qtip.js'
- ],
- '<%=dirs.dist%>/jquery.qtip.min.js': [
- '<%=dirs.dist%>/jquery.qtip.min.js'
+ '<%=dirs.dist%>/imagesloaded.pkg.js': [
+ '<%=dirs.libs%>/imagesloaded/components/eventEmitter/EventEmitter.js',
+ '<%=dirs.libs%>/imagesloaded/components/eventie/eventie.js',
+ '<%=dirs.libs%>/imagesloaded/imagesloaded.js'
]
}
}
@@ -132,7 +131,7 @@ module.exports = function(grunt) {
dist: {
files: {
'<%=dirs.dist%>/jquery.qtip.min.js': ['<%=dirs.dist%>/jquery.qtip.js'],
- '<%=dirs.dist%>/imagesloaded.min.js': ['<%=dirs.libs%>/imagesloaded/imagesloaded.js']
+ '<%=dirs.dist%>/imagesloaded.pkg.min.js': ['<%=dirs.dist%>/imagesloaded.pkg.js']
}
}
},
@@ -310,7 +309,7 @@ module.exports = function(grunt) {
});
});
- var defaultTasks = ['concat:dist', 'concat:css', 'uglify', 'cssmin', 'concat:libs', 'replace'];
+ var defaultTasks = ['concat', 'uglify', 'cssmin', 'replace'];
// Setup tasks
grunt.registerTask('basic', ['init:basic', 'clean'].concat(defaultTasks));
|
Added packaged imagesLoaded file
|
qTip2_qTip2
|
train
|
cbe74e151bae169b4bacec9da7c5d359623a79c3
|
diff --git a/spyderlib/plugins/__init__.py b/spyderlib/plugins/__init__.py
index <HASH>..<HASH> 100644
--- a/spyderlib/plugins/__init__.py
+++ b/spyderlib/plugins/__init__.py
@@ -511,15 +511,6 @@ class SpyderPluginMixin(object):
QApplication.restoreOverrideCursor()
self.__show_message(message, timeout=2000)
QApplication.processEvents()
-
- def set_default_color_scheme(self, name='spyder'):
- """Set default color scheme (only once)"""
- color_scheme_name = self.get_option('color_scheme_name', None)
- if color_scheme_name is None:
- names = CONF.get("color_schemes", "names")
- if name not in names:
- name = names[0]
- self.set_option('color_scheme_name', name)
def get_color_scheme(self):
"""Get current color scheme"""
|
Remove unneeded method in SpyderPluginMixin
|
spyder-ide_spyder
|
train
|
36e5519a596fb73315ff2dd6d1f187501539c066
|
diff --git a/src/jdataview.js b/src/jdataview.js
index <HASH>..<HASH> 100644
--- a/src/jdataview.js
+++ b/src/jdataview.js
@@ -133,16 +133,7 @@ var jDataView = function (buffer, byteOffset, byteLength, littleEndian) {
continue;
}
- var name;
- if (type === 'Int8' || type === 'Uint8') {
- name = 'read' + nodeNaming[type];
- } else if (littleEndian) {
- name = 'read' + nodeNaming[type] + 'LE';
- } else {
- name = 'read' + nodeNaming[type] + 'BE';
- }
-
- (function(type, view, name){
+ (function(type, view){
var size = dataTypes[type];
view['get' + type] = function (byteOffset, littleEndian) {
// Handle the lack of endianness
@@ -155,12 +146,21 @@ var jDataView = function (buffer, byteOffset, byteLength, littleEndian) {
byteOffset = view._offset;
}
+ var name;
+ if (type === 'Int8' || type === 'Uint8') {
+ name = 'read' + nodeNaming[type];
+ } else if (littleEndian) {
+ name = 'read' + nodeNaming[type] + 'LE';
+ } else {
+ name = 'read' + nodeNaming[type] + 'BE';
+ }
+
// Move the internal offset forward
view._offset = byteOffset + size;
return view.buffer[name](view._start + byteOffset);
}
- })(type, this, name);
+ })(type, this);
}
} else {
for (var type in dataTypes) {
|
Fixed bug when using Node Buffers - jDataView did not take into mind custom endianness argument and always used the one was set in constructor.
|
jDataView_jDataView
|
train
|
657fe40742b5fcefe0c3249b20b23031342b36fc
|
diff --git a/upload/admin/controller/localisation/currency.php b/upload/admin/controller/localisation/currency.php
index <HASH>..<HASH> 100644
--- a/upload/admin/controller/localisation/currency.php
+++ b/upload/admin/controller/localisation/currency.php
@@ -119,7 +119,7 @@ class Currency extends \Opencart\System\Engine\Controller {
$this->load->model('localisation/currency');
if ($this->validateRefresh()) {
- $this->load->controller('extension/currency/' . $this->config->get('config_currency_engine') . '/currency', $this->config->get('config_currency'));
+ $this->load->controller('extension/currency/' . $this->config->get('config_currency_engine') . '|currency', $this->config->get('config_currency'));
$this->session->data['success'] = $this->language->get('text_success');
|
Changed path /currency to |currency
|
opencart_opencart
|
train
|
3c76df5d2d5d1fd60e7ad7a1f92fc3b1022fe67b
|
diff --git a/lib/Thelia/Action/Translation.php b/lib/Thelia/Action/Translation.php
index <HASH>..<HASH> 100644
--- a/lib/Thelia/Action/Translation.php
+++ b/lib/Thelia/Action/Translation.php
@@ -14,8 +14,6 @@ namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
-use Symfony\Component\Translation\Loader\ArrayLoader;
-use Symfony\Component\Translation\Loader\PhpFileLoader;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\Translation\TranslationEvent;
use Thelia\Core\Translation\Translator;
@@ -262,7 +260,12 @@ class Translation extends BaseAction implements EventSubscriberInterface
);
}
} else {
+ /*$loader = new PhpFileLoader();
+ $catalogue = $loader->load($file);
+ $translations = $catalogue->all();
+ */
$translations = require $file;
+
if (! is_array($translations)) {
$translations = [];
}
@@ -274,13 +277,13 @@ class Translation extends BaseAction implements EventSubscriberInterface
$customs = $event->getCustomFallbackStrings();
$globals = $event->getGlobalFallbackStrings();
+ // just reset current translations for this domain to remove strings that do not exist anymore
+ $translations[$event->getDomain()] = [];
+
foreach ($texts as $key => $text) {
- $customKey = sprintf(Translator::GLOBAL_FALLBACK_KEY, $event->getDomain(), $text);
if (!empty($customs[$key])) {
- $translations[$customKey] = $customs[$key];
- } else {
- unset($translations[$customKey]);
+ $translations[$event->getDomain()][$text] = $customs[$key];
}
if (!empty($globals[$key])) {
@@ -291,7 +294,7 @@ class Translation extends BaseAction implements EventSubscriberInterface
}
fwrite($fp, '<' . "?php\n\n");
- fwrite($fp, "return array(\n");
+ fwrite($fp, "return [\n");
// Sort keys alphabetically while keeping index
ksort($translations);
@@ -299,13 +302,25 @@ class Translation extends BaseAction implements EventSubscriberInterface
foreach ($translations as $key => $text) {
// Write only defined (not empty) translations
if (!empty($translations[$key])) {
- $key = str_replace("'", "\'", $key);
- $translation = str_replace("'", "\'", $text);
- fwrite($fp, sprintf(" '%s' => '%s',\n", $key, $translation));
+ if (is_array($translations[$key])) {
+ $key = str_replace("'", "\'", $key);
+ fwrite($fp, sprintf(" '%s' => [\n", $key));
+ ksort($translations[$key]);
+ foreach ($translations[$key] as $subKey => $subText) {
+ $subKey = str_replace("'", "\'", $subKey);
+ $translation = str_replace("'", "\'", $subText);
+ fwrite($fp, sprintf(" '%s' => '%s',\n", $subKey, $translation));
+ }
+ fwrite($fp, " ],\n");
+ } else {
+ $key = str_replace("'", "\'", $key);
+ $translation = str_replace("'", "\'", $text);
+ fwrite($fp, sprintf(" '%s' => '%s',\n", $key, $translation));
+ }
}
}
- fwrite($fp, ");\n");
+ fwrite($fp, "];\n");
@fclose($fp);
}
diff --git a/lib/Thelia/Core/Translation/Translator.php b/lib/Thelia/Core/Translation/Translator.php
index <HASH>..<HASH> 100644
--- a/lib/Thelia/Core/Translation/Translator.php
+++ b/lib/Thelia/Core/Translation/Translator.php
@@ -19,7 +19,7 @@ class Translator extends BaseTranslator
{
const GLOBAL_FALLBACK_DOMAIN = 'global';
- const GLOBAL_FALLBACK_KEY = '[%s] %s';
+ const GLOBAL_FALLBACK_KEY = '%s.%s';
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface
|
Refactored the structure of the translation files
|
thelia_core
|
train
|
3494b2ac50da9eaf1834948e7a1562d2033ba14d
|
diff --git a/js/notebook/src/embed.js b/js/notebook/src/embed.js
index <HASH>..<HASH> 100644
--- a/js/notebook/src/embed.js
+++ b/js/notebook/src/embed.js
@@ -15,11 +15,11 @@ require('./plot/bko-plot.css');
var loadedModules = [
require("./Plot"),
- require("./TableDisplay"),
require("./EasyForm"),
require("./TabView"),
require("./GridView"),
require("./CyclingDisplayBox"),
+ require("./TableDisplay").default,
require("./SparkUI").default,
require("./Spinner").default,
require("./SparkStateProgress").default,
|
#<I> fix TableDisplay missing in Lab (#<I>)
|
twosigma_beakerx
|
train
|
6659306d3b4e227cc9eb8385cbdee2e82a0b4902
|
diff --git a/nailgun/entities.py b/nailgun/entities.py
index <HASH>..<HASH> 100644
--- a/nailgun/entities.py
+++ b/nailgun/entities.py
@@ -627,7 +627,13 @@ class Capsule(Entity, EntityReadMixin, EntitySearchMixin):
return super(Capsule, self).path(which)
-class CommonParameter(Entity):
+class CommonParameter(
+ Entity,
+ EntityCreateMixin,
+ EntityDeleteMixin,
+ EntityReadMixin,
+ EntitySearchMixin,
+ EntityUpdateMixin):
"""A representation of a Common Parameter entity."""
def __init__(self, server_config=None, **kwargs):
|
Update CommonParameters entity.
|
SatelliteQE_nailgun
|
train
|
9b99238a4072d582332ee2fc26a3157b68db9232
|
diff --git a/php_fast_cache.php b/php_fast_cache.php
index <HASH>..<HASH> 100644
--- a/php_fast_cache.php
+++ b/php_fast_cache.php
@@ -158,8 +158,12 @@
// PATH Edit by SecurityKey
// Auto create, Chmod and Warning
private static function getPath($skip_create = false) {
-
- self::$path = dirname(__FILE__);
+
+ if (self::$path=='')
+ {
+ self::$path = dirname(__FILE__);
+ }
+
if($skip_create == false || self::$checked['path'] == true) {
if(!file_exists(self::$path."/".self::$securityKey."/") || !is_writable(self::$path."/".self::$securityKey."/")) {
if(!file_exists(self::$path."/".self::$securityKey."/")) {
@@ -1810,4 +1814,4 @@
-?>
\ No newline at end of file
+?>
|
Update php_fast_cache.php
Change path by user definition.
|
PHPSocialNetwork_phpfastcache
|
train
|
f77b920f750b6625773b85c7668907653d61116f
|
diff --git a/libreantdb/api.py b/libreantdb/api.py
index <HASH>..<HASH> 100644
--- a/libreantdb/api.py
+++ b/libreantdb/api.py
@@ -1,3 +1,5 @@
+import time
+
from elasticsearch import NotFoundError
from elasticsearch.helpers import scan
@@ -5,6 +7,10 @@ import logging
log = logging.getLogger(__name__)
+def current_time_millisec():
+ return int(round(time.time() * 10**3))
+
+
def validate_book(body):
'''
This does not only accept/refuse a book. It also returns an ENHANCED
@@ -89,12 +95,10 @@ class DB(object):
'''
maps = {
'book': { # this need to be the document type!
- # special elasticsearch field
- # http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-timestamp-field.html
- # initialized with element creation date, hidden by default in query result
- "_timestamp": {"enabled": "true",
- "store": "yes"},
"properties": {
+ "_insertion_date" : {
+ "type": "long",
+ "null_value": 0},
"_text_en": {
"type": "string",
"analyzer": "english"},
@@ -142,6 +146,7 @@ class DB(object):
self.es.indices.create(index=self.index_name,
body={'settings': settings,
'mappings': maps})
+
if wait_for_ready:
log.debug('waiting for index "{}" to be ready'.format(self.index_name))
self.es.cluster.health(index=self.index_name, level='index', wait_for_status='yellow')
@@ -186,9 +191,9 @@ class DB(object):
return scan(self.es, index=self.index_name)
def get_last_inserted(self, size=30):
- query = {"fields": ["_timestamp", "_source"],
- "query": {"match_all": {}},
- "sort": [{"_timestamp": "desc"}]}
+ query = {"query": {"match_all": {}},
+ "sort": [{"_insertion_date": {"order":"desc",
+ "missing": "_last"}}]}
return self._search(body=query, size=size)
def get_books_simplequery(self, query):
@@ -240,6 +245,7 @@ class DB(object):
if 'doc_type' not in book:
book['doc_type'] = 'book'
book['body'] = validate_book(book['body'])
+ book['body']['_insertion_date'] = current_time_millisec()
return self.es.create(index=self.index_name, **book)
def delete_book(self, id):
diff --git a/libreantdb/test/test_last_inserted.py b/libreantdb/test/test_last_inserted.py
index <HASH>..<HASH> 100644
--- a/libreantdb/test/test_last_inserted.py
+++ b/libreantdb/test/test_last_inserted.py
@@ -20,9 +20,9 @@ def test_last():
@with_setup(cleanall, cleanall)
-def test_has_timestamp():
- ''' last_inserted results must have ['fields']['_timestamp']'''
+def test_has_insertion_date():
+ ''' last_inserted results must have '_insertion_date']'''
db.add_book(doc_type='book',
body=dict(title='ma che ne so', _language='it'))['_id']
db.es.indices.refresh(index=db.index_name)
- assert('_timestamp' in db.get_last_inserted()['hits']['hits'][0]['fields'])
+ assert('_insertion_date' in db.get_last_inserted()['hits']['hits'][0]['_source'])
diff --git a/webant/templates/recents.html b/webant/templates/recents.html
index <HASH>..<HASH> 100644
--- a/webant/templates/recents.html
+++ b/webant/templates/recents.html
@@ -62,8 +62,8 @@ header h1{
<div class="item-sub col-xs-12 col-sm-3 vcenter">
<ul class="meta-list list-unstyled">
<li><span class="glyphicon glyphicon-time"></span>
- <date data-timestamp="{{ b['fields']['_timestamp'] }}">
- {{ b['fields']['_timestamp'] | timepassedformat }}
+ <date data-timestamp="{{ b['_source']['_insertion_date'] }}">
+ {{ b['_source']['_insertion_date'] | timepassedformat }}
</date>
</li>
<li><span class="glyphicon glyphicon-flag"></span> {{ b['_source']['_language'] }}</li>
|
compatibility fix: es 2 has deprecated '_timestamp' field
this BREAKS compatibility with old already created index that were making
use of the '_timestamp' field.
Unfortunatly the elasticsaerch guys have decided
that we cannot use the put_mappings api to update the old index mapping
to the new one:
<URL>
|
insomnia-lab_libreant
|
train
|
50bb8eda29e5dfa94c3b97ddce74b0cb8fe34e1f
|
diff --git a/lib/store_watch_mixin.js b/lib/store_watch_mixin.js
index <HASH>..<HASH> 100644
--- a/lib/store_watch_mixin.js
+++ b/lib/store_watch_mixin.js
@@ -5,6 +5,7 @@ var StoreWatchMixin = function() {
return {
componentDidMount: function() {
var flux = this.props.flux || this.context.flux;
+ this.mounted = true;
_each(storeNames, function(store) {
flux.store(store).on("change", this._setStateFromFlux);
}, this);
@@ -12,13 +13,14 @@ var StoreWatchMixin = function() {
componentWillUnmount: function() {
var flux = this.props.flux || this.context.flux;
+ this.mounted = false;
_each(storeNames, function(store) {
flux.store(store).removeListener("change", this._setStateFromFlux);
}, this);
},
_setStateFromFlux: function() {
- if(this.isMounted()) {
+ if(this.mounted) {
this.setState(this.getStateFromFlux());
}
},
|
Remove isMounted() (deprecated)
|
BinaryMuse_fluxxor
|
train
|
d0b6e2e7177846682eeb2fd9d995a138a8c148c5
|
diff --git a/test/test_distance.py b/test/test_distance.py
index <HASH>..<HASH> 100644
--- a/test/test_distance.py
+++ b/test/test_distance.py
@@ -6,7 +6,6 @@ import unittest
import warnings
from mock import patch
-from geopy import distance as geopy_distance
from geopy.point import Point
from geopy.distance import (Distance,
GreatCircleDistance,
@@ -342,12 +341,6 @@ class TestWhenComputingVincentyDistance(CommonDistanceCases,
self.assertAlmostEqual(destination.latitude, -37.6528177174, 10)
self.assertAlmostEqual(destination.longitude, 143.9264976682, 10)
- def test_should_compute_same_destination_as_other_libraries(self):
- distance = self.cls(54.972271)
- destination = distance.destination((-37.95103, 144.42487), 306.86816)
- self.assertAlmostEqual(destination.latitude, -37.6528177174, 10)
- self.assertAlmostEqual(destination.longitude, 143.9264976682, 10)
-
def test_should_get_distinct_results_for_different_ellipsoids(self):
results = [
self.cls((0, 0), (0, 1), ellipsoid=ELLIPSOIDS[ellipsoid_name])
|
test_distance: remove duplicated test
Apparently this was caused by a mistake during a merge conflict
resolution.
|
geopy_geopy
|
train
|
3ec7bb83b7524554855d88ecda705149c5a50dea
|
diff --git a/src/main/java/au/com/southsky/jfreesane/SaneEnums.java b/src/main/java/au/com/southsky/jfreesane/SaneEnums.java
index <HASH>..<HASH> 100644
--- a/src/main/java/au/com/southsky/jfreesane/SaneEnums.java
+++ b/src/main/java/au/com/southsky/jfreesane/SaneEnums.java
@@ -75,4 +75,8 @@ public final class SaneEnums {
public static <T extends Enum<T> & SaneEnum> T valueOf(Class<T> enumType, int valueType) {
return mapForType(enumType).get(valueType);
}
+
+ public static <T extends Enum<T> & SaneEnum> T valueOf(Class<T> enumType, SaneWord value) {
+ return valueOf(enumType, value.integerValue());
+ }
}
diff --git a/src/main/java/au/com/southsky/jfreesane/SaneSession.java b/src/main/java/au/com/southsky/jfreesane/SaneSession.java
index <HASH>..<HASH> 100644
--- a/src/main/java/au/com/southsky/jfreesane/SaneSession.java
+++ b/src/main/java/au/com/southsky/jfreesane/SaneSession.java
@@ -131,8 +131,15 @@ public class SaneSession implements Closeable {
SaneWord status = inputStream.readWord();
if (status.integerValue() != 0) {
- throw new IOException(
- "unexpected status (" + status.integerValue() + ") while opening device");
+ SaneStatus statusEnum = SaneEnums.valueOf(SaneStatus.class, status);
+ if (statusEnum == null) {
+ throw new IOException(
+ "unexpected status " + status.integerValue() + " while opening device");
+ } else {
+ throw new IOException(
+ "unexpected status " + status.integerValue() + " (" + statusEnum
+ + ") while opening device");
+ }
}
SaneWord handle = inputStream.readWord();
|
Improve reporting of unexpected exceptions while opening a device
|
sjamesr_jfreesane
|
train
|
b82416bba212d324230c63fde87bba0910654106
|
diff --git a/src/main/java/org/jenetics/util/MappedAccumulator.java b/src/main/java/org/jenetics/util/MappedAccumulator.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jenetics/util/MappedAccumulator.java
+++ b/src/main/java/org/jenetics/util/MappedAccumulator.java
@@ -90,7 +90,7 @@ public abstract class MappedAccumulator<T>
* @return the adapter view with the different type.
* @throws NullPointerException if the given {@code converter} is {@code null}.
*/
- public <B> MappedAccumulator<B> map(final Function<B, T> mapper) {
+ public <B> MappedAccumulator<B> map(final Function<? super B, ? extends T> mapper) {
nonNull(mapper, "Mapper");
return new MappedAccumulator<B>() {
@Override
|
Change generic type signature for mapper method.
|
jenetics_jenetics
|
train
|
2a5ee590824be0c23e8419100088c6715b7cc6e3
|
diff --git a/src/main/java/net/agkn/hll/util/HLLUtil.java b/src/main/java/net/agkn/hll/util/HLLUtil.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/agkn/hll/util/HLLUtil.java
+++ b/src/main/java/net/agkn/hll/util/HLLUtil.java
@@ -26,11 +26,13 @@ import net.agkn.hll.HLL;
*/
public final class HLLUtil {
/**
- * The set of pwMaxMasks
- * is used as a quick way for calculating by this formula:
- * int maxRegisterValue = (1 << registerSizeInBits) - 1;
- * // Mask with all bits set except for (maxRegisterValue - 1) least significant bits (see #addRaw())
- * return ~((1L << (maxRegisterValue - 1)) - 1);
+ * Precomputed <code>pwMaxMask</code> values indexed by <code>registerSizeInBits</code>.
+ * Calculated with this formula:
+ * <pre>
+ * int maxRegisterValue = (1 << registerSizeInBits) - 1;
+ * // Mask with all bits set except for (maxRegisterValue - 1) least significant bits (see #addRaw())
+ * return ~((1L << (maxRegisterValue - 1)) - 1);
+ * </pre>
*
* @see #pwMaxMask(int)
*/
@@ -47,29 +49,35 @@ public final class HLLUtil {
};
/**
- * The set of twoToL's
- * is used as a quick way for calculating by this formula:
+ * Precomputed <code>twoToL</code> values indexed by a linear combination of
+ * <code>regWidth</code> and <code>log2m</code>. Calculated with this formula:
*
+ * <pre>
* int maxRegisterValue = (1 << registerSizeInBits) - 1;
* // since 1 is added to p(w) only maxRegisterValue - 1 bits are inspected
* final int pwBits = (maxRegisterValue - 1);
* final int totalBits = (pwBits + log2m);
* final long twoToL = (1L << totalBits);
+ * </pre>
*
+ * The array is one-dimensional and can be accessed by using index
+ * <code>(REG_WIDTH_INDEX_MULTIPLIER * regWidth) + log2m</code>
+ * for <code>regWidth</code> and <code>log2m</code> between the specified
+ * <code>HLL.{MINIMUM,MAXIMUM}_{REGWIDTH,LOG2M}_PARAM</code> constants.
*
- * Array is one-dimensional, and can be accessed by using index [REG_WIDTH_INDEX_MULTIPLIER*regWidth + log2m]
- * no values for regWidth = 0, and for log2m[0..3]
- * A bit overhead by size, but structure is simple and logical, without magic offsets
* @see #largeEstimatorCutoff(int, int), #largeEstimator(int, int, double),
*/
- private static final long[] TWO_TO_L = new long[(HLL.MAXIMUM_REGWIDTH_PARAM + 1)*(HLL.MAXIMUM_LOG2M_PARAM + 1)];
+ private static final long[] TWO_TO_L = new long[(HLL.MAXIMUM_REGWIDTH_PARAM + 1) * (HLL.MAXIMUM_LOG2M_PARAM + 1)];
+ /**
+ * Spacing constant used to compute offsets into {@link TWO_TO_L}.
+ */
private static final int REG_WIDTH_INDEX_MULTIPLIER = HLL.MAXIMUM_LOG2M_PARAM + 1;
static {
for(int regWidth = HLL.MINIMUM_REGWIDTH_PARAM; regWidth <= HLL.MAXIMUM_REGWIDTH_PARAM; regWidth++) {
for(int log2m = HLL.MINIMUM_LOG2M_PARAM ; log2m <= HLL.MAXIMUM_LOG2M_PARAM; log2m++) {
- TWO_TO_L[REG_WIDTH_INDEX_MULTIPLIER*regWidth + log2m] = (1L << (((1 << regWidth) - 1 - 1) + log2m));
+ TWO_TO_L[(REG_WIDTH_INDEX_MULTIPLIER * regWidth) + log2m] = (1L << (((1 << regWidth) - 1 - 1) + log2m));
}
}
}
@@ -170,7 +178,7 @@ public final class HLLUtil {
* @see #largeEstimator(int, int, double)
*/
public static double largeEstimatorCutoff(final int log2m, final int registerSizeInBits) {
- return (double) (TWO_TO_L[REG_WIDTH_INDEX_MULTIPLIER*registerSizeInBits + log2m])/30;
+ return (TWO_TO_L[(REG_WIDTH_INDEX_MULTIPLIER * registerSizeInBits) + log2m]) / 30.0;
}
/**
@@ -184,7 +192,7 @@ public final class HLLUtil {
* @return a corrected cardinality estimate.
*/
public static double largeEstimator(final int log2m, final int registerSizeInBits, final double estimator) {
- return (-1 * TWO_TO_L[REG_WIDTH_INDEX_MULTIPLIER*registerSizeInBits + log2m])
- * Math.log(1.0 - (estimator/TWO_TO_L[REG_WIDTH_INDEX_MULTIPLIER*registerSizeInBits + log2m]));
+ return (-1 * TWO_TO_L[(REG_WIDTH_INDEX_MULTIPLIER * registerSizeInBits) + log2m])
+ * Math.log(1.0 - (estimator/TWO_TO_L[(REG_WIDTH_INDEX_MULTIPLIER * registerSizeInBits) + log2m]));
}
}
|
Documentation and code style cleanup. No logic changed.
|
aggregateknowledge_java-hll
|
train
|
6c8f5e7685931556d486f813393cc92648d0baeb
|
diff --git a/java/src/com/google/template/soy/passes/HtmlTagEntry.java b/java/src/com/google/template/soy/passes/HtmlTagEntry.java
index <HASH>..<HASH> 100644
--- a/java/src/com/google/template/soy/passes/HtmlTagEntry.java
+++ b/java/src/com/google/template/soy/passes/HtmlTagEntry.java
@@ -266,6 +266,16 @@ final class HtmlTagEntry {
return false;
}
}
+ // Check the stack and queue again
+ if (openStack.isEmpty() && closeQueue.isEmpty()) {
+ continue;
+ } else if (openStack.isEmpty()) {
+ errorReporter.report(closeQueue.pollFirst().getSourceLocation(), UNEXPECTED_CLOSE_TAG);
+ return false;
+ } else {
+ errorReporter.report(openStack.pollFirst().getSourceLocation(), OPEN_TAG_NOT_CLOSED);
+ return false;
+ }
}
return true;
}
|
Fix a bug that does not check stack/queue after popping optional tags.
This bug means if we pop all optional tags in the openStack, but still have some tags in closeQueue, the validation pass will ignore the tags in the queue.
-------------
Created by MOE: <URL>
|
google_closure-templates
|
train
|
c8c41164f8f92cb6af0096301718b19d791134c4
|
diff --git a/eZ/Publish/Core/MVC/Legacy/SignalSlot/AbstractLegacySlot.php b/eZ/Publish/Core/MVC/Legacy/SignalSlot/AbstractLegacySlot.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/MVC/Legacy/SignalSlot/AbstractLegacySlot.php
+++ b/eZ/Publish/Core/MVC/Legacy/SignalSlot/AbstractLegacySlot.php
@@ -61,7 +61,8 @@ abstract class AbstractLegacySlot extends Slot
protected function runLegacyKernelCallback( $callback )
{
$this->persistenceCacheClearer->switchOff();
- $this->httpCacheClearer->switchOff();
+ // Temporarily disabled until smart HTTP cache clearing (EZP-23897) is implemented
+ // $this->httpCacheClearer->switchOff();
// Initialize legacy kernel if not already done
if ( $this->legacyKernel instanceof Closure )
@@ -77,7 +78,8 @@ abstract class AbstractLegacySlot extends Slot
);
$this->persistenceCacheClearer->switchOn();
- $this->httpCacheClearer->switchOn();
+ // Temporarily disabled until smart HTTP cache clearing is (EZP-23897) implemented
+ // $this->httpCacheClearer->switchOn();
return $return;
}
|
Workaround: re-enabled legacy HTTP cache clearing
Will take care of clearing HTTP caches until EZP-<I> is finished.
|
ezsystems_ezpublish-kernel
|
train
|
1213d085d72c2119a5fdefbe80d659bd34be273e
|
diff --git a/src/Graviton/CoreBundle/Tests/Services/ReadOnlyServiceTest.php b/src/Graviton/CoreBundle/Tests/Services/ReadOnlyServiceTest.php
index <HASH>..<HASH> 100644
--- a/src/Graviton/CoreBundle/Tests/Services/ReadOnlyServiceTest.php
+++ b/src/Graviton/CoreBundle/Tests/Services/ReadOnlyServiceTest.php
@@ -67,7 +67,7 @@ class ReadOnlyServiceTest extends RestTestCase
$client->request($method, $url, array(), array(), array(), $entry);
$this->assertEquals(Response::HTTP_METHOD_NOT_ALLOWED, $client->getResponse()->getStatusCode());
$content = $client->getResults();
- $this->assertContains("Method Not Allowed", $content->message);
+ $this->assertSame('Method Not Allowed', $content->error->message);
}
/**
diff --git a/src/Graviton/SchemaBundle/Listener/SchemaCacheInvalidationResponseListener.php b/src/Graviton/SchemaBundle/Listener/SchemaCacheInvalidationResponseListener.php
index <HASH>..<HASH> 100644
--- a/src/Graviton/SchemaBundle/Listener/SchemaCacheInvalidationResponseListener.php
+++ b/src/Graviton/SchemaBundle/Listener/SchemaCacheInvalidationResponseListener.php
@@ -31,12 +31,10 @@ class SchemaCacheInvalidationResponseListener
* Constructor
*
* @param CacheProvider $cache cache
- * @param string $cacheNamespace cache namespace
* @param string $cacheInvalidationMapKey cache key of invalidation map
*/
- public function __construct(CacheProvider $cache, $cacheNamespace, $cacheInvalidationMapKey)
+ public function __construct(CacheProvider $cache, $cacheInvalidationMapKey)
{
- $cache->setNamespace($cacheNamespace);
$this->cache = $cache;
$this->cacheInvalidationMapKey = $cacheInvalidationMapKey;
}
diff --git a/src/Graviton/SchemaBundle/Resources/config/services.xml b/src/Graviton/SchemaBundle/Resources/config/services.xml
index <HASH>..<HASH> 100644
--- a/src/Graviton/SchemaBundle/Resources/config/services.xml
+++ b/src/Graviton/SchemaBundle/Resources/config/services.xml
@@ -16,7 +16,6 @@
<parameter key="graviton.schema.serializer.handler.enum.class">Graviton\SchemaBundle\Serializer\Handler\SchemaEnumHandler</parameter>
<!-- non-class parameters -->
- <parameter key="graviton.schema.cache.namespace">schema</parameter>
<parameter key="graviton.schema.cache.invalidateMapKey">_invMap</parameter>
</parameters>
<services>
@@ -30,7 +29,6 @@
</service>
<service id="graviton.schema.listener.schemacacheinvalidation" class="%graviton.schema.listener.schemacacheinvalidation.class%">
<argument type="service" id="doctrine_cache.providers.local"/>
- <argument>%graviton.schema.cache.namespace%</argument>
<argument>%graviton.schema.cache.invalidateMapKey%</argument>
<tag name="kernel.event_listener" event="graviton.rest.request" method="onRestRequest"/>
</service>
@@ -101,7 +99,6 @@
<argument>%locale%</argument>
<argument type="service" id="graviton.schema.constraint.builder"/>
<argument type="service" id="doctrine_cache.providers.local"/>
- <argument>%graviton.schema.cache.namespace%</argument>
<argument>%graviton.schema.cache.invalidateMapKey%</argument>
</service>
<service id="graviton.schema.constraint.readonlyfield" class="%graviton.schema.constraint.readonlyfield.class%">
diff --git a/src/Graviton/SchemaBundle/SchemaUtils.php b/src/Graviton/SchemaBundle/SchemaUtils.php
index <HASH>..<HASH> 100644
--- a/src/Graviton/SchemaBundle/SchemaUtils.php
+++ b/src/Graviton/SchemaBundle/SchemaUtils.php
@@ -105,7 +105,6 @@ class SchemaUtils
* @param string $defaultLocale Default Language
* @param ConstraintBuilder $constraintBuilder Constraint builder
* @param CacheProvider $cache Doctrine cache provider
- * @param string $cacheNamespace Cache namespace
* @param string $cacheInvalidationMapKey Cache invalidation map cache key
*/
public function __construct(
@@ -119,7 +118,6 @@ class SchemaUtils
$defaultLocale,
ConstraintBuilder $constraintBuilder,
CacheProvider $cache,
- $cacheNamespace,
$cacheInvalidationMapKey
) {
$this->repositoryFactory = $repositoryFactory;
@@ -131,8 +129,6 @@ class SchemaUtils
$this->documentFieldNames = $documentFieldNames;
$this->defaultLocale = $defaultLocale;
$this->constraintBuilder = $constraintBuilder;
-
- $cache->setNamespace($cacheNamespace);
$this->cache = $cache;
$this->cacheInvalidationMapKey = $cacheInvalidationMapKey;
}
@@ -168,7 +164,7 @@ class SchemaUtils
*/
public function getModelSchema($modelName, DocumentModel $model, $online = true, $internal = false)
{
- $cacheKey = $model->getEntityClass().'.'.(string) $online.'.'.(string) $internal.uniqid();
+ $cacheKey = 'schema'.$model->getEntityClass().'.'.(string) $online.'.'.(string) $internal;
if ($this->cache->contains($cacheKey)) {
return $this->cache->fetch($cacheKey);
|
remove cache namespace again from schema caching stuff as it conflicts with i<I>n caching, fix readonlyservice expectation
|
libgraviton_graviton
|
train
|
58385c909c372928fd5090920188f59f83ccbc6f
|
diff --git a/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractRemoteClient.java b/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractRemoteClient.java
index <HASH>..<HASH> 100644
--- a/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractRemoteClient.java
+++ b/module/communication/controller/src/main/java/org/openbase/jul/communication/controller/AbstractRemoteClient.java
@@ -1817,12 +1817,34 @@ public abstract class AbstractRemoteClient<M extends Message> implements RPCRemo
try {
// get() is fine because ping task has internal timeout, so task will fail after timeout anyway.
ping().get();
- internalFuture = FutureProcessor.postProcess(
- (input, internalTimeout, timeUnit) -> input.getResponse(),
- internalRequestStatus());
- //internalFuture = internalRequestStatus();
//event = internalFuture.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
- receivedData = internalFuture.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
+ final RPCResponse<M> response = internalRequestStatus().get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
+
+ // skip events which were send later than the last received update
+ long userTime = RPCUtils.USER_TIME_VALUE_INVALID;
+ if (response.getProperties().containsKey(RPCUtils.USER_TIME_KEY)) {
+ userTime = Long.parseLong(response.getProperties().get(RPCUtils.USER_TIME_KEY));
+ } else {
+ logger.warn("Data message does not contain user time key on scope " + getScopeStringRep());
+ }
+
+ // filter outdated events
+ try {
+ long createTime = Long.parseLong(response.getProperties().get(RPCUtils.USER_TIME_KEY));
+ if (createTime < newestEventTime || (createTime == newestEventTime && userTime < newestEventTimeNano)) {
+ logger.debug("Skip event on scope[" + getScopeStringRep() + "] because event seems to be outdated! Received event time < latest event time [" + createTime + "<= " + newestEventTime + "][" + userTime + " < " + newestEventTimeNano + "]");
+ return data;
+ }
+ newestEventTime = createTime;
+ } catch (NullPointerException ex) {
+ ExceptionPrinter.printHistory("Data message does not contain valid creation timestamp on scope " + getScopeStringRep(), ex, logger);
+ }
+
+ if (userTime != RPCUtils.USER_TIME_VALUE_INVALID) {
+ newestEventTimeNano = userTime;
+ }
+ receivedData = response.getResponse();
+
if (timeout != METHOD_CALL_START_TIMEOUT && timeout > 15000 && isRelatedFutureCancelled()) {
logger.info("Got response from Controller[" + ScopeProcessor.generateStringRep(getScope()) + "] and continue processing.");
|
first attempt to implement requestData data filtering based on user time
|
openbase_jul
|
train
|
ace02bc0f73350fdf99b9f7e61103da82c08c213
|
diff --git a/telluric/georaster.py b/telluric/georaster.py
index <HASH>..<HASH> 100644
--- a/telluric/georaster.py
+++ b/telluric/georaster.py
@@ -670,7 +670,8 @@ class GeoRaster2(WindowMethodsMixin, _Raster):
if self._crs is None:
self._crs = copy(raster.crs)
- assert self._crs.is_valid
+ with rasterio.Env():
+ assert self._crs.is_valid
# if band_names not provided, try read them from raster tags.
# if not - leave empty, for default:
|
Fix rasterio environment issue
|
satellogic_telluric
|
train
|
1e077aca2f75d31979feea0bb3bac7c2e88a7fb4
|
diff --git a/clustergrammer_widget/_version.py b/clustergrammer_widget/_version.py
index <HASH>..<HASH> 100644
--- a/clustergrammer_widget/_version.py
+++ b/clustergrammer_widget/_version.py
@@ -1,2 +1,2 @@
-version_info = (1, 0, 1)
+version_info = (1, 1, 0)
__version__ = '.'.join(map(str, version_info))
|
going to publish clustergrammer_widget <I>
|
ismms-himc_clustergrammer2
|
train
|
f77eb62d58a453791f88b745c012e1dc74de5cf2
|
diff --git a/api/opentrons/drivers/smoothie_drivers/v3_0_0/driver_3_0.py b/api/opentrons/drivers/smoothie_drivers/v3_0_0/driver_3_0.py
index <HASH>..<HASH> 100644
--- a/api/opentrons/drivers/smoothie_drivers/v3_0_0/driver_3_0.py
+++ b/api/opentrons/drivers/smoothie_drivers/v3_0_0/driver_3_0.py
@@ -1,6 +1,6 @@
from opentrons.drivers.smoothie_drivers.v3_0_0 import serial_communication
from os import environ
-from opentrons.robot.robot_configs import current_config
+from opentrons.robot.robot_configs import config
'''
@@ -13,10 +13,10 @@ from opentrons.robot.robot_configs import current_config
'''
# TODO(artyom, ben 20171026): move to config
-DEFAULT_STEPS_PER_MM = current_config().steps_per_mm
-DEFAULT_MAX_AXIS_SPEEDS = current_config().max_speeds
-DEFAULT_ACCELERATION = current_config().acceleration
-DEFAULT_CURRENT_CONTROL = current_config().current
+DEFAULT_STEPS_PER_MM = config().steps_per_mm
+DEFAULT_MAX_AXIS_SPEEDS = config().max_speeds
+DEFAULT_ACCELERATION = config().acceleration
+DEFAULT_CURRENT_CONTROL = config().current
HOMING_OFFSETS = 'M206 X0'
# TODO (artyom, ben 20171026): move to config
diff --git a/api/opentrons/robot/base.py b/api/opentrons/robot/base.py
index <HASH>..<HASH> 100644
--- a/api/opentrons/robot/base.py
+++ b/api/opentrons/robot/base.py
@@ -1,7 +1,7 @@
-from .robot_configs import current_config
+from .robot_configs import config
-probe_center = current_config().probe_center
-probe_dimensions = current_config().probe_dimensions
+probe_center = config().probe_center
+probe_dimensions = config().probe_dimensions
class Probe:
diff --git a/api/opentrons/robot/robot.py b/api/opentrons/robot/robot.py
index <HASH>..<HASH> 100644
--- a/api/opentrons/robot/robot.py
+++ b/api/opentrons/robot/robot.py
@@ -15,15 +15,15 @@ from opentrons.data_storage import database
from opentrons import helpers
from opentrons import commands
from opentrons.broker import subscribe
-from .robot_configs import current_config
+from .robot_configs import config
from numpy import add, subtract
from functools import lru_cache
log = get_logger(__name__)
-DECK_OFFSET = current_config().deck_offset
-MAX_INSTRUMENT_HEIGHT = 220
+DECK_OFFSET = config().deck_offset
+MAX_INSTRUMENT_HEIGHT = 220.0000
class InstrumentMosfet(object):
diff --git a/api/opentrons/robot/robot_configs.py b/api/opentrons/robot/robot_configs.py
index <HASH>..<HASH> 100644
--- a/api/opentrons/robot/robot_configs.py
+++ b/api/opentrons/robot/robot_configs.py
@@ -1,17 +1,23 @@
+# TODO: jmg 11/2 This file is meant to be a temporary
+# fix to make development easier and should be removed
+# once this configuration information is part of persistent robot data
+
from collections import namedtuple
CURRENT_ROBOT = 'B2-5'
robot_config = namedtuple(
'robot_config',
- 'name '
- 'steps_per_mm '
- 'max_speeds '
- 'acceleration '
- 'current '
- 'deck_offset '
- 'probe_center '
- 'probe_dimensions'
+ [
+ 'name',
+ 'steps_per_mm',
+ 'max_speeds',
+ 'acceleration',
+ 'current',
+ 'deck_offset',
+ 'probe_center',
+ 'probe_dimensions'
+ ]
)
Ibn = robot_config(
@@ -26,7 +32,7 @@ Ibn = robot_config(
)
Amadeo = robot_config(
- name='Ibn al-Nafis',
+ name='Amedeo Avogadro',
steps_per_mm='M92 X80 Y80 Z400 A400 B767.38 C767.38',
max_speeds='M203.1 X300 Y200 Z50 A50 B8 C8',
acceleration='M204 S1000 X4000 Y3000 Z2000 A2000 B3000 C3000',
@@ -37,7 +43,7 @@ Amadeo = robot_config(
)
Ada = robot_config(
- name='Ibn al-Nafis',
+ name='Ada Lovelace',
steps_per_mm='M92 X80 Y80 Z400 A400 B767.38 C767.38',
max_speeds='M203.1 X300 Y200 Z50 A50 B8 C8',
acceleration='M204 S1000 X4000 Y3000 Z2000 A2000 B3000 C3000',
@@ -48,8 +54,8 @@ Ada = robot_config(
)
Rosalind = robot_config(
- name='Ibn al-Nafis',
- steps_per_mm='M92 X81.474 Y80.16 Z400 A400 B767.38 C767.38',
+ name='Rosalind Franklin',
+ steps_per_mm='M92 X80.0254 Y80.16 Z400 A400 B767.38 C767.38',
max_speeds='M203.1 X300 Y200 Z50 A50 B8 C8',
acceleration='M204 S1000 X4000 Y3000 Z2000 A2000 B3000 C3000',
current='M907 X1.2 Y1.5 Z0.8 A0.8 B0.25 C0.25',
@@ -66,5 +72,5 @@ robots = {
}
-def current_config():
+def config():
return robots[CURRENT_ROBOT]
|
implement readability refactors in robot_configs
|
Opentrons_opentrons
|
train
|
97fb045cfeb29d732a8d18005ec12136e3c42002
|
diff --git a/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/api/MFPAnalytics.java b/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/api/MFPAnalytics.java
index <HASH>..<HASH> 100644
--- a/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/api/MFPAnalytics.java
+++ b/lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/analytics/api/MFPAnalytics.java
@@ -88,7 +88,6 @@ public class MFPAnalytics {
NONE,
ALL,
LIFECYCLE
-
// NETWORK //Note: Temporarily disabled
}
@@ -120,6 +119,11 @@ public class MFPAnalytics {
case LIFECYCLE:
MFPActivityLifeCycleCallbackListener.init(app);
break;
+ case ALL:
+ MFPActivityLifeCycleCallbackListener.init(app);
+ break;
+ case NONE:
+ break;
}
}
}
|
Implement NONE and ALL device events in MFPAnalytics.
|
ibm-bluemix-mobile-services_bms-clientsdk-android-analytics
|
train
|
881d47801fc017df776a4076555907a4535fdc2d
|
diff --git a/tests/test_reading.py b/tests/test_reading.py
index <HASH>..<HASH> 100644
--- a/tests/test_reading.py
+++ b/tests/test_reading.py
@@ -34,3 +34,26 @@ def test_reading(files_source):
for fh in filehandles.filehandles(files_source, verbose=True, cif='text/cif'):
mock = Mock(fh)
assert mock.first_line.strip() in ('data_2RPV', b'data_2RPV')
+
+
+@pytest.mark.parametrize('files_source', [
+ 'tests/example_data/2rpv.cif',
+ 'tests/example_data/2rpv',
+ 'tests/example_data/2rpv.cif.gz',
+ 'tests/example_data/2rpv.cif.bz2',
+ 'tests/example_data/directory',
+ 'tests/example_data/archive.zip',
+ 'tests/example_data/archive.tar.gz',
+ 'tests/example_data/archive.tar.bz2',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/2rpv.cif',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/2rpv',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/2rpv.cif.gz',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/2rpv.cif.bz2',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/archive.zip',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/archive.tar.gz',
+ 'https://raw.githubusercontent.com/MoseleyBioinformaticsLab/filehandles/master/tests/example_data/archive.tar.bz2'
+])
+def test_reading_with_pattern(files_source):
+ for fh in filehandles.filehandles(files_source, verbose=True, cif='text/cif', pattern='[\w\d\s]+'):
+ mock = Mock(fh)
+ assert mock.first_line.strip() in ('data_2RPV', b'data_2RPV')
|
Added tests to include pattern parameter.
|
MoseleyBioinformaticsLab_filehandles
|
train
|
127db3d56edde6db52e3b4c162e6f49f73c5dfbc
|
diff --git a/CHANGES.md b/CHANGES.md
index <HASH>..<HASH> 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,3 +1,8 @@
+# 0.2.3
+
+* Add `Collection#find_by` for easier finding: `album.songs.find_by(id: 1)`.
+* Fix inheritance of the `:default` option. This would formerly wrap the default value into another `Uber::Options::Value`.
+
# 0.2.2
* Use `Uber::Options::Value#call` to evaluate.
@@ -105,4 +110,4 @@
# 0.0.4
-* Added `Composition#[]` to access contained models in favor of reader methods to models. The latter got removed. This allows mapping methods with the same name than the contained object.
\ No newline at end of file
+* Added `Composition#[]` to access contained models in favor of reader methods to models. The latter got removed. This allows mapping methods with the same name than the contained object.
diff --git a/lib/disposable/twin/default.rb b/lib/disposable/twin/default.rb
index <HASH>..<HASH> 100644
--- a/lib/disposable/twin/default.rb
+++ b/lib/disposable/twin/default.rb
@@ -10,12 +10,13 @@ module Disposable::Twin::Default
# TODO: introduce Null object in Declarative::Definition#[].
# dfn[:default].(self) # dfn#[] should return a Null object here if empty.
return unless dfn[:default]
- dfn[:default].(self) # TODO: use .()
+ dfn[:default].(self)
end
module ClassMethods
- def property(name, options={}, &block)
- options[:default] = Uber::Options::Value.new(options[:default]) if options[:default]
+ private
+ def build_definition(name, options={}, &block)
+ options = options.merge(default: Uber::Options::Value.new(options[:default])) if options[:default]
super
end
end
diff --git a/lib/disposable/version.rb b/lib/disposable/version.rb
index <HASH>..<HASH> 100644
--- a/lib/disposable/version.rb
+++ b/lib/disposable/version.rb
@@ -1,3 +1,3 @@
module Disposable
- VERSION = "0.2.2"
+ VERSION = "0.2.3"
end
diff --git a/test/twin/default_test.rb b/test/twin/default_test.rb
index <HASH>..<HASH> 100644
--- a/test/twin/default_test.rb
+++ b/test/twin/default_test.rb
@@ -35,6 +35,17 @@ class DefaultTest < Minitest::Spec
twin = Twin.new(Song.new(false))
twin.title.must_equal false
end
+
+ describe "inheritance" do
+ class SuperTwin < Disposable::Twin
+ feature Default
+ property :name, default: "n/a"
+ end
+ class MegaTwin < SuperTwin
+ end
+
+ it { MegaTwin.new(Composer.new).name.must_equal "n/a" }
+ end
end
class DefaultAndVirtualTest < Minitest::Spec
|
Fix inheritance of the `:default` option. This would formerly wrap the default value into another `Uber::Options::Value`.
|
apotonick_disposable
|
train
|
564b93df4fde52acef5ccb205d69dfbf111ce9c0
|
diff --git a/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java b/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java
index <HASH>..<HASH> 100644
--- a/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java
+++ b/value/src/main/java/com/google/auto/value/processor/AutoValueProcessor.java
@@ -25,6 +25,7 @@ import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
import java.io.IOException;
import java.io.Serializable;
@@ -115,15 +116,12 @@ public class AutoValueProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
- boolean claimed = (annotations.size() == 1
- && annotations.iterator().next().getQualifiedName().toString().equals(
- AutoValue.class.getName()));
- if (claimed) {
+ if (annotations.size() == 1
+ && Iterables.getOnlyElement(annotations).getQualifiedName().toString().equals(
+ AutoValue.class.getName())) {
process(roundEnv);
- return true;
- } else {
- return false;
}
+ return false; // never claim annotation, because who knows what other processors want?
}
private void process(RoundEnvironment roundEnv) {
|
In AutoValueProcessor, don't claim the @AutoValue annotation. We don't know what other processors there might be.
-------------
Created by MOE: <URL>
|
google_auto
|
train
|
c18d70a3e2611e76d4dce8717e15997e93fc23c1
|
diff --git a/spec/lib/phony/countries_spec.rb b/spec/lib/phony/countries_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/phony/countries_spec.rb
+++ b/spec/lib/phony/countries_spec.rb
@@ -356,7 +356,7 @@ describe 'country descriptions' do
it_splits '62877123456', %w(62 877 123 456)
it_splits '62881123456', %w(62 881 123 456)
it_splits '6288112345656', %w(62 881 1234 5656)
- it_splits '6288112345656', %w(62 881 1234 56567)
+ it_splits '62881123456567', %w(62 881 1234 56567)
it_splits '628990344805', %w(62 899 034 4805)
it_splits '6291234567', %w(62 9 1234 567)
it_splits '629123456789', %w(62 9 123 456 789)
|
Fix indonesia spec to support 9 digits
|
floere_phony
|
train
|
c79920199ed3b69f577e80e336750203d81015e3
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -40,13 +40,14 @@ var FunctionGraph = module.exports = function (options) {
// Initialize variables
var self = this
- , settings = self.options = Ul.merge(FunctionGraph.defaults, options)
+ , settings = self.options = Ul.merge(Ul.clone(FunctionGraph.defaults), options)
, i = 0
, character = null
, str = ""
;
self.graph = [];
+ settings.width *= settings.aRatio;
// Set the center of the graph
settings.center = Ul.merge({
@@ -54,9 +55,12 @@ var FunctionGraph = module.exports = function (options) {
, y: settings.height / 2
}, settings.center);
+ settings.center.x = parseInt(settings.center.x);
+ settings.center.y = parseInt(settings.center.y);
+
// Background
for (i = 0; i < settings.height; ++i) {
- self.graph[i] = new Array(settings.aRatio * settings.width).join(settings.marks.background).split("");
+ self.graph[i] = new Array(settings.width).join(settings.marks.background).split("");
}
// Center
@@ -71,7 +75,6 @@ var FunctionGraph = module.exports = function (options) {
character = settings.marks.rightArrow;
}
- console.log(character, i);
self.graph[settings.center.y][i] = character;
}
@@ -130,6 +133,26 @@ var FunctionGraph = module.exports = function (options) {
}
return str;
};
+
+ /**
+ * setFunction
+ * Adds the function on the graph.
+ *
+ * @name setFunction
+ * @function
+ * @param {Function} foo A function that receives `x` as the first parameter and returns the `y` value.
+ * @param {Number} min The minimum `x` (default: the lowest possible value).
+ * @param {Number} max The maximum `x`.(default: the highest possible value).
+ * @return {CliGraph} The CliGraph instance.
+ */
+ self.setFunction = function (foo, min, max) {
+ min = min || - (settings.width + settings.center.x) / 2;
+ max = max || (settings.width + settings.center.x) / 2;
+ for (i = min; i <= max; ++i) {
+ self.addPoint(i, foo(i));
+ }
+ return self;
+ };
};
// Defaults
@@ -137,12 +160,12 @@ FunctionGraph.defaults = {
width: 60
, height: 40
, marks: {
- hAxis: '-'
- , vAxis: '|'
- , center: '+'
- , point: '#'
- , rightArrow: ">"
- , topArrow: "^"
+ hAxis: '─'
+ , vAxis: '│'
+ , center: '┼'
+ , point: '•'
+ , rightArrow: "▶"
+ , topArrow: "▲"
, background: " "
}
, center: {}
|
Added the setFunction method.
|
IonicaBizau_node-cli-graph
|
train
|
21df2bfc4a916d5f9bbffa48fec0f08235d276b9
|
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -190,7 +190,7 @@ module ActionDispatch
end
# clean up after keys that could have been left over by calling reject! or shift on the flash
- (@used - keys).each{ |k| @used.delete(k) }
+ @used.subtract(@used - keys)
end
# Convenience accessor for flash[:alert]
|
again, use Set#subtract
|
rails_rails
|
train
|
d1727aaee3a34566a99db0cac5f32779756282ab
|
diff --git a/examples/generate_phpdoc.rb b/examples/generate_phpdoc.rb
index <HASH>..<HASH> 100755
--- a/examples/generate_phpdoc.rb
+++ b/examples/generate_phpdoc.rb
@@ -254,11 +254,6 @@ File.open("ImageAutodoc.php", "w") do |file|
file << preamble
file << "\n"
file << "namespace Jcupitt\\Vips;\n"
- file << "\n"
-
- $enums.each do |name|
- file << "use Jcupitt\\Vips\\#{name};\n"
- end
file << "\n"
file << "/**\n"
diff --git a/examples/vips_class.php b/examples/vips_class.php
index <HASH>..<HASH> 100755
--- a/examples/vips_class.php
+++ b/examples/vips_class.php
@@ -9,7 +9,7 @@ const LOG_FORMAT = "[%datetime%] %level_name%: %message% %context%\n";
const DATE_FORMAT = "Y-m-d\TH:i:sP";
Vips\Image::setLogger(new class implements Psr\Log\LoggerInterface {
- // Use the LoggerTrait so that we only have to implement the generic
+ // Use the LoggerTrait so that we only have to implement the generic
// log method.
use Psr\Log\LoggerTrait;
@@ -27,15 +27,7 @@ Vips\Image::setLogger(new class implements Psr\Log\LoggerInterface {
// `Vips\Image` to string convert
array_walk_recursive($context, function (&$value) {
if ($value instanceof Vips\Image) {
- // TODO: Should we override __toString() in `Vips\Image` instead
- $value = [
- 'instance' => 'Vips\Image',
- 'width' => $value->width,
- 'height' => $value->height,
- 'bands' => $value->bands,
- 'format' => $value->format,
- 'interpretation' => $value->interpretation,
- ];
+ $value = (string) $value;
}
});
diff --git a/src/Image.php b/src/Image.php
index <HASH>..<HASH> 100644
--- a/src/Image.php
+++ b/src/Image.php
@@ -39,17 +39,6 @@
namespace Jcupitt\Vips;
-use Jcupitt\Vips\Angle;
-use Jcupitt\Vips\Direction;
-use Jcupitt\Vips\Extend;
-use Jcupitt\Vips\OperationBoolean;
-use Jcupitt\Vips\OperationComplex;
-use Jcupitt\Vips\OperationComplexget;
-use Jcupitt\Vips\OperationMath;
-use Jcupitt\Vips\OperationMath2;
-use Jcupitt\Vips\OperationMorphology;
-use Jcupitt\Vips\OperationRelational;
-use Jcupitt\Vips\OperationRound;
use Psr\Log\LoggerInterface;
/**
@@ -884,6 +873,24 @@ class Image extends ImageAutodoc implements \ArrayAccess
}
/**
+ * Makes a string-ified version of the Image.
+ *
+ * @return string
+ */
+ public function __toString()
+ {
+ $array = [
+ 'width' => $this->get('width'),
+ 'height' => $this->get('height'),
+ 'bands' => $this->get('bands'),
+ 'format' => $this->get('format'),
+ 'interpretation' => $this->get('interpretation'),
+ ];
+
+ return json_encode($array);
+ }
+
+ /**
* Call any vips operation. The final element of $arguments can be
* (but doesn't have to be) an array of options to pass to the operation.
*
diff --git a/src/ImageAutodoc.php b/src/ImageAutodoc.php
index <HASH>..<HASH> 100644
--- a/src/ImageAutodoc.php
+++ b/src/ImageAutodoc.php
@@ -39,42 +39,6 @@
namespace Jcupitt\Vips;
-use Jcupitt\Vips\Access;
-use Jcupitt\Vips\Align;
-use Jcupitt\Vips\Angle;
-use Jcupitt\Vips\Angle45;
-use Jcupitt\Vips\BandFormat;
-use Jcupitt\Vips\Coding;
-use Jcupitt\Vips\Combine;
-use Jcupitt\Vips\CombineMode;
-use Jcupitt\Vips\DemandStyle;
-use Jcupitt\Vips\Direction;
-use Jcupitt\Vips\Extend;
-use Jcupitt\Vips\ForeignDzContainer;
-use Jcupitt\Vips\ForeignDzDepth;
-use Jcupitt\Vips\ForeignDzLayout;
-use Jcupitt\Vips\ForeignTiffCompression;
-use Jcupitt\Vips\ForeignTiffPredictor;
-use Jcupitt\Vips\ForeignTiffResunit;
-use Jcupitt\Vips\ForeignWebpPreset;
-use Jcupitt\Vips\ImageType;
-use Jcupitt\Vips\Intent;
-use Jcupitt\Vips\Interpretation;
-use Jcupitt\Vips\Kernel;
-use Jcupitt\Vips\OperationBoolean;
-use Jcupitt\Vips\OperationComplex;
-use Jcupitt\Vips\OperationComplex2;
-use Jcupitt\Vips\OperationComplexget;
-use Jcupitt\Vips\OperationMath;
-use Jcupitt\Vips\OperationMath2;
-use Jcupitt\Vips\OperationMorphology;
-use Jcupitt\Vips\OperationRelational;
-use Jcupitt\Vips\OperationRound;
-use Jcupitt\Vips\PCS;
-use Jcupitt\Vips\Precision;
-use Jcupitt\Vips\Saveable;
-use Jcupitt\Vips\Token;
-
/**
* Autodocs for the Image class.
* @category Images
|
Override __toString() + remove enums import
Importing enums isn't necessary because we are in the same namespace.
|
libvips_php-vips
|
train
|
bc214a669167b846552caedb1e464e568a736239
|
diff --git a/src/react/DebugPanel.js b/src/react/DebugPanel.js
index <HASH>..<HASH> 100644
--- a/src/react/DebugPanel.js
+++ b/src/react/DebugPanel.js
@@ -42,7 +42,7 @@ export default class DebugPanel {
render() {
return (
- <div style={this.props.getStyle(this.props)}>
+ <div style={{...this.props.getStyle(this.props), ...this.props.style}}>
{this.props.children}
</div>
);
|
Make DebugPanel style customizable.
With this you can pass style to DebugPanel component.
```js
<DebugPanel style={{maxWidth: '<I>%'}}> </DebugPanel>
```
|
reduxjs_redux-devtools
|
train
|
9ec116ce06b5be540857a2b014756dca3fade787
|
diff --git a/lib/Thelia/Tests/Condition/Implementation/MatchForEveryoneManagerTest.php b/lib/Thelia/Tests/Condition/Implementation/MatchForEveryoneManagerTest.php
index <HASH>..<HASH> 100644
--- a/lib/Thelia/Tests/Condition/Implementation/MatchForEveryoneManagerTest.php
+++ b/lib/Thelia/Tests/Condition/Implementation/MatchForEveryoneManagerTest.php
@@ -176,7 +176,7 @@ class MatchForEveryoneManagerTest extends \PHPUnit_Framework_TestCase
* Check validator
*
* @covers Thelia\Condition\Implementation\MatchForEveryoneManager::generateInputs
- *
+ * @covers Thelia\Condition\Implementation\MatchForEveryoneManager::setValidatorsFromForm
*/
public function testGetValidator()
{
@@ -184,38 +184,19 @@ class MatchForEveryoneManagerTest extends \PHPUnit_Framework_TestCase
/** @var FacadeInterface $stubFacade */
$condition1 = new MatchForEveryoneManager($stubFacade);
-
- $actual = $condition1->getValidators();
+ $actual1 = $condition1->setValidatorsFromForm(array(), array());
+ $expected1 = $condition1;
+ $actual2 = $condition1->getValidators();
$validators = array();
$validators['inputs'] = array();
$validators['setOperators'] = array();
$validators['setValues'] = array();
- $expected = $validators;
-
- $this->assertEquals($expected, $actual);
-
- }
-
- /**
- * Check validator
- *
- * @covers Thelia\Condition\Implementation\setValidatorsFromForm::generateInputs
- *
- */
- public function testSetValidator()
- {
- $stubFacade = $this->generateFacadeStub(399, 'EUR');
-
- /** @var FacadeInterface $stubFacade */
- $condition1 = new MatchForEveryoneManager($stubFacade);
+ $expected2 = $validators;
- $actual = $condition1->setValidatorsFromForm(array(), array());
+ $this->assertEquals($expected1, $actual1);
+ $this->assertEquals($expected2, $actual2);
- $expected = $condition1;
-
- $this->assertEquals($expected, $actual);
}
-
}
|
Adding/Refactoring unit test for MatchForEveryoneManager|MatchForTotalAmountManager|MatchForXArticlesManager
|
thelia_core
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.