hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
410908e9521d4817312e372104f9502102c769f0
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -327,7 +327,7 @@ function Monoxide() {
// }}}
// Apply populates {{{
.then(function(next) {
- if (!q.$populate || !q.$populate.length || q.$count || !q.decorate || q.$plain || this.result === undefined) return next(); // Skip
+ if (!q.$populate || !q.$populate.length || q.$count || q.$decorate === false || q.$plain === false || this.result === undefined) return next(); // Skip
if (q.$one) {
this.result.populate(q.$populate, next);
} else {
|
BUGFIX: Wrong field reference when determining if to post-populate
|
hash-bang_Monoxide
|
train
|
bca6a674d1be6a57f484c34c541a3417ce48c24e
|
diff --git a/okcupyd/profile.py b/okcupyd/profile.py
index <HASH>..<HASH> 100644
--- a/okcupyd/profile.py
+++ b/okcupyd/profile.py
@@ -3,7 +3,6 @@ import logging
from lxml import html
import simplejson
-import mock
from . import details
from . import essay
diff --git a/tasks.py b/tasks.py
index <HASH>..<HASH> 100644
--- a/tasks.py
+++ b/tasks.py
@@ -16,12 +16,14 @@ def install():
@ns.add_task
@task
def pypi():
+ """Upload to pypi"""
run("python setup.py sdist upload -r pypi")
@ns.add_task
@task
def rerecord(rest):
+ """Rerecord tests."""
run('tox -e py27 -- --record --credentials test_credentials {0} -s'
.format(rest), pty=True)
run('tox -e py27 -- --resave --scrub --credentials test_credentials {0} -s'
|
get rid of mock import in profile.
|
IvanMalison_okcupyd
|
train
|
ee8a8520bd4652b569f8f0e8c61c121b34acece1
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -2,7 +2,7 @@
"name": "ambrosus-node-contracts",
"author": "Ambrosus",
"description": "Smart contracts used in AMB-NET",
- "version": "0.0.41",
+ "version": "0.0.42",
"license": "MPL-2.0-no-copyleft-exception",
"repository": "git@github.com:ambrosus/ambrosus-node-contracts.git",
"main": "dist/index.js",
diff --git a/src/constants.js b/src/constants.js
index <HASH>..<HASH> 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -22,3 +22,5 @@ export const ATLAS1_STAKE = utils.toWei('10000');
export const ATLAS2_STAKE = utils.toWei('30000');
export const ATLAS3_STAKE = utils.toWei('75000');
export const APOLLO_DEPOSIT = utils.toWei('250000');
+
+export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
diff --git a/src/wrappers/head_wrapper.js b/src/wrappers/head_wrapper.js
index <HASH>..<HASH> 100644
--- a/src/wrappers/head_wrapper.js
+++ b/src/wrappers/head_wrapper.js
@@ -11,6 +11,7 @@ This Source Code Form is “Incompatible With Secondary Licenses”, as defined
import contractJsons from '../contract_jsons';
import {loadContract} from '../utils/web3_tools';
import GenesisContractWrapper from './genesis_contract_wrapper';
+import {ZERO_ADDRESS} from '../constants';
export default class HeadWrapper extends GenesisContractWrapper {
@@ -74,6 +75,9 @@ export default class HeadWrapper extends GenesisContractWrapper {
.methods
.context()
.call();
+ if (contextAddress === ZERO_ADDRESS) {
+ throw 'Context address is not set in the head contract';
+ }
if (this.cachedContractAddressHasChanged(contextAddress, 'context')) {
this.clearContractAddressCache();
this.updateContractAddressCache('context', contextAddress);
diff --git a/test/wrappers/head_wrapper.js b/test/wrappers/head_wrapper.js
index <HASH>..<HASH> 100644
--- a/test/wrappers/head_wrapper.js
+++ b/test/wrappers/head_wrapper.js
@@ -87,6 +87,11 @@ describe('Head Wrapper', () => {
expect(receivedContext.options.address).to.equal(context.options.address);
});
+ it('context method throws a meaningful error if context address is not set', async () => {
+ await headWrapper.setContext('0x0');
+ await expect(headWrapper.context()).to.eventually.be.rejectedWith('Context address is not set in the head contract');
+ });
+
it('catalogue method returns the catalogue contract instance', async () => {
const receivedCatalogue = await headWrapper.catalogue();
expect(receivedCatalogue instanceof web3.eth.Contract).to.be.true;
|
Throw meaningful error if context is not set in the head contract; (#<I>)
|
ambrosus_ambrosus-node-contracts
|
train
|
5ed40d053c78726492426ddf7658e59afd321125
|
diff --git a/pycbc/filter/resample.py b/pycbc/filter/resample.py
index <HASH>..<HASH> 100644
--- a/pycbc/filter/resample.py
+++ b/pycbc/filter/resample.py
@@ -148,8 +148,13 @@ def lfilter(coefficients, timeseries):
----------
coefficients: numpy.ndarray
Filter coefficients to apply
- timeseries: pycbc.types.TimeSeries
+ timeseries: numpy.ndarray
Time series to be filtered.
+
+ Returns
+ -------
+ tseries: numpy.ndarray
+ filtered array
"""
from pycbc.fft import fft, ifft
from pycbc.filter import correlate
@@ -181,6 +186,34 @@ def lfilter(coefficients, timeseries):
return out.numpy() / len(out)
+def fir_zero_filter(coeff, timeseries):
+ """Filter the timeseries with a set of FIR coefficients
+
+ Parameters
+ ----------
+ coeff: numpy.ndarray
+ FIR coefficients. Should be and odd length and symettric.
+ timeseries: pycbc.types.TimeSeries
+ Time series to be filtered.
+
+ Returns
+ -------
+ filtered_series: pycbc.types.TimeSeries
+ Return the filtered timeseries, which has been properly shifted to account
+ for the FIR filter delay and the corrupted regions zeroed out.
+ """
+ # apply the filter
+ series = lfilter(coeff, timeseries.numpy())
+
+ # reverse the time shift caused by the filter
+ data = numpy.zeros(len(timeseries))
+ data[:len(data)-len(coeff)/2] = series[len(coeff)/2:]
+
+ # zero out corrupted region
+ data[0:len(coeff)/2] = 0
+ data[len(data)-len(coeff)/2:] = 0
+ return data
+
def resample_to_delta_t(timeseries, delta_t, method='butterworth'):
"""Resmple the time_series to delta_t
@@ -249,20 +282,8 @@ def resample_to_delta_t(timeseries, delta_t, method='butterworth'):
except:
raise ValueError('Unsupported resample factor, %s, given' %factor)
- # apply the filter
- series = lfilter(filter_coefficients, timeseries.numpy())
-
- # reverse the time shift caused by the filter
- corruption_length = len(filter_coefficients)
- data = numpy.zeros(len(timeseries))
- data[:len(data)-corruption_length/2] = series[corruption_length/2:]
-
- # zero out corrupted region
- data[0:corruption_length/2] = 0
- data[len(data)-corruption_length/2:] = 0
-
- # Decimate the time series
- data = data[::factor] * 1
+ # apply the filter and decimate
+ data = fir_zero_filter(filter_coefficients, timeseries)[::factor]
else:
raise ValueError('Invalid resampling method: %s' % method)
|
refactor zero phase fir filtering into a helper function
|
gwastro_pycbc
|
train
|
7e24523bdece85be85ba69692d58fc94d916ae03
|
diff --git a/src/test/java/org/influxdb/InfluxDBTest.java b/src/test/java/org/influxdb/InfluxDBTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/influxdb/InfluxDBTest.java
+++ b/src/test/java/org/influxdb/InfluxDBTest.java
@@ -1,14 +1,10 @@
package org.influxdb;
-import java.util.Collections;
+import okhttp3.OkHttpClient;
import org.influxdb.InfluxDB.LogLevel;
import org.influxdb.InfluxDB.ResponseFormat;
-import org.influxdb.dto.BatchPoints;
+import org.influxdb.dto.*;
import org.influxdb.dto.BoundParameterQuery.QueryBuilder;
-import org.influxdb.dto.Point;
-import org.influxdb.dto.Pong;
-import org.influxdb.dto.Query;
-import org.influxdb.dto.QueryResult;
import org.influxdb.dto.QueryResult.Series;
import org.influxdb.impl.InfluxDBImpl;
import org.junit.jupiter.api.AfterEach;
@@ -19,25 +15,13 @@ import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
-import okhttp3.OkHttpClient;
-
import java.io.IOException;
import java.net.ConnectException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
+import java.util.*;
+import java.util.concurrent.*;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
@@ -194,6 +178,20 @@ public class InfluxDBTest {
result.result();
}
+ /**
+ * Tests for callback query with a failure.
+ * see Issue #602
+ */
+ @Test
+ public void testCallbackQueryFailureHandling() {
+ final AsyncResult<QueryResult> res = new AsyncResult<>();
+
+ this.influxDB.query(new Query("SHOW SERRIES"), res.resultConsumer, res.errorConsumer);
+
+ Assertions.assertThrows(InfluxDBException.class, res::result,
+ "Malformed query should throw InfluxDBException");
+ }
+
/**
* Test that describe Databases works.
*/
|
Added test for Issue #<I>
|
influxdata_influxdb-java
|
train
|
332ebf74c031863ba0552d720cee9653b3e70d44
|
diff --git a/Lib/glyphsLib/builder/instances.py b/Lib/glyphsLib/builder/instances.py
index <HASH>..<HASH> 100644
--- a/Lib/glyphsLib/builder/instances.py
+++ b/Lib/glyphsLib/builder/instances.py
@@ -17,6 +17,7 @@ from __future__ import print_function, division, absolute_import, unicode_litera
import os
import logging
+from fontTools.misc.py23 import basestring
from glyphsLib.util import build_ufo_path
from glyphsLib.classes import WEIGHT_CODES, GSCustomParameter
from .constants import GLYPHS_PREFIX, GLYPHLIB_PREFIX
@@ -330,12 +331,13 @@ def set_width_class(ufo, designspace, instance):
_set_class_from_instance(ufo, designspace, instance, "wdth")
-def apply_instance_data(designspace_path, include_filenames=None, Font=defcon.Font):
+def apply_instance_data(designspace, include_filenames=None, Font=defcon.Font):
"""Open UFO instances referenced by designspace, apply Glyphs instance
data if present, re-save UFOs and return updated UFO Font objects.
Args:
- designspace_path: path to a designspace file.
+ designspace: DesignSpaceDocument object or path (str or PathLike) to
+ a designspace file.
include_filenames: optional set of instance filenames (relative to
the designspace path) to be included. By default all instaces are
processed.
@@ -346,9 +348,12 @@ def apply_instance_data(designspace_path, include_filenames=None, Font=defcon.Fo
from fontTools.designspaceLib import DesignSpaceDocument
from os.path import normcase, normpath
- designspace = DesignSpaceDocument()
- designspace.read(designspace_path)
- basedir = os.path.dirname(designspace_path)
+ if hasattr(designspace, "__fspath__"):
+ designspace = designspace.__fspath__()
+ if isinstance(designspace, basestring):
+ designspace = DesignSpaceDocument.fromfile(designspace)
+
+ basedir = os.path.dirname(designspace.path)
instance_ufos = []
if include_filenames is not None:
include_filenames = {normcase(normpath(p)) for p in include_filenames}
|
apply_instance_data: allow DesignSpaceDocument object as input in addition to path
|
googlefonts_glyphsLib
|
train
|
7dd84e0f5416b2ee61f95b972c99c6dae6915237
|
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/AbstractNativeQuery.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/AbstractNativeQuery.java
index <HASH>..<HASH> 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/AbstractNativeQuery.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/AbstractNativeQuery.java
@@ -114,7 +114,12 @@ public abstract class AbstractNativeQuery<T extends NativeQuery< ? , ? >, U> imp
public Object execute(CommandContext commandContext) {
if (resultType == ResultType.LIST) {
- return executeList(commandContext, getParameterMap(), 0, Integer.MAX_VALUE);
+ Map<String, Object> parameterMap = getParameterMap();
+ if (StringUtils.isBlank(ObjectUtils.toString(parameterMap.get("orderBy")))) {
+ parameterMap.put("orderBy", "RES.ID_ asc");
+ }
+ return executeList(commandContext, parameterMap, 0, Integer.MAX_VALUE);
+
} else if (resultType == ResultType.LIST_PAGE) {
Map<String, Object> parameterMap = getParameterMap();
parameterMap.put("resultType", "LIST_PAGE");
|
Try again with native query order by issue
|
Activiti_Activiti
|
train
|
865ad9cbc2977517c2f71ca54224b35cc4e73526
|
diff --git a/lib/Models/CsvCatalogItem.js b/lib/Models/CsvCatalogItem.js
index <HASH>..<HASH> 100644
--- a/lib/Models/CsvCatalogItem.js
+++ b/lib/Models/CsvCatalogItem.js
@@ -720,19 +720,23 @@ function createRegionLookupFunc(csvItem) {
function determineRegionType(dataset, regionWmsMap) {
var varNames = dataset.getVariableNames();
+ var varNameLC = [], varTextCodes = [];
+ varNames.map(function(name) {
+ varNameLC.push(name.toLowerCase());
+ varTextCodes.push(defined(dataset.getVariableEnumList(name)));
+ });
+
//try to figure out the region variable and type based on aliases
- for (var i = 0; i < varNames.length; i++) {
- var varName = varNames[i].toLowerCase();
- var varTextCodes = defined(dataset.getVariableEnumList(varNames[i]));
- for (var region in regionWmsMap) {
- if (regionWmsMap.hasOwnProperty(region)) {
- var aliases = regionWmsMap[region].aliases;
+ for (var region in regionWmsMap) {
+ if (regionWmsMap.hasOwnProperty(region)) {
+ var aliases = regionWmsMap[region].aliases;
+ for (var i = 0; i < varNames.length; i++) {
//check that it is the right type of codes
- if ((regionWmsMap[region].textCodes && !varTextCodes) || (!regionWmsMap[region].textCodes && varTextCodes)) {
+ if ((regionWmsMap[region].textCodes && !varTextCodes[i]) || (!regionWmsMap[region].textCodes && varTextCodes[i])) {
continue;
}
for (var j = 0; j < aliases.length; j++) {
- if (varName.substring(0,aliases[j].length) === aliases[j]) {
+ if (varNameLC[i].substring(0,aliases[j].length) === aliases[j]) {
return { regionType: region, regionVariable: varNames[i] };
}
}
|
back to match region first - best of 2 flawed options
|
TerriaJS_terriajs
|
train
|
1244f0c3baf8b677b4a1263729b2f737a76c435b
|
diff --git a/test/engineTests.js b/test/engineTests.js
index <HASH>..<HASH> 100644
--- a/test/engineTests.js
+++ b/test/engineTests.js
@@ -107,51 +107,15 @@ describe('Engine', function() {
});
it('should be able to run async fetch script', function() {
- let browserScripts = engine.run('http://examples.sitespeed.io/3.0/2014-12-15-22-16-30/', null, {
+ let browserScripts = engine.run('http://httpbin.org/html', null, {
scripts: {
- stylesheets: `(function() {
- 'use strict';
-
- function getAbsoluteURL(url) {
- var a = window.document.createElement('a');
- a.href = url;
- return a.href;
- }
-
- if (!window.fetch) {
- return {};
- }
-
+ fetched: `(function() {
var request = new Request(document.URL, {
redirect: 'follow',
destination: 'document'
});
- return fetch(request)
- .then(function(response) {
- return response.text();
- })
- .then(function(text) {
- var parser = new DOMParser();
- var doc = parser.parseFromString(text, "text/html");
-
- var links = Array.prototype.slice.call(doc.head.getElementsByTagName('link'));
-
- return links.filter(function(link) {
- return (link.rel === 'stylesheet');
- })
- .filter(function(link) {
- var url = getAbsoluteURL(link.attributes['href'].value);
- return /^http(s)?:\/\//.test(url);
- })
- .map(function(link) {
- return {
- href: getAbsoluteURL(link.attributes['href'].value),
- media: link.media,
- rel: link.rel
- };
- });
- });
+ return fetch(request).then(response => response.ok);
})()`
}
})
@@ -161,18 +125,7 @@ describe('Engine', function() {
return browserScripts.should.become([
{
scripts: {
- stylesheets: [
- {
- 'href': 'http://examples.sitespeed.io/3.0/2014-12-15-22-16-30/css/bootstrap.min.css',
- 'media': '',
- 'rel': 'stylesheet'
- },
- {
- 'href': 'http://examples.sitespeed.io/3.0/2014-12-15-22-16-30/css/bootstrap-overrides.css',
- 'media': '',
- 'rel': 'stylesheet'
- }
- ]
+ fetched: true
}
}]);
});
|
Simplify test case.
Only just enough test code to actually test an async script.
|
sitespeedio_browsertime
|
train
|
c6342286586f6c903acc421309fc328821603095
|
diff --git a/lib/instance/login_user_manager.rb b/lib/instance/login_user_manager.rb
index <HASH>..<HASH> 100644
--- a/lib/instance/login_user_manager.rb
+++ b/lib/instance/login_user_manager.rb
@@ -128,7 +128,6 @@ module RightScale
when 0
home_dir = Shellwords.escape(Etc.getpwnam(username).dir)
- #FileUtils.chmod(0771, home_dir)
%x(sudo chmod 0771 #{home_dir})
RightScale::Log.info "User #{username} created successfully"
diff --git a/scripts/thunker.rb b/scripts/thunker.rb
index <HASH>..<HASH> 100644
--- a/scripts/thunker.rb
+++ b/scripts/thunker.rb
@@ -80,6 +80,7 @@ module RightScale
end
# Create user just-in-time; idempotent if user already exists
+ # Note that username == chosen here, they just get used in two different contexts
username = LoginUserManager.create_user(username, uuid, superuser ? true : false) do |chosen|
if :shell == access
puts "Creating your user profile (#{chosen}) on this machine."
@@ -87,6 +88,7 @@ module RightScale
end
create_audit_entry(email, username, access, orig, client_ip)
+ chown_tty(username)
create_profile(access, username, profile, force) if profile
# Note that when execing sudo we use the N-argument form of Kernel.exec,
@@ -326,6 +328,23 @@ module RightScale
# no-op.
end
+ # Ensure the user's PTY/TTY will be owned by him once we thunk through to his account.
+ # This helps apps like screen/tmux work better.
+ def chown_tty(username)
+ tty = `tty`.chomp
+ if File.exists?(tty)
+ %x(sudo chown #{Shellwords.escape(username)} #{Shellwords.escape(tty)})
+ raise RuntimeError, "Failed to change ownership of #{tty}" unless $?.success?
+ else
+ raise Errno::ENOENT, "'tty' command did not give a reasonable answer: #{tty}"
+ end
+ rescue Exception => e
+ STDERR.puts "Cannot chown your TTY - #{e.class.name}: #{e.message}"
+ STDERR.puts "Your session will continue, but screen and other terminal-magic apps"
+ STDERR.puts "may not work."
+ STDERR.puts
+ end
+
# Version information
#
# === Return
|
acu<I> - try to chown the user's pty before thunking him
|
rightscale_right_link
|
train
|
edf5bb2bd420692bfb5a65e62949334b64fcdc42
|
diff --git a/lib/reference.js b/lib/reference.js
index <HASH>..<HASH> 100644
--- a/lib/reference.js
+++ b/lib/reference.js
@@ -14,6 +14,15 @@ var Branch = NodeGit.Branch;
Reference.lookup = LookupWrapper(Reference);
/**
+* Retrieves the reference by it's short name
+* @param {Repository} repo The repo that the reference lives in
+* @param {String|Reference} id The reference to lookup
+* @param {Function} callback
+* @return {Reference}
+*/
+Reference.dwim = LookupWrapper(Reference, Reference.dwim);
+
+/**
* Returns true if this reference is valid
* @return {Boolean}
*/
diff --git a/lib/repository.js b/lib/repository.js
index <HASH>..<HASH> 100644
--- a/lib/repository.js
+++ b/lib/repository.js
@@ -55,7 +55,8 @@ function(name, commit, force, signature, logMessage) {
/**
* Look up a refs's commit.
*
- * @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master" or Branch Ref
+ * @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
+ * or Branch Ref
* @param {Function} callback
* @return {Commit}
*/
@@ -74,6 +75,30 @@ Repository.prototype.getReferenceCommit = function(name, callback) {
};
/**
+* Look up a branch. Alias for `getReference`
+*
+* @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
+* or Branch Ref
+* @param {Function} callback
+* @return {Ref}
+*/
+Repository.prototype.getBranch = function(name, callback) {
+ return this.getReference(name, callback);
+};
+
+/**
+* Look up a branch's most recent commit. Alias to `getReferenceCommit`
+*
+* @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
+* or Branch Ref
+* @param {Function} callback
+* @return {Commit}
+*/
+Repository.prototype.getBranchCommit = function(name, callback) {
+ return this.getReferenceCommit(name, callback);
+};
+
+/**
* Gets the branch that HEAD currently points to
* Is an alias to head()
* @return {Reference}
@@ -85,17 +110,15 @@ Repository.prototype.getCurrentBranch = function() {
/**
* Lookup the reference with the given name.
*
- * @param {String} name
+ * @param {String|Ref} name Ref name, e.g. "master", "refs/heads/master"
+ * or Branch Ref
* @param {Function} callback
* @return {Reference}
*/
Repository.prototype.getReference = function(name, callback) {
var repository = this;
- var lookup = name.indexOf("refs/") === 0
- ? Reference.lookup(this, name)
- : Reference.dwim(this, name);
- return lookup.then(function(reference) {
+ return Reference.dwim(this, name).then(function(reference) {
if (reference.isSymbolic()) {
return reference.resolve(function (error, reference) {
reference.repo = repository;
diff --git a/test/tests/remote.js b/test/tests/remote.js
index <HASH>..<HASH> 100644
--- a/test/tests/remote.js
+++ b/test/tests/remote.js
@@ -104,11 +104,10 @@ describe("Remote", function() {
});
it("can fetch from a remote", function() {
- return this.repository.fetch("origin")
- .then(function() {
- assert(true);
- }, function() {
- assert(false);
+ return this.repository.fetch("origin", {
+ credentials: function(url, userName) {
+ return NodeGit.Cred.sshKeyFromAgent(userName);
+ }
});
});
});
diff --git a/test/tests/repository.js b/test/tests/repository.js
index <HASH>..<HASH> 100644
--- a/test/tests/repository.js
+++ b/test/tests/repository.js
@@ -49,8 +49,8 @@ describe("Repository", function() {
it("can list remotes", function() {
return this.repository.getRemotes().then(function(remotes) {
- assert.equal(remotes.count(), 1);
- assert.equal(remotes.strings(), "origin");
+ assert.equal(remotes.length, 1);
+ assert.equal(remotes[0], "origin");
});
});
|
Fixed tests and reimplemented missing functions on Repository
|
nodegit_nodegit
|
train
|
cc2132413b0ed5717980be147fe77b1829b12716
|
diff --git a/lib/plz/command_builder.rb b/lib/plz/command_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/plz/command_builder.rb
+++ b/lib/plz/command_builder.rb
@@ -185,8 +185,18 @@ module Plz
end
# @return [String, nil] Base URL of the API
+ # @example
+ # base_url #=> "http://localhost:8080"
def base_url
- @base_url ||= options[:host] || base_url_from_schema
+ @base_url ||= begin
+ if url = (options[:host] || base_url_from_schema)
+ if url.start_with?("http")
+ url
+ else
+ "http://#{url}"
+ end
+ end
+ end
end
# Extracts the base url of the API from JSON Schema
|
Take --host option with only hostname
|
r7kamura_plz
|
train
|
ce36b20c50839cd276801677903f0243897eae2e
|
diff --git a/picuplib/checks.py b/picuplib/checks.py
index <HASH>..<HASH> 100644
--- a/picuplib/checks.py
+++ b/picuplib/checks.py
@@ -1,5 +1,5 @@
# -*- coding:utf8 -*-
-######################## BEGIN LICENSE BLOCK ########################
+# ####################### BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
@@ -14,7 +14,7 @@
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
+# ######################## END LICENSE BLOCK #########################
"""
module for some argument cheking
"""
@@ -35,6 +35,7 @@ def check_rotation(rotation):
raise UnsuportedRotation('Rotation %s is not allwoed. Allowed are %s'
% (rotation, allowed_rotation))
+
def check_resize(resize):
"""checks resize parameter if illegal value raises exception"""
@@ -43,11 +44,19 @@ def check_resize(resize):
raise UnsuportedResize('Resize %s is not allowed. Allowed are %s'
% (resize, allowed_resize))
+
def check_noexif(noexif):
"""checks if noexif parameter is boolean"""
if not isinstance(noexif, bool):
raise TypeError('noexif must be boolean')
+
+def check_callback(callback):
+ """checks if callback is callable"""
+ if not callable(callback) and callback is not None:
+ raise TypeError('%s is not callable' % callback)
+
+
def check_response(response):
"""
checks the response if the server returned an error raises an exception.
@@ -68,6 +77,7 @@ def check_response(response):
else:
raise UnkownError(response_text['failure'])
+
def check_if_redirect(url):
"""
checks if server redirects url
diff --git a/picuplib/upload.py b/picuplib/upload.py
index <HASH>..<HASH> 100644
--- a/picuplib/upload.py
+++ b/picuplib/upload.py
@@ -27,7 +27,7 @@ from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
from picuplib.checks import (check_resize, check_rotation, check_noexif,
- check_response, check_if_redirect)
+ check_response, check_if_redirect, check_callback)
from picuplib.globals import API_URL, USER_AGENT
class Upload(object):
@@ -49,12 +49,15 @@ class Upload(object):
:ivar boolean noexif: If true exif data will be deleted
"""
- def __init__(self, apikey, resize='og', rotation='00', noexif=False):
+ def __init__(self, apikey, resize='og', rotation='00', noexif=False,
+ callback=None):
self._apikey = apikey
self._resize = resize
self._rotation = rotation
self._noexif = noexif
+ self._callback = callback
+
@property
def resize(self):
"""getter for _resize"""
@@ -88,7 +91,20 @@ class Upload(object):
check_noexif(value)
self._noexif = value
- def upload(self, picture, resize=None, rotation=None, noexif=None):
+ @property
+ def callback(self):
+ """ getter for _callback"""
+ return self._callback
+
+ @callback.setter
+ def callback(self, value):
+ """setter for _callback"""
+ check_callback(value)
+ self._callback = value
+
+
+ def upload(self, picture, resize=None, rotation=None, noexif=None,
+ callback=None):
"""
wraps upload function
@@ -99,6 +115,9 @@ class Upload(object):
Allowed values are 00, 90, 180, 270.(optional)
:param boolean noexif: set to True when exif data should be purged.\
(optional)
+ :param function callback: function witch will be called after every read. \
+ Need to take one argument. you can use the len function to \
+ determine the body length and call bytes_read().
"""
if not resize:
@@ -107,8 +126,10 @@ class Upload(object):
rotation = self._rotation
if not noexif:
noexif = self._noexif
+ if not callback:
+ callback = self._callback
- return upload(self._apikey, picture, resize, rotation, noexif)
+ return upload(self._apikey, picture, resize, rotation, noexif, callback)
def remote_upload(self, picture_url, resize=None,
rotation=None, noexif=None):
@@ -155,10 +176,13 @@ def upload(apikey, picture, resize='og', rotation='00', noexif=False,
Allowed values are 00, 90, 180, 270.(optional)
:param boolean noexif: set to True when exif data should be purged.\
(optional)
-
+ :param function callback: function witch will be called after every read. \
+ Need to take one argument. you can use the len function to determine \
+ the body length and call bytes_read().
"""
check_rotation(rotation)
check_resize(resize)
+ check_callback(callback)
post_data = compose_post(apikey, resize, rotation, noexif)
|
added callback parameter to Class based interface and updated docs
|
Arvedui_picuplib
|
train
|
a587349c813d0e067960bc485c8ee9738b1eb2dd
|
diff --git a/VERSION b/VERSION
index <HASH>..<HASH> 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-5.0.0.rc1
+5.0.0.rc2
diff --git a/lib/rack/app/singleton_methods/http_methods.rb b/lib/rack/app/singleton_methods/http_methods.rb
index <HASH>..<HASH> 100644
--- a/lib/rack/app/singleton_methods/http_methods.rb
+++ b/lib/rack/app/singleton_methods/http_methods.rb
@@ -30,6 +30,18 @@ module Rack::App::SingletonMethods::HttpMethods
add_route(::Rack::App::Constants::HTTP::METHOD::PATCH, path, &block)
end
+ def link(path = '/', &block)
+ add_route(::Rack::App::Constants::HTTP::METHOD::LINK, path, &block)
+ end
+
+ def unlink(path = '/', &block)
+ add_route(::Rack::App::Constants::HTTP::METHOD::UNLINK, path, &block)
+ end
+
+ def trace(path = '/', &block)
+ add_route(::Rack::App::Constants::HTTP::METHOD::TRACE, path, &block)
+ end
+
def alias_endpoint(new_request_path, original_request_path)
new_request_path = Rack::App::Utils.normalize_path(new_request_path)
original_request_path = Rack::App::Utils.normalize_path(original_request_path)
diff --git a/spec/benchmark_spec.rb b/spec/benchmark_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/benchmark_spec.rb
+++ b/spec/benchmark_spec.rb
@@ -13,7 +13,7 @@ describe '#Performance Benchmark' do
let(:maximum_accepted_seconds) do
if RUBY_VERSION >= '1.9'
- 5
+ 6
else
13
end
|
feat: add more allowed http method to DSL
|
rack-app_rack-app
|
train
|
12bd929b1e733918b517c40e2528ea485c238130
|
diff --git a/lib/netext/httpext/request.go b/lib/netext/httpext/request.go
index <HASH>..<HASH> 100644
--- a/lib/netext/httpext/request.go
+++ b/lib/netext/httpext/request.go
@@ -23,6 +23,7 @@ package httpext
import (
"bytes"
"context"
+ "fmt"
"io"
"io/ioutil"
"net"
@@ -314,6 +315,15 @@ func MakeRequest(ctx context.Context, preq *ParsedHTTPRequest) (*Response, error
mreq := preq.Req.WithContext(ctx)
res, resErr := client.Do(mreq)
+ // TODO(imiric): It would be safer to check for a writeable
+ // response body here instead of status code, but those are
+ // wrapped in a read-only body when using client timeouts and are
+ // unusable until https://github.com/golang/go/issues/31391 is fixed.
+ if res != nil && res.StatusCode == http.StatusSwitchingProtocols {
+ _ = res.Body.Close()
+ return nil, fmt.Errorf("unsupported response status: %s", res.Status)
+ }
+
resp.Body, resErr = readResponseBody(state, preq.ResponseType, res, resErr)
finishedReq := tracerTransport.processLastSavedRequest(wrapDecompressionError(resErr))
if finishedReq != nil {
diff --git a/lib/netext/httpext/request_test.go b/lib/netext/httpext/request_test.go
index <HASH>..<HASH> 100644
--- a/lib/netext/httpext/request_test.go
+++ b/lib/netext/httpext/request_test.go
@@ -6,10 +6,14 @@ import (
"io"
"io/ioutil"
"net/http"
+ "net/http/httptest"
"net/url"
"testing"
+ "github.com/loadimpact/k6/lib"
+ "github.com/loadimpact/k6/stats"
"github.com/pkg/errors"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -82,6 +86,29 @@ func TestMakeRequestError(t *testing.T) {
require.Error(t, err)
require.Equal(t, err.Error(), "unknown compressionType CompressionType(13)")
})
+
+ t.Run("invalid upgrade response", func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Add("Connection", "Upgrade")
+ w.Header().Add("Upgrade", "h2c")
+ w.WriteHeader(http.StatusSwitchingProtocols)
+ }))
+ defer srv.Close()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ state := &lib.State{
+ Options: lib.Options{RunTags: &stats.SampleTags{}},
+ Transport: srv.Client().Transport,
+ }
+ ctx = lib.WithState(ctx, state)
+ req, _ := http.NewRequest("GET", srv.URL, nil)
+ var preq = &ParsedHTTPRequest{Req: req, URL: &URL{u: req.URL}, Body: new(bytes.Buffer)}
+
+ res, err := MakeRequest(ctx, preq)
+
+ assert.Nil(t, res)
+ assert.EqualError(t, err, "unsupported response status: 101 Switching Protocols")
+ })
}
func TestURL(t *testing.T) {
|
fix(httpext): return error on unsupported <I> response
The hanging behavior described in #<I> happens after this Golang change:
<URL> or other protocols.
[1]: <URL>
|
loadimpact_k6
|
train
|
3c480d4e42c57a7d148725cf1bb25826c6b7ae05
|
diff --git a/lib/rake/javaextensiontask.rb b/lib/rake/javaextensiontask.rb
index <HASH>..<HASH> 100644
--- a/lib/rake/javaextensiontask.rb
+++ b/lib/rake/javaextensiontask.rb
@@ -35,8 +35,8 @@ module Rake
@source_pattern = '**/*.java'
@classpath = nil
@debug = false
- @source_version = '1.6'
- @target_version = '1.6'
+ @source_version = '1.7'
+ @target_version = '1.7'
@encoding = nil
@java_compiling = nil
@lint_option = nil
|
Default to <I>-level bytecode in Java build (#<I>)
|
rake-compiler_rake-compiler
|
train
|
8edaeafba3d22a4262b2f4c21751db5044ed7e8e
|
diff --git a/lib/modules/apostrophe-schemas/index.js b/lib/modules/apostrophe-schemas/index.js
index <HASH>..<HASH> 100644
--- a/lib/modules/apostrophe-schemas/index.js
+++ b/lib/modules/apostrophe-schemas/index.js
@@ -880,7 +880,7 @@ module.exports = {
}
},
isEmpty: function(field, value) {
- return self.apos.areas.isEmpty({ area: area });
+ return self.apos.areas.isEmpty({ area: value });
},
bless: function(req, field) {
if (field.options && field.options.widgets) {
@@ -895,7 +895,7 @@ module.exports = {
name: 'singleton',
extend: 'area',
isEmpty: function(field, value) {
- return self.apos.areas.isEmptySingleton({ area: area, type: field.widgetType });
+ return self.apos.areas.isEmptySingleton({ area: value, type: field.widgetType });
},
bless: function(req, field) {
self.apos.utils.bless(req, field.options || {}, 'widget', field.widgetType);
|
typo in isEmpty for area and singleton field type
|
apostrophecms_apostrophe
|
train
|
33ea6d3a4d55738ff55d1403469b8b16302fe05d
|
diff --git a/lib/class-wp-json-server.php b/lib/class-wp-json-server.php
index <HASH>..<HASH> 100644
--- a/lib/class-wp-json-server.php
+++ b/lib/class-wp-json-server.php
@@ -395,12 +395,20 @@ class WP_JSON_Server implements WP_JSON_ResponseHandler {
}
if ( $supported & self::ACCEPT_JSON ) {
- $data = json_decode( $this->get_raw_data(), true );
+ $raw_data = $this->get_raw_data();
+ $data = json_decode( $raw_data, true );
// test for json_decode() error
$json_error_message = $this->get_json_last_error();
if ( $json_error_message ) {
- return new WP_Error( 'json_decode_error', $json_error_message, array( 'status' => 500 ) );
+
+ $data = array();
+ parse_str( $raw_data, $data );
+
+ if ( empty( $data ) ) {
+
+ return new WP_Error( 'json_decode_error', $json_error_message, array( 'status' => 500 ) );
+ }
}
if ( $data !== null ) {
|
account for possible query strings in our dispatch method
|
WP-API_WP-API
|
train
|
5ad2f51e25bb1e4f658e3b28ea4a08e1695ca4a3
|
diff --git a/src/Menu/MenuModulesInterpreter.php b/src/Menu/MenuModulesInterpreter.php
index <HASH>..<HASH> 100644
--- a/src/Menu/MenuModulesInterpreter.php
+++ b/src/Menu/MenuModulesInterpreter.php
@@ -114,23 +114,21 @@ class MenuModulesInterpreter implements MenuModulesInterpreterInterface
$index = 0;
// Make a mapping to easily look up configured order with
- $moduleConfig = config('cms-modules.menu.modules', []);
-
// Account for possibility of either 'module key' => [] or 'module key' format in config
$orderMap = array_map(
- function ($key) use ($moduleConfig) {
+ function ($key) {
if (is_string($key)) return $key;
- if ( ! is_string($moduleConfig[$key])) {
+ if ( ! is_string($this->configModules[$key])) {
throw new UnexpectedValueException(
"cms-modules.menu.modules entry '{$key}' must be string or have a non-numeric key"
);
}
- return $moduleConfig[$key];
+ return $this->configModules[$key];
},
- array_keys($moduleConfig)
+ array_keys($this->configModules)
);
$orderMap = array_flip($orderMap);
@@ -138,7 +136,11 @@ class MenuModulesInterpreter implements MenuModulesInterpreterInterface
return $modules->sortBy(function (ModuleInterface $module) use (&$index, $orderMap) {
// Order by configured order first, natural modules order second.
- $primaryOrder = array_get($orderMap, $module->getKey(), -2) + 1;
+ if (count($orderMap)) {
+ $primaryOrder = (int) array_get($orderMap, $module->getKey(), -2) + 1;
+ } else {
+ $primaryOrder = -1;
+ }
return $primaryOrder < 0 ? ++$index : (1 - 1 / $primaryOrder);
});
|
Fixed issues with menu modules interpreter
- inconsistent access of configuration
- sorting problem, safeguard added
|
czim_laravel-cms-core
|
train
|
67b8fef960fb68322cd766af94fd070190f7e66d
|
diff --git a/lib/record_blueprint.py b/lib/record_blueprint.py
index <HASH>..<HASH> 100644
--- a/lib/record_blueprint.py
+++ b/lib/record_blueprint.py
@@ -82,7 +82,7 @@ def request_record(f):
if not current_user.is_guest:
user = User.query.get(current_user.get_id())
title = get_fieldvalues(recid, '245__a')
- title = title[0] if len(title) > 0 else ''
+ title = title[0].decode('utf-8') if len(title) > 0 else ''
b = get_collection_breadcrumbs(collection, [(_('Home'),'')])
b += [(title, 'record.metadata', dict(recid=recid))]
|
WebSearch: fix title encoding problem
|
inveniosoftware_invenio-records
|
train
|
25f6e7c341a0cc0c2981793b7c104751a73797b3
|
diff --git a/js/lib/mediawiki.parser.environment.js b/js/lib/mediawiki.parser.environment.js
index <HASH>..<HASH> 100644
--- a/js/lib/mediawiki.parser.environment.js
+++ b/js/lib/mediawiki.parser.environment.js
@@ -76,6 +76,7 @@ var MWParserEnvironment = function(opts) {
pageName: 'Main page',
interwikiMap: interwikiMap,
interwikiRegexp: Object.keys(interwikiMap).join('|'),
+ usePHPPreProcessor: false,
uid: 1
};
// XXX: this should be namespaced
diff --git a/js/tests/client/client.js b/js/tests/client/client.js
index <HASH>..<HASH> 100644
--- a/js/tests/client/client.js
+++ b/js/tests/client/client.js
@@ -59,7 +59,7 @@ function runTest( cb, title ) {
} );
try {
- rtTest.fetch( title, callback, { wiki: config.interwiki } );
+ rtTest.fetch( title, callback, { wiki: config.interwiki, setup: config.setup } );
} catch ( err ) {
// Log it to console (for gabriel to watch scroll by)
console.error( "ERROR in " + title + ': ' + err );
diff --git a/js/tests/client/config.example.js b/js/tests/client/config.example.js
index <HASH>..<HASH> 100644
--- a/js/tests/client/config.example.js
+++ b/js/tests/client/config.example.js
@@ -20,7 +20,11 @@ if ( typeof module === 'object' ) {
clientName: 'AnonymousClient',
// The interwiki prefix you want to use (see mediawiki.parser.environment.js for more information)
- interwiki: 'en'
+ interwiki: 'en',
+
+ setup = function ( env ) {
+ env.usePHPPreProcessor = false;
+ }
};
}
diff --git a/js/tests/roundtrip-test.js b/js/tests/roundtrip-test.js
index <HASH>..<HASH> 100644
--- a/js/tests/roundtrip-test.js
+++ b/js/tests/roundtrip-test.js
@@ -390,6 +390,10 @@ fetch = function ( page, cb, options ) {
cb( error, null, [] );
};
+ if ( options.setup ) {
+ options.setup( env );
+ }
+
var target = env.resolveTitle( env.normalizeTitle( env.pageName ), '' );
var tpr = new TemplateRequest( env, target, null );
|
Add a usePHPPreProcessor config flag to the env defaults and client conf
Defaults to false.
The client config can now define a setup function that has access to the
environment.
Change-Id: I7aecb<I>fd<I>d<I>b<I>e<I>ed6c9
|
wikimedia_parsoid
|
train
|
1ee242ac6fa9028e776b0e1db8558121d2df3f10
|
diff --git a/shinken/modules/graphite_ui.py b/shinken/modules/graphite_ui.py
index <HASH>..<HASH> 100644
--- a/shinken/modules/graphite_ui.py
+++ b/shinken/modules/graphite_ui.py
@@ -212,8 +212,10 @@ class Graphite_Webui(BaseModule):
if self.graphite_data_source:
uri += "&target=%s.%s.__HOST__.%s" % (
host_name, self.graphite_data_source, metric)
+ uri += "&target=%s.%s.__HOST__.%s" % (host_name, self.graphite_data_source, metric + "?????")
else:
uri += "&target=%s.__HOST__.%s" % (host_name, metric)
+ uri += "&target=%s.__HOST__.%s" % (host_name, metric + "?????")
v = {}
v['link'] = self.uri
v['img_src'] = uri
@@ -243,8 +245,10 @@ class Graphite_Webui(BaseModule):
uri += "&target=%s.%s.%s.%s" % (host_name,
self.graphite_data_source,
desc, metric)
+ uri += "&target=%s.%s.%s.%s" % (host_name, self.graphite_data_source, desc, metric + "?????")
else:
uri += "&target=%s.%s.%s" % (host_name, desc, metric)
+ uri += "&target=%s.%s.%s" % (host_name, desc, metric + "?????")
v = {}
v['link'] = self.uri
v['img_src'] = uri
|
Enh: Re-add crit and warn graph line with main metric line
|
Alignak-monitoring_alignak
|
train
|
15d93fa983ef462c886749cafeb1bc818395d043
|
diff --git a/src/josegonzalez/Queuesadilla/Backend/MysqlBackend.php b/src/josegonzalez/Queuesadilla/Backend/MysqlBackend.php
index <HASH>..<HASH> 100644
--- a/src/josegonzalez/Queuesadilla/Backend/MysqlBackend.php
+++ b/src/josegonzalez/Queuesadilla/Backend/MysqlBackend.php
@@ -2,13 +2,15 @@
/*
CREATE TABLE IF NOT EXISTS `jobs` (
- `id` mediumint(20) NOT NULL AUTO_INCREMENT,
- `queue` char(32) NULL DEFAULT 'default',
- `data` mediumtext NULL DEFAULT '',
- `locked` tinyint(1) NULL DEFAULT 0,
- PRIMARY KEY (`id`),
- KEY `queue` (`queue`, `locked`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
+ `id` mediumint(20) NOT NULL AUTO_INCREMENT,
+ `queue` char(32) NOT NULL DEFAULT 'default',
+ `data` mediumtext NOT NULL,
+ `priority` int(1) NOT NULL DEFAULT '0',
+ `expires_at` datetime DEFAULT NULL,
+ `locked` tinyint(1) NOT NULL DEFAULT '0',
+ PRIMARY KEY (`id`),
+ KEY `queue` (`queue`,`locked`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
namespace josegonzalez\Queuesadilla\Backend;
@@ -23,13 +25,13 @@ class MysqlBackend extends Backend
'api_version' => 1, # unsupported
'delay' => 0, # unsupported
'database' => 'queuesadilla',
- 'expires_in' => 86400, # unsupported
+ 'expires_in' => null, # unsupported
'login' => 'root',
'password' => 'password',
'persistent' => true,
'port' => '3306',
'prefix' => null, # unsupported
- 'priority' => 0, # unsupported
+ 'priority' => 0,
'protocol' => 'https', # unsupported
'queue' => 'default',
'serializer' => null, # unsupported
@@ -110,7 +112,7 @@ class MysqlBackend extends Backend
$queue = $this->setting($options, 'queue');
$sql = sprintf(
- 'SELECT `id`, `data` FROM `%s` WHERE `queue` = ? and `locked` != 1 ORDER BY id asc LIMIT 1',
+ 'SELECT `id`, `data` FROM `%s` WHERE `queue` = ? and `locked` != 1 ORDER BY priority asc LIMIT 1',
$this->settings['table']
);
$sth = $this->connection->prepare($sql);
@@ -136,11 +138,23 @@ class MysqlBackend extends Backend
public function push($class, $vars = array(), $options = array())
{
$queue = $this->setting($options, 'queue');
+ $priority = $this->setting($options, 'priority');
+ $expires_in = $this->setting($options, 'expires_in');
+
+ $expires_at = null;
+ if ($expires_in) {
+ $expires_at = (new \DateTime())
+ ->add(new DateInterval(sprintf('PT%sS', $expires_in)))
+ ->format('Y-m-d H:i:s');
+ }
+
$data = json_encode(compact('class', 'vars'));
- $sql = sprintf('INSERT INTO `%s` (`data`, `queue`) VALUES (?, ?)', $this->settings['table']);
+ $sql = sprintf('INSERT INTO `%s` (`data`, `queue`, `priority`, `expires_at`) VALUES (?, ?, ?, ?)', $this->settings['table']);
$sth = $this->connection->prepare($sql);
$sth->bindParam(1, $data, PDO::PARAM_STR);
$sth->bindParam(2, $queue, PDO::PARAM_STR);
+ $sth->bindParam(3, $priority, PDO::PARAM_INT);
+ $sth->bindParam(4, $expires_at, PDO::PARAM_STR);
$sth->execute();
return $sth->rowCount() == 1;
}
|
Add expires_in and priority support to MysqlBackend. Refs #<I>
|
josegonzalez_php-queuesadilla
|
train
|
cda992f933ad0bc0803c7e79780368fe0775fe61
|
diff --git a/sling/core/console/src/main/java/com/composum/sling/nodes/servlet/SourceModel.java b/sling/core/console/src/main/java/com/composum/sling/nodes/servlet/SourceModel.java
index <HASH>..<HASH> 100644
--- a/sling/core/console/src/main/java/com/composum/sling/nodes/servlet/SourceModel.java
+++ b/sling/core/console/src/main/java/com/composum/sling/nodes/servlet/SourceModel.java
@@ -20,15 +20,16 @@ import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigDecimal;
+import java.nio.file.attribute.FileTime;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
-import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -58,6 +59,8 @@ public class SourceModel extends ConsoleSlingBean {
public static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
+ public static final FileTime NO_TIME = FileTime.from(0, TimeUnit.MILLISECONDS);
+
public class Property implements Comparable<Property> {
protected final String name;
@@ -164,6 +167,7 @@ public class SourceModel extends ConsoleSlingBean {
protected final NodesConfiguration config;
+ private transient FileTime lastModified;
private transient List<Property> propertyList;
private transient List<Resource> subnodeList;
@@ -183,6 +187,15 @@ public class SourceModel extends ConsoleSlingBean {
return StringUtils.defaultString(ResourceUtil.getPrimaryType(resource));
}
+ public FileTime getLastModified() {
+ if (lastModified == null) {
+ Calendar timestamp = resource.getProperties().get(JcrConstants.JCR_LASTMODIFIED, Calendar.class);
+ lastModified = timestamp != null ?
+ FileTime.from(timestamp.getTimeInMillis(), TimeUnit.MILLISECONDS) : NO_TIME;
+ }
+ return lastModified == NO_TIME ? null : lastModified;
+ }
+
public List<Property> getPropertyList() {
if (propertyList == null) {
propertyList = new ArrayList<>();
@@ -353,8 +366,12 @@ public class SourceModel extends ConsoleSlingBean {
ZipEntry entry;
String path = resource.getPath();
+ FileTime lastModified = getLastModified();
entry = new ZipEntry(getZipName(root, path + "/.content.xml"));
+ if (lastModified != null) {
+ entry.setLastModifiedTime(lastModified);
+ }
zipStream.putNextEntry(entry);
Writer writer = new OutputStreamWriter(zipStream, "UTF-8");
writeFile(writer, true);
|
merge back from Nodes (<I>)
|
ist-dresden_composum
|
train
|
1617b3bb8daa0e42328355cae25c23fdad255f44
|
diff --git a/json-path/src/main/java/com/jayway/jsonpath/internal/filter/FilterCompiler.java b/json-path/src/main/java/com/jayway/jsonpath/internal/filter/FilterCompiler.java
index <HASH>..<HASH> 100644
--- a/json-path/src/main/java/com/jayway/jsonpath/internal/filter/FilterCompiler.java
+++ b/json-path/src/main/java/com/jayway/jsonpath/internal/filter/FilterCompiler.java
@@ -109,6 +109,9 @@ public class FilterCompiler {
opsStack.push(operatorNode);
break;
default:
+ if(expStack.size() > 0 && opsStack.isEmpty()){
+ throw new InvalidPathException("Expected logical operator (&&, ||) to follow expression " + expStack.peek().toString());
+ }
RelationalExpressionNode relationalExpressionNode = readExpression();
expStack.push(relationalExpressionNode);
break;
diff --git a/json-path/src/test/java/com/jayway/jsonpath/FilterCompilerTest.java b/json-path/src/test/java/com/jayway/jsonpath/FilterCompilerTest.java
index <HASH>..<HASH> 100644
--- a/json-path/src/test/java/com/jayway/jsonpath/FilterCompilerTest.java
+++ b/json-path/src/test/java/com/jayway/jsonpath/FilterCompilerTest.java
@@ -72,6 +72,7 @@ public class FilterCompilerTest {
assertInvalidPathException("[?(@ == 'foo )]");
assertInvalidPathException("[?(@ == 1' )]");
assertInvalidPathException("[?(@.foo bar == 1)]");
+ assertInvalidPathException("[?(@.i == 5 @.i == 8)]");
}
@@ -80,7 +81,7 @@ public class FilterCompilerTest {
compile(filter);
throw new AssertionError("Expected " + filter + " to throw InvalidPathException");
} catch (InvalidPathException e){
- //e.printStackTrace();
+ e.printStackTrace();
}
}
}
|
Fix issue #<I> - Excess filter expressions should be disallowed.
|
json-path_JsonPath
|
train
|
2f40b60145d9c4739e3fc9394dad05fdacc00dc4
|
diff --git a/help.php b/help.php
index <HASH>..<HASH> 100644
--- a/help.php
+++ b/help.php
@@ -34,19 +34,21 @@ if (!empty($file)) {
// Get the list of parent languages.
if (empty($forcelang)) {
$langs = array(current_language(), get_string('parentlanguage'), 'en_utf8'); // Fallback
- // _local language packs take precedence
- $xlangs = array();
- foreach ($langs as $lang) {
- if (!empty($lang)) {
- $xlangs[] = $lang . '_local';
- $xlangs[] = $lang;
- }
- }
- $langs = $xlangs;
- unset($xlangs);
} else {
$langs = array($forcelang);
}
+
+ // _local language packs take precedence with both forced language and non-forced language settings
+ $xlangs = array();
+ foreach ($langs as $lang) {
+ if (!empty($lang)) {
+ $xlangs[] = $lang . '_local';
+ $xlangs[] = $lang;
+ }
+ }
+ $langs = $xlangs;
+ unset($xlangs);
+
// Define possible locations for help file similar to locations for language strings
// Note: Always retain module directory as before
|
_local language packs take precedence with both forced language and non-forced language settings.
Fixes reopened MDL-<I>.
|
moodle_moodle
|
train
|
58ec11ea95733f55aaee13ee8d227339d7be83ba
|
diff --git a/src/Plugins/Exceptions/AutoloadFileNotFound.php b/src/Plugins/Exceptions/AutoloadFileNotFound.php
index <HASH>..<HASH> 100644
--- a/src/Plugins/Exceptions/AutoloadFileNotFound.php
+++ b/src/Plugins/Exceptions/AutoloadFileNotFound.php
@@ -5,7 +5,7 @@ namespace Fiesta\Kernel\Plugins\Exception;
/**
* Directory not fount exception
*/
-class AutoloadFileNotFound extends \Exception
+class AutoloadFileNotFoundException extends \Exception
{
protected $message;
//
|
edit AutoloadFileNotFound name by adding Exception word
|
vinala_kernel
|
train
|
7d893e0bbd8d0094aafe052b395cd132c4e2b75a
|
diff --git a/tests/QtTestCase.py b/tests/QtTestCase.py
index <HASH>..<HASH> 100644
--- a/tests/QtTestCase.py
+++ b/tests/QtTestCase.py
@@ -31,6 +31,8 @@ class QtTestCase(unittest.TestCase):
self.form = MainController()
def add_signal_to_form(self, filename: str):
+ QApplication.instance().processEvents()
+ QTest.qWait(1)
self.form.add_signalfile(get_path_for_data_file(filename))
def tearDown(self):
|
add timeout before adding signalfile to prevent graphic view segfaults
|
jopohl_urh
|
train
|
4ff88133639991d0856ea466dd16b8265d41f902
|
diff --git a/classic.py b/classic.py
index <HASH>..<HASH> 100644
--- a/classic.py
+++ b/classic.py
@@ -285,7 +285,10 @@ class ClassicRequestServer(Module):
f.write("ERROR::%s" % e)
return
f.write("REQUEST::SUCCESS")
-
+
+ def _handle_list_pls(self, conn, addr, l, f, cmd):
+ f.write("TOTAL::0\n")
+
def _handle_request_upload(self, conn, addr, l, f, cmd):
bits = cmd.strip().split('::')
if len(bits) != 10:
@@ -342,8 +345,9 @@ class ClassicRequestServer(Module):
self._sleep_socket_pair = socket.socketpair()
self.n_conn = 0
self.cmd_map = {'LIST::QUEUE\n': self._handle_list_queue,
- 'LIST::NOWPLAYING\n': self._handle_nowplaying,
+ 'LIST::NOWPLAYING': self._handle_nowplaying,
'LIST::ALL': self._handle_list_all,
+ 'LIST::PLAYLISTS::USER::': self._handle_list_pls,
'REQUEST::SONG::': self._handle_request_song,
'REQUEST::UPLOAD::': self._handle_request_upload,
'LOGIN::USER::': self._handle_login_user}
|
classic: fix RequestServer for old marietje
|
bwesterb_mirte
|
train
|
a6d11fcfd056dbb3cefcb2d207da3a70f9a93222
|
diff --git a/test/test_bulk.py b/test/test_bulk.py
index <HASH>..<HASH> 100644
--- a/test/test_bulk.py
+++ b/test/test_bulk.py
@@ -902,20 +902,27 @@ class TestBulkWriteConcern(BulkTestBase):
OperationFailure,
batch.execute, {'fsync': True, 'j': True})
+ def test_j_without_journal(self):
+ client = self.coll.database.connection
+ if not server_started_with_option(client, '--nojournal', 'nojournal'):
+ raise SkipTest("Need mongod started with --nojournal")
+
+ # Using j=True without journaling is a hard failure.
+ batch = self.coll.initialize_ordered_bulk_op()
+ batch.insert({})
+ self.assertRaises(OperationFailure, batch.execute, {'j': True})
+
def test_write_concern_failure_ordered(self):
batch = self.coll.initialize_ordered_bulk_op()
batch.insert({'a': 1})
batch.insert({'a': 2})
- client = self.coll.database.connection
- # Using j=True without journaling is a hard failure.
- if server_started_with_option(client, '--nojournal', 'nojournal'):
- self.assertRaises(OperationFailure, batch.execute, {'j': True})
- # So is using w > 1 with no replication.
- elif not self.is_repl:
- self.assertRaises(BulkWriteError,
+ # Using w > 1 with no replication is a hard failure.
+ if not self.is_repl:
+ self.assertRaises(OperationFailure,
batch.execute, {'w': 5, 'wtimeout': 1})
+
# Replication wtimeout is a 'soft' error.
# It shouldn't stop batch processing.
else:
|
Bulk operations raise OperationFailure, not BulkWriteError, if write concern is invalid.
|
mongodb_mongo-python-driver
|
train
|
6f08e35834a353a817e2ca46f9a2f618cb98e6c5
|
diff --git a/lib/octocatalog-diff/util/parallel.rb b/lib/octocatalog-diff/util/parallel.rb
index <HASH>..<HASH> 100644
--- a/lib/octocatalog-diff/util/parallel.rb
+++ b/lib/octocatalog-diff/util/parallel.rb
@@ -11,6 +11,8 @@ module OctocatalogDiff
# If parallel processing has been disabled, this instead executes the tasks serially,
# but provides the same API as the parallel tasks.
class Parallel
+ BLOCK_SIZE = 1024 * 16
+
# This class is called for a task that didn't complete.
class IncompleteTask < RuntimeError; end
@@ -107,32 +109,55 @@ module OctocatalogDiff
# :nocov:
this_pid = fork do
reader.close
- logger.reopen
+ logger.reopen if logger.respond_to?(:reopen)
task_result = execute_task(task, logger)
writer.write YAML.dump(task_result)
+ writer.close
+ logger.close
exit 0
end
# :nocov:
- pidmap[this_pid] = { reader: reader, index: index, start_time: Time.now }
+ pidmap[this_pid] = { reader: reader, index: index, start_time: Time.now, result: [] }
writer.close
logger.debug "Launched pid=#{this_pid} for index=#{index}"
logger.reopen
end
while pidmap.any?
- this_pid, exit_obj = Process.wait2
- next unless pidmap.key?(this_pid)
+ # Read from all pipes
+ pidmap.each do |_this_pid, obj|
+ begin
+ buf = obj[:reader].read_nonblock(BLOCK_SIZE, buf)
+ obj[:result] << buf if buf
+ rescue IO::EAGAINWaitReadable, EOFError, Errno::EAGAIN # rubocop:disable Lint/ShadowedException
+ next
+ end
+ end
+
+ # Any exits?
+ this_pid, exit_obj = Process.wait2(0, Process::WNOHANG)
+ next unless this_pid && pidmap.key?(this_pid)
+ index = pidmap[this_pid][:index]
exitstatus = exit_obj.exitstatus
+ raise "PID=#{this_pid} exited abnormally: #{exit_obj.inspect}" if exitstatus.nil?
raise "PID=#{this_pid} exited with status #{exitstatus}" unless exitstatus.zero?
- logger.debug "PID=#{this_pid} completed task in #{Time.now - pidmap[this_pid][:start_time]} seconds"
- index = pidmap[this_pid][:index]
- result[index] = YAML.load(pidmap[this_pid][:reader].read)
- pidmap[this_pid][:reader].close
+ begin
+ buf = pidmap[this_pid][:reader].read_nonblock(BLOCK_SIZE, buf)
+ pidmap[this_pid][:result] << buf if buf
+ rescue IO::EAGAINWaitReadable, EOFError, Errno::EAGAIN # rubocop:disable Lint/ShadowedException
+ pidmap[this_pid][:reader].close
+ end
+
+ input = pidmap[this_pid][:result].join('')
+ logger.debug "PID=#{this_pid} completed in #{Time.now - pidmap[this_pid][:start_time]} seconds, #{input.length} bytes"
+
pidmap.delete(this_pid)
+ result[index] = YAML.load(input)
+
next if result[index].status
return result[index].exception
end
|
Implement non-blocking read and PID checking
|
github_octocatalog-diff
|
train
|
3f30b6aa3a4765fa2239d8276c257a768b9856e1
|
diff --git a/gitsuggest/commandline.py b/gitsuggest/commandline.py
index <HASH>..<HASH> 100644
--- a/gitsuggest/commandline.py
+++ b/gitsuggest/commandline.py
@@ -49,9 +49,14 @@ def main():
parser.print_help()
return
- password = getpass.getpass()
+ print('')
+ print('INFO: Authentication (with password) have higher rate limits.')
+ print('INFO: Skipping password might cause failure due to rate limit.')
+ print('')
- print("Generating suggestions...")
+ password = getpass.getpass('Password (to skip press enter):')
+
+ print('Generating suggestions...')
gs = GitSuggest(arguments.username, password)
repos = list(gs.get_suggested_repositories())
|
Making provision for passwordless suggestion procurement.
|
csurfer_gitsuggest
|
train
|
caa49ced5aca62a366dfc3768e737ebceb8fd0f0
|
diff --git a/.coveragerc b/.coveragerc
index <HASH>..<HASH> 100644
--- a/.coveragerc
+++ b/.coveragerc
@@ -1,3 +1,3 @@
[run]
branch = True
-omit = *mock*
+include = eventtracking*
diff --git a/eventtracking/tests/test_track.py b/eventtracking/tests/test_track.py
index <HASH>..<HASH> 100644
--- a/eventtracking/tests/test_track.py
+++ b/eventtracking/tests/test_track.py
@@ -1,6 +1,7 @@
"""
Test the event tracking module
"""
+from __future__ import absolute_import
from datetime import datetime
from unittest import TestCase
@@ -28,9 +29,9 @@ class TestTrack(TestCase): # pylint: disable=missing-docstring
def test_event_simple_event_without_data(self):
track.event(sentinel.event_type)
- self.__assert_backend_called_with(sentinel.event_type)
+ self.assert_backend_called_with(sentinel.event_type)
- def __assert_backend_called_with(self, event_type, data=None, backend=None):
+ def assert_backend_called_with(self, event_type, data=None, backend=None):
"""Ensures the backend is called exactly once with the expected data."""
if not backend:
backend = self._mock_backend
@@ -51,7 +52,7 @@ class TestTrack(TestCase): # pylint: disable=missing-docstring
}
)
- self.__assert_backend_called_with(
+ self.assert_backend_called_with(
sentinel.event_type,
{
sentinel.key: sentinel.value
@@ -64,8 +65,8 @@ class TestTrack(TestCase): # pylint: disable=missing-docstring
try:
track.event(sentinel.event_type)
- self.__assert_backend_called_with(sentinel.event_type)
- self.__assert_backend_called_with(
+ self.assert_backend_called_with(sentinel.event_type)
+ self.assert_backend_called_with(
sentinel.event_type, backend=another_backend)
finally:
track.BACKENDS.remove(another_backend)
@@ -78,7 +79,7 @@ class TestTrack(TestCase): # pylint: disable=missing-docstring
try:
track.event(sentinel.event_type)
- self.__assert_backend_called_with(
+ self.assert_backend_called_with(
sentinel.event_type, backend=another_backend)
finally:
track.BACKENDS.remove(another_backend)
diff --git a/eventtracking/track.py b/eventtracking/track.py
index <HASH>..<HASH> 100644
--- a/eventtracking/track.py
+++ b/eventtracking/track.py
@@ -3,16 +3,18 @@ Track application events. Supports persisting events to multiple backends.
Best Practices:
* It is recommended that event types are namespaced using dot notation to
- avoid naming collisions, similar to DNS names. For example:
- org.edx.video.stop, edu.mit.audio.stop
+ avoid naming collisions, similar to DNS names. For example:
+ org.edx.video.stop, edu.mit.audio.stop
* Avoid using event type names that may cause collisions. The burden is
- on the analyst to decide whether your event is equivalent to another
- and should be grouped accordingly etc.
+ on the analyst to decide whether your event is equivalent to another
+ and should be grouped accordingly etc.
* Do not emit events that you don't own. This could negatively impact
- the analysis of the event stream. If you suspect your event is
- equivalent to another, say so in your documenation, and the analyst
- can decide whether or not to group them.
+ the analysis of the event stream. If you suspect your event is
+ equivalent to another, say so in your documenation, and the analyst
+ can decide whether or not to group them.
"""
+from __future__ import absolute_import
+
from datetime import datetime
import logging
@@ -25,8 +27,9 @@ def event(event_type, data=None):
"""
Emit an event annotated with the UTC time when this function was called.
- :event_type: A unique identification string for an event that has already been registered.
- :data: A dictionary mapping field names to the value to include in the event. Note that all values provided must be serializable.
+ `event_type` is a unique identification string for an event that has already been registered.
+ `data` is a dictionary mapping field names to the value to include in the event.
+ Note that all values provided must be serializable.
"""
full_event = {
|
clean up some minor details
* Ensure "from future import __absolute__" is included in new files
* Clean up some doc strings
* Remove __ prefix from some internal test methods
|
edx_event-tracking
|
train
|
1751c43479f193ba9f76e33c299ff9d52d01561d
|
diff --git a/spec/metainspector_spec.rb b/spec/metainspector_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/metainspector_spec.rb
+++ b/spec/metainspector_spec.rb
@@ -332,7 +332,7 @@ describe MetaInspector do
describe "parsed?" do
it "should return true if we have a parsed document" do
- good = MetaInspector.new('https://www.w3clove.com')
+ good = MetaInspector.new('http://pagerankalert.com')
title = good.title
good.parsed?.should == true
|
update spec to use a mocked response
|
jaimeiniesta_metainspector
|
train
|
f4156b146c894724ac016f941b8414bbc0f9d33b
|
diff --git a/src/InfoViz/Native/ParallelCoordinates/index.js b/src/InfoViz/Native/ParallelCoordinates/index.js
index <HASH>..<HASH> 100644
--- a/src/InfoViz/Native/ParallelCoordinates/index.js
+++ b/src/InfoViz/Native/ParallelCoordinates/index.js
@@ -406,6 +406,7 @@ function parallelCoordinate(publicAPI, model) {
d3
.select(this)
.select('svg')
+ .attr('viewBox', d.legend.shape.viewBox)
.attr('fill', d.legend.color)
.attr('stroke', 'black')
.attr('width', glyphSize)
@@ -415,7 +416,7 @@ function parallelCoordinate(publicAPI, model) {
.select('use')
.classed(style.colorToFill, true) // Firefox SVG use color bug workaround fix
.classed(style.blackStroke, true)
- .attr('xlink:href', d.legend.shape);
+ .attr('xlink:href', `#${d.legend.shape.id}`);
});
// Augment the legend glyphs with extra DOM for annotated axes
|
fix(ParallelCoordinates): Expect new SVG loader behavior
|
Kitware_paraviewweb
|
train
|
ed59368c10052e022209c544584c8df95003b496
|
diff --git a/generators/entity-server/templates/src/main/java/package/service/_EntityQueryService.java b/generators/entity-server/templates/src/main/java/package/service/_EntityQueryService.java
index <HASH>..<HASH> 100644
--- a/generators/entity-server/templates/src/main/java/package/service/_EntityQueryService.java
+++ b/generators/entity-server/templates/src/main/java/package/service/_EntityQueryService.java
@@ -68,7 +68,6 @@ import <%=packageName%>.domain.enumeration.<%= fields[idx].fieldType %>;
public class <%= serviceClassName %> extends QueryService<<%= entityClass %>> {
private final Logger log = LoggerFactory.getLogger(<%= serviceClassName %>.class);
-
<%- include('../common/inject_template', {viaService: false, constructorName: serviceClassName, queryService: false}); -%>
/**
diff --git a/generators/entity-server/templates/src/main/java/package/service/_EntityService.java b/generators/entity-server/templates/src/main/java/package/service/_EntityService.java
index <HASH>..<HASH> 100644
--- a/generators/entity-server/templates/src/main/java/package/service/_EntityService.java
+++ b/generators/entity-server/templates/src/main/java/package/service/_EntityService.java
@@ -25,12 +25,15 @@ import <%=packageName%>.service.dto.<%= entityClass %>DTO;
import <%=packageName%>.domain.<%= entityClass %>;
<%_ } _%>
<%_ if (pagination !== 'no') { _%>
+
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
<%_ } _%>
+
<%_ if (pagination === 'no' || fieldsContainNoOwnerOneToOne === true) { _%>
import java.util.List;
<%_ } _%>
+import java.util.Optional;
/**
* Service Interface for managing <%= entityClass %>.
@@ -67,7 +70,7 @@ public interface <%= entityClass %>Service {
* @param id the id of the entity
* @return the entity
*/
- <%= instanceType %> findOne(<%= pkType %> id);
+ Optional<<%= instanceType %>> findOne(<%= pkType %> id);
/**
* Delete the "id" <%= entityInstance %>.
|
[WIP] migration to Spring Boot 2 - fix some DTO compilation issues
|
jhipster_generator-jhipster
|
train
|
e888b37e98a175162f3d293c0edfad5c8e3c7dcc
|
diff --git a/spec/helper-spec.js b/spec/helper-spec.js
index <HASH>..<HASH> 100644
--- a/spec/helper-spec.js
+++ b/spec/helper-spec.js
@@ -42,13 +42,7 @@ describe('linter helpers', function () {
await atom.workspace.open(somethingFile)
const textEditor = atom.workspace.getActiveTextEditor()
const range = helpers.rangeFromLineNumber(textEditor, 7)
- expect(range instanceof Array).toBe(true)
- expect(range[0] instanceof Array).toBe(true)
- expect(range[1] instanceof Array).toBe(true)
- expect(range[0][0]).toEqual(7)
- expect(range[0][1]).toEqual(0)
- expect(range[1][0]).toEqual(7)
- expect(range[1][1]).toEqual(2)
+ expect(range).toEqual([[7, 0], [7, 2]])
})
)
@@ -57,13 +51,7 @@ describe('linter helpers', function () {
await atom.workspace.open(somethingFile)
const textEditor = atom.workspace.getActiveTextEditor()
const range = helpers.rangeFromLineNumber(textEditor, 7, 4)
- expect(range instanceof Array).toBe(true)
- expect(range[0] instanceof Array).toBe(true)
- expect(range[1] instanceof Array).toBe(true)
- expect(range[0][0]).toEqual(7)
- expect(range[0][1]).toEqual(4)
- expect(range[1][0]).toEqual(7)
- expect(range[1][1]).toEqual(11)
+ expect(range).toEqual([[7, 4], [7, 11]])
})
)
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -12,11 +12,11 @@ import { exec, execNode } from 'sb-exec'
let NamedRegexp = null
export const FindCache = new Map()
-export function rangeFromLineNumber(textEditor: TextEditor, line: number, column: ?number): Range {
+export function rangeFromLineNumber(textEditor: TextEditor, line: ?number, column: ?number): Range {
Helpers.validateEditor(textEditor)
let lineNumber = line
- if (!Number.isFinite(lineNumber) || Number.isNaN(lineNumber) || lineNumber < 0) {
+ if (typeof lineNumber !== 'number' || !Number.isFinite(lineNumber) || lineNumber < 0) {
lineNumber = 0
}
@@ -38,8 +38,7 @@ export function rangeFromLineNumber(textEditor: TextEditor, line: number, column
let colEnd = lineLength
let colStart = columnGiven ? column : 0
- const rowText = buffer.lineForRow(lineNumber).substr(colStart)
- const match = Helpers.getWordRegexp(textEditor, [lineNumber, colStart]).exec(rowText)
+ const match = Helpers.getWordRegexp(textEditor, [lineNumber, colStart]).exec(lineText)
if (match) {
colEnd = colStart + match.index + match[0].length
if (!columnGiven) {
|
:art: Address reviewer's comments
|
steelbrain_atom-linter
|
train
|
3e24568822395ee94049b826e7a33b17cb49d9fd
|
diff --git a/cf/app_files/app_files.go b/cf/app_files/app_files.go
index <HASH>..<HASH> 100644
--- a/cf/app_files/app_files.go
+++ b/cf/app_files/app_files.go
@@ -131,25 +131,15 @@ func (appfiles ApplicationFiles) WalkAppFiles(dir string, onEachFile func(string
fileRelativePath, _ := filepath.Rel(dir, fullPath)
fileRelativeUnixPath := filepath.ToSlash(fileRelativePath)
- if cfIgnore.FileShouldBeIgnored(fileRelativeUnixPath) {
- if err == nil {
- if f.IsDir() {
- return filepath.SkipDir
- }
- }
-
- if runtime.GOOS == "windows" {
- fi, statErr := os.Lstat(`\\?\` + fullPath)
- if statErr != nil {
- return statErr
- }
+ if err != nil && runtime.GOOS == "windows" {
+ f, err = os.Lstat(`\\?\` + fullPath)
+ }
- if fi.IsDir() {
- return filepath.SkipDir
- }
+ if cfIgnore.FileShouldBeIgnored(fileRelativeUnixPath) {
+ if err == nil && f.IsDir() {
+ return filepath.SkipDir
}
-
- return err
+ return nil
}
if err != nil {
|
WalkAppFiles handles paths that exceed MAX_PATH
Previously WalkAppFiles handled the situation where a path was traversed
that exceeded Windows' MAX_PATH but was .cfignored.
With this change it handles the path even if the path is not .cfignored.
|
cloudfoundry_cli
|
train
|
d1b464300c45c271c16e3f9474a6d69624a7c6b0
|
diff --git a/scapy/volatile.py b/scapy/volatile.py
index <HASH>..<HASH> 100644
--- a/scapy/volatile.py
+++ b/scapy/volatile.py
@@ -75,13 +75,13 @@ class RandField(VolatileValue):
pass
class RandNum(RandField):
+ """Instances evaluate to random integers in selected range"""
min = 0
max = 0
def __init__(self, min, max):
self.min = min
self.max = max
def _fix(self):
- # XXX: replace with sth that guarantee unicity
return random.randrange(self.min, self.max+1)
class RandNumGamma(RandField):
@@ -105,43 +105,76 @@ class RandNumExpo(RandField):
def _fix(self):
return self.base+int(round(random.expovariate(self.lambd)))
-class RandSeq(RandNum):
+class RandDraw(RandNum):
+ """Instances evaluate to integer sampling without replacement from the given interval"""
def __init__(self, min, max):
self.seq = RandomSequence(min,max)
def _fix(self):
return self.seq.next()
-class RandByte(RandSeq):
+class RandByte(RandNum):
def __init__(self):
- RandSeq.__init__(self, 0, 2L**8-1)
+ RandNum.__init__(self, 0, 2L**8-1)
-class RandSByte(RandSeq):
+class RandSByte(RandNum):
def __init__(self):
- RandSeq.__init__(self, -2L**7, 2L**7-1)
+ RandNum.__init__(self, -2L**7, 2L**7-1)
-class RandShort(RandSeq):
+class RandShort(RandNum):
def __init__(self):
- RandSeq.__init__(self, 0, 2L**16-1)
+ RandNum.__init__(self, 0, 2L**16-1)
-class RandSShort(RandSeq):
+class RandSShort(RandNum):
def __init__(self):
- RandSeq.__init__(self, -2L**15, 2L**15-1)
+ RandNum.__init__(self, -2L**15, 2L**15-1)
-class RandInt(RandSeq):
+class RandInt(RandNum):
def __init__(self):
- RandSeq.__init__(self, 0, 2L**32-1)
+ RandNum.__init__(self, 0, 2L**32-1)
-class RandSInt(RandSeq):
+class RandSInt(RandNum):
def __init__(self):
- RandSeq.__init__(self, -2L**31, 2L**31-1)
+ RandNum.__init__(self, -2L**31, 2L**31-1)
-class RandLong(RandSeq):
+class RandLong(RandNum):
def __init__(self):
- RandSeq.__init__(self, 0, 2L**64-1)
+ RandNum.__init__(self, 0, 2L**64-1)
-class RandSLong(RandSeq):
+class RandSLong(RandNum):
def __init__(self):
- RandSeq.__init__(self, -2L**63, 2L**63-1)
+ RandNum.__init__(self, -2L**63, 2L**63-1)
+
+class RandDrawByte(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, 0, 2L**8-1)
+
+class RandDrawSByte(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, -2L**7, 2L**7-1)
+
+class RandDrawShort(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, 0, 2L**16-1)
+
+class RandDrawSShort(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, -2L**15, 2L**15-1)
+
+class RandDrawInt(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, 0, 2L**32-1)
+
+class RandDrawSInt(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, -2L**31, 2L**31-1)
+
+class RandDrawLong(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, 0, 2L**64-1)
+
+class RandDrawSLong(RandDraw):
+ def __init__(self):
+ RandDraw.__init__(self, -2L**63, 2L**63-1)
class RandChoice(RandField):
def __init__(self, *args):
|
WARNING: API changes. Rationalized random volatile objects naming.
RandDraw*: random draw from a set without replacement.
Guarantees that a name is not drawn twice
before all elements have been drawn.
Rand*: random draw from a set with replacement.
RandSing*: singular values from a set, drawn at random
with replacement.
|
secdev_scapy
|
train
|
4b802827527285b5fa4d164ec5b1da32e50c61bc
|
diff --git a/cassiopeia/__init__.py b/cassiopeia/__init__.py
index <HASH>..<HASH> 100644
--- a/cassiopeia/__init__.py
+++ b/cassiopeia/__init__.py
@@ -0,0 +1,2 @@
+from future import standard_library
+standard_library.install_aliases()
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -26,6 +26,8 @@ setup(
packages=find_packages(),
zip_safe=True,
install_requires=[
- "sqlalchemy"
+ "sqlalchemy",
+ "future==0.15.2",
+ "enum34==1.1.1",
]
)
|
add python <I> patching and reqs
|
meraki-analytics_cassiopeia
|
train
|
fa16e464aff70da1db679aaea5bacd476313cd43
|
diff --git a/chef/lib/chef/provider/package.rb b/chef/lib/chef/provider/package.rb
index <HASH>..<HASH> 100644
--- a/chef/lib/chef/provider/package.rb
+++ b/chef/lib/chef/provider/package.rb
@@ -71,7 +71,7 @@ class Chef
def action_upgrade
if @current_resource.version != @candidate_version
- if @current_resource.version =~ //
+ if @current_resource.version == nil
@current_resource.version("uninstalled")
end
Chef::Log.info("Upgrading #{@new_resource} version from #{@current_resource.version} to #{@candidate_version}")
|
chef-<I> if package version is nil, set to uninstalled for log message
|
chef_chef
|
train
|
c05f2f763bae8d66a4a460ecf702fcf22e3d605b
|
diff --git a/lang/en/chat.php b/lang/en/chat.php
index <HASH>..<HASH> 100644
--- a/lang/en/chat.php
+++ b/lang/en/chat.php
@@ -12,6 +12,7 @@ $string['chatreport'] = "Chat sessions";
$string['currentchats'] = "Active chat sessions";
$string['currentusers'] = "Current users";
$string['enterchat'] = "Click here to enter the chat";
+$string['errornousers'] = "Could not find any users!";
$string['idle'] = "Idle";
$string['messagebeepseveryone'] = "\$a beeps everyone!";
$string['messagebeepsyou'] = "\$a has just beeped you!";
diff --git a/mod/chat/users.php b/mod/chat/users.php
index <HASH>..<HASH> 100644
--- a/mod/chat/users.php
+++ b/mod/chat/users.php
@@ -53,13 +53,6 @@ if (isset($_GET['beep'])) {
chat_delete_old_users();
-
-/// Get list of users
-
-if (!$chatusers = chat_get_users($chatuser->chatid)) {
- error("Could not find any users!");
-}
-
/// Print headers
@@ -85,6 +78,14 @@ $str->mins = get_string("mins");
$str->sec = get_string("sec");
$str->secs = get_string("secs");
+/// Get list of users
+
+if (!$chatusers = chat_get_users($chatuser->chatid)) {
+ print_string("errornousers");
+ exit;
+}
+
+
echo "<table width=\"100%\">";
foreach ($chatusers as $chatuser) {
$lastping = $timenow - $chatuser->lastmessageping;
|
Slightly more robust in case it can't find users. See bug <I>.
|
moodle_moodle
|
train
|
0aafd19134c44edaff8e27c8f82baab53f5ac7e9
|
diff --git a/specs/error.js b/specs/error.js
index <HASH>..<HASH> 100644
--- a/specs/error.js
+++ b/specs/error.js
@@ -20,6 +20,8 @@
'use strict';
+module.exports = SpecError;
+
function SpecError(message) {
var error = new Error(message);
error.context = [];
|
Fix missing exports for SpecError
This needs to be followed-up with test coverage.
|
uber-archive_thriftify
|
train
|
860e9590be6ff1aad968b3606686b8fe19a5084e
|
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index <HASH>..<HASH> 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -23,6 +23,7 @@ Changed
~~~~~~~
- Update translations
- Add traceback stack to DB logs with no Exception
+- Set max_page of 1000 for API and default page size to 25
Fixed
~~~~~
diff --git a/trionyx/api/pagination.py b/trionyx/api/pagination.py
index <HASH>..<HASH> 100644
--- a/trionyx/api/pagination.py
+++ b/trionyx/api/pagination.py
@@ -14,6 +14,8 @@ from rest_framework.pagination import PageNumberPagination as RestPageNumberPagi
class PageNumberPagination(RestPageNumberPagination):
"""Api Pagination class"""
+ max_page_size = 1000
+
def get_paginated_response(self, data):
"""Get paginated response, added extra fields"""
return Response(OrderedDict([
diff --git a/trionyx/settings.py b/trionyx/settings.py
index <HASH>..<HASH> 100644
--- a/trionyx/settings.py
+++ b/trionyx/settings.py
@@ -287,7 +287,7 @@ REST_FRAMEWORK = {
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'trionyx.api.pagination.PageNumberPagination',
- 'PAGE_SIZE': 20,
+ 'PAGE_SIZE': 25,
}
# ==============================================================================
|
[TASK] Set max_page of <I> for API and default page size to <I>
|
krukas_Trionyx
|
train
|
4176eb589f8817080691aacc6f67933362e94652
|
diff --git a/plaso/frontend/log2timeline.py b/plaso/frontend/log2timeline.py
index <HASH>..<HASH> 100755
--- a/plaso/frontend/log2timeline.py
+++ b/plaso/frontend/log2timeline.py
@@ -311,8 +311,9 @@ def Main():
print e
sys.exit(1)
+ print 'Sector size: {}'.format(partition_map[0])
print u'Index {:10s} {:10s} {}'.format('Offset', 'Length', 'Description')
- for entry in partition_map:
+ for entry in partition_map[1:]:
print u'{:02d}: {:010d} {:010d} {}'.format(
entry['address'], entry['offset'], entry['length'],
entry['description'])
@@ -361,7 +362,8 @@ def Main():
partition_map = pfile.FilesystemCache.PartitionMap(options.filename)
offset = 0
options.image = True
- for entry in partition_map:
+ options.bytes_per_sector = partition_map[0]
+ for entry in partition_map[1:]:
if options.partition_number == entry['address']:
offset = entry['offset']
break
diff --git a/plaso/lib/collector_filter.py b/plaso/lib/collector_filter.py
index <HASH>..<HASH> 100644
--- a/plaso/lib/collector_filter.py
+++ b/plaso/lib/collector_filter.py
@@ -94,12 +94,12 @@ class CollectionFilter(object):
yield fh.pathspec_root.ToProtoString()
except errors.PreProcessFail as e:
logging.warning(
- u'Unable to parse filter: {}|{} - path not found [{}].'.format(
+ u'Unable to parse filter: {}/{} - path not found [{}].'.format(
filter_path, filter_file, e))
continue
except sre_constants.error:
logging.warning(
- (u'Unable to parse the filter: {}|{} - illegal regular '
+ (u'Unable to parse the filter: {}/{} - illegal regular '
'expression.').format(filter_path, filter_file))
continue
diff --git a/plaso/lib/pfile.py b/plaso/lib/pfile.py
index <HASH>..<HASH> 100644
--- a/plaso/lib/pfile.py
+++ b/plaso/lib/pfile.py
@@ -98,6 +98,9 @@ class FilesystemCache(object):
raise errors.UnableToOpenFilesystem(
u'Unable to open the disk image [%s]' % path)
+ block_size = getattr(volume.info, 'block_size', 512)
+ partition_map.append(block_size)
+
for part in volume:
partition_map.append({
'address': part.addr,
diff --git a/plaso/registry/userassist.py b/plaso/registry/userassist.py
index <HASH>..<HASH> 100644
--- a/plaso/registry/userassist.py
+++ b/plaso/registry/userassist.py
@@ -87,7 +87,7 @@ class UserAssistPlugin(win_registry_interface.KeyPlugin):
try:
value_name = value.name.decode('rot-13')
except UnicodeEncodeError as e:
- logging.warning(
+ logging.debug(
(u'Unable to decode UserAssist string in whole (piecewise '
'decoding instead): {0:s} - [{1!s}]').format(value.name, e))
|
Code review: <I>: Minor cosmetic changes, adding sector to partition map, logging level changes.
|
log2timeline_plaso
|
train
|
877c46262873ac14d2231c848000e4a17c80b595
|
diff --git a/lib/fluent/plugin/in_kubernetes_objects.rb b/lib/fluent/plugin/in_kubernetes_objects.rb
index <HASH>..<HASH> 100644
--- a/lib/fluent/plugin/in_kubernetes_objects.rb
+++ b/lib/fluent/plugin/in_kubernetes_objects.rb
@@ -72,9 +72,6 @@ module Fluent::Plugin
desc 'A selector to restrict the list of returned objects by fields.'
config_param :field_selector, :string, default: nil
-
- desc 'The interval at which the objects will be watched.'
- config_param :interval, :time, default: 15 * 60
end
config_section :storage do
@@ -102,7 +99,6 @@ module Fluent::Plugin
end
def close
- @watchers.each &:finish if @watchers
super
end
@@ -118,6 +114,21 @@ module Fluent::Plugin
[@tag_prefix, item_name, @tag_suffix].join
end
+ def init_with_kubeconfig()
+ options = {}
+ config = Kubeclient::Config.read @kubeconfig
+ current_context = config.context
+
+ @client = Kubeclient::Client.new(
+ current_context.api_endpoint,
+ current_context.api_version,
+ options.merge(
+ ssl_options: current_context.ssl_options,
+ auth_options: current_context.auth_options
+ )
+ )
+ end
+
def initialize_client
# mostly borrowed from Fluentd Kubernetes Metadata Filter Plugin
if @kubernetes_url.nil?
@@ -173,16 +184,7 @@ module Fluent::Plugin
end
def start_watchers
- @watchers = @watch_objects.map do |o|
- o = o.to_h.dup
- o[:as] = :raw
- resource_name = o.delete(:resource_name)
- watch_interval = o.delete(:interval)
-
- version = @storage.get(resource_name)
- o[:resource_version] = version if version
- create_watcher_thread resource_name, o, watch_interval
- end
+ @watch_objects.each(&method(:create_watcher_thread))
end
def create_pull_thread(conf)
@@ -225,19 +227,35 @@ module Fluent::Plugin
end
end
- def create_watcher_thread(object_name, watcher, interval)
- thread_create(:"watch_#{object_name}") do
- @client.public_send("watch_#{object_name}", watcher).tap { |watcher|
- tag = generate_tag "#{object_name}.watch"
- watcher.each do |entity|
- log.trace { "Received new object from watching #{object_name}" }
- entity = JSON.parse(entity)
- router.emit tag, Fluent::Engine.now, entity
- @storage.put object_name, entity['object']['metadata']['resourceVersion']
- sleep(interval)
+ def create_watcher_thread(conf)
+ options = conf.to_h.dup
+ options[:as] = :raw
+ resource_name = options[:resource_name]
+ version = @storage.get(resource_name)
+ if version
+ options[:resource_version] = version
+ else
+ options[:resource_version] = 0
+ end
+
+ thread_create :"watch_#{resource_name}" do
+ while thread_current_running?
+ @client.public_send("watch_#{resource_name}", options).tap do |watcher|
+ tag = generate_tag "#{resource_name}"
+ watcher.each do |entity|
+ begin
+ entity = JSON.parse(entity)
+ router.emit tag, Fluent::Engine.now, entity
+ options[:resource_version] = entity['object']['metadata']['resourceVersion']
+ @storage.put resource_name, entity['object']['metadata']['resourceVersion']
+ rescue => e
+ log.info "Got exception #{e} parsing entity #{entity}. Resetting watcher."
+ end
+ end
end
- }
+ end
end
end
end
end
+
diff --git a/test/fluent/plugin/in_kubernetes_objects_test.rb b/test/fluent/plugin/in_kubernetes_objects_test.rb
index <HASH>..<HASH> 100644
--- a/test/fluent/plugin/in_kubernetes_objects_test.rb
+++ b/test/fluent/plugin/in_kubernetes_objects_test.rb
@@ -109,9 +109,12 @@ describe Fluent::Plugin::KubernetesObjectsInput do
</watch>
CONF
+ stub_k8s_events params: {resourceVersion: "0"}
+ stub_k8s_events params: {resourceVersion: "6621683"}
+
d.run expect_emits: 1, timeout: 3
events = d.events
- expect(events.all? { |e| e[0] == 'kubernetes.events.watch'}).must_equal true
+ expect(events.all? { |e| e[0] == 'kubernetes.events'}).must_equal true
end
it "should use checkpoints for watching" do
@@ -133,6 +136,7 @@ describe Fluent::Plugin::KubernetesObjectsInput do
CONF
stub_k8s_events params: {resourceVersion: "123456"}
+ stub_k8s_events params: {resourceVersion: "6621683"}
d.run expect_emits: 1, timeout: 3
ensure
|
watcher fix (#<I>)
|
splunk_fluent-plugin-kubernetes-objects
|
train
|
90c0445423ea4991c4e8dcc8d37d87be4bac3067
|
diff --git a/connection.js b/connection.js
index <HASH>..<HASH> 100644
--- a/connection.js
+++ b/connection.js
@@ -1266,6 +1266,18 @@ Connection.prototype.auth_results = function(message) {
return header;
};
+Connection.prototype.auth_results_clean = function(conn) {
+ // http://tools.ietf.org/html/draft-kucherawy-original-authres-00.html
+ var ars = conn.transaction.header.get_all('Authentication-Results');
+ if ( ars.length === 0 ) { return; };
+
+ for (var i=0; i < ars.length; i++) {
+ conn.transaction.header.remove_header( ars[i] );
+ conn.transaction.header.add_header('Original-Authentication-Results', ars[i] );
+ }
+ conn.loginfo("Authentication-Results moved to Original-Authentication-Results" );
+};
+
Connection.prototype.cmd_data = function(args) {
// RFC 5321 Section 4.3.2
// DATA does not accept arguments
@@ -1280,6 +1292,7 @@ Connection.prototype.cmd_data = function(args) {
}
this.accumulate_data('Received: ' + this.received_line() + "\r\n");
+ this.auth_results_clean(this);
this.transaction.add_header('Authentication-Results', this.auth_results() );
plugins.run_hooks('data', this);
};
|
move old Auth-Results to Original-Auth-Results
|
haraka_Haraka
|
train
|
2d82fa94eb42e8d7b7dee59e08252dc65562131e
|
diff --git a/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/MultiCriteriaLabelSetting.java b/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/MultiCriteriaLabelSetting.java
index <HASH>..<HASH> 100644
--- a/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/MultiCriteriaLabelSetting.java
+++ b/reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/MultiCriteriaLabelSetting.java
@@ -35,6 +35,7 @@ import java.util.stream.StreamSupport;
*
* @author Michael Zilske
* @author Peter Karich
+ * @author Wesam Herbawi
*/
class MultiCriteriaLabelSetting {
|
Add a contributor to JavaDoc
|
graphhopper_graphhopper
|
train
|
2cf76b236556b37ffa351a21ed401f8a5caac260
|
diff --git a/xhr.js b/xhr.js
index <HASH>..<HASH> 100644
--- a/xhr.js
+++ b/xhr.js
@@ -34,7 +34,7 @@ function request(method, url, params, callback, headers, opts) {
if (onBeforeUnloadFired) { return }
var text = xhr.responseText,
isJson = xhr.getResponseHeader('Content-Type') == 'application/json'
- if (xhr.status == 200) {
+ if (xhr.status == 200 || xhr.status == 204) {
result = isJson ? json.parse(text) : text
} else {
try { err = isJson ? json.parse(text) : new Error(text) }
|
Accept <I> responses as successes
|
marcuswestin_std.js
|
train
|
877faa76aad73e17e542cedb8bbdcde6762ec738
|
diff --git a/lib/json-dry.js b/lib/json-dry.js
index <HASH>..<HASH> 100644
--- a/lib/json-dry.js
+++ b/lib/json-dry.js
@@ -186,4 +186,8 @@ function parseRecursion(text, reviver) {
}
this.stringify = stringifyRecursion;
-this.parse = parseRecursion;
\ No newline at end of file
+this.parse = parseRecursion;
+
+this.info = {
+ path: require.main.filename
+};
\ No newline at end of file
|
Add path of json-dry file to the export
|
skerit_json-dry
|
train
|
8d1b574d147ff7da4354e4a9eee4e50bc7beaa33
|
diff --git a/tests/Doctrine/MongoDB/Tests/CollectionTest.php b/tests/Doctrine/MongoDB/Tests/CollectionTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/MongoDB/Tests/CollectionTest.php
+++ b/tests/Doctrine/MongoDB/Tests/CollectionTest.php
@@ -54,22 +54,17 @@ class CollectionTest extends \PHPUnit_Framework_TestCase
}
/**
- * @expectedException \RuntimeException
- * @expectedExceptionMessage foo
+ * @expectedException \Doctrine\MongoDB\Exception\ResultException
*/
public function testAggregateShouldThrowExceptionOnError()
{
- $pipeline = array(array('$invalidOp' => true));
-
$database = $this->getMockDatabase();
$database->expects($this->once())
->method('command')
- ->with(array('aggregate' => self::collectionName, 'pipeline' => $pipeline))
- ->will($this->returnValue(array('ok' => 0, 'errmsg' => 'foo')));
+ ->will($this->returnValue(array('ok' => 0)));
$coll = $this->getTestCollection($this->getMockConnection(), $this->getMockMongoCollection(), $database);
-
- $result = $coll->aggregate($pipeline);
+ $coll->aggregate(array());
}
public function testBatchInsert()
@@ -226,7 +221,7 @@ class CollectionTest extends \PHPUnit_Framework_TestCase
$database->expects($this->once())
->method('command')
->with($command)
- ->will($this->returnValue(array('value' => $document)));
+ ->will($this->returnValue(array('ok' => 1, 'value' => $document)));
$coll = $this->getTestCollection($this->getMockConnection(), $this->getMockMongoCollection(), $database);
@@ -252,7 +247,7 @@ class CollectionTest extends \PHPUnit_Framework_TestCase
$database->expects($this->once())
->method('command')
->with($command)
- ->will($this->returnValue(array('value' => $document)));
+ ->will($this->returnValue(array('ok' => 1, 'value' => $document)));
$coll = $this->getTestCollection($this->getMockConnection(), $this->getMockMongoCollection(), $database);
@@ -492,6 +487,20 @@ class CollectionTest extends \PHPUnit_Framework_TestCase
}
/**
+ * @expectedException \Doctrine\MongoDB\Exception\ResultException
+ */
+ public function testMapReduceShouldThrowExceptionOnError()
+ {
+ $database = $this->getMockDatabase();
+ $database->expects($this->once())
+ ->method('command')
+ ->will($this->returnValue(array('ok' => 0)));
+
+ $coll = $this->getTestCollection($this->getMockConnection(), $this->getMockMongoCollection(), $database);
+ $coll->mapReduce('', '');
+ }
+
+ /**
* @dataProvider providePoint
*/
public function testNearWithGeoJsonPoint($point, array $expected)
|
Add "ok" field to mocked command return values
|
doctrine_mongodb
|
train
|
1960b0d378270098d37aab223ff29237fa0b0372
|
diff --git a/addon/search/searchcursor.js b/addon/search/searchcursor.js
index <HASH>..<HASH> 100644
--- a/addon/search/searchcursor.js
+++ b/addon/search/searchcursor.js
@@ -40,15 +40,21 @@
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
- if (target.length == 1)
- this.matches = function(reverse, pos) {
- var line = fold(cm.getLine(pos.line)), len = query.length, match;
- if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
- : (match = line.indexOf(query, pos.ch)) != -1)
- return {from: {line: pos.line, ch: match},
- to: {line: pos.line, ch: match + len}};
- };
- else
+ if (target.length == 1) {
+ if (!query.length) {
+ // Empty string would match anything and never progress, so
+ // we define it to match nothing instead.
+ this.matches = function() {};
+ } else {
+ this.matches = function(reverse, pos) {
+ var line = fold(cm.getLine(pos.line)), len = query.length, match;
+ if (reverse ? (pos.ch >= len && (match = line.lastIndexOf(query, pos.ch - len)) != -1)
+ : (match = line.indexOf(query, pos.ch)) != -1)
+ return {from: {line: pos.line, ch: match},
+ to: {line: pos.line, ch: match + len}};
+ };
+ }
+ } else {
this.matches = function(reverse, pos) {
var ln = pos.line, idx = (reverse ? target.length - 1 : 0), match = target[idx], line = fold(cm.getLine(ln));
var offsetA = (reverse ? line.indexOf(match) + match.length : line.lastIndexOf(match));
@@ -70,6 +76,7 @@
return {from: reverse ? end : start, to: reverse ? start : end};
}
};
+ }
}
}
|
Guard against search cursors with a query of ""
They'd exhibit the same infinite traversal behavior mentioned in
#<I>
|
codemirror_CodeMirror
|
train
|
36efa8c1003d53d4789f954a6121c984d2d2596f
|
diff --git a/hamper/plugins/help.py b/hamper/plugins/help.py
index <HASH>..<HASH> 100644
--- a/hamper/plugins/help.py
+++ b/hamper/plugins/help.py
@@ -47,7 +47,7 @@ class Help(ChatCommandPlugin):
response.append('{0.short_desc}'.format(command))
response = '\n'.join(response)
- bot.reply(comm, response)
+ bot.msg(comm['user'], response)
class HelpCommand(Command):
name = 'help.individual'
|
PM result of help command to the user
|
hamperbot_hamper
|
train
|
3fb8c34767a7a167fa12bae820da2efc50a740f8
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@ with open('README.md') as f:
readme = f.read()
setup(name='python-meteor',
- version='0.1.0',
+ version='0.1.1',
description='An event driven meteor client',
long_description=readme,
license='MIT',
@@ -25,7 +25,6 @@ setup(name='python-meteor',
],
py_modules=['MeteorClient'],
install_requires=[
- 'python-ddp',
- 'hashlib'
+ 'python-ddp'
],
)
\ No newline at end of file
|
hashblib was added to python in <I>
|
hharnisc_python-meteor
|
train
|
9aab96f2d36ce547587170169a138c0f7e8ce963
|
diff --git a/grunt.js b/grunt.js
index <HASH>..<HASH> 100644
--- a/grunt.js
+++ b/grunt.js
@@ -25,7 +25,7 @@ module.exports = function (grunt) {
},
concat: {
build: {
- src: ['<banner:meta.banner>'],
+ src: ['<banner:meta.banner>', 'common/*.js'],
dest: '<%= builddir %>/<%= pkg.name %>.js'
},
ieshiv: {
@@ -74,7 +74,7 @@ module.exports = function (grunt) {
grunt.registerTask('build', 'build all or some of the angular-ui modules', function () {
var jsBuildFiles = grunt.config('concat.build.src');
- var lessBuildFiles = grunt.config('recess.build.src');
+ var lessBuildFiles = [];
if (this.args.length > 0) {
@@ -92,8 +92,8 @@ module.exports = function (grunt) {
grunt.config('recess.build.src', lessBuildFiles);
} else {
- grunt.config('concat.build.src', jsBuildFiles.concat(['common/*.js', 'modules/*/*/*.js']));
- grunt.config('recess.build.src', lessBuildFiles.concat(['common/**/*.less']));
+ grunt.config('concat.build.src', jsBuildFiles.concat(['modules/*/*/*.js']));
+ grunt.config('recess.build.src', lessBuildFiles.concat(grunt.config('recess.build.src')));
}
grunt.task.run('concat min recess:build recess:min');
|
Fix merge of the issue<I>
|
angular-ui_ui-select2
|
train
|
ec6d3e68137070e644d20a664ca39919ec99bb59
|
diff --git a/org.jenetics/src/main/java/org/jenetics/Chromosome.java b/org.jenetics/src/main/java/org/jenetics/Chromosome.java
index <HASH>..<HASH> 100644
--- a/org.jenetics/src/main/java/org/jenetics/Chromosome.java
+++ b/org.jenetics/src/main/java/org/jenetics/Chromosome.java
@@ -20,6 +20,7 @@
package org.jenetics;
import java.io.Serializable;
+import java.util.stream.Collector;
import org.jenetics.util.Factory;
import org.jenetics.util.ISeq;
@@ -29,12 +30,16 @@ import org.jenetics.util.Verifiable;
* A chromosome consists of one or more genes. It also provides a factory
* method for creating new, random chromosome instances of the same type and the
* same constraint.
+ * <p>
+ * <span class="simpleTagLabel">API Note: </span>
+ * Implementations of the {@code Chromosome} interface must be <em>immutable</em>
+ * and guarantee an efficient random access ({@code O(1)}) to the genes.
*
* @see <a href="http://en.wikipedia.org/wiki/Chromosome">Wikipdida: Chromosome</a>
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.0
- * @version 2.0 — <em>$Date: 2014-12-07 $</em>
+ * @version 2.0 — <em>$Date: 2014-12-12 $</em>
*/
public interface Chromosome<G extends Gene<?, G>>
extends
|
Add implementation hints in API notes.
|
jenetics_jenetics
|
train
|
5b4402cce01286577947605687a00dbf1741834c
|
diff --git a/azurerm/config.go b/azurerm/config.go
index <HASH>..<HASH> 100644
--- a/azurerm/config.go
+++ b/azurerm/config.go
@@ -90,23 +90,6 @@ type ArmClient struct {
// Services
// NOTE: all new services should be Public as they're going to be relocated in the near-future
- DataBricks *databricks.Client
- DataFactory *datafactory.Client
- Datalake *datalake.Client
- DevSpace *devspace.Client
- DevTestLabs *devtestlabs.Client
- Dns *dns.Client
- EventGrid *eventgrid.Client
- Eventhub *eventhub.Client
- Frontdoor *frontdoor.Client
- Graph *graph.Client
- HDInsight *hdinsight.Client
- Healthcare *healthcare.Client
- IoTHub *iothub.Client
- KeyVault *keyvault.Client
- Kusto *kusto.Client
- LogAnalytics *loganalytics.Client
- Logic *logic.Client
ManagementGroups *managementgroup.Client
Maps *maps.Client
MariaDB *mariadb.Client
diff --git a/azurerm/internal/clients/client.go b/azurerm/internal/clients/client.go
index <HASH>..<HASH> 100644
--- a/azurerm/internal/clients/client.go
+++ b/azurerm/internal/clients/client.go
@@ -14,6 +14,23 @@ import (
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/cognitive"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/containers"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/cosmos"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/databricks"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/datafactory"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/datalake"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/devspace"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/devtestlabs"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/dns"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventgrid"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/eventhub"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/frontdoor"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/graph"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/hdinsight"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/healthcare"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/iothub"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/keyvault"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/kusto"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/loganalytics"
+ "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/logic"
)
type Client struct {
@@ -32,4 +49,21 @@ type Client struct {
Containers *containers.Client
Cosmos *cosmos.Client
Compute *ComputeClient
+ DataBricks *databricks.Client
+ DataFactory *datafactory.Client
+ Datalake *datalake.Client
+ DevSpace *devspace.Client
+ DevTestLabs *devtestlabs.Client
+ Dns *dns.Client
+ EventGrid *eventgrid.Client
+ Eventhub *eventhub.Client
+ Frontdoor *frontdoor.Client
+ Graph *graph.Client
+ HDInsight *hdinsight.Client
+ Healthcare *healthcare.Client
+ IoTHub *iothub.Client
+ KeyVault *keyvault.Client
+ Kusto *kusto.Client
+ LogAnalytics *loganalytics.Client
+ Logic *logic.Client
}
|
refactor: moving clients up a level
|
terraform-providers_terraform-provider-azurerm
|
train
|
d0946bdc381bb920de84748131c43ef4c99840a6
|
diff --git a/experiments/nips2015-model-selection.py b/experiments/nips2015-model-selection.py
index <HASH>..<HASH> 100755
--- a/experiments/nips2015-model-selection.py
+++ b/experiments/nips2015-model-selection.py
@@ -78,7 +78,7 @@ parser.add_argument(
parser.add_argument(
"--training-epochs",
- default=100,
+ default=200,
type=int,
help="Number of passes over the dataset to perform during model fitting")
@@ -105,7 +105,7 @@ def kfold_cross_validation_for_single_allele(
n_training_epochs=100,
cv_folds=5,
max_ic50=5000,
- minibatch_size=128):
+ minibatch_size=512):
"""
Estimate the per-allele AUC score of a model via k-fold cross-validation.
Returns the per-fold AUC scores and accuracies.
@@ -287,6 +287,7 @@ def leave_out_allele_cross_validation(
("auc", aucs),
("accuracy", accuracies),
("f1", f1_scores)]:
+ print(name, values)
result_dict["%s_mean" % name].append(np.mean(values))
result_dict["%s_median" % name].append(np.median(values))
result_dict["%s_std" % name].append(np.std(values))
|
use bigger batches for more epochs
|
openvax_mhcflurry
|
train
|
5ba68ccf952646dfe34840c7b6e0bc0565ef8334
|
diff --git a/generator.go b/generator.go
index <HASH>..<HASH> 100644
--- a/generator.go
+++ b/generator.go
@@ -40,11 +40,15 @@ func (g *GifGenerator) Generate(input string, output string) (err error) {
// play and capture
var (
- images []*image.Paletted
- delays []int
+ images []*image.Paletted
+ delays []int
+ ttyTime int64
+ gifTime int64
)
err = g.TtyPlay(input, vt, func(diff int32) (err error) {
- delay := int(float64(diff)/g.Speed) / 10000
+ ttyTime += int64(float64(diff) / g.Speed)
+ delay := int((ttyTime-gifTime)/10000/10) * 10
+ gifTime += int64(delay) * 10000
if delay > 0 {
var img *image.Paletted
img, err = g.Capture(&state)
|
chage: calc delay time
|
sugyan_ttyrec2gif
|
train
|
a48d0b0373318b24131830c2a20bebc1d311c53b
|
diff --git a/src/components/VAutocomplete/VAutocomplete.js b/src/components/VAutocomplete/VAutocomplete.js
index <HASH>..<HASH> 100644
--- a/src/components/VAutocomplete/VAutocomplete.js
+++ b/src/components/VAutocomplete/VAutocomplete.js
@@ -23,7 +23,6 @@ export default {
type: String,
default: 'off'
},
- delimiters: Array,
filter: {
type: Function,
default: (item, queryText, itemText) => {
diff --git a/src/components/VCombobox/VCombobox.js b/src/components/VCombobox/VCombobox.js
index <HASH>..<HASH> 100755
--- a/src/components/VCombobox/VCombobox.js
+++ b/src/components/VCombobox/VCombobox.js
@@ -15,6 +15,10 @@ export default {
extends: VAutocomplete,
props: {
+ delimiters: {
+ type: Array,
+ default: () => ([])
+ },
returnObject: {
type: Boolean,
default: true
|
refactor(v-autocomplete/combobox): move prop
delimiters isn't used in `v-autocomplete` anymore
|
vuetifyjs_vuetify
|
train
|
cd2889e370a6ffac0696ff25d5e849a9df0120f8
|
diff --git a/packages/wxa-cli/src/resolvers/ast/index.js b/packages/wxa-cli/src/resolvers/ast/index.js
index <HASH>..<HASH> 100644
--- a/packages/wxa-cli/src/resolvers/ast/index.js
+++ b/packages/wxa-cli/src/resolvers/ast/index.js
@@ -9,6 +9,12 @@ import {generateCodeFromAST} from '../../compilers/script';
let debug = debugPKG('WXA:ASTManager');
+const isStaticSource = (filepath) => {
+ let ext = path.extname(filepath);
+
+ return ~['png','jpg','jpeg','webp','eot','woff','woff2','ttf','file', 'gif','webm', 'mp3', 'mp4'].indexOf(ext.replace(/^\./, ''));
+}
+
export default class ASTManager {
constructor(resolve, meta, wxaConfigs) {
this.resolve = resolve;
@@ -136,6 +142,12 @@ export default class ASTManager {
source, outputPath, resolved,
},
});
+
+ // Allow use import to add static file to project
+ if (isStaticSource(source)) {
+ path.remove();
+ return;
+ }
switch (typeOfPath) {
case StringLiteralRequire:
|
feat(cli): Allow use import declaration to add static file to project
re #<I>
|
wxajs_wxa
|
train
|
6b9d90a8973d75268174915d42f7b52f524dc2ff
|
diff --git a/ipywidgets/widgets/interaction.py b/ipywidgets/widgets/interaction.py
index <HASH>..<HASH> 100644
--- a/ipywidgets/widgets/interaction.py
+++ b/ipywidgets/widgets/interaction.py
@@ -208,12 +208,12 @@ class interactive(VBox):
if self.manual:
self.manual_button.disabled = True
try:
- for widget in self.kwargs_widgets:
- value = widget.get_interact_value()
- self.kwargs[widget._kwarg] = value
with self.out:
if self.clear_output:
clear_output(wait=True)
+ for widget in self.kwargs_widgets:
+ value = widget.get_interact_value()
+ self.kwargs[widget._kwarg] = value
self.result = self.f(**self.kwargs)
if self.auto_display and self.result is not None:
display(self.result)
|
Call get_interact_value inside "with out" block
This way, exceptions raised by get_interact_value() will be shown in
the output area
|
jupyter-widgets_ipywidgets
|
train
|
f68ab29fc88e353d8bf433f42be371583e99e16a
|
diff --git a/sustain/src/main/java/net/happyonroad/component/container/support/DefaultComponentResolver.java b/sustain/src/main/java/net/happyonroad/component/container/support/DefaultComponentResolver.java
index <HASH>..<HASH> 100644
--- a/sustain/src/main/java/net/happyonroad/component/container/support/DefaultComponentResolver.java
+++ b/sustain/src/main/java/net/happyonroad/component/container/support/DefaultComponentResolver.java
@@ -90,15 +90,28 @@ public class DefaultComponentResolver implements ComponentResolver {
component.validate();
//把各个解析出来的组件存储到仓库中,因为在解析 sub module时,其reference parent时会需要
repository.addComponent(component);
+ //处理 dependency management scope = import的dependency(需要merge)
+ DependencyManagement dm = component.getDependencyManagement();
+ if( !dm.isEmpty() ){
+ //TO avoid concurrent modifications
+ List<Dependency> dependencies = new ArrayList<Dependency>(dm.getDependencies());
+ for(Dependency d : dependencies){
+ d.interpolate(component);
+ if( "import".equalsIgnoreCase(d.getScope())){
+ Component importing = repository.resolveComponent(d);
+ dm.merge(importing.getDependencyManagement());
+ }
+ }
+ }
//解析Parent信息
parent = processParent(dependency, component, parent);
//解析组件的基本动态属性,放在parent解析之后,这样可以获取到parent的属性
component.interpolate();
if( parent != null )
- component.getDependencyManagement().merge(parent.getDependencyManagement());
+ dm.merge(parent.getDependencyManagement());
//验证依赖信息
- dependencyManagements.push(component.getDependencyManagement());
+ dependencyManagements.push(dm);
try {
processDependencies(dependency, component);
} finally {
@@ -202,11 +215,16 @@ public class DefaultComponentResolver implements ComponentResolver {
List<Component> dependedComponents = new ArrayList<Component>(dependencies.size());
for (Dependency depended : dependencies) {
depended.reform();//move the artifactId prefix with dot into group Id
- qualify(depended);
if (dependency.exclude(depended)) {
logger.trace("Skip excluded {}", depended);
continue;
}
+ //继承depended的依赖排除
+ if(dependency.hasExclusions()){
+ depended.exclude(dependency.getExclusions());
+ }
+ //继承组件的依赖排除
+ qualify(depended);
if (!depended.isTest()) {//只要不是Test的,就都尝试解析
try {
Component dependedComponent = repository.resolveComponent(depended);
diff --git a/sustain/src/main/java/net/happyonroad/component/core/support/Dependency.java b/sustain/src/main/java/net/happyonroad/component/core/support/Dependency.java
index <HASH>..<HASH> 100644
--- a/sustain/src/main/java/net/happyonroad/component/core/support/Dependency.java
+++ b/sustain/src/main/java/net/happyonroad/component/core/support/Dependency.java
@@ -504,4 +504,13 @@ public class Dependency implements Versionize{
}
return null;
}
+
+ public boolean hasExclusions() {
+ return exclusions != null && !exclusions.isEmpty();
+ }
+
+ public void exclude(List<Exclusion> exclusions) {
+ if( this.exclusions == null ) this.exclusions = new ArrayList<Exclusion>();
+ this.exclusions.addAll(exclusions);
+ }
}
diff --git a/sustain/src/main/java/net/happyonroad/component/core/support/DependencyManagement.java b/sustain/src/main/java/net/happyonroad/component/core/support/DependencyManagement.java
index <HASH>..<HASH> 100644
--- a/sustain/src/main/java/net/happyonroad/component/core/support/DependencyManagement.java
+++ b/sustain/src/main/java/net/happyonroad/component/core/support/DependencyManagement.java
@@ -22,12 +22,13 @@ public class DependencyManagement {
public void merge(DependencyManagement another) {
if( another == null || another.dependencies == null ) return;
- getDependencies().addAll(another.getDependencies());
+ dependencies.addAll(another.getDependencies());
}
+ @SuppressWarnings("UnusedDeclaration")
public void unmerge(DependencyManagement another) {
if( another == null || another.dependencies == null ) return;
- getDependencies().removeAll(another.getDependencies());
+ dependencies.removeAll(another.getDependencies());
}
public void qualify(Dependency dependency) {
@@ -38,4 +39,8 @@ public class DependencyManagement {
}
}
}
+
+ public boolean isEmpty() {
+ return dependencies == null || dependencies.isEmpty();
+ }
}
|
Exclution can be inherit between depended components
|
Kadvin_spring-component-framework
|
train
|
9ce1a9bdd313e52deed1a85bee2355ac502410e9
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -50,6 +50,7 @@
"rsuite-selectpicker": "^3.0.0-next.9",
"rsuite-table": "^3.0.0-next.3",
"rsuite-treepicker": "^3.0.0-next.3",
+ "rsuite-uploader": "^3.0.0-next",
"rsuite-utils": "^1.0.0-next.8"
},
"peerDependencies": {
diff --git a/src/Drawer.js b/src/Drawer.js
index <HASH>..<HASH> 100644
--- a/src/Drawer.js
+++ b/src/Drawer.js
@@ -39,7 +39,6 @@ class Drawer extends React.Component<Props> {
<Modal
{...props}
drawer
- overflow={false}
classPrefix={classPrefix}
className={classes}
show={show}
diff --git a/src/IntlProvider/locales/default.js b/src/IntlProvider/locales/default.js
index <HASH>..<HASH> 100644
--- a/src/IntlProvider/locales/default.js
+++ b/src/IntlProvider/locales/default.js
@@ -1,5 +1,3 @@
-
-
const Calendar = {
sunday: 'Su',
monday: 'Mo',
@@ -37,10 +35,18 @@ export default {
},
DateRangePicker: {
...Calendar,
- last7Days: 'Last 7 Days',
+ last7Days: 'Last 7 Days'
},
Picker: {
placeholder: 'Select',
searchPlaceholder: 'Search'
+ },
+ Uploader: {
+ inited: 'Initial',
+ progress: 'Uploading',
+ error: 'Error',
+ complete: 'Finished',
+ emptyFile: 'Empty',
+ upload: 'Upload'
}
};
diff --git a/src/IntlProvider/locales/zh_CN.js b/src/IntlProvider/locales/zh_CN.js
index <HASH>..<HASH> 100644
--- a/src/IntlProvider/locales/zh_CN.js
+++ b/src/IntlProvider/locales/zh_CN.js
@@ -1,5 +1,3 @@
-
-
const Calendar = {
sunday: '日',
monday: '一',
@@ -37,10 +35,18 @@ export default {
},
DateRangePicker: {
...Calendar,
- last7Days: '最近 7 天',
+ last7Days: '最近 7 天'
},
Picker: {
placeholder: '选择',
searchPlaceholder: '搜索'
+ },
+ Uploader: {
+ inited: '初始状态',
+ progress: '上传中',
+ error: '上传出错',
+ complete: '上传完成',
+ emptyFile: '无文件',
+ upload: '上传'
}
};
diff --git a/src/Modal.js b/src/Modal.js
index <HASH>..<HASH> 100644
--- a/src/Modal.js
+++ b/src/Modal.js
@@ -128,8 +128,11 @@ class Modal extends React.Component<Props, State> {
}
};
- if (overflow || drawer) {
+ if (overflow) {
const dialogDOM: any = findDOMNode(this.dialog);
+ const bodyStyles: Object = {
+ overflow: 'auto'
+ };
// default margin
let headerHeight = 46;
@@ -146,26 +149,20 @@ class Modal extends React.Component<Props, State> {
contentHeight = contentDOM ? getHeight(contentDOM) + contentHeight : contentHeight;
- if (overflow) {
+ if (drawer) {
+ bodyStyles.height = contentHeight - (headerHeight + footerHeight);
+ } else {
/**
* Header height + Footer height + Dialog margin
*/
const excludeHeight = headerHeight + footerHeight + 60;
const bodyHeight = getHeight(window) - excludeHeight;
const maxHeight = (scrollHeight >= bodyHeight) ? bodyHeight : scrollHeight;
-
- styles.bodyStyles = {
- maxHeight,
- overflow: 'auto'
- };
+ bodyStyles.maxHeight = maxHeight;
}
- if (drawer) {
- styles.bodyStyles = {
- height: contentHeight - (headerHeight + footerHeight),
- overflow: 'auto'
- };
- }
+ styles.bodyStyles = bodyStyles;
+
}
return styles;
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -51,6 +51,7 @@ export DatePicker from './DatePicker';
export DateRangePicker from './DateRangePicker';
export TreePicker from './TreePicker';
export AutoComplete from './AutoComplete';
+export Uploader from './Uploader';
export Schema from './Schema';
|
Added support for overflow in Drawer
|
rsuite_rsuite
|
train
|
0a1e872b96777fc284533f4ebdd41f971f5fe2e9
|
diff --git a/src/utils/lombok/javac/JavacTreeMaker.java b/src/utils/lombok/javac/JavacTreeMaker.java
index <HASH>..<HASH> 100644
--- a/src/utils/lombok/javac/JavacTreeMaker.java
+++ b/src/utils/lombok/javac/JavacTreeMaker.java
@@ -441,7 +441,9 @@ public class JavacTreeMaker {
//javac versions: 6-8
private static final MethodId<JCVariableDecl> VarDef = MethodId("VarDef");
public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init) {
- return invoke(VarDef, mods, name, vartype, init);
+ JCVariableDecl varDef = invoke(VarDef, mods, name, vartype, init);
+ if (varDef.vartype != null && varDef.vartype.pos == -1) varDef.vartype.pos = 0;
+ return varDef;
}
//javac versions: 8
|
[jdk<I>] delombok was printing most variable declarations that are generated by lombok with ‘var’.
|
rzwitserloot_lombok
|
train
|
ee8436b2abc9b799d5fcc2314bd3405f0738394c
|
diff --git a/src/ORM/Marshaller.php b/src/ORM/Marshaller.php
index <HASH>..<HASH> 100644
--- a/src/ORM/Marshaller.php
+++ b/src/ORM/Marshaller.php
@@ -86,10 +86,6 @@ class Marshaller
/**
* Hydrate one entity and its associated data.
*
- * When marshalling HasMany or BelongsToMany associations, `_ids` format can be used.
- * `ids` option can also be used to determine whether the association must use the `_ids`
- * format.
- *
* ### Options:
*
* * associated: Associations listed here will be marshalled as well.
@@ -97,6 +93,16 @@ class Marshaller
* the accessible fields list in the entity will be used.
* * accessibleFields: A list of fields to allow or deny in entity accessible fields.
*
+ * The above options can be used in each nested `associated` array. In addition to the above
+ * options you can also use the `ids` option for HasMany and BelongsToMany associations.
+ * When true this option restricts the request data to only be read from `_ids`.
+ *
+ * ```
+ * $result = $marshaller->one($data, [
+ * 'associated' => ['Tags' => ['ids' => true]]
+ * ]);
+ * ```
+ *
* @param array $data The data to hydrate.
* @param array $options List of options
* @return \Cake\ORM\Entity
@@ -416,6 +422,16 @@ class Marshaller
* the accessible fields list in the entity will be used.
* * accessibleFields: A list of fields to allow or deny in entity accessible fields.
*
+ * The above options can be used in each nested `associated` array. In addition to the above
+ * options you can also use the `ids` option for HasMany and BelongsToMany associations.
+ * When true this option restricts the request data to only be read from `_ids`.
+ *
+ * ```
+ * $result = $marshaller->merge($entity, $data, [
+ * 'associated' => ['Tags' => ['ids' => true]]
+ * ]);
+ * ```
+ *
* @param \Cake\Datasource\EntityInterface $entity the entity that will get the
* data merged in
* @param array $data key value list of fields to be merged into the entity
|
Add additional documentation for `ids` option.
|
cakephp_cakephp
|
train
|
37d95bfc72d06adb3ab41ecc098ce3fc6034558b
|
diff --git a/src/Moka/Moka.php b/src/Moka/Moka.php
index <HASH>..<HASH> 100644
--- a/src/Moka/Moka.php
+++ b/src/Moka/Moka.php
@@ -44,7 +44,7 @@ class Moka
{
if (!isset(self::$mockingStrategies[$name])) {
/** @var PluginInterface $pluginFQCN */
- $pluginFQCN = PluginHelper::loadPlugin($name);
+ $pluginFQCN = PluginHelper::load($name);
self::$mockingStrategies[$name] = $pluginFQCN::getStrategy();
}
diff --git a/src/Moka/Plugin/PluginHelper.php b/src/Moka/Plugin/PluginHelper.php
index <HASH>..<HASH> 100644
--- a/src/Moka/Plugin/PluginHelper.php
+++ b/src/Moka/Plugin/PluginHelper.php
@@ -17,9 +17,9 @@ final class PluginHelper
* @return string
* @throws NotImplementedException
*/
- public static function loadPlugin(string $pluginName): string
+ public static function load(string $pluginName): string
{
- $pluginFQCN = PluginHelper::generatePluginFQCN($pluginName);
+ $pluginFQCN = PluginHelper::generateFQCN($pluginName);
if (!class_exists($pluginFQCN) || !in_array(PluginInterface::class, class_implements($pluginFQCN), true)) {
throw new NotImplementedException(
@@ -37,7 +37,7 @@ final class PluginHelper
* @param string $pluginName
* @return string
*/
- private static function generatePluginFQCN(string $pluginName): string
+ private static function generateFQCN(string $pluginName): string
{
return sprintf(
self::PLUGIN_NAMESPACE_TEMPLATE,
|
Fix naming into PluginHelper
|
facile-it_moka
|
train
|
0950a65fde7058e1517300a78a7b252c2bbe4110
|
diff --git a/ReleaseNotes.md b/ReleaseNotes.md
index <HASH>..<HASH> 100644
--- a/ReleaseNotes.md
+++ b/ReleaseNotes.md
@@ -5,6 +5,13 @@
### API Changes
+ [deleteJob throws exception but works anyway][issue-154]
+ [Some HTTP calls to jenkins result in a 302, which currently throws an HttpResponseException #7[issue-7]
+ [Create Job is failing - any idea on this error][issue-121]
+
+ * Fixed. by changing call to client.post(, crumbFlag = true) into
+ client.post(, crumbFlag = false).
+
[Added getPluginManager() to JenkinsServer][issue-120]
```java
@@ -309,6 +316,7 @@ TestReport testReport = mavenJob.getLastSuccessfulBuild().getTestReport();
[2]: https://github.com/RisingOak/jenkins-client/blob/master/src/test/java/com/offbytwo/jenkins/integration/JenkinsLoadStatisticsExample.java
[3]: https://github.com/RisingOak/jenkins-client/blob/master/src/test/java/com/offbytwo/jenkins/integration/BuildJobTestReports.java
[4]: https://github.com/RisingOak/jenkins-client/blob/master/src/main/java/com/offbytwo/jenkins/model/Executor.java
+[issue-7]: https://github.com/RisingOak/jenkins-client/issues/7
[issue-53]: https://github.com/RisingOak/jenkins-client/issues/53
[issue-67]: https://github.com/RisingOak/jenkins-client/issues/67
[issue-82]: https://github.com/RisingOak/jenkins-client/issues/82
@@ -320,12 +328,14 @@ TestReport testReport = mavenJob.getLastSuccessfulBuild().getTestReport();
[issue-108]: https://github.com/RisingOak/jenkins-client/issues/108
[issue-119]: https://github.com/RisingOak/jenkins-client/issues/119
[issue-120]: https://github.com/RisingOak/jenkins-client/issues/120
+[issue-121]: https://github.com/RisingOak/jenkins-client/issues/121
[issue-128]: https://github.com/RisingOak/jenkins-client/issues/128
[issue-130]: https://github.com/RisingOak/jenkins-client/issues/130
[issue-133]: https://github.com/RisingOak/jenkins-client/issues/133
[issue-135]: https://github.com/RisingOak/jenkins-client/issues/135
[issue-144]: https://github.com/RisingOak/jenkins-client/issues/144
[issue-146]: https://github.com/RisingOak/jenkins-client/issues/146
+[issue-154]: https://github.com/RisingOak/jenkins-client/issues/154
[issue-155]: https://github.com/RisingOak/jenkins-client/issues/155
[pull-123]: https://github.com/RisingOak/jenkins-client/pull/123
[pull-149]: https://github.com/RisingOak/jenkins-client/pull/149
diff --git a/src/main/java/com/offbytwo/jenkins/client/JenkinsHttpClient.java b/src/main/java/com/offbytwo/jenkins/client/JenkinsHttpClient.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/offbytwo/jenkins/client/JenkinsHttpClient.java
+++ b/src/main/java/com/offbytwo/jenkins/client/JenkinsHttpClient.java
@@ -431,7 +431,7 @@ public class JenkinsHttpClient {
* HttpResponseException
*/
public void post(String path) throws IOException {
- post(path, null, null, true);
+ post(path, null, null, false);
}
public void post(String path, boolean crumbFlag) throws IOException {
diff --git a/src/main/java/com/offbytwo/jenkins/model/Job.java b/src/main/java/com/offbytwo/jenkins/model/Job.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/offbytwo/jenkins/model/Job.java
+++ b/src/main/java/com/offbytwo/jenkins/model/Job.java
@@ -68,7 +68,7 @@ public class Job extends BaseModel {
* Trigger a build without parameters
*/
public void build() throws IOException {
- client.post(url + "build", true);
+ client.post(url + "build");
}
public void build(boolean crumbFlag) throws IOException {
@@ -84,7 +84,7 @@ public class Job extends BaseModel {
*/
public void build(Map<String, String> params) throws IOException {
String qs = join(Collections2.transform(params.entrySet(), new MapEntryToQueryStringPair()), "&");
- client.post(url + "buildWithParameters?" + qs, null, null);
+ client.post(url + "buildWithParameters?" + qs);
}
/**
|
Fixed #<I>
Fixed #<I>
Fixed #7
o deleteJob(name), enabledJob(name), disableJob(name),
cancelQuietDown(), build(), build(params) producing a
HttpResponseException cause by the wrong calling
client.post with crumbFlag set to true which was wrong.
Changed to false.
|
jenkinsci_java-client-api
|
train
|
66f51a14afced0aa6782c25edc66e56392b14551
|
diff --git a/package.js b/package.js
index <HASH>..<HASH> 100644
--- a/package.js
+++ b/package.js
@@ -32,7 +32,7 @@ Package.on_use(function (api) {
api.use('angular:angular@1.4.1', 'client');
api.use('minimongo'); // for idStringify
api.use('observe-sequence');
- api.use('dburles:mongo-collection-instances@0.3.3', 'client'); // For getCollectionByName
+ api.use('dburles:mongo-collection-instances@0.3.4', 'client'); // For getCollectionByName
// Files to load in Client only.
api.add_files([
|
Update mongo-collection-instances
This update fixes a couple issues regarding `Mongo.Collection` wrapping.
|
Urigo_angular-meteor
|
train
|
249402547a956541d794dfc0bf5679901b57488f
|
diff --git a/test/test_parsing.rb b/test/test_parsing.rb
index <HASH>..<HASH> 100644
--- a/test/test_parsing.rb
+++ b/test/test_parsing.rb
@@ -753,7 +753,7 @@ class TestParsing < Test::Unit::TestCase
assert_equal Time.local(2007, 11, 3, 12), t1
t1 = Chronic.parse('1st sunday in november', :now => Time.local(2007))
- assert_equal Time.local(2007, 11, 4, 11), t1
+ assert_equal Time.local(2007, 11, 4, 12), t1
# Chronic.debug = true
#
|
fix typo in test_days_in_november test case
|
mojombo_chronic
|
train
|
beb07fd2e481a27a7f802da4ae8a00e86ab47d1a
|
diff --git a/lib/fb_graph/connections/settings.rb b/lib/fb_graph/connections/settings.rb
index <HASH>..<HASH> 100644
--- a/lib/fb_graph/connections/settings.rb
+++ b/lib/fb_graph/connections/settings.rb
@@ -51,6 +51,7 @@ module FbGraph
:connection => :settings
)
if succeeded
+ @settings ||= []
if value
@settings << setting.to_sym
else
|
@settings can be nil here
|
nov_fb_graph
|
train
|
d915856aed1318326ad043fb27d8ce917304ef4d
|
diff --git a/packages/react-atlas-core/src/utils/utils.js b/packages/react-atlas-core/src/utils/utils.js
index <HASH>..<HASH> 100644
--- a/packages/react-atlas-core/src/utils/utils.js
+++ b/packages/react-atlas-core/src/utils/utils.js
@@ -100,5 +100,9 @@ export default {
}
}
catch (e) { /* not focused or not visible */ }
+ },
+ getComponentName(comp) {
+ const name = comp.type.displayName || comp.type.name || comp.type;
+ return name;
}
};
|
Add utility to look up React Component names.
|
DigitalRiver_react-atlas
|
train
|
d6404b7bf97edf377f94d662cb08c573ef6e85a2
|
diff --git a/benchexec/tools/metaval.py b/benchexec/tools/metaval.py
index <HASH>..<HASH> 100644
--- a/benchexec/tools/metaval.py
+++ b/benchexec/tools/metaval.py
@@ -96,8 +96,6 @@ class Tool(benchexec.tools.template.BaseTool2):
"benchexec.tools." + verifierName, fromlist=["Tool"]
).Tool()
- if not verifierName in self.wrappedTools:
- sys.exit("ERROR: Could not find wrapped tool") # noqa: R503 always raises
tool = self.wrappedTools[verifierName]
assert isinstance(
tool, BaseTool2
|
Remove check that can never fail
According to @PhilippWendler
|
sosy-lab_benchexec
|
train
|
8baad9e786c0c894c5aad42f2524bb11714af169
|
diff --git a/spec/data_visitor_spec.rb b/spec/data_visitor_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/data_visitor_spec.rb
+++ b/spec/data_visitor_spec.rb
@@ -113,6 +113,10 @@ describe Shape::DataVisitor do
include Shape
property :name
property :ssn , if: ->{ _source[:secure] }
+
+ property :private do
+ property :age, if: -> { _source[:secure] }
+ end
end)
end
@@ -131,6 +135,10 @@ describe Shape::DataVisitor do
expect(subject.to_json).not_to include('ssn')
end
+ it 'does not include the nested property' do
+ expect(subject.to_json).not_to include('age')
+ end
+
end
context 'when true' do
@@ -147,6 +155,10 @@ describe Shape::DataVisitor do
expect(subject.to_json).to include('ssn')
end
+ it 'includes the nested property' do
+ expect(subject.to_json).to include('age')
+ end
+
end
end
|
Add spec for if clause on nested properties.
|
robincurry_shape
|
train
|
65c3ffc7d88f28f39b57885801d117362c2568a2
|
diff --git a/core/BaseSession.core.php b/core/BaseSession.core.php
index <HASH>..<HASH> 100644
--- a/core/BaseSession.core.php
+++ b/core/BaseSession.core.php
@@ -90,6 +90,15 @@ class BaseSession {
session_unset();
}//flush
+
+ /**
+ * Destroy A session
+ */
+ public function destroy(){
+ session_destroy();
+ }//destroy
+
+
}//BaseSession
?>
|
added method destroy() to allow destroying a session
|
discophp_framework
|
train
|
a3c7978e4968786f39d11d30250f0d49b8914467
|
diff --git a/src/com/opencms/file/genericSql/CmsResourceBroker.java b/src/com/opencms/file/genericSql/CmsResourceBroker.java
index <HASH>..<HASH> 100644
--- a/src/com/opencms/file/genericSql/CmsResourceBroker.java
+++ b/src/com/opencms/file/genericSql/CmsResourceBroker.java
@@ -1,7 +1,7 @@
/*
* File : $Source: /alkacon/cvs/opencms/src/com/opencms/file/genericSql/Attic/CmsResourceBroker.java,v $
-* Date : $Date: 2002/01/18 08:29:01 $
-* Version: $Revision: 1.304 $
+* Date : $Date: 2002/01/18 13:40:40 $
+* Version: $Revision: 1.305 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
@@ -53,7 +53,7 @@ import java.sql.SQLException;
* @author Michaela Schleich
* @author Michael Emmerich
* @author Anders Fugmann
- * @version $Revision: 1.304 $ $Date: 2002/01/18 08:29:01 $
+ * @version $Revision: 1.305 $ $Date: 2002/01/18 13:40:40 $
*
*/
public class CmsResourceBroker implements I_CmsResourceBroker, I_CmsConstants {
@@ -4469,8 +4469,7 @@ public synchronized void exportStaticResources(CmsUser currentUser, CmsProject c
// the project was stored in the backuptables for history
//new projectmechanism: the project can be still used after publishing
// it will be deleted if the project_flag = C_PROJECT_STATE_TEMP
- if (publishProject.getType() == C_PROJECT_TYPE_TEMPORARY ||
- publishProject.getType() == (C_PROJECT_TYPE_TEMPORARY + C_PROJECT_TYPE_STATICEXPORT)) {
+ if (publishProject.getType() == C_PROJECT_TYPE_TEMPORARY) {
m_dbAccess.deleteProject(publishProject);
try{
m_projectCache.remove(id);
@@ -4479,7 +4478,10 @@ public synchronized void exportStaticResources(CmsUser currentUser, CmsProject c
A_OpenCms.log(A_OpenCms.C_OPENCMS_CACHE,"Could not remove project "+id+" from cache");
}
}
- //deleteProject(currentUser, currentProject, id);
+ if(id == currentProject.getId()){
+ cms.getRequestContext().setCurrentProject(I_CmsConstants.C_PROJECT_ONLINE_ID);
+ }
+
}
// finally set the refrish signal to another server if nescessary
|
Removed constant for project type for static export.
Change current project to online project after publishing a temporary project.
|
alkacon_opencms-core
|
train
|
97b42492bb391bab346d265b70dc62e9d90ecd3d
|
diff --git a/test/unit/core.js b/test/unit/core.js
index <HASH>..<HASH> 100644
--- a/test/unit/core.js
+++ b/test/unit/core.js
@@ -661,7 +661,7 @@ test("jQuery.merge()", function() {
});
test("jQuery.extend(Object, Object)", function() {
- expect(26);
+ expect(28);
var settings = { xnumber1: 5, xnumber2: 7, xstring1: "peter", xstring2: "pan" },
options = { xnumber2: 1, xstring2: "x", xxx: "newstring" },
@@ -689,6 +689,10 @@ test("jQuery.extend(Object, Object)", function() {
equals( deep1.foo2, document, "Make sure that a deep clone was not attempted on the document" );
ok( jQuery.extend(true, {}, nestedarray).arr !== arr, "Deep extend of object must clone child array" );
+
+ // #5991
+ ok( jQuery.isArray( jQuery.extend(true, { arr: {} }, nestedarray).arr ), "Cloned array heve to be an Array" );
+ ok( jQuery.isPlainObject( jQuery.extend(true, { arr: arr }, { arr: {} }).arr ), "Cloned object heve to be an plain object" );
var empty = {};
var optionsWithLength = { foo: { length: -1 } };
|
Added some tests for #<I>.
|
jquery_jquery
|
train
|
8a754076672d69187ba655d284c14554b9e0f58a
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -253,6 +253,7 @@ Python 2.7 and 3.0 - 3.4 are supported. Note that development occurs on Python 3
* Add support for secure connections.
* Add auth name for users if they are logged in and the track command module is enabled.
+* Add option to denote a command for admins only for management commands.
* Fix not being able to connect on Python 2.7.
#### 1.0 - 2014-10-18
diff --git a/pyromancer/decorators.py b/pyromancer/decorators.py
index <HASH>..<HASH> 100644
--- a/pyromancer/decorators.py
+++ b/pyromancer/decorators.py
@@ -22,6 +22,7 @@ class command(object):
self.raw = kwargs.get('raw', False)
self.code = kwargs.get('code')
self.command = kwargs.get('command')
+ self.admins_only = kwargs.get('admins', False)
if self.code is not None and not isinstance(self.code, int):
raise CommandException('The code argument must be an integer.')
@@ -54,6 +55,10 @@ class command(object):
if not line.usermsg and not self.raw:
return
+ if self.admins_only and hasattr(line, 'sender') and line.sender.auth \
+ not in settings.admins:
+ return
+
if self.code and getattr(line, 'code', None) == self.code:
return True
diff --git a/pyromancer/settings.py b/pyromancer/settings.py
index <HASH>..<HASH> 100644
--- a/pyromancer/settings.py
+++ b/pyromancer/settings.py
@@ -9,3 +9,4 @@ packages = []
command_prefix = None
database = None
ssl = False
+admins = []
|
Add option to denote a command for admins only
|
Gwildor_Pyromancer
|
train
|
c6b05988eb0422f1db265423f7d2c63472af4cb0
|
diff --git a/app/models/manager_refresh/dto.rb b/app/models/manager_refresh/dto.rb
index <HASH>..<HASH> 100644
--- a/app/models/manager_refresh/dto.rb
+++ b/app/models/manager_refresh/dto.rb
@@ -73,6 +73,8 @@ module ManagerRefresh
private
+ attr_writer :object
+
def allowed?(dto_collection_scope, key)
# TODO(lsmola) can we make this O(1)? This check will be performed for each record in the DB
@@ -81,10 +83,6 @@ module ManagerRefresh
true
end
- def object=(built_object)
- @object = built_object
- end
-
def loadable?(value)
value.kind_of?(::ManagerRefresh::DtoLazy) || value.kind_of?(::ManagerRefresh::Dto)
end
|
Use private attr writter instead of explicit method
Use private attr writter instead of explicit method
(transferred from ManageIQ/manageiq@4dce<I>afd<I>b9f<I>bfc<I>c<I>e)
|
ManageIQ_inventory_refresh
|
train
|
e1e05140e89bf9be9a9398f61a8fda8115dc20a5
|
diff --git a/jax/experimental/jax2tf/jax2tf.py b/jax/experimental/jax2tf/jax2tf.py
index <HASH>..<HASH> 100644
--- a/jax/experimental/jax2tf/jax2tf.py
+++ b/jax/experimental/jax2tf/jax2tf.py
@@ -1386,8 +1386,8 @@ tf_impl[lax.rev_p] = _rev
tf_impl[lax.select_p] = tf.where
-def _transpose(operand, permutation):
- return tf.transpose(operand, permutation)
+def _transpose(operand, *, permutation):
+ return tf.transpose(operand, perm=permutation)
tf_impl[lax.transpose_p] = _transpose
axes_to_axis = lambda func: lambda operand, axes: func(operand, axis=axes)
diff --git a/jax/experimental/jax2tf/tests/primitive_harness.py b/jax/experimental/jax2tf/tests/primitive_harness.py
index <HASH>..<HASH> 100644
--- a/jax/experimental/jax2tf/tests/primitive_harness.py
+++ b/jax/experimental/jax2tf/tests/primitive_harness.py
@@ -539,6 +539,26 @@ lax_select = tuple( # Validate dtypes
]
)
+def _make_transpose_harness(name, *, shape=(2, 3), permutation=(1, 0),
+ dtype=np.float32):
+ return Harness(f"{name}_shape={jtu.format_shape_dtype_string(shape, dtype)}_permutation={permutation}".replace(' ', ''),
+ lambda x: lax.transpose_p.bind(x, permutation=permutation),
+ [RandArg(shape, dtype)],
+ shape=shape,
+ dtype=dtype,
+ permutation=permutation)
+
+lax_transpose = tuple( # Validate dtypes
+ _make_transpose_harness("dtypes", dtype=dtype)
+ for dtype in jtu.dtypes.all
+) + tuple( # Validate permutations
+ _make_transpose_harness("permutations", shape=shape, permutation=permutation)
+ for shape, permutation in [
+ ((2, 3, 4), (0, 1, 2)), # identity
+ ((2, 3, 4), (1, 2, 0)), # transposition
+ ]
+)
+
def _make_cumreduce_harness(name, *, f_jax=lax_control_flow.cummin,
shape=(8, 9), dtype=np.float32,
axis=0, reverse=False):
diff --git a/jax/experimental/jax2tf/tests/primitives_test.py b/jax/experimental/jax2tf/tests/primitives_test.py
index <HASH>..<HASH> 100644
--- a/jax/experimental/jax2tf/tests/primitives_test.py
+++ b/jax/experimental/jax2tf/tests/primitives_test.py
@@ -115,6 +115,10 @@ class JaxPrimitiveTest(tf_test_util.JaxToTfTestCase):
def test_select(self, harness: primitive_harness.Harness):
self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))
+ @primitive_harness.parameterized(primitive_harness.lax_transpose)
+ def test_transpose(self, harness: primitive_harness.Harness):
+ self.ConvertAndCompare(harness.dyn_fun, *harness.dyn_args_maker(self.rng()))
+
@primitive_harness.parameterized(primitive_harness.lax_control_flow_cumreduce)
def test_cumreduce(self, harness: primitive_harness.Harness):
f_jax, dtype = harness.params["f_jax"], harness.params["dtype"]
|
[jax2tf] Added tests for the conversion of transpose.
|
tensorflow_probability
|
train
|
37cb88b1d71bfbf2f9e0a62b53991e6b8b103f52
|
diff --git a/js/mandala.js b/js/mandala.js
index <HASH>..<HASH> 100644
--- a/js/mandala.js
+++ b/js/mandala.js
@@ -15,7 +15,7 @@ module.exports = class mandala extends Exchange {
'countries': [ 'MT' ],
'version': 'v2',
'rateLimit': 1500,
- 'certified': true,
+ 'certified': false,
// new metainfo interface
'has': {
'cancelAllOrders': true,
|
mandala certified = false #<I>
|
ccxt_ccxt
|
train
|
2d5a1a52a88e60707f198415abd5e90cb64b3f6f
|
diff --git a/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/CRLChecker.java b/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/CRLChecker.java
index <HASH>..<HASH> 100644
--- a/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/CRLChecker.java
+++ b/ssl-proxies/src/main/java/org/globus/gsi/trustmanager/CRLChecker.java
@@ -125,11 +125,19 @@ public class CRLChecker implements CertificateChecker {
// validate CRL
verifyCRL(caCert, crl);
- if (crl.isRevoked(cert)) {
- throw new CertPathValidatorException(
- "Certificate " + cert.getSubjectDN() + " has been revoked");
-
- }
+ /* One would have thought that a CRL is immutable and thus
+ * thread safe, however inside the ASN1 parse tree we find
+ * LazyDERSequence. LazyDERSequence is parsed lazily and
+ * does so in a non-thread safe manner. One may very well
+ * classify this as a bouncy castle bug, but as a
+ * workaround synchronizing on the CRL solves the problem.
+ */
+ synchronized (crl) {
+ if (crl.isRevoked(cert)) {
+ throw new CertPathValidatorException(
+ "Certificate " + cert.getSubjectDN() + " has been revoked");
+ }
+ }
}
}
|
ssl-proxies: Fix CRL check race condition
JGlobus uses CRLs as if they were immutable objects, however when
using the Bouncy Castle provider, the ASN<I> parser uses lazy
evaluation internally, which means the X<I>CRL object is not
thread safe.
|
jglobus_JGlobus
|
train
|
f37b45b3867eadf1fb7fe00774862284509ccb80
|
diff --git a/lib/data_structures/column.rb b/lib/data_structures/column.rb
index <HASH>..<HASH> 100644
--- a/lib/data_structures/column.rb
+++ b/lib/data_structures/column.rb
@@ -1,9 +1,9 @@
module ActiveScaffold::DataStructures
class Column
include ActiveScaffold::Configurable
-
+
attr_reader :active_record_class
-
+
# this is the name of the getter on the ActiveRecord model. it is the only absolutely required attribute ... all others will be inferred from this name.
attr_accessor :name
@@ -45,27 +45,46 @@ module ActiveScaffold::DataStructures
@sort = value ? true : false # force true or false
end
end
-
+
def sort
self.initialize_sort if @sort === true
@sort
end
-
+
def sortable?
sort != false && !sort.nil?
end
-
+
# a configuration helper for the self.sort property. simply provides a method syntax instead of setter syntax.
def sort_by(options)
self.sort = options
end
# supported options:
- # * :select will display a simple <select> (or collection of checkboxes) on the form to (dis)associate records
- # * :crud (default) will display a sub-form
- attr_writer :ui_type
- def ui_type
- @ui_type || (column.type if column)
+ # * for association columns
+ # * :select - displays a simple <select> or a collection of checkboxes to (dis)associate records
+ # * :crud - will display a sub-form (default)
+ #
+ # proposed options:
+ # * for string fields
+ # * :text - (default)
+ # * :textarea - use a textarea for larger expected input
+ # * for datetime fields
+ # * :calendar - (ActiveScaffold 1.1 default)
+ # * :select - (ActiveScaffold 1.0 default)
+ # * for boolean fields
+ # * :checkbox
+ # * :select
+ attr_writer :form_ui
+ def form_ui
+ @form_ui || (column.type if column)
+ end
+
+ # DEPRECATED
+ alias :ui_type :form_ui
+ def ui_type=(val)
+ ::ActiveSupport::Deprecation.warn("config.columns[:#{name}].ui_type has been deprecated in ActiveScaffold 1.1 and will disappear in 1.2. Please use config.columns[:#{name}].form_ui instead.", caller)
+ self.form_ui = val
end
# associate an action_link with this column
@@ -93,9 +112,9 @@ module ActiveScaffold::DataStructures
# a collection of associations to pre-load when finding the records on a page
attr_reader :includes
def includes=(value)
- @includes = value.is_a?(Array) ? value : [value] # automatically convert to an array
+ @includes = value.is_a?(Array) ? value : [value] # automatically convert to an array
end
-
+
# describes how to search on a column
# search = true default, uses intelligent search sql
# search = "CONCAT(a, b)" define your own sql for searching. this should be the "left-side" of a WHERE condition. the operator and value will be supplied by ActiveScaffold.
|
create the form_ui column attribute. this is the same as ui_type, except with a better name. ui_type still works but is deprecated and marked for removal in version <I>.
closes issue #<I>
git-svn-id: <URL>
|
activescaffold_active_scaffold
|
train
|
df41fb66b1c0a4eaea54c8ec2ae713c48414ffe1
|
diff --git a/src/Support/Content/MimeTypeHelper.php b/src/Support/Content/MimeTypeHelper.php
index <HASH>..<HASH> 100644
--- a/src/Support/Content/MimeTypeHelper.php
+++ b/src/Support/Content/MimeTypeHelper.php
@@ -6,6 +6,7 @@ use finfo;
use Symfony\Component\HttpFoundation\File\MimeType\ExtensionGuesserInterface;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
+use Symfony\Component\Mime\MimeTypes;
/**
* Class MimeTypeHelper
@@ -28,6 +29,11 @@ class MimeTypeHelper implements MimeTypeHelperInterface
*/
public function guessMimeTypeForPath($path)
{
+ if (class_exists(MimeTypes::class)) {
+ return (new MimeTypes())->guessMimeType($path);
+ }
+
+ // Deprecated, but kept as backwards compatibility fallback for now.
return MimeTypeGuesser::getInstance()->guess($path);
}
|
Updated MimeTypeHelper to use new MimeTypes class where available
This removes the deprecation warning
|
czim_file-handling
|
train
|
6dae51540f17afa3536097970b1d1340392c5b2e
|
diff --git a/src/lambda/handler-runner/ruby-runner/RubyRunner.js b/src/lambda/handler-runner/ruby-runner/RubyRunner.js
index <HASH>..<HASH> 100644
--- a/src/lambda/handler-runner/ruby-runner/RubyRunner.js
+++ b/src/lambda/handler-runner/ruby-runner/RubyRunner.js
@@ -26,6 +26,8 @@ export default class RubyRunner {
cleanup() {}
_parsePayload(value) {
+ let payload
+
for (const item of value.split(EOL)) {
let json
@@ -43,11 +45,13 @@ export default class RubyRunner {
typeof json === 'object' &&
has(json, '__offline_payload__')
) {
- return json.__offline_payload__
+ payload = json.__offline_payload__
+ } else {
+ console.log(item) // log non-JSON stdout to console (puts, p, logger.info, ...)
}
}
- return undefined
+ return payload
}
// invokeLocalRuby, loosely based on:
|
Fix bug where ruby stdout not printed to console
|
dherault_serverless-offline
|
train
|
c0b2c9c9f8d234c6ecc67e240a2369ee770e41a5
|
diff --git a/TYPO3.Flow/Tests/MVC/Web/Routing/F3_FLOW3_MVC_Web_Routing_StaticRoutePartTest.php b/TYPO3.Flow/Tests/MVC/Web/Routing/F3_FLOW3_MVC_Web_Routing_StaticRoutePartTest.php
index <HASH>..<HASH> 100644
--- a/TYPO3.Flow/Tests/MVC/Web/Routing/F3_FLOW3_MVC_Web_Routing_StaticRoutePartTest.php
+++ b/TYPO3.Flow/Tests/MVC/Web/Routing/F3_FLOW3_MVC_Web_Routing_StaticRoutePartTest.php
@@ -111,6 +111,7 @@ class F3_FLOW3_MVC_Web_Routing_StaticRoutePartTest extends F3_Testing_BaseTestCa
* @author Robert Lemke <robert@typo3.org>
*/
public function staticRoutePartDoesNotMatchIfNameIsEqualToTheBeginningOfTheFirstUrlSegmentButTheSegmentIsLonger() {
+ $this->markTestSkipped();
$this->routePart1->setName('foo');
$urlSegments = array('foos', 'bar');
|
* FLOW3: Marked the previously, mistakenly committed test as skipped. Relates to #<I>
Original-Commit-Hash: 3e<I>dc4dad9a<I>e<I>d<I>be<I>eb<I>f<I>b5
|
neos_flow-development-collection
|
train
|
8170804ddb51e42252ef3fccf563db70cf61e1b9
|
diff --git a/osmdroid-android/src/main/java/org/osmdroid/config/DefaultConfigurationProvider.java b/osmdroid-android/src/main/java/org/osmdroid/config/DefaultConfigurationProvider.java
index <HASH>..<HASH> 100644
--- a/osmdroid-android/src/main/java/org/osmdroid/config/DefaultConfigurationProvider.java
+++ b/osmdroid-android/src/main/java/org/osmdroid/config/DefaultConfigurationProvider.java
@@ -275,6 +275,8 @@ public class DefaultConfigurationProvider implements IConfigurationProvider {
//trap for android studio layout editor and some for certain devices
//see https://github.com/osmdroid/osmdroid/issues/508
}
+ if (osmdroidBasePath==null && context!=null)
+ osmdroidBasePath = context.getFilesDir();
return osmdroidBasePath;
}
|
#<I> potential fix a NPE (DefaultConfigProvider) (#<I>)
* #<I> potential fix a NPE
* #<I> should fix the test failure
|
osmdroid_osmdroid
|
train
|
183bbd6068bbf4bb8d42856a980d88c6a2c2b37b
|
diff --git a/CHANGELOG b/CHANGELOG
index <HASH>..<HASH> 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,3 +1,8 @@
+v0.17:
+ - `f90nml.write()` works for normal (non-`Namelist`) dicts
+ - `Parser` properties moved outside of function arguments, and are now
+ handled with property decorators (as in `Namelist`)
+
v0.16:
- User-defined comment delimiters (e.g. `#` comment support)
diff --git a/f90nml/__init__.py b/f90nml/__init__.py
index <HASH>..<HASH> 100644
--- a/f90nml/__init__.py
+++ b/f90nml/__init__.py
@@ -7,8 +7,9 @@
:license: Apache License, Version 2.0, see LICENSE for details.
"""
from f90nml.parser import Parser
+from f90nml.namelist import Namelist
-__version__ = '0.16'
+__version__ = '0.17-dev'
def read(nml_path, row_major=None, strict_logical=None):
@@ -42,8 +43,11 @@ def read(nml_path, row_major=None, strict_logical=None):
``t`` are interpreted as ``True``, while any string starting with ``.f`` or
``f`` is interpreted as ``False``."""
- return Parser().read(nml_path, row_major=row_major,
- strict_logical=strict_logical)
+ parser = Parser()
+ parser.row_major = row_major
+ parser.strict_logical = strict_logical
+
+ return parser.read(nml_path)
def write(nml, nml_path, force=False):
@@ -62,7 +66,13 @@ def write(nml, nml_path, force=False):
>>> nml.write('data.nml', force=True)"""
- nml.write(nml_path, force=force)
+ # Promote dicts to Namelists
+ if not isinstance(nml, Namelist) and isinstance(nml, dict):
+ nml_in = Namelist(nml)
+ else:
+ nml_in = nml
+
+ nml_in.write(nml_path, force=force)
def patch(nml_path, nml_patch, out_path=None, row_major=None,
@@ -81,5 +91,8 @@ def patch(nml_path, nml_patch, out_path=None, row_major=None,
original namelist file. Any modified values will be formatted based on the
settings of the ``Namelist`` object."""
- return Parser().read(nml_path, nml_patch, out_path, row_major=row_major,
- strict_logical=strict_logical)
+ parser = Parser()
+ parser.row_major = row_major
+ parser.strict_logical = strict_logical
+
+ return parser.read(nml_path, nml_patch, out_path)
diff --git a/f90nml/parser.py b/f90nml/parser.py
index <HASH>..<HASH> 100644
--- a/f90nml/parser.py
+++ b/f90nml/parser.py
@@ -30,33 +30,50 @@ class Parser(object):
self.pfile = None
# Control flags
- self.row_major = False
- self.strict_logical = True
+ self._row_major = False
+ self._strict_logical = True
# Configuration
self.comment_tokens = '!'
- def read(self, nml_fname, nml_patch_in=None, patch_fname=None,
- row_major=None, strict_logical=None):
- """Parse a Fortran 90 namelist file and store the contents.
+ @property
+ def row_major(self):
+ """Return true if multidimensional arrays are in row-major format."""
+ return self._row_major
- >>> from f90nml.parser import Parser
- >>> parser = Parser()
- >>> data_nml = parser.read('data.nml')"""
+ @row_major.setter
+ def row_major(self, value):
+ """Validate and set row-major format for multidimensional arrays."""
- if row_major is not None:
- if not isinstance(row_major, bool):
- raise ValueError('f90nml: error: row_major must be a logical '
- 'value.')
+ if value is not None:
+ if not isinstance(value, bool):
+ raise ValueError(''
+ 'f90nml: error: row_major must be a logical value.')
else:
- self.row_major = row_major
+ self._row_major = value
+
+ @property
+ def strict_logical(self):
+ """Return true for strict logical value parsing."""
+ return self._strict_logical
+
+ @strict_logical.setter
+ def strict_logical(self, value):
+ """Validate and set the strict logical flag."""
- if strict_logical is not None:
- if not isinstance(strict_logical, bool):
- raise ValueError('f90nml: error: strict_logical must be a '
- 'logical value.')
+ if value is not None:
+ if not isinstance(value, bool):
+ raise ValueError(''
+ 'f90nml: error: strict_logical must be a logical value.')
else:
- self.strict_logical = strict_logical
+ self._strict_logical = value
+
+ def read(self, nml_fname, nml_patch_in=None, patch_fname=None):
+ """Parse a Fortran 90 namelist file and store the contents.
+
+ >>> from f90nml.parser import Parser
+ >>> parser = Parser()
+ >>> data_nml = parser.read('data.nml')"""
nml_file = open(nml_fname, 'r')
|
Namelist writes for dicts; Parser properties
Non-namelist dicts can now be saved to files with `f<I>nml.write`.
The `Parser` reader properties `strict_logical` and `row_major` are now
private and managed by decorated property functions.
|
marshallward_f90nml
|
train
|
6ff76464bac4469dcc9f82b83ea4d91eb54d3329
|
diff --git a/lib/ecdsa/version.rb b/lib/ecdsa/version.rb
index <HASH>..<HASH> 100644
--- a/lib/ecdsa/version.rb
+++ b/lib/ecdsa/version.rb
@@ -1,3 +1,3 @@
module ECDSA
- VERSION = '0.1.1'
+ VERSION = '0.1.2'
end
|
Bumped version to <I>.
|
DavidEGrayson_ruby_ecdsa
|
train
|
9a34f0a419b1a704b29a7ebeb98b7ec2a0824497
|
diff --git a/packages/node_modules/@ciscospark/plugin-teams/test/integration/spec/teams.js b/packages/node_modules/@ciscospark/plugin-teams/test/integration/spec/teams.js
index <HASH>..<HASH> 100644
--- a/packages/node_modules/@ciscospark/plugin-teams/test/integration/spec/teams.js
+++ b/packages/node_modules/@ciscospark/plugin-teams/test/integration/spec/teams.js
@@ -12,7 +12,6 @@ import {assert} from '@ciscospark/test-helper-chai';
import sinon from '@ciscospark/test-helper-sinon';
import testUsers from '@ciscospark/test-helper-test-users';
import {find} from 'lodash';
-import {nodeOnly} from '@ciscospark/test-helper-mocha';
const http = require('http');
const path = require('path');
@@ -81,11 +80,11 @@ describe('plugin-teams', function () {
spark = new CiscoSpark({credentials: user.token});
}));
- nodeOnly(before)(() => {
+ before(() => {
proxy.listen(3000);
});
- nodeOnly(after)(() => proxy.close());
+ after(() => proxy.close());
describe('#teams', () => {
describe('#create()', () => {
|
refactor(plugin-teams): remove nodeOnly, which does not work
|
webex_spark-js-sdk
|
train
|
d56bad47fcbae99fb5ff6da14bbef5b0784d5060
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,7 +1,5 @@
var _ = require('lodash');
-var util = require('util'); // FIXME: DEBUG
-
// Constants {{{
var FK_OBJECTID = 1; // 1:1 objectID mapping
var FK_OBJECTID_ARRAY = 2; // Array of objectIDs
|
BUGFIX: Removed some debugging artefacts
|
hash-bang_Node-Mongoose-Scenario
|
train
|
d6a147c37e3090fbd21119ab8922ce32329456d9
|
diff --git a/src/core/calmar.py b/src/core/calmar.py
index <HASH>..<HASH> 100644
--- a/src/core/calmar.py
+++ b/src/core/calmar.py
@@ -105,7 +105,7 @@ def calmar(data, margins, param = {}, pondini='wprm_init'):
nj = 1
margins_new = {}
-
+ margins_new_dict = {}
for var, val in margins.iteritems():
if isinstance(val, dict):
dummies_dict = build_dummies_dict(data[var])
@@ -114,6 +114,9 @@ def calmar(data, margins, param = {}, pondini='wprm_init'):
cat_varname = var + '_' + str(cat)
data[cat_varname] = dummies_dict[cat]
margins_new[cat_varname] = nb
+ if not margins_new_dict.has_key(var):
+ margins_new_dict[var] = {}
+ margins_new_dict[var][cat] = nb
pop += nb
k += 1
nj += 1
@@ -125,10 +128,12 @@ def calmar(data, margins, param = {}, pondini='wprm_init'):
for cat, nb in val.iteritems():
cat_varname = var + '_' + str(cat)
margins_new[cat_varname] = nb*totalpop/pop
+ margins_new_dict[var][cat] = nb
else:
raise Exception('calmar: categorical variable ', var, ' is inconsistent with population')
else:
margins_new[var] = val
+ margins_new_dict[var] = val
nj += 1
# On conserve systematiquement la population
@@ -173,7 +178,7 @@ def calmar(data, margins, param = {}, pondini='wprm_init'):
pondfin = d*F( dot(x, lambdasol))
print "nombre d'essais: ", essai
- return pondfin, lambdasol, margins_new
+ return pondfin, lambdasol, margins_new_dict
def test1():
data = dict(ident = range(4),
@@ -266,7 +271,7 @@ def test4():
n, bins, patches = hist(weight_ratio, 100, normed=1, histtype='stepfilled')
setp(patches, 'facecolor', 'g', 'alpha', 0.75)
show()
- plot(wprm, pondfin/wprm, 'x')
+ plot(data['wprm'], pondfin/data['wprm'], 'x')
show()
if __name__ == '__main__':
|
Calibration almost migrated to use DataFrame(s)
Need some work on menu/combobox and
load/save config
|
openfisca_openfisca-core
|
train
|
46ecc3507faca171bbcb027188568413a95cff46
|
diff --git a/public/js/app-middle.js b/public/js/app-middle.js
index <HASH>..<HASH> 100644
--- a/public/js/app-middle.js
+++ b/public/js/app-middle.js
@@ -153,6 +153,10 @@
}
app.starter.$(function (next) {
+ if (app.middle.disable) {
+ return next();
+ }
+
app.store("middle", function (store) {
store.get(ID, function (id) {
app.middle.id = (id && id.id) || app.utils.uuid();
|
allow the middle layer to be diabled.
|
jolira_site-manager-baseline
|
train
|
2d1e9e4b1973721f020b31a2941db08a3f12516a
|
diff --git a/lib/Config.py b/lib/Config.py
index <HASH>..<HASH> 100644
--- a/lib/Config.py
+++ b/lib/Config.py
@@ -21,6 +21,7 @@ This module contains some definitions to configure the application.
DEFAULT_ACTION = 'ls'
COLORS = True
HIGHLIGHT_PROJECTS_CONTEXTS = True
+LIST_LIMIT=25
FILENAME = 'todo.txt'
ARCHIVE_FILENAME = 'done.txt'
diff --git a/lib/Filter.py b/lib/Filter.py
index <HASH>..<HASH> 100644
--- a/lib/Filter.py
+++ b/lib/Filter.py
@@ -15,14 +15,13 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Filter(object):
- def filter(self, p_todos, p_limit=None):
+ def filter(self, p_todos):
"""
Filters a list of todos. Truncates the list after p_limit todo
items (or no maximum limit if omitted).
"""
- result = [t for t in p_todos if self.match(t)]
- return result[:p_limit]
+ return [t for t in p_todos if self.match(t)]
def match(self, p_todo):
""" Default match value. """
@@ -111,3 +110,10 @@ class InstanceFilter(Filter):
return True
except ValueError:
return False
+
+class LimitFilter(Filter):
+ def __init__(self, p_limit):
+ self.limit = max(0, p_limit)
+
+ def filter(self, p_todos):
+ return p_todos[:self.limit]
diff --git a/lib/ListCommand.py b/lib/ListCommand.py
index <HASH>..<HASH> 100644
--- a/lib/ListCommand.py
+++ b/lib/ListCommand.py
@@ -57,6 +57,8 @@ class ListCommand(Command.Command):
if len(args) > 0:
filters.append(Filter.GrepFilter(args[0]))
+ filters.append(Filter.LimitFilter(Config.LIST_LIMIT))
+
self.out(self.todolist.view(sorter, filters).pretty_print())
def usage(self):
diff --git a/test/FilterTest.py b/test/FilterTest.py
index <HASH>..<HASH> 100644
--- a/test/FilterTest.py
+++ b/test/FilterTest.py
@@ -24,20 +24,6 @@ import Todo
import TodoList
class FilterTest(unittest.TestCase):
- def test_filter1(self):
- todo = Todo.Todo("(C) Relevant")
- relevance = Filter.RelevanceFilter()
- result = relevance.filter([todo], 0)
-
- self.assertEquals(result, [])
-
- def test_filter2(self):
- todo = Todo.Todo("(C) Relevant")
- relevance = Filter.RelevanceFilter()
- result = relevance.filter([todo], 100)
-
- self.assertEquals(result, [todo])
-
def test_filter3(self):
todo = Todo.Todo("(C) Relevant")
relevance = Filter.RelevanceFilter()
@@ -126,3 +112,40 @@ class FilterTest(unittest.TestCase):
filtered_todos = instance_filter.filter([])
self.assertEquals([], filtered_todos)
+
+ def test_filter12(self):
+ """ Test limit filter. """
+ todos = load_file('data/FilterTest1.txt')
+ limit_filter = Filter.LimitFilter(0)
+
+ filtered_todos = limit_filter.filter(todos)
+
+ self.assertEquals([], filtered_todos)
+
+ def test_filter13(self):
+ """ Test limit filter. """
+ todos = load_file('data/FilterTest1.txt')
+ limit_filter = Filter.LimitFilter(1)
+
+ filtered_todos = limit_filter.filter(todos)
+
+ self.assertEquals(len(filtered_todos), 1)
+ self.assertEquals(filtered_todos[0].source(), '(C) This is part of some +Project')
+
+ def test_filter14(self):
+ """ Test limit filter. """
+ todos = load_file('data/FilterTest1.txt')
+ limit_filter = Filter.LimitFilter(-1)
+
+ filtered_todos = limit_filter.filter(todos)
+
+ self.assertEquals([], filtered_todos)
+
+ def test_filter15(self):
+ """ Test limit filter. """
+ todos = load_file('data/FilterTest1.txt')
+ limit_filter = Filter.LimitFilter(100)
+
+ filtered_todos = limit_filter.filter(todos)
+
+ self.assertEquals(len(filtered_todos), 4)
|
Introduce LimitFilter which truncates todolist at given number.
|
bram85_topydo
|
train
|
474196a9b47929b9938d805ce8abb5cb95f1836f
|
diff --git a/lib/rprogram/compat.rb b/lib/rprogram/compat.rb
index <HASH>..<HASH> 100644
--- a/lib/rprogram/compat.rb
+++ b/lib/rprogram/compat.rb
@@ -5,7 +5,7 @@ module RProgram
#
# Compat.arch #=> "linux"
#
- def self.platform
+ def Compat.platform
RUBY_PLATFORM.split('-').last
end
@@ -16,7 +16,7 @@ module RProgram
#
# Compat.paths #=> ["/bin", "/usr/bin"]
#
- def self.paths
+ def Compat.paths
# return an empty array in case
# the PATH variable does not exist
return [] unless ENV['PATH']
@@ -34,8 +34,8 @@ module RProgram
#
# Compat.find_program('as') #=> "/usr/bin/as"
#
- def self.find_program(name)
- self.paths.each do |dir|
+ def Compat.find_program(name)
+ Compat.paths.each do |dir|
full_path = File.expand_path(File.join(dir,name))
return full_path if File.file?(full_path)
@@ -51,8 +51,8 @@ module RProgram
#
# Compat.find_program_by_names("gas","as") #=> "/usr/bin/as"
#
- def self.find_program_by_names(*names)
- names.map { |name| self.find_program(name) }.compact.first
+ def Compat.find_program_by_names(*names)
+ names.map { |name| Compat.find_program(name) }.compact.first
end
end
end
|
Put methods in the Compat namespace.
|
postmodern_rprogram
|
train
|
406f583777076fa4e9b35f726d92888270005a8f
|
diff --git a/src/label/base.js b/src/label/base.js
index <HASH>..<HASH> 100644
--- a/src/label/base.js
+++ b/src/label/base.js
@@ -282,7 +282,7 @@ class Label extends Component {
VisualCenter(labels, shapes);
}
if (type === 'treemap') {
- canLabelFill();
+ canLabelFill(labels, shapes);
} else {
const greedyPlacement = new Greedy();
greedyPlacement.adjust(labels, shapes, type);
|
fix(label-base): fix treemap area calculation
|
antvis_component
|
train
|
4b0e5892258077f8c55a0419e00d43d9286f3c0b
|
diff --git a/make_release.py b/make_release.py
index <HASH>..<HASH> 100644
--- a/make_release.py
+++ b/make_release.py
@@ -112,5 +112,6 @@ if token:
response = requests.post(releases_url, json=release, headers={'Authorization': 'token ' + token})
print(response.status_code, response.text)
-run(['python', 'setup.py', 'sdist', '--format=zip', 'bdist', '--format=zip', 'bdist_wheel', '--universal', 'bdist_wininst'], check=True)
+run(['python', 'setup.py', 'clean'], check=True)
+run(['python', 'setup.py', 'sdist', '--format=zip', 'bdist_wheel', '--universal'], check=True)
run(['twine', 'upload', 'dist/*'], check=True, shell=True)
|
Remove features deprecated by PyPI
|
boppreh_mouse
|
train
|
094d875720ff35176f05510eb410541803268111
|
diff --git a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java
index <HASH>..<HASH> 100644
--- a/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java
+++ b/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java
@@ -286,10 +286,14 @@ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> {
handleDistributable(deploymentInfo);
if (securityFunction.getOptionalValue() == null) {
- handleIdentityManager(deploymentInfo);
- handleJASPIMechanism(deploymentInfo);
- handleJACCAuthorization(deploymentInfo);
- handleAuthManagerLogout(deploymentInfo, mergedMetaData);
+ if (securityDomain != null) {
+ handleIdentityManager(deploymentInfo);
+ handleJASPIMechanism(deploymentInfo);
+ handleJACCAuthorization(deploymentInfo);
+ handleAuthManagerLogout(deploymentInfo, mergedMetaData);
+ } else {
+ deploymentInfo.setSecurityDisabled(true);
+ }
if(mergedMetaData.isUseJBossAuthorization()) {
deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager()));
@@ -431,9 +435,6 @@ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> {
}
private void handleAuthManagerLogout(DeploymentInfo deploymentInfo, JBossWebMetaData mergedMetaData) {
- if(securityDomain == null) {
- return;
- }
AuthenticationManager manager = securityDomainContextValue.getValue().getAuthenticationManager();
deploymentInfo.addNotificationReceiver(new LogoutNotificationReceiver(manager, securityDomain));
if(mergedMetaData.isFlushOnSessionInvalidation()) {
@@ -470,9 +471,6 @@ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> {
* @param deploymentInfo
*/
private void handleJASPIMechanism(final DeploymentInfo deploymentInfo) {
- if(securityDomain == null) {
- return;
- }
ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain);
if (applicationPolicy != null && JASPIAuthenticationInfo.class.isInstance(applicationPolicy.getAuthenticationInfo())) {
@@ -496,9 +494,6 @@ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> {
* @param deploymentInfo the {@link DeploymentInfo} instance.
*/
private void handleJACCAuthorization(final DeploymentInfo deploymentInfo) {
- if(securityDomain == null) {
- return;
- }
// TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml
ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain);
if (applicationPolicy != null) {
@@ -521,13 +516,11 @@ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> {
}
private void handleIdentityManager(final DeploymentInfo deploymentInfo) {
- if(securityDomain != null) {
- SecurityDomainContext sdc = securityDomainContextValue.getValue();
- deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc));
- AuditManager auditManager = sdc.getAuditManager();
- if (auditManager != null && !mergedMetaData.isDisableAudit()) {
- deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager));
- }
+ SecurityDomainContext sdc = securityDomainContextValue.getValue();
+ deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc));
+ AuditManager auditManager = sdc.getAuditManager();
+ if (auditManager != null && !mergedMetaData.isDisableAudit()) {
+ deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager));
}
}
|
[WFLY-<I>] If security is disabled pass this to the DeploymentInfo.
|
wildfly_wildfly
|
train
|
077c546391bcfdb428c8514f2902d5e9045ac5d8
|
diff --git a/marcx.py b/marcx.py
index <HASH>..<HASH> 100644
--- a/marcx.py
+++ b/marcx.py
@@ -238,7 +238,7 @@ class Record(pymarc.Record):
marc.add('020', a='0201657880', z='0201802398')
"""
- if tag.startswith("00") and (data is None or data == "") and not bool(self.strict):
+ if tag.startswith("00") and (data is None or data == "") and not self.strict:
return
if data:
@@ -280,6 +280,13 @@ class Record(pymarc.Record):
subfields += [key, val]
else:
raise ValueError('subfield values must be strings')
+
+ if not any(subfields[1::2]):
+ if self.strict:
+ raise ValueError('none of the subfields contains a value')
+ else:
+ return
+
field = pymarc.Field(tag, indicators, subfields=subfields)
self.add_field(field)
diff --git a/tests/test_misc.py b/tests/test_misc.py
index <HASH>..<HASH> 100644
--- a/tests/test_misc.py
+++ b/tests/test_misc.py
@@ -399,7 +399,6 @@ class RecordTests(unittest.TestCase):
def test_add_strict_flag(self):
obj = marcx.Record()
- obj.strict = True
with self.assertRaises(ValueError):
obj.add("007", data="")
@@ -408,3 +407,19 @@ class RecordTests(unittest.TestCase):
obj.add("001", data="")
obj.add("007", data="")
self.assertEquals(len(obj.get_fields()), 0)
+
+ def test_add_many_empty_subfields(self):
+ obj = marcx.Record()
+ obj.strict = True
+ with self.assertRaises(ValueError):
+ obj.add("245", a="", b="", c="")
+
+ obj = marcx.Record()
+ obj.strict = False
+ obj.add("245", a="", b="", c="")
+ self.assertEquals(len(obj.get_fields()), 0)
+
+ obj = marcx.Record()
+ obj.strict = False
+ obj.add("245", a="", b="", c="x")
+ self.assertEquals(len(obj.get_fields()), 1)
|
scrict handling of subfields
Default mode is strict mode, where invalid cases fail with an Exception.
For example adding a field with only empty subfields will result in an error.
To be more forgiving, set the Record.strict flag to False. This won't raise
errors, but tries to keep the record MARC conform by not adding subfields that
only contain empty values, for example.
|
ubleipzig_marcx
|
train
|
6301a22cc2d1cd756db018b663fba9efa8490a93
|
diff --git a/protocols/raft/src/main/java/io/atomix/protocols/raft/RaftServer.java b/protocols/raft/src/main/java/io/atomix/protocols/raft/RaftServer.java
index <HASH>..<HASH> 100644
--- a/protocols/raft/src/main/java/io/atomix/protocols/raft/RaftServer.java
+++ b/protocols/raft/src/main/java/io/atomix/protocols/raft/RaftServer.java
@@ -29,6 +29,8 @@ import io.atomix.protocols.raft.storage.log.RaftLog;
import io.atomix.storage.StorageLevel;
import io.atomix.utils.concurrent.ThreadModel;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
@@ -39,6 +41,7 @@ import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
+import static io.atomix.protocols.raft.RaftException.*;
/**
* Provides a standalone implementation of the <a href="http://raft.github.io/">Raft consensus algorithm</a>.
@@ -153,7 +156,12 @@ public interface RaftServer {
* @return The server builder.
*/
static Builder builder() {
- return builder(null);
+ try {
+ InetAddress address = InetAddress.getByName("0.0.0.0");
+ return builder(NodeId.from(address.getHostName()));
+ } catch (UnknownHostException e) {
+ throw new ConfigurationException("Cannot configure local node", e);
+ }
}
/**
|
Fix bad builder, arg is passed directly into checkNotNull..
|
atomix_atomix
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.