content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
use relative path in pipeprefix
971aad1b132a5ec37216c0d755d3ea59afc63812
<ide><path>test/common/index.js <ide> Object.defineProperty(exports, 'hasFipsCrypto', { <ide> }); <ide> <ide> { <del> const pipePrefix = exports.isWindows ? '\\\\.\\pipe\\' : `${exports.tmpDir}/`; <add> const localRelative = path.relative(process.cwd(), `${exports.tmpDir}/`); <add> const pipePrefix = exports.isWindows ? '\\\\.\\pipe\\' : localRelative; <ide> const pipeName = `node-test.${process.pid}.sock`; <ide> exports.PIPE = pipePrefix + pipeName; <ide> }
1
Text
Text
add link to unofficial discord
474e94d4c0d59a12f8feb1b826a566f2de009a4c
<ide><path>README.md <ide> search these unofficial resources: <ide> * [Questions tagged 'node.js' on StackOverflow][] <ide> * [#node.js channel on chat.freenode.net][]. See <http://nodeirc.info/> for more <ide> information. <add>* [Node.js Discord Community](https://discordapp.com/invite/v7rrPdE) <ide> * [Node.js Slack Community](https://node-js.slack.com/): Visit <ide> [nodeslackers.com](http://www.nodeslackers.com/) to register. <ide>
1
Python
Python
fix decimal support with yamlrenderer
b730aec0f46e2b849b3c597bcf1a1bcdc158e415
<ide><path>rest_framework/tests/test_renderers.py <ide> def test_render_and_parse(self): <ide> data = parser.parse(StringIO(content)) <ide> self.assertEqual(obj, data) <ide> <add> def test_render_decimal(self): <add> """ <add> Test YAML decimal rendering. <add> """ <add> renderer = YAMLRenderer() <add> content = renderer.render({'field': Decimal('111.2')}, 'application/yaml') <add> self.assertYAMLContains(content, "field: '111.2'") <add> <add> def assertYAMLContains(self, content, string): <add> self.assertTrue(string in content, '%r not in %r' % (string, content)) <add> <ide> <ide> class XMLRendererTestCase(TestCase): <ide> """ <ide><path>rest_framework/utils/encoders.py <ide> def represent_mapping(self, tag, mapping, flow_style=None): <ide> node.flow_style = best_style <ide> return node <ide> <add> SafeDumper.add_representer(decimal.Decimal, <add> SafeDumper.represent_decimal) <add> <ide> SafeDumper.add_representer(SortedDict, <ide> yaml.representer.SafeRepresenter.represent_dict) <ide> SafeDumper.add_representer(DictWithMetadata,
2
Javascript
Javascript
add jsdoc typings for http
d3162da8ddc47b7e2ac08d7e2006ea52a2246f19
<ide><path>lib/http.js <ide> const { <ide> } = require('_http_server'); <ide> let maxHeaderSize; <ide> <add>/** <add> * Returns a new instance of `http.Server`. <add> * @param {{ <add> * IncomingMessage?: IncomingMessage; <add> * ServerResponse?: ServerResponse; <add> * insecureHTTPParser?: boolean; <add> * maxHeaderSize?: number; <add> * }} [opts] <add> * @param {Function} [requestListener] <add> * @returns {Server} <add> */ <ide> function createServer(opts, requestListener) { <ide> return new Server(opts, requestListener); <ide> } <ide> <add>/** <add> * @typedef {Object} HTTPRequestOptions <add> * @property {httpAgent.Agent | boolean} [agent] <add> * @property {string} [auth] <add> * @property {Function} [createConnection] <add> * @property {number} [defaultPort] <add> * @property {number} [family] <add> * @property {Object} [headers] <add> * @property {number} [hints] <add> * @property {string} [host] <add> * @property {string} [hostname] <add> * @property {boolean} [insecureHTTPParser] <add> * @property {string} [localAddress] <add> * @property {number} [localPort] <add> * @property {Function} [lookup] <add> * @property {number} [maxHeaderSize] <add> * @property {string} [method] <add> * @property {string} [path] <add> * @property {number} [port] <add> * @property {string} [protocol] <add> * @property {boolean} [setHost] <add> * @property {string} [socketPath] <add> * @property {number} [timeout] <add> * @property {AbortSignal} [signal] <add> */ <add> <add>/** <add> * Makes an HTTP request. <add> * @param {string | URL} url <add> * @param {HTTPRequestOptions} [options] <add> * @param {Function} [cb] <add> * @returns {ClientRequest} <add> */ <ide> function request(url, options, cb) { <ide> return new ClientRequest(url, options, cb); <ide> } <ide> <add>/** <add> * Makes a `GET` HTTP request. <add> * @param {string | URL} url <add> * @param {HTTPRequestOptions} [options] <add> * @param {Function} [cb] <add> * @returns {ClientRequest} <add> */ <ide> function get(url, options, cb) { <ide> const req = request(url, options, cb); <ide> req.end();
1
Go
Go
fix swarm pending state tests
fa3b5964b93260acb0083500377756300ddbd43d
<ide><path>integration-cli/docker_api_swarm_test.go <ide> func (s *DockerSwarmSuite) TestApiSwarmLeaveOnPendingJoin(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> id = strings.TrimSpace(id) <ide> <del> go d2.Join(swarm.JoinRequest{ <del> RemoteAddrs: []string{"nosuchhost:1234"}, <add> err = d2.Join(swarm.JoinRequest{ <add> RemoteAddrs: []string{"123.123.123.123:1234"}, <ide> }) <add> c.Assert(err, check.NotNil) <add> c.Assert(err.Error(), checker.Contains, "Timeout was reached") <ide> <del> waitAndAssert(c, defaultReconciliationTimeout, d2.checkLocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <add> info, err := d2.info() <add> c.Assert(err, checker.IsNil) <add> c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStatePending) <add> <add> c.Assert(d2.Leave(true), checker.IsNil) <ide> <ide> waitAndAssert(c, defaultReconciliationTimeout, d2.checkActiveContainerCount, checker.Equals, 1) <ide> <ide> func (s *DockerSwarmSuite) TestApiSwarmLeaveOnPendingJoin(c *check.C) { <ide> // #23705 <ide> func (s *DockerSwarmSuite) TestApiSwarmRestoreOnPendingJoin(c *check.C) { <ide> d := s.AddDaemon(c, false, false) <del> go d.Join(swarm.JoinRequest{ <del> RemoteAddrs: []string{"nosuchhost:1234"}, <add> err := d.Join(swarm.JoinRequest{ <add> RemoteAddrs: []string{"123.123.123.123:1234"}, <ide> }) <add> c.Assert(err, check.NotNil) <add> c.Assert(err.Error(), checker.Contains, "Timeout was reached") <ide> <del> waitAndAssert(c, defaultReconciliationTimeout, d.checkLocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) <add> waitAndAssert(c, defaultReconciliationTimeout, d.checkLocalNodeState, checker.Equals, swarm.LocalNodeStatePending) <ide> <ide> c.Assert(d.Stop(), checker.IsNil) <ide> c.Assert(d.Start(), checker.IsNil)
1
Javascript
Javascript
improve performance of namespace stringification
0eae4c91d196b97decb34be66cd45d08d3fa8a44
<ide><path>packages/sproutcore-metal/lib/mixin.js <ide> function processNames(paths, root, seen) { <ide> paths.length = idx; // cut out last item <ide> } <ide> <add>function findNamespaces() { <add> var Namespace = SC.Namespace, obj; <add> <add> if (Namespace.PROCESSED) { return; } <add> <add> for (var prop in window) { <add> if (!window.hasOwnProperty(prop)) { continue; } <add> <add> obj = window[prop]; <add> <add> if (obj instanceof Namespace) { <add> obj[NAME_KEY] = prop; <add> } <add> } <add>} <add> <add>SC.identifyNamespaces = findNamespaces; <add> <ide> superClassString = function(mixin) { <ide> var superclass = mixin.superclass; <ide> if (superclass) { <ide> superClassString = function(mixin) { <ide> } <ide> <ide> classToString = function() { <del> if (!this[NAME_KEY] && !classToString.processed) { <del> classToString.processed = true; <del> processNames([], window, {}); <add> var Namespace = SC.Namespace, namespace; <add> <add> // TODO: Namespace should really be in Metal <add> if (Namespace) { <add> if (!this[NAME_KEY] && !classToString.processed) { <add> if (!Namespace.PROCESSED) { <add> findNamespaces(); <add> Namespace.PROCESSED = true; <add> } <add> <add> classToString.processed = true; <add> <add> var namespaces = Namespace.NAMESPACES; <add> for (var i=0, l=namespaces.length; i<l; i++) { <add> namespace = namespaces[i]; <add> processNames([namespace.toString()], namespace, {}); <add> } <add> } <ide> } <ide> <ide> if (this[NAME_KEY]) { <ide> classToString = function() { <ide> return "(unknown mixin)"; <ide> } <ide> } <del> <del> return this[NAME_KEY] || "(unknown mixin)"; <ide> }; <ide> <ide> Mixin.prototype.toString = classToString; <ide><path>packages/sproutcore-runtime/lib/system/namespace.js <ide> require('sproutcore-runtime/system/object'); <ide> <ide> /** <ide> @private <del> A Namespace is an object usually used to contain other objects or methods <add> A Namespace is an object usually used to contain other objects or methods <ide> such as an application or framework. Create a namespace anytime you want <ide> to define one of these new containers. <del> <add> <ide> # Example Usage <del> <add> <ide> MyFramework = SC.Namespace.create({ <ide> VERSION: '1.0.0' <ide> }); <del> <add> <ide> */ <del>SC.Namespace = SC.Object.extend(); <add>SC.Namespace = SC.Object.extend({ <add> init: function() { <add> SC.Namespace.NAMESPACES.push(this); <add> SC.Namespace.PROCESSED = false; <add> }, <add> <add> toString: function() { <add> SC.identifyNamespaces(); <add> return this[SC.GUID_KEY+'_name']; <add> }, <add> <add> destroy: function() { <add> var namespaces = SC.Namespace.NAMESPACES; <add> window[this.toString()] = undefined; <add> namespaces.splice(namespaces.indexOf(this), 1); <add> this._super(); <add> } <add>}); <add> <add>SC.Namespace.NAMESPACES = []; <add>SC.Namespace.PROCESSED = true; <ide><path>packages/sproutcore-runtime/tests/system/namespace/base_test.js <ide> // License: Licensed under MIT license (see license.js) <ide> // ========================================================================== <ide> <del>module('SC.Namepsace'); <add>module('SC.Namespace', { <add> teardown: function() { <add> if (window.NamespaceA) { window.NamespaceA.destroy(); } <add> if (window.NamespaceB) { window.NamespaceB.destroy(); } <add> } <add>}); <ide> <ide> test('SC.Namespace should be a subclass of SC.Object', function() { <ide> ok(SC.Object.detect(SC.Namespace)); <ide> }); <add> <add>test('SC.Namespace is found and named', function() { <add> var nsA = window.NamespaceA = SC.Namespace.create(); <add> equal(nsA.toString(), "NamespaceA", "namespaces should have a name if they are on window"); <add> <add> var nsB = window.NamespaceB = SC.Namespace.create(); <add> equal(nsB.toString(), "NamespaceB", "namespaces work if created after the first namespace processing pass"); <add>}); <add> <add>test("Classes under SC.Namespace are properly named", function() { <add> var nsA = window.NamespaceA = SC.Namespace.create(); <add> nsA.Foo = SC.Object.extend(); <add> equal(nsA.Foo.toString(), "NamespaceA.Foo", "Classes pick up their parent namespace"); <add> <add> nsA.Bar = SC.Object.extend(); <add> equal(nsA.Bar.toString(), "NamespaceA.Bar", "New Classes get the naming treatment too"); <add> <add> var nsB = window.NamespaceB = SC.Namespace.create(); <add> nsB.Foo = SC.Object.extend(); <add> equal(nsB.Foo.toString(), "NamespaceB.Foo", "Classes in new namespaces get the naming treatment"); <add>}); <ide><path>packages/sproutcore-views/tests/views/view/attribute_bindings_test.js <ide> test("should allow attributes to be set in the inBuffer state", function() { <ide> equals(parentView.get('childViews')[0].$().attr('foo'), 'baz'); <ide> <ide> parentView.destroy(); <del> <add> Test.destroy(); <ide> }); <ide>
4
Javascript
Javascript
put error filtering in the handler
87ae387ecb3fffc73338cc031d8fbf4f10ea978f
<ide><path>api-server/server/middlewares/sentry-error-handler.js <ide> import { Handlers, captureException } from '@sentry/node'; <ide> import { sentry } from '../../../config/secrets'; <add>import { isHandledError } from '../utils/create-handled-error'; <ide> <add>// sends directly to Sentry <ide> export function reportError(err) { <ide> return sentry.dns === 'dsn_from_sentry_dashboard' <ide> ? console.error(err) <ide> : captureException(err); <ide> } <ide> <add>// determines which errors should be reported <ide> export default function sentryErrorHandler() { <ide> return sentry.dns === 'dsn_from_sentry_dashboard' <ide> ? (req, res, next) => next() <ide> : Handlers.errorHandler({ <del> shouldHandleError(error) { <del> // NOTE: 400 is too low, this is just for debugging <del> return !error.status || error.status >= 400; <add> shouldHandleError(err) { <add> // CSRF errors have status 403, consider ignoring them once csurf is <add> // no longer rejecting people incorrectly. <add> return ( <add> !isHandledError(err) && <add> (!err.status || err.status === 403 || err.status >= 500) <add> ); <ide> } <ide> }); <ide> }
1
Ruby
Ruby
fix build failure being non-verbose when --verbose
beb5f9761415899f587a0a61ec795381b9e1764b
<ide><path>Library/Homebrew/formula.rb <ide> def system cmd, *args <ide> f.puts <ide> require 'cmd/--config' <ide> Homebrew.write_build_config(f) <del> raise BuildError.new(self, cmd, args, $?) <add> raise ErrorDuringExecution <ide> end <ide> end <del> <add> rescue ErrorDuringExecution => e <add> raise BuildError.new(self, cmd, args, $?) <ide> ensure <ide> f.close if f <ide> removed_ENV_variables.each do |key, value|
1
Javascript
Javascript
fix permanent deoptimizations
e283319969bc0940ed6baff2637608488ef0c195
<ide><path>lib/_http_agent.js <ide> Agent.prototype.getName = function getName(options) { <ide> return name; <ide> }; <ide> <del>Agent.prototype.addRequest = function addRequest(req, options) { <add>Agent.prototype.addRequest = function addRequest(req, options, port/*legacy*/, <add> localAddress/*legacy*/) { <ide> // Legacy API: addRequest(req, host, port, localAddress) <ide> if (typeof options === 'string') { <ide> options = { <ide> host: options, <del> port: arguments[2], <del> localAddress: arguments[3] <add> port, <add> localAddress <ide> }; <ide> } <ide> <ide><path>lib/_http_client.js <ide> function ClientRequest(options, cb) { <ide> 'Expected "' + expectedProtocol + '"'); <ide> } <ide> <del> const defaultPort = options.defaultPort || <del> this.agent && this.agent.defaultPort; <add> var defaultPort = options.defaultPort || <add> this.agent && this.agent.defaultPort; <ide> <ide> var port = options.port = options.port || defaultPort || 80; <ide> var host = options.host = validateHost(options.hostname, 'hostname') || <ide> function ClientRequest(options, cb) { <ide> <ide> var called = false; <ide> <del> const oncreate = (err, socket) => { <add> var oncreate = (err, socket) => { <ide> if (called) <ide> return; <ide> called = true; <ide> function ClientRequest(options, cb) { <ide> this._deferToConnect(null, null, () => this._flush()); <ide> }; <ide> <add> var newSocket; <ide> if (this.socketPath) { <ide> this._last = true; <ide> this.shouldKeepAlive = false; <del> const optionsPath = { <add> var optionsPath = { <ide> path: this.socketPath, <ide> timeout: this.timeout <ide> }; <del> const newSocket = this.agent.createConnection(optionsPath, oncreate); <add> newSocket = this.agent.createConnection(optionsPath, oncreate); <ide> if (newSocket && !called) { <ide> called = true; <ide> this.onSocket(newSocket); <ide> function ClientRequest(options, cb) { <ide> this._last = true; <ide> this.shouldKeepAlive = false; <ide> if (typeof options.createConnection === 'function') { <del> const newSocket = options.createConnection(options, oncreate); <add> newSocket = options.createConnection(options, oncreate); <ide> if (newSocket && !called) { <ide> called = true; <ide> this.onSocket(newSocket);
2
Python
Python
change the chunk_iter function to handle
a192f61e0825150e54e15fdc451cf37e23532b3f
<ide><path>src/transformers/pipelines/automatic_speech_recognition.py <ide> def chunk_iter(inputs, feature_extractor, chunk_len, stride_left, stride_right): <ide> chunk = inputs[i : i + chunk_len] <ide> processed = feature_extractor(chunk, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt") <ide> _stride_left = 0 if i == 0 else stride_left <del> is_last = i + step >= inputs_len <add> is_last = i + step + stride_left >= inputs_len <ide> _stride_right = 0 if is_last else stride_right <del> <ide> if chunk.shape[0] > _stride_left: <ide> yield {"is_last": is_last, "stride": (chunk.shape[0], _stride_left, _stride_right), **processed} <ide> <ide><path>tests/pipelines/test_pipelines_automatic_speech_recognition.py <ide> def test_chunk_iterator(self): <ide> self.assertEqual([o["input_values"].shape for o in outs], [(1, 80), (1, 20)]) <ide> self.assertEqual([o["is_last"] for o in outs], [False, True]) <ide> <add> # one chunk since first is also last, because it contains only data <add> # in the right strided part we just mark that part as non stride <add> # This test is specifically crafted to trigger a bug if next chunk <add> # would be ignored by the fact that all the data would be <add> # contained in the strided left data. <add> outs = list(chunk_iter(inputs, feature_extractor, 105, 5, 5)) <add> self.assertEqual(len(outs), 1) <add> self.assertEqual([o["stride"] for o in outs], [(100, 0, 0)]) <add> self.assertEqual([o["input_values"].shape for o in outs], [(1, 100)]) <add> self.assertEqual([o["is_last"] for o in outs], [True]) <add> <ide> @require_torch <ide> def test_chunk_iterator_stride(self): <ide> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
2
Mixed
Python
add run individual step only option
088e24fb3a99d081b5e02a0815f23234f094d3af
<ide><path>research/minigo/README.md <ide> # MiniGo <ide> This is a simplified implementation of MiniGo based on the code provided by the authors: [MiniGo](https://github.com/tensorflow/minigo). <ide> <del>MiniGo is a minimalist Go engine modeled after AlphaGo Zero, built on MuGo. The current implementation consists of three main modules: the DualNet model, the Monte Carlo Tree Search (MCTS), and Go domain knowledge. Currently the **model** part is our focus. <add>MiniGo is a minimalist Go engine modeled after AlphaGo Zero, ["Mastering the Game of Go without Human <add>Knowledge"](https://www.nature.com/articles/nature24270). An useful one-diagram overview of Alphago Zero can be found in the [cheat sheet](https://medium.com/applied-data-science/alphago-zero-explained-in-one-diagram-365f5abf67e0). <ide> <del>This implementation maintains the features of model training and validation, and also provides evaluation of two Go models. <add>The implementation of MiniGo consists of three main components: the DualNet model, the Monte Carlo Tree Search (MCTS), and Go domain knowledge. Currently, the **DualNet model** is our focus. <ide> <ide> <del>## DualNet Model <add>## DualNet Architecture <add>DualNet is the neural network used in MiniGo. It's based on residual blocks with two heads output. Following is a brief overview of the DualNet architecture. <add> <add>### Input Features <ide> The input to the neural network is a [board_size * board_size * 17] image stack <ide> comprising 17 binary feature planes. 8 feature planes consist of binary values <ide> indicating the presence of the current player's stones; A further 8 feature <ide> planes represent the corresponding features for the opponent's stones; The final <ide> feature plane represents the color to play, and has a constant value of either 1 <del>if black is to play or 0 if white to play. Check `features.py` for more details. <add>if black is to play or 0 if white to play. Check [features.py](features.py) for more details. <ide> <add>### Neural Network Structure <ide> In MiniGo implementation, the input features are processed by a residual tower <ide> that consists of a single convolutional block followed by either 9 or 19 <ide> residual blocks. <ide> Each residual block applies the following modules sequentially to its input: <ide> 6. A skip connection that adds the input to the block <ide> 7. A rectifier non-linearity <ide> <del>Note: num_filter is 128 for 19 x 19 board size, and 32 for 9 x 9 board size. <add>Note: num_filter is 128 for 19 x 19 board size, and 32 for 9 x 9 board size in MiniGo implementation. <ide> <add>### Dual Heads Output <ide> The output of the residual tower is passed into two separate "heads" for <ide> computing the policy and value respectively. The policy head applies the <ide> following modules: <ide> The value head applies the following modules: <ide> 6. A fully connected linear layer to a scalar <ide> 7. A tanh non-linearity outputting a scalar in the range [-1, 1] <ide> <del>The overall network depth, in the 10 or 20 block network, is 19 or 39 <add>In MiniGo, the overall network depth, in the 10 or 20 block network, is 19 or 39 <ide> parameterized layers respectively for the residual tower, plus an additional 2 <ide> layers for the policy head and 3 layers for the value head. <ide> <ide> ## Getting Started <ide> This project assumes you have virtualenv, TensorFlow (>= 1.5) and two other Go-related <ide> packages pygtp(>=0.4) and sgf (==0.5). <ide> <del> <ide> ## Training Model <del>One iteration of reinforcement learning consists of the following steps: <del> - Bootstrap: initializes a random model <del> - Selfplay: plays games with the latest model, producing data used for training <add>One iteration of reinforcement learning (RL) consists of the following steps: <add> - Bootstrap: initializes a random DualNet model. If the estimator directory has exist, the model is initialized with the last checkpoint. <add> - Selfplay: plays games with the latest model or the best model so far identified by evaluation, producing data used for training <ide> - Gather: groups games played with the same model into larger files of tfexamples. <del> - Train: trains a new model with the selfplay results from the most recent N <del> generations. <add> - Train: trains a new model with the selfplay results from the most recent N generations. <ide> <del> Run `minigo.py`. <add>To run the RL pipeline, issue the following command: <ide> ``` <del> python minigo.py <add> python minigo.py --base_dir=$HOME/minigo/ --board_size=9 --batch_size=256 <ide> ``` <add> Arguments: <add> * `--base_dir`: Base directory for MiniGo data and models. If not specified, it's set as /tmp/minigo/ by default. <add> * `--board_size`: Go board size. It can be either 9 or 19. By default, it's 9. <add> * `--batch_size`: Batch size for model training. If not specified, it's calculated based on go board size. <add> Use the `--help` or `-h` flag to get a full list of possible arguments. Besides all these arguments, other parameters about RL pipeline and DualNet model can be found and configured in [model_params.py](model_params.py). <add> <add>Suppose the base directory argument `base_dir` is `$HOME/minigo/` and we use 9 as the `board_size`. After model training, the following directories are created to store models and game data: <add> <add> $HOME/minigo # base directory <add> │ <add> ├── 9_size # directory for 9x9 board size <add> │ │ <add> │ ├── data <add> │ │ ├── holdout # holdout data for model validation <add> │ │ ├── selfplay # data generated by selfplay of each model <add> │ │ └── training_chunks # gatherd tf_examples for model training <add> │ │ <add> │ ├── estimator_model_dir # estimator working directory <add> │ │ <add> │ ├── trained_models # all the trained models <add> │ │ <add> │ └── sgf # sgf (smart go files) folder <add> │ ├── 000000-bootstrap # model name <add> │ │ ├── clean # clean sgf files of model selfplay <add> │ │ └── full # full sgf files of model selfplay <add> │ ├── ... <add> │ └── evaluate # clean sgf files of model evaluation <add> │ <add> └── ... <ide> <ide> ## Validating Model <del> Run `minigo.py` with `--validation` argument <add>To validate the trained model, issue the following command with `--validation` argument: <ide> ``` <del> python minigo.py --validation <del> ``` <del> The `--validation` argument is to generate holdout dataset for model validation <del> <del>## Evaluating MiniGo Models <del> Run `minigo.py` with `--evaluation` argument <add> python minigo.py --base_dir=$HOME/minigo/ --board_size=9 --batch_size=256 --validation <ide> ``` <del> python minigo.py --evaluation <del> ``` <del> The `--evaluation` argument is to invoke the evaluation between the latest model and the current best model. <del> <del>## Testing Pipeline <del>As the whole RL pipeline may takes hours to train even for a 9x9 board size, we provide a dummy model with a `--debug` mode for testing purpose. <ide> <del> Run `minigo.py` with `--debug` argument <del> ``` <del> python minigo.py --debug <del> ``` <del> The `--debug` argument is for testing purpose with a dummy model. <add>## Evaluating Models <add>The performance of two models are compared with evaluation step. Given two models, one plays black and the other plays white. They play several games (# of games can be configured by parameter `eval_games` in [model_params.py](model_params.py)), and the one wins by a margin of 55% will be the winner. <ide> <del>Validation and evaluation can also be tested with the dummy model by combing their corresponding arguments with `--debug`. <del>To test validation, run the following commands: <del> ``` <del> python minigo.py --debug --validation <del> ``` <del>To test evaluation, run the following commands: <add>To include the evaluation step in the RL pipeline, `--evaluation` argument can be specified to compare the performance of the `current_trained_model` and the `best_model_so_far`. The winner is used to update `best_model_so_far`. Run the following command to include evaluation step in the pipeline: <ide> ``` <del> python minigo.py --debug --evaluation <del> ``` <del>To test both validation and evaluation, run the following commands: <del> ``` <del> python minigo.py --debug --validation --evaluation <add> python minigo.py --base_dir=$HOME/minigo/ --board_size=9 --batch_size=256 --evaluation <ide> ``` <ide> <del>## MCTS and Go features (TODO) <del>Code clean up on MCTS and Go features. <add>## Testing Pipeline <add>As the whole RL pipeline may take hours to train even for a 9x9 board size, a `--test` argument is provided to test the pipeline quickly with a dummy neural network model. <add> <add>To test the RL pipeline with a dummy model, issue the following command: <add>``` <add> python minigo.py --base_dir=$HOME/minigo/ --board_size=9 --batch_size=256 --test <add>``` <add> <add>## Running Self-play Only <add>Self-play only option is provided to run selfplay step individually to generate training data in parallel. Issue the following command to run selfplay only with the latest trained model: <add>``` <add> python minigo.py --selfplay <add>``` <add>Other optional arguments: <add> * `--selfplay_model_name`: The name of the model used for selfplay only. If not specified, the latest trained model will be used for selfplay. <add> * `--selfplay_max_games`: The maximum number of games selfplay is required to generate. If not specified, the default parameter `max_games_per_generation` is used. <ide><path>research/minigo/dualnet.py <ide> def export_model(working_dir, model_path): <ide> tf.gfile.Copy(filename, destination_path) <ide> <ide> <del>def train(working_dir, tf_records, generation_num, params): <add>def train(working_dir, tf_records, generation, params): <ide> """Train the model for a specific generation. <ide> <ide> Args: <ide> working_dir: The model working directory to save model parameters, <ide> drop logs, checkpoints, and so on. <ide> tf_records: A list of tf_record filenames for training input. <del> generation_num: The generation to be trained. <add> generation: The generation to be trained. <ide> params: hyperparams of the model. <ide> <ide> Raises: <del> ValueError: if generation_num is not greater than 0. <add> ValueError: if generation is not greater than 0. <ide> """ <del> if generation_num <= 0: <add> if generation <= 0: <ide> raise ValueError('Model 0 is random weights') <ide> estimator = tf.estimator.Estimator( <ide> dualnet_model.model_fn, model_dir=working_dir, params=params) <del> max_steps = (generation_num * params.examples_per_generation <add> max_steps = (generation * params.examples_per_generation <ide> // params.batch_size) <ide> profiler_hook = tf.train.ProfilerHook(output_dir=working_dir, save_secs=600) <ide> <ide><path>research/minigo/gtp_wrapper.py <ide> def __init__(self, board_size): <ide> def set_size(self, n): <ide> if n != self.board_size: <ide> raise ValueError(( <del> '''Can't handle boardsize {n}!Restart with env var BOARD_SIZE={n}''' <del> ).format(n=n)) <add> "Can't handle boardsize {}! Please check the board size.").format(n)) <ide> <ide> def set_komi(self, komi): <ide> self.komi = komi <ide> def accomodate_out_of_turn(self, color): <ide> self.position.flip_playerturn(mutate=True) <ide> <ide> def make_move(self, color, vertex): <del> c = coords.from_pygtp(vertex) <add> c = coords.from_pygtp(self.board_size, vertex) <ide> # let's assume this never happens for now. <ide> # self.accomodate_out_of_turn(color) <ide> return self.play_move(c) <ide> def get_move(self, color): <ide> move = self.suggest_move(self.position) <ide> if self.should_resign(): <ide> return gtp.RESIGN <del> return coords.to_pygtp(move) <add> return coords.to_pygtp(self.board_size, move) <ide> <ide> def final_score(self): <ide> return self.position.result_string() <ide><path>research/minigo/minigo.py <ide> def bootstrap(estimator_model_dir, trained_models_dir, params): <ide> estimator_model_dir: tf.estimator model directory. <ide> trained_models_dir: Dir to save the trained models. Here to export the first <ide> bootstrapped generation. <del> params: An object of hyperparameters for the model. <add> params: A MiniGoParams instance of hyperparameters for the model. <ide> """ <ide> bootstrap_name = utils.generate_model_name(0) <ide> _ensure_dir_exists(trained_models_dir) <ide> def bootstrap(estimator_model_dir, trained_models_dir, params): <ide> dualnet.export_model(estimator_model_dir, bootstrap_model_path) <ide> <ide> <del>def selfplay(model_name, trained_models_dir, selfplay_dir, holdout_dir, sgf_dir, <del> params): <add>def selfplay(selfplay_dirs, selfplay_model, params): <ide> """Perform selfplay with a specific model. <ide> <ide> Args: <del> model_name: The name of the model used for selfplay. <del> trained_models_dir: The path to the model files. <del> selfplay_dir: Where to write the games. Set as 'base_dir/data/selfplay/'. <del> holdout_dir: Where to write the holdout data. Set as <del> 'base_dir/data/holdout/'. <del> sgf_dir: Where to write the sgf (Smart Game Format) files. Set as <del> 'base_dir/sgf/'. <del> params: An object of hyperparameters for the model. <add> selfplay_dirs: A dict to specify the directories used in selfplay. <add> selfplay_dirs = { <add> 'output_dir': output_dir, <add> 'holdout_dir': holdout_dir, <add> 'clean_sgf': clean_sgf, <add> 'full_sgf': full_sgf <add> } <add> selfplay_model: The actual Dualnet runner for selfplay. <add> params: A MiniGoParams instance of hyperparameters for the model. <ide> """ <del> print('Playing a game with model {}'.format(model_name)) <del> # Set paths for the model with 'model_name' <del> model_path = os.path.join(trained_models_dir, model_name) <del> output_dir = os.path.join(selfplay_dir, model_name) <del> holdout_dir = os.path.join(holdout_dir, model_name) <del> # clean_sgf is to write sgf file without comments. <del> # full_sgf is to write sgf file with comments. <del> clean_sgf = os.path.join(sgf_dir, model_name, 'clean') <del> full_sgf = os.path.join(sgf_dir, model_name, 'full') <del> <del> _ensure_dir_exists(output_dir) <del> _ensure_dir_exists(holdout_dir) <del> _ensure_dir_exists(clean_sgf) <del> _ensure_dir_exists(full_sgf) <del> <del> with utils.logged_timer('Loading weights from {} ... '.format(model_path)): <del> network = dualnet.DualNetRunner(model_path, params) <del> <ide> with utils.logged_timer('Playing game'): <ide> player = selfplay_mcts.play( <del> params.board_size, network, params.selfplay_readouts, <add> params.board_size, selfplay_model, params.selfplay_readouts, <ide> params.selfplay_resign_threshold, params.simultaneous_leaves, <ide> params.selfplay_verbose) <ide> <ide> def _write_sgf_data(dir_sgf, use_comments): <ide> os.path.join(dir_sgf, '{}.sgf'.format(output_name)), 'w') as f: <ide> f.write(player.to_sgf(use_comments=use_comments)) <ide> <del> _write_sgf_data(clean_sgf, use_comments=False) <del> _write_sgf_data(full_sgf, use_comments=True) <add> _write_sgf_data(selfplay_dirs['clean_sgf'], use_comments=False) <add> _write_sgf_data(selfplay_dirs['full_sgf'], use_comments=True) <ide> <ide> game_data = player.extract_data() <ide> tf_examples = preprocessing.make_dataset_from_selfplay(game_data, params) <ide> <ide> # Hold out 5% of games for evaluation. <ide> if random.random() < params.holdout_pct: <ide> fname = os.path.join( <del> holdout_dir, ('{}'+_TF_RECORD_SUFFIX).format(output_name)) <add> selfplay_dirs['holdout_dir'], output_name + _TF_RECORD_SUFFIX) <ide> else: <ide> fname = os.path.join( <del> output_dir, ('{}'+_TF_RECORD_SUFFIX).format(output_name)) <add> selfplay_dirs['output_dir'], output_name + _TF_RECORD_SUFFIX) <ide> <ide> preprocessing.write_tf_examples(fname, tf_examples) <ide> <ide> def gather(selfplay_dir, training_chunk_dir, params): <ide> selfplay_dir: Where to look for games. Set as 'base_dir/data/selfplay/'. <ide> training_chunk_dir: where to put collected games. Set as <ide> 'base_dir/data/training_chunks/'. <del> params: An object of hyperparameters for the model. <add> params: A MiniGoParams instance of hyperparameters for the model. <ide> """ <ide> # Check the selfplay data from the most recent 50 models. <ide> _ensure_dir_exists(training_chunk_dir) <ide> def gather(selfplay_dir, training_chunk_dir, params): <ide> f.write('\n'.join(sorted(already_processed))) <ide> <ide> <del>def train(trained_models_dir, estimator_model_dir, training_chunk_dir, params): <add>def train(trained_models_dir, estimator_model_dir, training_chunk_dir, <add> generation, params): <ide> """Train the latest model from gathered data. <ide> <ide> Args: <ide> trained_models_dir: Where to export the completed generation. <ide> estimator_model_dir: tf.estimator model directory. <ide> training_chunk_dir: Directory where gathered training chunks are. <del> params: An object of hyperparameters for the model. <add> generation: Which generation you are training. <add> params: A MiniGoParams instance of hyperparameters for the model. <ide> """ <del> model_num, model_name = utils.get_latest_model(trained_models_dir) <del> print('Initializing from model {}'.format(model_name)) <del> <del> new_model_name = utils.generate_model_name(model_num + 1) <add> new_model_name = utils.generate_model_name(generation) <ide> print('New model will be {}'.format(new_model_name)) <del> save_file = os.path.join(trained_models_dir, new_model_name) <add> new_model = os.path.join(trained_models_dir, new_model_name) <ide> <add> print('Training on gathered game data...') <ide> tf_records = sorted( <ide> tf.gfile.Glob(os.path.join(training_chunk_dir, '*'+_TF_RECORD_SUFFIX))) <ide> tf_records = tf_records[ <ide> -(params.train_window_size // params.examples_per_chunk):] <ide> <ide> print('Training from: {} to {}'.format(tf_records[0], tf_records[-1])) <ide> with utils.logged_timer('Training'): <del> dualnet.train(estimator_model_dir, tf_records, model_num + 1, params) <del> dualnet.export_model(estimator_model_dir, save_file) <add> dualnet.train(estimator_model_dir, tf_records, generation, params) <add> dualnet.export_model(estimator_model_dir, new_model) <ide> <ide> <ide> def validate(trained_models_dir, holdout_dir, estimator_model_dir, params): <ide> def validate(trained_models_dir, holdout_dir, estimator_model_dir, params): <ide> trained_models_dir: Directories where the completed generations/models are. <ide> holdout_dir: Directories where holdout data are. <ide> estimator_model_dir: tf.estimator model directory. <del> params: An object of hyperparameters for the model. <add> params: A MiniGoParams instance of hyperparameters for the model. <ide> """ <ide> model_num, _ = utils.get_latest_model(trained_models_dir) <ide> <ide> def validate(trained_models_dir, holdout_dir, estimator_model_dir, params): <ide> tf_records.extend( <ide> tf.gfile.Glob(os.path.join(record_dir, '*'+_TF_RECORD_SUFFIX))) <ide> <add> if not tf_records: <add> print('No holdout dataset for validation! ' <add> 'Please check your holdout directory: {}'.format(holdout_dir)) <add> return <add> <ide> print('The length of tf_records is {}.'.format(len(tf_records))) <ide> first_tf_record = os.path.basename(tf_records[0]) <ide> last_tf_record = os.path.basename(tf_records[-1]) <ide> def validate(trained_models_dir, holdout_dir, estimator_model_dir, params): <ide> dualnet.validate(estimator_model_dir, tf_records, params) <ide> <ide> <del>def evaluate(trained_models_dir, black_model_name, white_model_name, <add>def evaluate(black_model_name, black_net, white_model_name, white_net, <ide> evaluate_dir, params): <ide> """Evaluate with two models. <ide> <del> With the model name, construct two DualNetRunners to play as black and white <del> in a Go match. Two models play several names, and the model that wins by a <del> margin of 55% will be the winner. <add> With two DualNetRunners to play as black and white in a Go match. Two models <add> play several games, and the model that wins by a margin of 55% will be the <add> winner. <ide> <ide> Args: <del> trained_models_dir: Directories where the completed generations/models are. <ide> black_model_name: The name of the model playing black. <add> black_net: The DualNetRunner model for black <ide> white_model_name: The name of the model playing white. <add> white_net: The DualNetRunner model for white. <ide> evaluate_dir: Where to write the evaluation results. Set as <del> 'base_dir/sgf/evaluate/'' <del> params: An object of hyperparameters for the model. <add> 'base_dir/sgf/evaluate/'. <add> params: A MiniGoParams instance of hyperparameters for the model. <ide> <ide> Returns: <ide> The model name of the winner. <ide> <ide> Raises: <ide> ValueError: if neither `WHITE` or `BLACK` is returned. <ide> """ <del> <del> black_model = os.path.join(trained_models_dir, black_model_name) <del> white_model = os.path.join(trained_models_dir, white_model_name) <del> <del> print('Evaluate models between {} and {}'.format( <del> black_model_name, white_model_name)) <del> <del> _ensure_dir_exists(evaluate_dir) <del> <del> with utils.logged_timer('Loading weights'): <del> black_net = dualnet.DualNetRunner(black_model, params) <del> white_net = dualnet.DualNetRunner(white_model, params) <del> <ide> with utils.logged_timer('{} games'.format(params.eval_games)): <ide> winner = evaluation.play_match( <ide> params, black_net, white_net, params.eval_games, <ide> def evaluate(trained_models_dir, black_model_name, white_model_name, <ide> return black_model_name if winner == go.BLACK_NAME else white_model_name <ide> <ide> <del>def _set_params_from_board_size(board_size): <del> """Set hyperparameters from board size.""" <add>def _set_params(flags): <add> """Set hyperparameters from board size. <add> <add> Args: <add> flags: Flags from Argparser. <add> <add> Returns: <add> An MiniGoParams instance of hyperparameters. <add> """ <ide> params = model_params.MiniGoParams() <del> k = utils.round_power_of_two(board_size ** 2 / 3) <add> k = utils.round_power_of_two(flags.board_size ** 2 / 3) <ide> params.num_filters = k # Number of filters in the convolution layer <ide> params.fc_width = 2 * k # Width of each fully connected layer <del> params.num_shared_layers = board_size # Number of shared trunk layers <del> params.board_size = board_size # Board size <add> params.num_shared_layers = flags.board_size # Number of shared trunk layers <add> params.board_size = flags.board_size # Board size <ide> <ide> # How many positions can fit on a graphics card. 256 for 9s, 16 or 32 for 19s. <del> if FLAGS.board_size == 9: <del> params.batch_size = 256 <add> if flags.batch_size is None: <add> if flags.board_size == 9: <add> params.batch_size = 256 <add> else: <add> params.batch_size = 32 <ide> else: <del> params.batch_size = 32 <add> params.batch_size = flags.batch_size <add> <ide> return params <ide> <ide> <add>def _prepare_selfplay( <add> model_name, trained_models_dir, selfplay_dir, holdout_dir, sgf_dir, params): <add> """Set directories and load the network for selfplay. <add> <add> Args: <add> model_name: The name of the model for self-play <add> trained_models_dir: Directories where the completed generations/models are. <add> selfplay_dir: Where to write the games. Set as 'base_dir/data/selfplay/'. <add> holdout_dir: Where to write the holdout data. Set as <add> 'base_dir/data/holdout/'. <add> sgf_dir: Where to write the sgf (Smart Game Format) files. Set as <add> 'base_dir/sgf/'. <add> params: A MiniGoParams instance of hyperparameters for the model. <add> <add> Returns: <add> The directories and network model for selfplay. <add> """ <add> # Set paths for the model with 'model_name' <add> model_path = os.path.join(trained_models_dir, model_name) <add> output_dir = os.path.join(selfplay_dir, model_name) <add> holdout_dir = os.path.join(holdout_dir, model_name) <add> # clean_sgf is to write sgf file without comments. <add> # full_sgf is to write sgf file with comments. <add> clean_sgf = os.path.join(sgf_dir, model_name, 'clean') <add> full_sgf = os.path.join(sgf_dir, model_name, 'full') <add> <add> _ensure_dir_exists(output_dir) <add> _ensure_dir_exists(holdout_dir) <add> _ensure_dir_exists(clean_sgf) <add> _ensure_dir_exists(full_sgf) <add> selfplay_dirs = { <add> 'output_dir': output_dir, <add> 'holdout_dir': holdout_dir, <add> 'clean_sgf': clean_sgf, <add> 'full_sgf': full_sgf <add> } <add> # cache the network model for self-play <add> with utils.logged_timer('Loading weights from {} ... '.format(model_path)): <add> network = dualnet.DualNetRunner(model_path, params) <add> return selfplay_dirs, network <add> <add> <add>def run_selfplay(selfplay_model, selfplay_games, dirs, params): <add> """Run selfplay to generate training data. <add> <add> Args: <add> selfplay_model: The model name for selfplay. <add> selfplay_games: The number of selfplay games. <add> dirs: A MiniGoDirectory instance of directories used in each step. <add> params: A MiniGoParams instance of hyperparameters for the model. <add> """ <add> selfplay_dirs, network = _prepare_selfplay( <add> selfplay_model, dirs.trained_models_dir, dirs.selfplay_dir, <add> dirs.holdout_dir, dirs.sgf_dir, params) <add> <add> print('Self-play with model: {}'.format(selfplay_model)) <add> for _ in range(selfplay_games): <add> selfplay(selfplay_dirs, network, params) <add> <add> <ide> def main(_): <ide> """Run the reinforcement learning loop.""" <ide> tf.logging.set_verbosity(tf.logging.INFO) <ide> <del> params = _set_params_from_board_size(FLAGS.board_size) <add> params = _set_params(FLAGS) <ide> <ide> # A dummy model for debug/testing purpose with fewer games and iterations <del> if FLAGS.debug: <add> if FLAGS.test: <ide> params = model_params.DummyMiniGoParams() <add> base_dir = FLAGS.base_dir + str(FLAGS.board_size) + '_size_dummy/' <add> else: <add> # Set directories for models and datasets <add> base_dir = FLAGS.base_dir + str(FLAGS.board_size) + '_size/' <ide> <del> # Set directories for models and datasets <del> base_dir = FLAGS.base_dir + str(FLAGS.board_size) + '_board_size/' <ide> dirs = utils.MiniGoDirectory(base_dir) <add> <add> # Run selfplay only if user specifies the argument. <add> if FLAGS.selfplay: <add> selfplay_model_name = FLAGS.selfplay_model_name or utils.get_latest_model( <add> dirs.trained_models_dir)[1] <add> max_games = FLAGS.selfplay_max_games or params.max_games_per_generation <add> run_selfplay(selfplay_model_name, max_games, dirs, params) <add> return <add> <add> # Run the RL pipeline <ide> # if no models have been trained, start from bootstrap model <del> if os.path.isdir(base_dir) is False: <add> <add> if not os.path.isdir(dirs.trained_models_dir): <ide> print('No trained model exists! Starting from Bootstrap...') <ide> print('Creating random initial weights...') <ide> bootstrap(dirs.estimator_model_dir, dirs.trained_models_dir, params) <ide> def main(_): <ide> print('Start from the last checkpoint...') <ide> <ide> _, best_model_so_far = utils.get_latest_model(dirs.trained_models_dir) <del> <ide> for rl_iter in range(params.max_iters_per_pipeline): <ide> print('RL_iteration: {}'.format(rl_iter)) <add> # Self-play with the best model to generate training data <add> run_selfplay( <add> best_model_so_far, params.max_games_per_generation, dirs, params) <ide> <del> # Self-play to generate at least params.max_games_per_generation games <del> selfplay(best_model_so_far, dirs.trained_models_dir, dirs.selfplay_dir, <del> dirs.holdout_dir, dirs.sgf_dir, params) <del> games = tf.gfile.Glob( <del> os.path.join(dirs.selfplay_dir, best_model_so_far, '*.zz')) <del> while len(games) < params.max_games_per_generation: <del> selfplay(best_model_so_far, dirs.trained_models_dir, dirs.selfplay_dir, <del> dirs.holdout_dir, dirs.sgf_dir, params) <del> if FLAGS.validation: <del> params = model_params.DummyValidationParams() <del> selfplay(best_model_so_far, dirs.trained_models_dir, dirs.selfplay_dir, <del> dirs.holdout_dir, dirs.sgf_dir, params) <del> games = tf.gfile.Glob( <del> os.path.join(dirs.selfplay_dir, best_model_so_far, '*.zz')) <del> <add> # gather selfplay data for training <ide> print('Gathering game output...') <ide> gather(dirs.selfplay_dir, dirs.training_chunk_dir, params) <ide> <add> # train the next generation model <add> model_num, _ = utils.get_latest_model(dirs.trained_models_dir) <ide> print('Training on gathered game data...') <ide> train(dirs.trained_models_dir, dirs.estimator_model_dir, <del> dirs.training_chunk_dir, params) <add> dirs.training_chunk_dir, model_num + 1, params) <ide> <add> # validate the latest model if needed <ide> if FLAGS.validation: <ide> print('Validating on the holdout game data...') <ide> validate(dirs.trained_models_dir, dirs.holdout_dir, <ide> dirs.estimator_model_dir, params) <ide> <ide> _, current_model = utils.get_latest_model(dirs.trained_models_dir) <add> <ide> if FLAGS.evaluation: # Perform evaluation if needed <del> print('Evaluating the latest model...') <add> print('Evaluate models between {} and {}'.format( <add> best_model_so_far, current_model)) <add> black_model = os.path.join(dirs.trained_models_dir, best_model_so_far) <add> white_model = os.path.join(dirs.trained_models_dir, current_model) <add> _ensure_dir_exists(dirs.evaluate_dir) <add> with utils.logged_timer('Loading weights'): <add> black_net = dualnet.DualNetRunner(black_model, params) <add> white_net = dualnet.DualNetRunner(white_model, params) <add> <ide> best_model_so_far = evaluate( <del> dirs.trained_models_dir, best_model_so_far, current_model, <add> best_model_so_far, black_net, current_model, white_net, <ide> dirs.evaluate_dir, params) <del> print('Winner: {}!'.format(best_model_so_far)) <add> print('Winner of evaluation: {}!'.format(best_model_so_far)) <ide> else: <ide> best_model_so_far = current_model <ide> <ide> <ide> if __name__ == '__main__': <ide> parser = argparse.ArgumentParser() <add> # flags to run the RL pipeline <ide> parser.add_argument( <ide> '--base_dir', <ide> type=str, <ide> def main(_): <ide> metavar='N', <ide> choices=[9, 19], <ide> help='Go board size. The default size is 9.') <add> parser.add_argument( <add> '--batch_size', <add> type=int, <add> default=None, <add> metavar='BS', <add> help='Batch size for training. The default size is None') <add> # Test the pipeline with a dummy model <add> parser.add_argument( <add> '--test', <add> action='store_true', <add> help='A boolean to test RL pipeline with a dummy model.') <add> # Run RL pipeline with the validation step <add> parser.add_argument( <add> '--validation', <add> action='store_true', <add> help='A boolean to specify validation in the RL pipeline.') <add> # Run RL pipeline with the evaluation step <ide> parser.add_argument( <ide> '--evaluation', <ide> action='store_true', <ide> help='A boolean to specify evaluation in the RL pipeline.') <add> <add> # self-play only <ide> parser.add_argument( <del> '--debug', <add> '--selfplay', <ide> action='store_true', <del> help='A boolean to indicate debug mode for testing purpose.') <add> help='A boolean to run self-play only.') <ide> parser.add_argument( <del> '--validation', <del> action='store_true', <del> help='A boolean to explicitly generate holdout data for validation.') <add> '--selfplay_model_name', <add> type=str, <add> default=None, <add> metavar='SM', <add> help='The model used for self-play only.') <add> parser.add_argument( <add> '--selfplay_max_games', <add> type=int, <add> default=None, <add> metavar='SMG', <add> help='The number of game data self-play only needs to generate') <ide> <ide> FLAGS, unparsed = parser.parse_known_args() <ide> tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) <ide><path>research/minigo/model_params.py <ide> class MiniGoParams(object): <ide> """Parameters for MiniGo.""" <ide> <del> # Go params <add> # Go board size <ide> board_size = 9 <ide> <ide> # RL pipeline <ide> class MiniGoParams(object): <ide> # the number of simultaneous leaves in MCTS <ide> simultaneous_leaves = 8 <ide> <add> # holdout data for validation <ide> holdout_pct = 0.05 # How many games to hold out for validation <ide> holdout_generation = 50 # How many recent generations/models for holdout data <ide> <ide> class MiniGoParams(object): <ide> # AGZ used the most recent 500k games, which, assuming 250 moves/game = 125M <ide> train_window_size = 125000000 <ide> <del> # evaluation <add> # evaluation with two models <ide> eval_games = 50 # The number of games to play in evaluation <ide> eval_readouts = 100 # How many readouts to make per move in evaluation <ide> eval_verbose = 1 # How verbose the players should be in evaluation <ide><path>research/minigo/utils.py <ide> class MiniGoDirectory(object): <ide> """The class to set up directories of MiniGo.""" <ide> <ide> def __init__(self, base_dir): <del> self.trained_models_dir = os.path.join(base_dir, 'models') <add> self.trained_models_dir = os.path.join(base_dir, 'trained_models') <ide> self.estimator_model_dir = os.path.join(base_dir, 'estimator_model_dir/') <ide> self.selfplay_dir = os.path.join(base_dir, 'data/selfplay/') <ide> self.holdout_dir = os.path.join(base_dir, 'data/holdout/')
6
PHP
PHP
fix virtual attributes
29a6692fb0f0d14e5109ae5f02ed70065f10e966
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php <ide> protected function mergeAttributesFromClassCasts() <ide> protected function mergeAttributesFromAttributeCasts() <ide> { <ide> foreach ($this->attributeCastCache as $key => $value) { <del> $callback = $this->{Str::camel($key)}()->set ?: function ($value) use ($key) { <add> $attribute = $this->{Str::camel($key)}(); <add> <add> if ($attribute->get && ! $attribute->set) { <add> continue; <add> } <add> <add> $callback = $attribute->set ?: function ($value) use ($key) { <ide> $this->attributes[$key] = $value; <ide> }; <ide> <ide><path>tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php <ide> public function testSettingRawAttributesClearsTheCastCache() <ide> <ide> $this->assertSame('117 Spencer St.', $model->address->lineOne); <ide> } <add> <add> public function testCastsThatOnlyHaveGetterDoNotPeristAnythingToModelOnSave() <add> { <add> $model = new TestEloquentModelWithAttributeCast; <add> <add> $model->virtual; <add> <add> $model->getAttributes(); <add> <add> $this->assertTrue(empty($model->getDirty())); <add> } <ide> } <ide> <ide> class TestEloquentModelWithAttributeCast extends Model <ide> public function password(): Attribute <ide> return hash('sha256', $value); <ide> }); <ide> } <add> <add> public function virtual(): Attribute <add> { <add> return new Attribute( <add> function () { <add> return collect(); <add> } <add> ); <add> } <ide> } <ide> <ide> class AttributeCastAddress
2
Javascript
Javascript
check manageditems in snapshot
db265cbff82435f574db38d3855d340e2b468cf6
<ide><path>lib/FileSystemInfo.js <ide> class FileSystemInfo { <ide> fileHashes, <ide> contextTimestamps, <ide> contextHashes, <del> missingTimestamps <add> missingTimestamps, <add> managedItemInfo <ide> } = snapshot; <ide> let jobs = 1; <ide> const jobDone = () => { <ide> class FileSystemInfo { <ide> } <ide> } <ide> } <add> if (managedItemInfo) { <add> for (const [path, info] of managedItemInfo) { <add> const cache = this._managedItems.get(path); <add> if (cache !== undefined) { <add> if (!checkHash(cache, info)) { <add> invalid(); <add> } <add> } else { <add> jobs++; <add> this.managedItemQueue.add(path, (err, entry) => { <add> if (err) return invalid(); <add> if (!checkHash(entry, info)) { <add> invalid(); <add> } else { <add> jobDone(); <add> } <add> }); <add> } <add> } <add> } <ide> jobDone(); <ide> } <ide>
1
PHP
PHP
show notice for non existent controller property
4e11ad9236d32d40a7b90a12e398c0d0328a739c
<ide><path>src/Controller/Controller.php <ide> public function __get($name) <ide> <ide> list($plugin, $class) = pluginSplit($this->modelClass, true); <ide> if ($class !== $name) { <add> $trace = debug_backtrace(); <add> $parts = explode('\\', get_class($this)); <add> trigger_error( <add> sprintf( <add> 'Undefined property: %s::$%s in %s on line %s', <add> array_pop($parts), <add> $name, <add> $trace[0]['file'], <add> $trace[0]['line'] <add> ), <add> E_USER_NOTICE <add> ); <add> <ide> return false; <ide> } <ide> <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> use Cake\Http\ServerRequest; <ide> use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <add>use PHPUnit\Framework\Error\Notice; <ide> use TestApp\Controller\Admin\PostsController; <ide> use TestPlugin\Controller\TestPluginController; <ide> <ide> public function testTableAutoload() <ide> $Controller = new Controller($request, $response); <ide> $Controller->modelClass = 'SiteArticles'; <ide> <del> $this->assertFalse($Controller->Articles); <add> $this->assertFalse(isset($Controller->Articles)); <ide> $this->assertInstanceOf( <ide> 'Cake\ORM\Table', <ide> $Controller->SiteArticles <ide> public function testTableAutoload() <ide> <ide> $Controller->modelClass = 'Articles'; <ide> <del> $this->assertFalse($Controller->SiteArticles); <add> $this->assertFalse(isset($Controller->SiteArticles)); <ide> $this->assertInstanceOf( <ide> 'TestApp\Model\Table\ArticlesTable', <ide> $Controller->Articles <ide> ); <ide> } <ide> <add> /** <add> * testUndefinedPropertyError <add> * <add> * @return void <add> */ <add> public function testUndefinedPropertyError() <add> { <add> $controller = new Controller(); <add> <add> $controller->Bar = true; <add> $this->assertTrue($controller->Bar); <add> <add> $this->expectException(Notice::class); <add> $this->expectExceptionMessage(sprintf( <add> 'Undefined property: Controller::$Foo in %s on line %s', <add> __FILE__, <add> __LINE__ + 2 <add> )); <add> $controller->Foo->baz(); <add> } <add> <ide> /** <ide> * testLoadModel method <ide> *
2
Javascript
Javascript
add support for global mutation listeners
526f588870e5833a70c4133b4c13ed94fe751a9f
<ide><path>packages/ember-handlebars/lib/views/metamorph_view.js <ide> require("ember-views/views/view"); <ide> var set = Ember.set, get = Ember.get; <ide> var Metamorph = requireModule('metamorph'); <ide> <add>function notifyMutationListeners() { <add> Ember.run.once(Ember.View, 'notifyMutationListeners'); <add>} <add> <ide> // DOMManager should just abstract dom manipulation between jquery and metamorph <ide> var DOMManager = { <ide> remove: function(view) { <ide> view.morph.remove(); <add> notifyMutationListeners(); <ide> }, <ide> <ide> prepend: function(view, html) { <ide> view.morph.prepend(html); <add> notifyMutationListeners(); <ide> }, <ide> <ide> after: function(view, html) { <ide> view.morph.after(html); <add> notifyMutationListeners(); <ide> }, <ide> <ide> html: function(view, html) { <ide> view.morph.html(html); <add> notifyMutationListeners(); <ide> }, <ide> <ide> // This is messed up. <ide> var DOMManager = { <ide> morph.replaceWith(buffer.string()); <ide> view.transitionTo('inDOM'); <ide> view.triggerRecursively('didInsertElement'); <add> notifyMutationListeners(); <ide> }); <ide> }, <ide> <ide> empty: function(view) { <ide> view.morph.html(""); <add> notifyMutationListeners(); <ide> } <ide> }; <ide> <ide><path>packages/ember-handlebars/tests/controls/checkbox_test.js <ide> test("checked property mirrors input value", function() { <ide> <ide> equal(checkboxView.$().prop('checked'), true, "changing the value property changes the DOM"); <ide> <del> checkboxView.remove(); <add> Ember.run(function() { checkboxView.remove(); }); <ide> Ember.run(function() { checkboxView.append(); }); <ide> <ide> equal(checkboxView.$().prop('checked'), true, "changing the value property changes the DOM"); <ide><path>packages/ember-routing/lib/helpers/shared.js <ide> Ember.onLoad('Ember.Handlebars', function() { <ide> function resolveParams(context, params, options) { <ide> var resolved = handlebarsResolve(context, params, options); <ide> return map.call(resolved, unwrap); <del> } <ide> <del> function unwrap(object) { <del> if (Ember.ControllerMixin.detect(object)) { <del> return unwrap(get(object, 'model')); <del> } else { <del> return object; <add> function unwrap(object, i) { <add> if (params[i] === 'controller') { return object; } <add> <add> if (Ember.ControllerMixin.detect(object)) { <add> return unwrap(get(object, 'model')); <add> } else { <add> return object; <add> } <ide> } <ide> } <ide> <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.CoreView.extend( <ide> // once the view has been inserted into the DOM, legal manipulations <ide> // are done on the DOM element. <ide> <add>function notifyMutationListeners() { <add> Ember.run.once(Ember.View, 'notifyMutationListeners'); <add>} <add> <ide> var DOMManager = { <ide> prepend: function(view, html) { <ide> view.$().prepend(html); <add> notifyMutationListeners(); <ide> }, <ide> <ide> after: function(view, html) { <ide> view.$().after(html); <add> notifyMutationListeners(); <ide> }, <ide> <ide> html: function(view, html) { <ide> view.$().html(html); <add> notifyMutationListeners(); <ide> }, <ide> <ide> replace: function(view) { <ide> var DOMManager = { <ide> <ide> view._insertElementLater(function() { <ide> Ember.$(element).replaceWith(get(view, 'element')); <add> notifyMutationListeners(); <ide> }); <ide> }, <ide> <ide> remove: function(view) { <ide> view.$().remove(); <add> notifyMutationListeners(); <ide> }, <ide> <ide> empty: function(view) { <ide> view.$().empty(); <add> notifyMutationListeners(); <ide> } <ide> }; <ide> <ide> Ember.View.reopenClass({ <ide> } <ide> }); <ide> <add>var mutation = Ember.Object.extend(Ember.Evented).create(); <add> <add>Ember.View.addMutationListener = function(callback) { <add> mutation.on('change', callback); <add>}; <add> <add>Ember.View.removeMutationListener = function(callback) { <add> mutation.off('change', callback); <add>}; <add> <add>Ember.View.notifyMutationListeners = function() { <add> mutation.trigger('change'); <add>}; <add> <ide> /** <ide> Global views hash <ide> <ide><path>packages/ember-views/tests/views/view/is_visible_test.js <ide> test("should hide views when isVisible is false", function() { <ide> <ide> set(view, 'isVisible', true); <ide> ok(view.$().is(':visible'), "the view is visible"); <del> view.remove(); <add> Ember.run(function() { <add> view.remove(); <add> }); <ide> }); <ide> <ide> test("should hide element if isVisible is false before element is created", function() { <ide> test("should hide element if isVisible is false before element is created", func <ide> <ide> ok(view.$().is(':hidden'), "should be hidden"); <ide> <del> view.remove(); <add> Ember.run(function() { <add> view.remove(); <add> }); <add> <ide> set(view, 'isVisible', true); <ide> <ide> Ember.run(function() { <ide><path>packages/ember-views/tests/views/view/remove_test.js <ide> test("removes view from parent view", function() { <ide> <ide> ok(parentView.$('div').length, "precond - has a child DOM element"); <ide> <del> child.removeFromParent(); <add> Ember.run(function() { <add> child.removeFromParent(); <add> }); <add> <ide> ok(!get(child, 'parentView'), 'no longer has parentView'); <ide> ok(indexOf(get(parentView, 'childViews'), child)<0, 'no longer in parent childViews'); <ide> equal(parentView.$('div').length, 0, "removes DOM element from parent"); <ide> test("removes view from parent view", function() { <ide> test("returns receiver", function() { <ide> parentView = Ember.ContainerView.create({ childViews: [Ember.View] }); <ide> child = get(parentView, 'childViews').objectAt(0); <del> equal(child.removeFromParent(), child, 'receiver'); <add> var removed = Ember.run(function() { <add> return child.removeFromParent(); <add> }); <add> <add> equal(removed, child, 'receiver'); <ide> }); <ide> <ide> test("does nothing if not in parentView", function() {
6
PHP
PHP
add interface checks for context objects
17e3dbfc1302308dd9932719e8564e243142a1a5
<ide><path>src/View/Helper/FormHelper.php <ide> use Cake\Utility\Inflector; <ide> use Cake\Utility\Security; <ide> use Cake\View\Form\ArrayContext; <add>use Cake\View\Form\ContextInterface; <ide> use Cake\View\Form\EntityContext; <ide> use Cake\View\Form\NullContext; <ide> use Cake\View\Helper; <ide> protected function _addDefaultContextProviders() { <ide> return new EntityContext($request, $data); <ide> } <ide> }); <del> <del> $this->addContextProvider('_default', function ($request, $data) { <del> return new NullContext($request, (array)$data); <del> }); <ide> } <ide> <ide> /** <ide> public function context() { <ide> /** <ide> * Find the matching context provider for the data. <ide> * <del> * If no type can be matched the default provider will be returned. <add> * If no type can be matched a NullContext will be returned. <ide> * <ide> * @param mixed $data The data to get a context provider for. <ide> * @return mixed Context provider. <add> * @throws RuntimeException when the context class does not implement the <add> * ContextInterface. <ide> */ <ide> protected function _buildContext($data) { <ide> foreach ($this->_contextProviders as $key => $check) { <ide> $context = $check($this->request, $data); <ide> if ($context) { <del> return $context; <add> break; <ide> } <ide> } <del> $check = $this->_contextProviders['_default']; <del> return $check($this->request, $data); <add> if (!isset($context)) { <add> $context = new NullContext($this->request, $data); <add> } <add> if (!($context instanceof ContextInterface)) { <add> throw new \RuntimeException( <add> 'Context objects must implement Cake\View\Form\ContextInterface' <add> ); <add> } <add> return $context; <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testAddWidgetInvalid() { <ide> * <ide> * @return void <ide> */ <del> public function testContextClassMatching() { <add> public function testAddContextProvider() { <ide> $context = 'My data'; <ide> $this->Form->addContextProvider('test', function ($request, $data) use ($context) { <ide> $this->assertInstanceOf('Cake\Network\Request', $request); <del> $this->assertEquals($context, $data); <del> return new \StdObject(); <add> $this->assertEquals($context, $data['entity']); <add> return $this->getMock('Cake\View\Form\ContextInterface'); <add> }); <add> $this->Form->create($context); <add> } <add> <add>/** <add> * Test adding an invalid context class. <add> * <add> * @expectedException RuntimeException <add> * @expectedExceptionMessage Context objects must implement Cake\View\Form\ContextInterface <add> * @return void <add> */ <add> public function testAddContextProviderInvalid() { <add> $context = 'My data'; <add> $this->Form->addContextProvider('test', function ($request, $data) use ($context) { <add> return new \StdClass(); <ide> }); <ide> $this->Form->create($context); <ide> }
2
Ruby
Ruby
remove trailing whitespace
ff91808651a19549ea8b101b8abdf5c3f811e0f4
<ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb <ide> def mysql2_connection(config) <ide> if config[:flags].kind_of? Array <ide> config[:flags].push "FOUND_ROWS".freeze <ide> else <del> config[:flags] |= Mysql2::Client::FOUND_ROWS <add> config[:flags] |= Mysql2::Client::FOUND_ROWS <ide> end <ide> end <ide>
1
PHP
PHP
remove automatic route loading
5dee28709cffe6e4ca66e9a8c26bcd28e65ab344
<ide><path>src/Http/BaseApplication.php <ide> public function pluginBootstrap() <ide> */ <ide> public function routes($routes) <ide> { <del> if (!Router::$initialized) { <del> // Prevent routes from being loaded again <del> Router::$initialized = true; <del> <add> // Only load routes if the router is empty <add> if (!Router::routes()) { <ide> require $this->configDir . '/routes.php'; <ide> } <ide> } <ide><path>src/Routing/Router.php <ide> class Router <ide> { <ide> <del> /** <del> * Have routes been loaded <del> * <del> * @var bool <del> * @deprecated 3.5.0 Routes will be loaded via the Application::routes() hook in 4.0.0 <del> */ <del> public static $initialized = false; <del> <ide> /** <ide> * Default route class. <ide> * <ide> public static function getNamedExpressions() <ide> */ <ide> public static function connect($route, $defaults = [], $options = []) <ide> { <del> static::$initialized = true; <ide> static::scope('/', function ($routes) use ($route, $defaults, $options) { <ide> $routes->connect($route, $defaults, $options); <ide> }); <ide> public static function connect($route, $defaults = [], $options = []) <ide> */ <ide> public static function parseRequest(ServerRequestInterface $request) <ide> { <del> if (!static::$initialized) { <del> static::_loadRoutes(); <del> } <del> <ide> return static::$_collection->parseRequest($request); <ide> } <ide> <ide> protected static function _applyUrlFilters($url) <ide> */ <ide> public static function url($url = null, $full = false) <ide> { <del> if (!static::$initialized) { <del> static::_loadRoutes(); <del> } <del> <ide> $params = [ <ide> 'plugin' => null, <ide> 'controller' => null, <ide> public static function extensions($extensions = null, $merge = true) <ide> { <ide> $collection = static::$_collection; <ide> if ($extensions === null) { <del> if (!static::$initialized) { <del> static::_loadRoutes(); <del> } <del> <ide> return array_unique(array_merge(static::$_defaultExtensions, $collection->getExtensions())); <ide> } <ide> $extensions = (array)$extensions; <ide> public static function plugin($name, $options = [], $callback = null) <ide> */ <ide> public static function routes() <ide> { <del> if (!static::$initialized) { <del> static::_loadRoutes(); <del> } <del> <ide> return static::$_collection->routes(); <ide> } <ide> <del> /** <del> * Loads route configuration <del> * <del> * @deprecated 3.5.0 Routes will be loaded via the Application::routes() hook in 4.0.0 <del> * @return void <del> */ <del> protected static function _loadRoutes() <del> { <del> static::$initialized = true; <del> include CONFIG . 'routes.php'; <del> } <del> <ide> /** <ide> * Get the RouteCollection inside the Router <ide> * <ide> public static function getRouteCollection() <ide> public static function setRouteCollection($routeCollection) <ide> { <ide> static::$_collection = $routeCollection; <del> static::$initialized = true; <ide> } <ide> } <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testInitializeCallback() <ide> public function testInitializeContentTypeSettingExt() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $this->Controller->setRequest($this->request->withHeader('Accept', 'application/json')); <ide> <ide> $this->RequestHandler->ext = null; <ide> public function testInitializeContentTypeSettingExt() <ide> public function testInitializeContentTypeWithjQueryAccept() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $this->Controller->setRequest($this->request <ide> ->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01') <ide> ->withHeader('X-Requested-With', 'XMLHttpRequest')); <ide> public function testInitializeContentTypeWithjQueryAccept() <ide> public function testInitializeContentTypeWithjQueryTextPlainAccept() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $this->Controller->setRequest($this->request->withHeader('Accept', 'text/plain, */*; q=0.01')); <ide> <ide> $this->RequestHandler->startup(new Event('Controller.startup', $this->Controller)); <ide> public function testInitializeContentTypeWithjQueryTextPlainAccept() <ide> public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $this->Controller->setRequest($this->request->withHeader('Accept', 'application/json, application/javascript, */*; q=0.01')); <ide> $this->RequestHandler->ext = null; <ide> Router::extensions(['rss', 'json'], false); <ide> public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions( <ide> public function testInitializeNoContentTypeWithSingleAccept() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $_SERVER['HTTP_ACCEPT'] = 'application/json, text/html, */*; q=0.01'; <ide> $this->assertNull($this->RequestHandler->ext); <ide> <ide> public function testInitializeNoContentTypeWithMultipleAcceptedTypes() <ide> public function testInitializeContentTypeWithMultipleAcceptedTypes() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $this->Controller->setRequest($this->request->withHeader( <ide> 'Accept', <ide> 'text/csv;q=1.0, application/json;q=0.8, application/xml;q=0.7' <ide> public function testInitializeContentTypeWithMultipleAcceptedTypes() <ide> public function testInitializeAmbiguousAndroidAccepts() <ide> { <ide> Router::reload(); <del> Router::$initialized = true; <ide> $this->request = $this->request->withEnv( <ide> 'HTTP_ACCEPT', <ide> 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5' <ide><path>tests/TestCase/Http/BaseApplicationTest.php <ide> public function testPluginBootstrapRecursivePlugins() <ide> 'Nested plugin should have bootstrap run' <ide> ); <ide> } <del> <del> /** <del> * Ensure that Router::$initialized is toggled even if the routes <del> * file fails. This prevents the routes file from being re-parsed <del> * during the error handling process. <del> * <del> * @return void <del> */ <del> public function testRouteHookInitializesRouterOnError() <del> { <del> $app = $this->getMockForAbstractClass( <del> 'Cake\Http\BaseApplication', <del> [TEST_APP . 'invalid_routes' . DS] <del> ); <del> $builder = Router::createRouteBuilder('/'); <del> try { <del> $app->routes($builder); <del> <del> $this->fail('invalid_routes/routes.php file should raise an error.'); <del> } catch (\InvalidArgumentException $e) { <del> $this->assertTrue(Router::$initialized, 'Should be toggled to prevent duplicate route errors'); <del> $this->assertContains('route class', $e->getMessage()); <del> } <del> } <ide> } <ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <ide> public function testPreservingExistingParams() <ide> public function testRoutesHookInvokedOnApp() <ide> { <ide> Router::reload(); <del> $this->assertFalse(Router::$initialized, 'Router precondition failed'); <ide> <ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']); <ide> $response = new Response(); <ide> public function testRoutesHookInvokedOnApp() <ide> '_matchedRoute' => '/app/articles' <ide> ]; <ide> $this->assertEquals($expected, $req->getAttribute('params')); <del> $this->assertTrue(Router::$initialized, 'Router state should indicate routes loaded'); <ide> $this->assertNotEmpty(Router::routes()); <ide> $this->assertEquals('/app/articles', Router::routes()[0]->template); <ide> }; <ide> public function testRoutesHookInvokedOnApp() <ide> public function testRoutesHookCallsPluginHook() <ide> { <ide> Router::reload(); <del> $this->assertFalse(Router::$initialized, 'Router precondition failed'); <ide> <ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']); <ide> $response = new Response(); <ide> public function testCacheRoutes() <ide> 'engine' => 'File', <ide> 'path' => TMP, <ide> ]); <del> Router::$initialized = false; <ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']); <ide> $response = new Response(); <ide> $next = function ($req, $res) use ($cacheConfigName) { <ide> public function testCacheNotUsedIfCacheDisabled() <ide> 'engine' => 'File', <ide> 'path' => TMP, <ide> ]); <del> Router::$initialized = false; <ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']); <ide> $response = new Response(); <ide> $next = function ($req, $res) use ($cacheConfigName) { <ide> public function testCacheConfigNotFound() <ide> 'engine' => 'File', <ide> 'path' => TMP, <ide> ]); <del> Router::$initialized = false; <ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']); <ide> $response = new Response(); <ide> $next = function ($req, $res) { <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function tearDown() <ide> */ <ide> public function testBaseUrl() <ide> { <add> Router::scope('/', function ($routes) { <add> $routes->fallbacks(); <add> }); <ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url('/', true)); <ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url(null, true)); <ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url(['_full' => true])); <ide> public function testBaseUrl() <ide> */ <ide> public function testFullBaseURL() <ide> { <add> Router::scope('/', function ($routes) { <add> $routes->fallbacks(); <add> }); <ide> Router::fullBaseUrl('http://example.com'); <ide> $this->assertEquals('http://example.com/', Router::url('/', true)); <ide> $this->assertEquals('http://example.com', Configure::read('App.fullBaseUrl')); <ide> public function testReverseCakeRequestQuery() <ide> <ide> public function testReverseFull() <ide> { <add> Router::scope('/', function ($routes) { <add> $routes->fallbacks(); <add> }); <ide> $params = [ <ide> 'lang' => 'eng', <ide> 'controller' => 'posts', <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function setUp() <ide> $routes->options('/options/:controller/:action', []); <ide> $routes->connect('/:controller/:action/*', []); <ide> }); <del> Router::$initialized = true; <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/BreadcrumbsHelperTest.php <ide> */ <ide> namespace Cake\Test\TestCase\View\Helper; <ide> <add>use Cake\Routing\Router; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\View\Helper\BreadcrumbsHelper; <ide> use Cake\View\View; <ide> public function setUp() <ide> parent::setUp(); <ide> $view = new View(); <ide> $this->breadcrumbs = new BreadcrumbsHelper($view); <add> <add> Router::reload(); <add> Router::scope('/', function ($routes) { <add> $routes->fallbacks(); <add> }); <ide> } <ide> <ide> /** <ide> public function testRender() <ide> '/span', <ide> '/li', <ide> ['li' => []], <del> ['a' => ['href' => '/some_alias']], <add> ['a' => ['href' => '/tests_apps/some_method']], <ide> 'Some text', <ide> '/a', <ide> '/li', <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function setUp() <ide> Plugin::load(['TestTheme']); <ide> static::setAppNamespace(); <ide> Configure::write('Asset.timestamp', false); <add> <add> Router::scope('/', function ($routes) { <add> $routes->fallbacks(); <add> }); <ide> } <ide> <ide> /** <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> Plugin::unload('TestTheme'); <add> Router::reload(); <ide> unset($this->Html, $this->View); <ide> } <ide> <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> <del> Router::reload(); <ide> $this->View = new View(); <ide> $this->Helper = new UrlHelper($this->View); <ide> $this->Helper->request = new ServerRequest(); <ide> <ide> static::setAppNamespace(); <ide> Plugin::load(['TestTheme']); <add> Router::scope('/', function ($routes) { <add> $routes->fallbacks(); <add> }); <ide> } <ide> <ide> /** <ide> public function tearDown() <ide> Configure::delete('Asset'); <ide> <ide> Plugin::unload(); <add> Router::reload(); <ide> unset($this->Helper, $this->View); <ide> } <ide> <ide> public function testBuildUrlConversion() <ide> $this->assertEquals('/controller/action/1?one=1&amp;two=2', $result); <ide> <ide> $result = $this->Helper->build(['controller' => 'posts', 'action' => 'index', 'page' => '1" onclick="alert(\'XSS\');"']); <del> $this->assertEquals('/posts/index?page=1%22+onclick%3D%22alert%28%27XSS%27%29%3B%22', $result); <add> $this->assertEquals('/posts?page=1%22+onclick%3D%22alert%28%27XSS%27%29%3B%22', $result); <ide> <ide> $result = $this->Helper->build('/controller/action/1/param:this+one+more'); <ide> $this->assertEquals('/controller/action/1/param:this+one+more', $result); <ide> public function testBuildUrlConversion() <ide> $result = $this->Helper->build([ <ide> 'controller' => 'posts', 'action' => 'index', 'param' => '%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24' <ide> ]); <del> $this->assertEquals('/posts/index?param=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524', $result); <add> $this->assertEquals('/posts?param=%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524', $result); <ide> <ide> $result = $this->Helper->build([ <ide> 'controller' => 'posts', 'action' => 'index', 'page' => '1', <ide> '?' => ['one' => 'value', 'two' => 'value', 'three' => 'purple'] <ide> ]); <del> $this->assertEquals('/posts/index?one=value&amp;two=value&amp;three=purple&amp;page=1', $result); <add> $this->assertEquals('/posts?one=value&amp;two=value&amp;three=purple&amp;page=1', $result); <ide> } <ide> <ide> /**
10
Text
Text
remove some extra text
e0f26b70d321dcd5d719739e82f29b658e2ea181
<ide><path>readme.md <ide> Laravel is accessible, yet powerful, providing powerful tools needed for large, <ide> <ide> Documentation for the entire framework can be found on the [Laravel website](http://laravel.com/docs). <ide> <del>## Contributing To Laravel <add>## Contributing <ide> <ide> Thank you for considering contributing to the Laravel framework. If you are submitting a bug-fix, or an enhancement that is **not** a breaking change, submit your pull request to the branch corresponding to the latest stable release of the framework, such as the `4.1` branch. If you are submitting a breaking change or an entirely new component, submit your pull request to the `master` branch. <ide>
1
Javascript
Javascript
fix the perspective projection
843b5567698327525015326e87bcaaa5cfbe807f
<ide><path>Libraries/Utilities/MatrixMath.js <ide> var MatrixMath = { <ide> ]; <ide> }, <ide> <add> /** <add> * This create a perspective projection towards negative z <add> * Clipping the z range of [-near, -far] <add> * <add> * @param fovInRadians - field of view in randians <add> */ <ide> createPerspective: function(fovInRadians, aspect, near, far) { <del> var h = 1 / Math.tan(fovInRadians); <add> var h = 1 / Math.tan(fovInRadians / 2); <ide> var r_depth = 1 / (near - far); <ide> var C = (far + near) * r_depth; <ide> var D = 2 * (far * near * r_depth);
1
Python
Python
fix pronoun handling
53e17296e98ba8db1b9b99fec0a39aaa56d12e5c
<ide><path>spacy/ja/__init__.py <ide> def resolve_pos(token): <ide> # PoS mappings. <ide> <ide> if token.part_of_speech == '連体詞,*,*,*': <del> # determiner-likes get DET, otherwise ADJ <ide> if re.match('^[こそあど此其彼]の', token.surface): <ide> return token.part_of_speech + ',DET' <add> if re.match('^[こそあど此其彼]', token.surface): <add> return token.part_of_speech + ',PRON' <ide> else: <ide> return token.part_of_speech + ',ADJ' <ide> return token.part_of_speech
1
Python
Python
fix spancat initialize with labels
733e8ceea9f691aec8ef2ac7dfcc6e83fd90d47a
<ide><path>spacy/cli/init_pipeline.py <ide> def init_labels_cli( <ide> config = util.load_config(config_path, overrides=overrides) <ide> with show_validation_error(hint_fill=False): <ide> nlp = init_nlp(config, use_gpu=use_gpu) <add> _init_labels(nlp, output_path) <add> <add> <add>def _init_labels(nlp, output_path): <ide> for name, component in nlp.pipeline: <ide> if getattr(component, "label_data", None) is not None: <ide> output_file = output_path / f"{name}.json" <ide><path>spacy/pipeline/spancat.py <ide> def initialize( <ide> get_examples: Callable[[], Iterable[Example]], <ide> *, <ide> nlp: Language = None, <del> labels: Optional[Dict] = None, <add> labels: Optional[List[str]] = None, <ide> ) -> None: <ide> """Initialize the pipe for training, using a representative set <ide> of data examples. <ide><path>spacy/tests/test_cli.py <ide> import os <ide> <ide> from .util import make_tempdir <add>from ..cli.init_pipeline import _init_labels <ide> <ide> <ide> def test_cli_info(): <ide> def test_validate_compatibility_table(): <ide> current_compat = compat.get(spacy_version, {}) <ide> assert len(current_compat) > 0 <ide> assert "en_core_web_sm" in current_compat <add> <add> <add>@pytest.mark.parametrize("component_name", ["ner", "textcat", "spancat", "tagger"]) <add>def test_init_labels(component_name): <add> nlp = Dutch() <add> component = nlp.add_pipe(component_name) <add> for label in ["T1", "T2", "T3", "T4"]: <add> component.add_label(label) <add> assert len(nlp.get_pipe(component_name).labels) == 4 <add> <add> with make_tempdir() as tmp_dir: <add> _init_labels(nlp, tmp_dir) <add> <add> config = init_config( <add> lang="nl", <add> pipeline=[component_name], <add> optimize="efficiency", <add> gpu=False, <add> ) <add> config["initialize"]["components"][component_name] = { <add> "labels": { <add> "@readers": "spacy.read_labels.v1", <add> "path": f"{tmp_dir}/{component_name}.json", <add> } <add> } <add> <add> nlp2 = load_model_from_config(config, auto_fill=True) <add> assert len(nlp2.get_pipe(component_name).labels) == 0 <add> nlp2.initialize() <add> assert len(nlp2.get_pipe(component_name).labels) == 4
3
Javascript
Javascript
add detectinstance to classes
3e525e29c0b1f906186f202fe95a9246401d7de3
<ide><path>packages/sproutcore-runtime/lib/system/core_object.js <ide> var ClassMixin = SC.Mixin.create({ <ide> obj = obj.superclass; <ide> } <ide> return false; <add> }, <add> <add> detectInstance: function(obj) { <add> return this.PrototypeMixin.detect(obj); <ide> } <ide> <ide> }); <ide><path>packages/sproutcore-runtime/tests/legacy_1x/system/object/base_test.js <ide> test("Checking the detect() function on an object and its subclass", function(){ <ide> equals(obj1.detect(obj), NO); <ide> }); <ide> <add>test("Checking the detectInstance() function on an object and its subclass", function() { <add> ok(SC.Object.detectInstance(obj.create())); <add> ok(obj.detectInstance(obj.create())); <add>}); <add> <ide> test("subclasses should contain defined subclasses", function() { <ide> ok(obj.subclasses.contains(obj1), 'obj.subclasses should contain obj1'); <ide>
2
Python
Python
remove unneeded repo() test
734ca7ca8c2ba6f0ca83ede015652720b2a7246d
<ide><path>tests/test_serializer.py <ide> def __init__(self): <ide> ) <ide> <ide> <del>class TestUnicodeRepr: <del> def test_repr(self): <del> class ExampleSerializer(serializers.Serializer): <del> example = serializers.CharField() <del> <del> class ExampleObject: <del> def __init__(self): <del> self.example = '한국' <del> <del> def __repr__(self): <del> return repr(self.example) <del> <del> instance = ExampleObject() <del> serializer = ExampleSerializer(instance) <del> repr(serializer) # Should not error. <del> <del> <ide> class TestNotRequiredOutput: <ide> def test_not_required_output_for_dict(self): <ide> """
1
Text
Text
add chinese translation of reusable-components
943c2aa77a4b6eed19ea6effe3248e553f6286ae
<ide><path>docs/docs/05-reusable-components.zh-CN.md <ide> React.render( <ide> ); <ide> ``` <ide> <del> <ide> ## 单个子级 <ide> <ide> `React.PropTypes.element` 可以限定只能有一个子级传入。 <ide> var MyComponent = React.createClass({ <ide> render: function() { <ide> return ( <ide> <div> <del> {this.props.children} // 只能有一个元素,否则会抛异常。 <add> {this.props.children} // 有且仅有一个元素,否则会抛异常。 <ide> </div> <ide> ); <ide> } <ide> React.render( <ide> ); <ide> ``` <ide> <del>关于 mixin 值得一提的优点是,如果一个组件使用了多个 mixin,并用有多个 mixin 定义了同样的生命周期方法(如:多个 mixin 都需要在组件销毁时做资源清理操作),所有这些生命周期方法都保证会被执行到。方法执行顺序是:首先按 mixin 引入顺序执行 mixin 里方法,最后执行组件内定义的方法。 <ide>\ No newline at end of file <add>关于 mixin 值得一提的优点是,如果一个组件使用了多个 mixin,并用有多个 mixin 定义了同样的生命周期方法(如:多个 mixin 都需要在组件销毁时做资源清理操作),所有这些生命周期方法都保证会被执行到。方法执行顺序是:首先按 mixin 引入顺序执行 mixin 里方法,最后执行组件内定义的方法。
1
Javascript
Javascript
add a helper function to reduce code size
ceaa4ff03f7bc53bbc19711a023ea9313fdfde7f
<ide><path>src/core/core.tooltip.js <ide> }, <ide> }; <ide> <add> // Helper to push or concat based on if the 2nd parameter is an array or not <add> function pushOrConcat(base, toPush) { <add> if (toPush) { <add> if (helpers.isArray(toPush)) { <add> base = base.concat(toPush); <add> } else { <add> base.push(toPush); <add> } <add> } <add> <add> return base; <add> } <add> <ide> Chart.Tooltip = Chart.Element.extend({ <ide> initialize: function() { <ide> var options = this._options; <ide> }); <ide> }, <ide> <add> // Get the title <ide> getTitle: function() { <ide> var beforeTitle = this._options.tooltips.callbacks.beforeTitle.apply(this, arguments), <ide> title = this._options.tooltips.callbacks.title.apply(this, arguments), <ide> afterTitle = this._options.tooltips.callbacks.afterTitle.apply(this, arguments); <ide> <ide> var lines = []; <add> lines = pushOrConcat(lines, beforeTitle); <add> lines = pushOrConcat(lines, title); <add> lines = pushOrConcat(lines, afterTitle); <ide> <del> if (beforeTitle) { <del> if (helpers.isArray(beforeTitle)) { <del> lines = lines.concat(beforeTitle); <del> } else { <del> lines.push(beforeTitle); <del> } <del> } <del> if (title) { <del> if (helpers.isArray(title)) { <del> lines = lines.concat(title); <del> } else { <del> lines.push(title); <del> } <del> } <del> if (afterTitle) { <del> if (helpers.isArray(afterTitle)) { <del> lines = lines.concat(afterTitle); <del> } else { <del> lines.push(afterTitle); <del> } <del> } <ide> return lines; <ide> }, <ide> <ide> return helpers.isArray(lines) ? lines : [lines]; <ide> }, <ide> <add> // Get the footer and beforeFooter and afterFooter lines <ide> getFooter: function() { <del> var beforeFooter = this._options.tooltips.callbacks.beforeFooter.apply(this, arguments), <del> footer = this._options.tooltips.callbacks.footer.apply(this, arguments), <del> afterFooter = this._options.tooltips.callbacks.afterFooter.apply(this, arguments); <add> var beforeFooter = this._options.tooltips.callbacks.beforeFooter.apply(this, arguments); <add> var footer = this._options.tooltips.callbacks.footer.apply(this, arguments); <add> var afterFooter = this._options.tooltips.callbacks.afterFooter.apply(this, arguments); <ide> <ide> var lines = []; <del> <del> if (beforeFooter) { <del> if (helpers.isArray(beforeFooter)) { <del> lines = lines.concat(beforeFooter); <del> } else { <del> lines.push(beforeFooter); <del> } <del> } <del> if (footer) { <del> if (helpers.isArray(footer)) { <del> lines = lines.concat(footer); <del> } else { <del> lines.push(footer); <del> } <del> } <del> if (afterFooter) { <del> if (helpers.isArray(afterFooter)) { <del> lines = lines.concat(afterFooter); <del> } else { <del> lines.push(afterFooter); <del> } <del> } <add> lines = pushOrConcat(lines, beforeFooter); <add> lines = pushOrConcat(lines, footer); <add> lines = pushOrConcat(lines, afterFooter); <ide> <ide> return lines; <ide> },
1
PHP
PHP
remove auth migration that is now in laravel/ui
13e43893ba2457c3e49898f0066a5ce8d7ea74f4
<ide><path>database/migrations/2014_10_12_100000_create_password_resets_table.php <del><?php <del> <del>use Illuminate\Database\Migrations\Migration; <del>use Illuminate\Database\Schema\Blueprint; <del>use Illuminate\Support\Facades\Schema; <del> <del>class CreatePasswordResetsTable extends Migration <del>{ <del> /** <del> * Run the migrations. <del> * <del> * @return void <del> */ <del> public function up() <del> { <del> Schema::create('password_resets', function (Blueprint $table) { <del> $table->string('email')->index(); <del> $table->string('token'); <del> $table->timestamp('created_at')->nullable(); <del> }); <del> } <del> <del> /** <del> * Reverse the migrations. <del> * <del> * @return void <del> */ <del> public function down() <del> { <del> Schema::dropIfExists('password_resets'); <del> } <del>}
1
Python
Python
fix more lint issues in demos/ directory
afa09ef99b29d7dfbace3a5316520a38ec1312f0
<ide><path>demos/example_aliyun_ecs.py <ide> <ide> auth = NodeAuthPassword('P@$$w0rd') <ide> <add> ex_internet_charge_type = ecs.internet_charge_types.BY_TRAFFIC <ide> node = ecs.create_node(image=image, size=small, name='test', <ide> ex_security_group_id=sg, <del> ex_internet_charge_type=ecs.internet_charge_types.BY_TRAFFIC, <add> ex_internet_charge_type=ex_internet_charge_type, <ide> ex_internet_max_bandwidth_out=1, <ide> ex_data_disk=data_disk, <ide> auth=auth) <ide><path>demos/example_aliyun_oss.py <ide> oss.ex_abort_all_multipart_uploads(c1) <ide> print('Abort them all') <ide> <add> <ide> def data_iter(limit): <ide> i = 0 <ide> while True: <ide> def data_iter(limit): <ide> break <ide> <ide> print('Starting to upload 1MB using multipart api') <del>one_mb = 1024*1024 <add>one_mb = 1024 * 1024 <ide> obj = oss.upload_object_via_stream(data_iter(one_mb), c1, upload_object_name) <ide> print('Finish uploading') <ide> <ide> def data_iter(limit): <ide> oss.delete_object(obj) <ide> <ide> # Create container <del>#c2 = oss.create_container(container_name='20160117') <del>#c2 = oss.create_container(container_name='20160117', ex_location='oss-cn-beijing') <del>#c2_got = oss.get_container('20160117') <add># c2 = oss.create_container(container_name='20160117') <add># c2 = oss.create_container(container_name='20160117', <add># ex_location='oss-cn-beijing') <add># c2_got = oss.get_container('20160117') <ide><path>demos/example_aliyun_slb.py <ide> 'HealthCheck': 'off'} <ide> nodes = ecs.list_nodes() <ide> print('Found %d nodes' % len(nodes)) <del> members = [Member(node.id, node.public_ips[0], 80, extra={'Weight': 50*(i+1)}) <add> members = [Member(node.id, node.public_ips[0], 80, <add> extra={'Weight': 50 * (i + 1)}) <ide> for i, node in enumerate(nodes)] <ide> new_b = slb.create_balancer('test-balancer', 80, 'http', <ide> Algorithm.WEIGHTED_ROUND_ROBIN, members,
3
Javascript
Javascript
add node version to fingerprint
962b814bb653e4a77795ed22c9e7c4cf90060e10
<ide><path>script/utils/fingerprint.js <ide> var fingerprintPath = path.resolve(__dirname, '..', '..', 'node_modules', '.atom <ide> module.exports = { <ide> fingerprint: function () { <ide> var packageJson = fs.readFileSync(path.resolve(__dirname, '..', '..', 'package.json')) <del> var body = packageJson.toString() + process.platform <add> var body = packageJson.toString() + process.platform + process.version <ide> return crypto.createHash('sha1').update(body).digest('hex') <ide> }, <ide>
1
PHP
PHP
allow optional path into _path helpers
1a2c340fdaa5f860c5bbd608f1c90f13811dcb46
<ide><path>src/Illuminate/Support/helpers.php <ide> function app($make = null) <ide> /** <ide> * Get the path to the application folder. <ide> * <add> * @param string $path <ide> * @return string <ide> */ <del> function app_path() <add> function app_path($path = '') <ide> { <del> return app('path'); <add> return app('path').($path ? '/'.$path : $path); <ide> } <ide> } <ide> <ide> function asset($path, $secure = null) <ide> * <ide> * @return string <ide> */ <del> function base_path() <add> function base_path($path = '') <ide> { <del> return app()->make('path.base'); <add> return app()->make('path.base').($path ? '/'.$path : $path); <ide> } <ide> } <ide> <ide> function object_get($object, $key, $default = null) <ide> * <ide> * @return string <ide> */ <del> function public_path() <add> function public_path($path = '') <ide> { <del> return app()->make('path.public'); <add> return app()->make('path.public').($path ? '/'.$path : $path); <ide> } <ide> } <ide> <ide> function starts_with($haystack, $needle) <ide> * <ide> * @return string <ide> */ <del> function storage_path() <add> function storage_path($path = '') <ide> { <del> return app('path.storage'); <add> return app('path.storage').($path ? '/'.$path : $path); <ide> } <ide> } <ide>
1
Text
Text
unify deprecation wording
f417ea1eae47a9ef04a82f58eb3f24db45cfdc27
<ide><path>doc/api/deprecations.md <ide> deprecated and support will be removed in the future. <ide> <ide> Type: Documentation-only <ide> <del>The option `produceCachedData` has been deprecated. Use <add>The `produceCachedData` option is deprecated. Use <ide> [`script.createCachedData()`][] instead. <ide> <ide> <a id="DEP0111"></a>
1
Python
Python
remove unused arguments in multiple choice example
e8db8b845a971b0cf63a0896b9deb5b316028a8b
<ide><path>examples/multiple-choice/utils_multiple_choice.py <ide> def __init__( <ide> else: <ide> examples = processor.get_train_examples(data_dir) <ide> logger.info("Training examples: %s", len(examples)) <del> # TODO clean up all this to leverage built-in features of tokenizers <del> self.features = convert_examples_to_features( <del> examples, <del> label_list, <del> max_seq_length, <del> tokenizer, <del> pad_on_left=bool(tokenizer.padding_side == "left"), <del> pad_token=tokenizer.pad_token_id, <del> pad_token_segment_id=tokenizer.pad_token_type_id, <del> ) <add> self.features = convert_examples_to_features(examples, label_list, max_seq_length, tokenizer,) <ide> logger.info("Saving features into cached file %s", cached_features_file) <ide> torch.save(self.features, cached_features_file) <ide> <ide> def __init__( <ide> else: <ide> examples = processor.get_train_examples(data_dir) <ide> logger.info("Training examples: %s", len(examples)) <del> # TODO clean up all this to leverage built-in features of tokenizers <del> self.features = convert_examples_to_features( <del> examples, <del> label_list, <del> max_seq_length, <del> tokenizer, <del> pad_on_left=bool(tokenizer.padding_side == "left"), <del> pad_token=tokenizer.pad_token_id, <del> pad_token_segment_id=tokenizer.pad_token_type_id, <del> ) <add> <add> self.features = convert_examples_to_features(examples, label_list, max_seq_length, tokenizer,) <ide> <ide> def gen(): <ide> for (ex_index, ex) in tqdm.tqdm(enumerate(self.features), desc="convert examples to features"): <ide> def normalize(truth): <ide> <ide> <ide> def convert_examples_to_features( <del> examples: List[InputExample], <del> label_list: List[str], <del> max_length: int, <del> tokenizer: PreTrainedTokenizer, <del> pad_token_segment_id=0, <del> pad_on_left=False, <del> pad_token=0, <del> mask_padding_with_zero=True, <add> examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, <ide> ) -> List[InputFeatures]: <ide> """ <ide> Loads a data file into a list of `InputFeatures`
1
Python
Python
improve perceiver docs
aece7badc1ea1b20f6ae5d3e449f48fcc30cd0f0
<ide><path>src/transformers/models/perceiver/modeling_perceiver.py <ide> def forward( <ide> >>> # EXAMPLE 2: using the Perceiver to classify images <ide> >>> # - we define an ImagePreprocessor, which can be used to embed images <ide> >>> preprocessor=PerceiverImagePreprocessor( <del> config, <del> prep_type="conv1x1", <del> spatial_downsample=1, <del> out_channels=256, <del> position_encoding_type="trainable", <del> concat_or_add_pos="concat", <del> project_pos_dim=256, <del> trainable_position_encoding_kwargs=dict(num_channels=256, index_dims=config.image_size ** 2), <del> ) <add> ... config, <add> ... prep_type="conv1x1", <add> ... spatial_downsample=1, <add> ... out_channels=256, <add> ... position_encoding_type="trainable", <add> ... concat_or_add_pos="concat", <add> ... project_pos_dim=256, <add> ... trainable_position_encoding_kwargs=dict(num_channels=256, index_dims=config.image_size ** 2, <add> ... ), <add> ... ) <ide> <ide> >>> model = PerceiverModel( <ide> ... config, <ide> def forward( <ide> This model uses learned position embeddings. In other words, this model is not given any privileged information about <ide> the structure of images. As shown in the paper, this model can achieve a top-1 accuracy of 72.7 on ImageNet. <ide> <del>`PerceiverForImageClassificationLearned` uses <del>`transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with `prep_type` = "conv1x1") to <del>preprocess the input images, and `transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder` to <del>decode the latent representation of `~transformers.PerceiverModel` into classification logits. <add>:class:`~transformers.PerceiverForImageClassificationLearned` uses <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with :obj:`prep_type="conv1x1"`) <add>to preprocess the input images, and <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder` to decode the latent <add>representation of :class:`~transformers.PerceiverModel` into classification logits. <ide> """, <ide> PERCEIVER_START_DOCSTRING, <ide> ) <ide> def forward( <ide> This model uses fixed 2D Fourier position embeddings. As shown in the paper, this model can achieve a top-1 accuracy of <ide> 79.0 on ImageNet, and 84.5 when pre-trained on a large-scale dataset (i.e. JFT). <ide> <del>`PerceiverForImageClassificationLearned` uses <del>`transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with `prep_type` = "pixels") to <del>preprocess the input images, and `transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder` to <del>decode the latent representation of `~transformers.PerceiverModel` into classification logits. <add>:class:`~transformers.PerceiverForImageClassificationLearned` uses <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with :obj:`prep_type="pixels"`) <add>to preprocess the input images, and <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder` to decode the latent <add>representation of :class:`~transformers.PerceiverModel` into classification logits. <ide> """, <ide> PERCEIVER_START_DOCSTRING, <ide> ) <ide> def forward( <ide> This model uses a 2D conv+maxpool preprocessing network. As shown in the paper, this model can achieve a top-1 accuracy <ide> of 82.1 on ImageNet. <ide> <del>`PerceiverForImageClassificationLearned` uses <del>`transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with `prep_type` = "conv") to preprocess <del>the input images, and `transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder` to decode the <del>latent representation of `~transformers.PerceiverModel` into classification logits. <add>:class:`~transformers.PerceiverForImageClassificationLearned` uses <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with :obj:`prep_type="conv"`) to <add>preprocess the input images, and <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverClassificationDecoder` to decode the latent <add>representation of :class:`~transformers.PerceiverModel` into classification logits. <ide> """, <ide> PERCEIVER_START_DOCSTRING, <ide> ) <ide> def forward( <ide> <ide> @add_start_docstrings( <ide> """ <del>Example use of Perceiver for optical flow, for tasks such as Sintel and KITTI. `PerceiverForOpticalFlow` uses <del>`transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with `prep_type` = "patches") to <del>preprocess the input images, and `transformers.models.perceiver.modeling_perceiver.PerceiverOpticalFlowDecoder` to <del>decode the latent representation of `~transformers.PerceiverModel`. <add>Example use of Perceiver for optical flow, for tasks such as Sintel and KITTI. <add>:class:`~transformers.PerceiverForOpticalFlow` uses <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverImagePreprocessor` (with `prep_type="patches"`) to <add>preprocess the input images, and :class:`~transformers.models.perceiver.modeling_perceiver.PerceiverOpticalFlowDecoder` <add>to decode the latent representation of :class:`~transformers.PerceiverModel`. <ide> <ide> As input, one concatenates 2 subsequent frames along the channel dimension and extract a 3 x 3 patch around each pixel <ide> (leading to 3 x 3 x 3 x 2 = 54 values for each pixel). Fixed Fourier position encodings are used to encode the position <ide> def forward( <ide> """ <ide> Example use of Perceiver for multimodal (video) autoencoding, for tasks such as Kinetics-700. <ide> <del>`PerceiverForMultimodalAutoencoding` uses <del>`transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor` to preprocess the 3 modalities: <del>images, audio and class labels. This preprocessor uses modality-specific preprocessors to preprocess every modality <del>separately, after which they are concatenated. Trainable position embeddings are used to pad each modality to the same <del>number of channels to make concatenation along the time dimension possible. Next, one applies the Perceiver encoder. <add>:class:`~transformers.PerceiverForMultimodalAutoencoding` uses <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalPreprocessor` to preprocess the 3 <add>modalities: images, audio and class labels. This preprocessor uses modality-specific preprocessors to preprocess every <add>modality separately, after which they are concatenated. Trainable position embeddings are used to pad each modality to <add>the same number of channels to make concatenation along the time dimension possible. Next, one applies the Perceiver <add>encoder. <ide> <del>`transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder` is used to decode the latent <del>representation of `~transformers.PerceiverModel`. This decoder uses each modality-specific decoder to construct <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder` is used to decode the latent <add>representation of :class:`~transformers.PerceiverModel`. This decoder uses each modality-specific decoder to construct <ide> queries. The decoder queries are created based on the inputs after preprocessing. However, autoencoding an entire video <ide> in a single forward pass is computationally infeasible, hence one only uses parts of the decoder queries to do <ide> cross-attention with the latent representation. This is determined by the subsampled indices for each modality, which <del>can be provided as additional input to the forward pass of `PerceiverForMultimodalAutoencoding`. <add>can be provided as additional input to the forward pass of :class:`~transformers.PerceiverForMultimodalAutoencoding`. <ide> <del>`transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder` also pads the decoder queries of the <del>different modalities to the same number of channels, in order to concatenate them along the time dimension. Next, <del>cross-attention is performed with the latent representation of `PerceiverModel`. <add>:class:`~transformers.models.perceiver.modeling_perceiver.PerceiverMultimodalDecoder` also pads the decoder queries of <add>the different modalities to the same number of channels, in order to concatenate them along the time dimension. Next, <add>cross-attention is performed with the latent representation of :class:`~transformers.PerceiverModel`. <ide> <del>Finally, `transformers.models.perceiver.modeling_perceiver.PerceiverMultiModalPostprocessor` is used to turn this <del>tensor into an actual video. It first splits up the output into the different modalities, and then applies the <add>Finally, :class:`~transformers.models.perceiver.modeling_perceiver.PerceiverMultiModalPostprocessor` is used to turn <add>this tensor into an actual video. It first splits up the output into the different modalities, and then applies the <ide> respective postprocessor for each modality. <ide> <ide> Note that, by masking the classification label during evaluation (i.e. simply providing a tensor of zeros for the
1
Python
Python
replace whitespaces in the signature argument
ed7f30db21f4510e3e6106a68991e8ee21d781ff
<ide><path>numpy/lib/function_base.py <ide> def disp(mesg, device=None, linefeed=True): <ide> <ide> <ide> # See https://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html <del>_DIMENSION_NAME = r'\s*\w+\s*' <add>_DIMENSION_NAME = r'\w+' <ide> _CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME) <del>_ARGUMENT = r'\s*\({}\s*\)\s*'.format(_CORE_DIMENSION_LIST) <add>_ARGUMENT = r'\({}\)'.format(_CORE_DIMENSION_LIST) <ide> _ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT) <ide> _SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST) <ide> <ide> def _parse_gufunc_signature(signature): <ide> Tuple of input and output core dimensions parsed from the signature, each <ide> of the form List[Tuple[str, ...]]. <ide> """ <add> signature = re.sub(r'\s+', '', signature) <add> <ide> if not re.match(_SIGNATURE, signature): <ide> raise ValueError( <ide> 'not a valid gufunc signature: {}'.format(signature)) <del> return tuple([tuple([dim.strip() <del> for dim in re.findall(_DIMENSION_NAME, arg)]) <add> return tuple([tuple(re.findall(_DIMENSION_NAME, arg)) <ide> for arg in re.findall(_ARGUMENT, arg_list)] <ide> for arg_list in signature.split('->')) <ide>
1
Python
Python
fix gpuconfig initialization
79e40801c1ca59e221a18e0abc6e35aa6313fb93
<ide><path>tutorials/image/cifar10_estimator/cifar10_main.py <ide> def main(unused_argv): <ide> eval_steps = num_eval_examples // FLAGS.eval_batch_size <ide> <ide> # Session configuration. <del> sess_config = tf.ConfigProto() <del> sess_config.allow_soft_placement = True <del> sess_config.log_device_placement = FLAGS.log_device_placement <del> sess_config.intra_op_parallelism_threads = FLAGS.num_intra_threads <del> sess_config.inter_op_parallelism_threads = FLAGS.num_inter_threads <del> sess_config.gpu_options.force_gpu_compatible = FLAGS.force_gpu_compatible <add> sess_config = tf.ConfigProto( <add> allow_soft_placement=True, <add> log_device_placement=FLAGS.log_device_placement, <add> intra_op_parallelism_threads=FLAGS.num_intra_threads, <add> inter_op_parallelism_threads=FLAGS.num_inter_threads, <add> gpu_options=tf.GPUOptions( <add> force_gpu_compatible=FLAGS.force_gpu_compatible <add> ) <add> ) <ide> <ide> # Hooks that add extra logging that is useful to see the loss more often in <ide> # the console as well as examples per second.
1
Javascript
Javascript
use typeof for checking preload option
fe63992bd1e0d6e4eb7783584bce17c2796c4a2c
<ide><path>src/js/tech/html5.js <ide> class Html5 extends Tech { <ide> el.playerId = this.options_.playerId; <ide> } <ide> <del> if (this.options_.preload !== 'undefined') { <add> if (typeof this.options_.preload !== 'undefined') { <ide> Dom.setAttribute(el, 'preload', this.options_.preload); <ide> } <ide>
1
Javascript
Javascript
fix closing backticks indentation on bug report
01d10c53168dc4b2ef81bfb6b5b2e71152458522
<ide><path>common/app/routes/challenges/redux/bug-saga.js <del>import dedent from 'dedent'; <del> <ide> import types from '../redux/types'; <ide> import { closeBugModal } from '../redux/actions'; <ide> <ide> function filesToMarkdown(files = {}) { <ide> } <ide> const fileName = moreThenOneFile ? `\\ file: ${file.contents}` : ''; <ide> const fileType = file.ext; <del> return fileString + dedent` <del> \`\`\`${fileType} <del> ${fileName} <del> ${file.contents} <del> \`\`\` <del> \n <del> `; <add> return fileString + <add> '\`\`\`' + <add> fileType + <add> '\n' + <add> fileName + <add> '\n' + <add> file.contents + <add> '\n' + <add> '\`\`\`\n\n'; <ide> }, '\n'); <ide> } <ide>
1
Javascript
Javascript
remove object assign
9add2cf46557cfe77c1ccb5c157890d85af5304a
<ide><path>gulpfile.js <ide> // enable debug for gulp <del>/* eslint-disable prefer-object-spread/prefer-object-spread */ <ide> process.env.DEBUG = process.env.DEBUG || 'fcc:*'; <ide> require('dotenv').load(); <ide> <ide> gulp.task('pack-client', function() { <ide> <ide> return gulp.src(webpackConfig.entry.bundle) <ide> .pipe(plumber({ errorHandler })) <del> .pipe(webpackStream(Object.assign( <del> {}, <del> webpackConfig, <del> webpackOptions <del> ))) <add> .pipe(webpackStream({ <add> ...webpackConfig, <add> ...webpackOptions <add> })) <ide> .pipe(gulpif(condition, gutil.noop(), uglify())) <ide> .pipe(gulp.dest(dest)); <ide> }); <ide> gulp.task('js', function() { <ide> }); <ide> <ide> <del>function collector(file, memo) { <del> return Object.assign({}, JSON.parse(file.contents), memo); <del>} <add>const collector = (file, memo) => <add> Object.assign(memo, JSON.parse(file.contents)); <ide> <ide> function done(manifest) { <ide> return sortKeys(manifest); <ide><path>webpack.frame-runner.js <add>const webpack = require('webpack'); <add>const path = require('path'); <add> <add>const __DEV__ = process.env.NODE_ENV !== 'production'; <add> <add>module.exports = { <add> entry: { <add> 'frame-runner': './client/frame-runner.js' <add> }, <add> devtool: __DEV__ ? 'inline-source-map' : null, <add> node: { <add> // Mock Node.js modules that Babel require()s but that we don't <add> // particularly care about. <add> fs: 'empty', <add> module: 'empty', <add> net: 'empty' <add> }, <add> output: { <add> filename: '[name].js', <add> chunkFilename: '[name]-[name].js', <add> path: path.join(__dirname, '/public/js'), <add> publicPath: '/js' <add> }, <add> module: { <add> loaders: [ <add> { <add> test: /\.jsx?$/, <add> include: [ path.join(__dirname, 'client/') ], <add> loaders: [ 'babel' ] <add> } <add> ] <add> }, <add> externals: { <add> rx: 'Rx' <add> }, <add> plugins: [ <add> new webpack.DefinePlugin({ <add> 'process.env': { <add> NODE_ENV: JSON.stringify(__DEV__ ? 'development' : 'production') <add> }, <add> __DEVTOOLS__: !__DEV__ <add> }), <add> // Use browser version of visionmedia-debug <add> new webpack.NormalModuleReplacementPlugin( <add> /debug\/node/, <add> 'debug/src/browser' <add> ), <add> new webpack.optimize.DedupePlugin(), <add> new webpack.optimize.OccurenceOrderPlugin(true) <add> ] <add>}; <add> <add>if (__DEV__) { <add> module.exports.plugins.push( <add> // prevents build on error <add> new webpack.NoErrorsPlugin() <add> ); <add>}
2
Javascript
Javascript
remove new keyword from errnoexception
a8845ebd45ea7a96e7c63c6bb0a122b264aced5e
<ide><path>lib/dgram.js <ide> Socket.prototype.addMembership = function(multicastAddress, <ide> <ide> var err = this._handle.addMembership(multicastAddress, interfaceAddress); <ide> if (err) { <del> throw new errnoException(err, 'addMembership'); <add> throw errnoException(err, 'addMembership'); <ide> } <ide> }; <ide> <ide> Socket.prototype.dropMembership = function(multicastAddress, <ide> <ide> var err = this._handle.dropMembership(multicastAddress, interfaceAddress); <ide> if (err) { <del> throw new errnoException(err, 'dropMembership'); <add> throw errnoException(err, 'dropMembership'); <ide> } <ide> }; <ide>
1
Text
Text
update chinese readme.md
ae45c491b28206a2b4e4203a79b07d70f951cae1
<ide><path>docs/i18n-languages/chinese/README.md <ide> freeCodeCamp.org提供了一些免费的开发技能认证证书。每个证书 <ide> <ide> ### 发现了一个安全问题? <ide> <del>请不要在GitHub上为安全问题创建Issues。作为替代,请发送一个E-mail到`[email protected]`,我们会紧接地对此进行调查。 <add>请不要在GitHub上为安全问题创建Issues。作为替代,请发送E-mail到`[email protected]`,我们会立刻对此进行调查。 <ide> <ide> ### 参与贡献 <ide>
1
Python
Python
fix multiple choice doc examples
144cea253f80bcd9b3c596d12902183c77ceceae
<ide><path>src/transformers/file_utils.py <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> choice0 = "It is eaten with a fork and a knife." <ide> >>> choice1 = "It is eaten while held in the hand." <ide> <del> >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='tf', padding=True) <add> >>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors='tf', padding=True) <ide> >>> inputs = {{k: tf.expand_dims(v, 0) for k, v in encoding.items()}} <ide> >>> outputs = model(inputs) # batch size is 1 <ide> <ide> def _prepare_output_docstrings(output_type, config_class): <ide> >>> choice0 = "It is eaten with a fork and a knife." <ide> >>> choice1 = "It is eaten while held in the hand." <ide> <del> >>> encoding = tokenizer([[prompt, prompt], [choice0, choice1]], return_tensors='jax', padding=True) <add> >>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors='jax', padding=True) <ide> >>> outputs = model(**{{k: v[None, :] for k,v in encoding.items()}}) <ide> <ide> >>> logits = outputs.logits
1
Ruby
Ruby
save a string allocation in visit_star
79fcdab538dedc5fcacae560e3d8e066f4c212f0
<ide><path>actionpack/lib/action_dispatch/journey/path/pattern.rb <ide> def visit_SLASH(node) <ide> end <ide> <ide> def visit_STAR(node) <del> re = @matchers[node.left.to_sym] || ".+" <del> "(#{re})" <add> re = @matchers[node.left.to_sym] <add> re ? "(#{re})" : "(.+)" <ide> end <ide> <ide> def visit_OR(node)
1
Ruby
Ruby
move button_to_function to prototype helper
570e02c96a12ad06888b4ba8d6d8bd3262705dcf
<ide><path>actionpack/lib/action_view/helpers/javascript_helper.rb <ide> module Helpers <ide> module JavaScriptHelper <ide> include PrototypeHelper <ide> <del> # Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the <del> # onclick handler. <del> # <del> # The first argument +name+ is used as the button's value or display text. <del> # <del> # The next arguments are optional and may include the javascript function definition and a hash of html_options. <del> # <del> # The +function+ argument can be omitted in favor of an +update_page+ <del> # block, which evaluates to a string when the template is rendered <del> # (instead of making an Ajax request first). <del> # <del> # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button" <del> # <del> # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil <del> # <del> # Examples: <del> # button_to_function "Greeting", "alert('Hello world!')" <del> # button_to_function "Delete", "if (confirm('Really?')) do_delete()" <del> # button_to_function "Details" do |page| <del> # page[:details].visual_effect :toggle_slide <del> # end <del> # button_to_function "Details", :class => "details_button" do |page| <del> # page[:details].visual_effect :toggle_slide <del> # end <del> def button_to_function(name, *args, &block) <del> html_options = args.extract_options!.symbolize_keys <del> <del> function = block_given? ? update_page(&block) : args[0] || '' <del> onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};" <del> <del> tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick)) <del> end <del> <ide> JS_ESCAPE_MAP = { <ide> '\\' => '\\\\', <ide> '</' => '<\/', <ide><path>actionpack/lib/action_view/helpers/prototype_helper.rb <ide> module PrototypeHelper <ide> :form, :with, :update, :script, :type ]).merge(CALLBACKS) <ide> end <ide> <add> # Returns a button with the given +name+ text that'll trigger a JavaScript +function+ using the <add> # onclick handler. <add> # <add> # The first argument +name+ is used as the button's value or display text. <add> # <add> # The next arguments are optional and may include the javascript function definition and a hash of html_options. <add> # <add> # The +function+ argument can be omitted in favor of an +update_page+ <add> # block, which evaluates to a string when the template is rendered <add> # (instead of making an Ajax request first). <add> # <add> # The +html_options+ will accept a hash of html attributes for the link tag. Some examples are :class => "nav_button", :id => "articles_nav_button" <add> # <add> # Note: if you choose to specify the javascript function in a block, but would like to pass html_options, set the +function+ parameter to nil <add> # <add> # Examples: <add> # button_to_function "Greeting", "alert('Hello world!')" <add> # button_to_function "Delete", "if (confirm('Really?')) do_delete()" <add> # button_to_function "Details" do |page| <add> # page[:details].visual_effect :toggle_slide <add> # end <add> # button_to_function "Details", :class => "details_button" do |page| <add> # page[:details].visual_effect :toggle_slide <add> # end <add> def button_to_function(name, *args, &block) <add> html_options = args.extract_options!.symbolize_keys <add> <add> function = block_given? ? update_page(&block) : args[0] || '' <add> onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};" <add> <add> tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick)) <add> end <add> <ide> # Returns the JavaScript needed for a remote function. <ide> # Takes the same arguments as link_to_remote. <ide> #
2
Javascript
Javascript
update materialloader.js
a907060783c020581eaeedd6cde05cbb6c0e0802
<ide><path>src/loaders/MaterialLoader.js <ide> class MaterialLoader extends Loader { <ide> if ( json.defines !== undefined ) material.defines = json.defines; <ide> if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader; <ide> if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader; <add> if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion; <ide> <ide> if ( json.extensions !== undefined ) { <ide>
1
Go
Go
create a new job from a shell-like text command
2019a73f0387af273be3b6e085fdae0e5a67ba3b
<ide><path>engine/engine.go <ide> package engine <ide> <ide> import ( <add> "bufio" <ide> "fmt" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> func (eng *Engine) Job(name string, args ...string) *Job { <ide> return job <ide> } <ide> <add>// ParseJob creates a new job from a text description using a shell-like syntax. <add>// <add>// The following syntax is used to parse `input`: <add>// <add>// * Words are separated using standard whitespaces as separators. <add>// * Quotes and backslashes are not interpreted. <add>// * Words of the form 'KEY=[VALUE]' are added to the job environment. <add>// * All other words are added to the job arguments. <add>// <add>// For example: <add>// <add>// job, _ := eng.ParseJob("VERBOSE=1 echo hello TEST=true world") <add>// <add>// The resulting job will have: <add>// job.Args={"echo", "hello", "world"} <add>// job.Env={"VERBOSE":"1", "TEST":"true"} <add>// <add>func (eng *Engine) ParseJob(input string) (*Job, error) { <add> // FIXME: use a full-featured command parser <add> scanner := bufio.NewScanner(strings.NewReader(input)) <add> scanner.Split(bufio.ScanWords) <add> var ( <add> cmd []string <add> env Env <add> ) <add> for scanner.Scan() { <add> word := scanner.Text() <add> kv := strings.SplitN(word, "=", 2) <add> if len(kv) == 2 { <add> env.Set(kv[0], kv[1]) <add> } else { <add> cmd = append(cmd, word) <add> } <add> } <add> if len(cmd) == 0 { <add> return nil, fmt.Errorf("empty command: '%s'", input) <add> } <add> job := eng.Job(cmd[0], cmd[1:]...) <add> job.Env().Init(&env) <add> return job, nil <add>} <add> <ide> func (eng *Engine) Logf(format string, args ...interface{}) (n int, err error) { <ide> if os.Getenv("TEST") == "" { <ide> prefixedFormat := fmt.Sprintf("[%s] %s\n", eng, strings.TrimRight(format, "\n")) <ide><path>engine/env.go <ide> func (env *Env) Exists(key string) bool { <ide> return exists <ide> } <ide> <add>func (env *Env) Init(src *Env) { <add> *env = make([]string, 0, len(*src)) <add> for _, val := range *src { <add> (*env) = append((*env), val) <add> } <add>} <add> <ide> func (env *Env) GetBool(key string) (value bool) { <ide> s := strings.ToLower(strings.Trim(env.Get(key), " \t")) <ide> if s == "" || s == "0" || s == "no" || s == "false" || s == "none" { <ide><path>engine/job.go <ide> func (job *Job) String() string { <ide> return fmt.Sprintf("%s.%s%s", job.Eng, job.CallString(), job.StatusString()) <ide> } <ide> <add>func (job *Job) Env() *Env { <add> return job.env <add>} <add> <ide> func (job *Job) EnvExists(key string) (value bool) { <ide> return job.env.Exists(key) <ide> }
3
Text
Text
tweak the changelog
6f4fb4a05937b2d27ea38cddc9104859adbf12eb
<ide><path>CHANGELOG.md <ide> <ide> ### React <ide> <del>* Add a new experimental `React.unstable_Profiler` component for measuring performance. ([@bvaughn](https://github.com/bvaughn) in [#12745](https://github.com/facebook/react/pull/12745)) <add>* Add a new [experimental](https://github.com/reactjs/rfcs/pull/51) `React.unstable_Profiler` component for measuring performance. ([@bvaughn](https://github.com/bvaughn) in [#12745](https://github.com/facebook/react/pull/12745)) <ide> <ide> ### React DOM <ide> <ide> * Add support for the Pointer Events specification. ([@philipp-spiess](https://github.com/philipp-spiess) in [#12507](https://github.com/facebook/react/pull/12507)) <del>* Call `getDerivedFromProps()` regardless of why rendering happened. ([@acdlite](https://github.com/acdlite) in [#12600](https://github.com/facebook/react/pull/12600) and [#12802](https://github.com/facebook/react/pull/12802)) <add>* Properly call `getDerivedFromProps()` regardless of the reason for re-rendering. ([@acdlite](https://github.com/acdlite) in [#12600](https://github.com/facebook/react/pull/12600) and [#12802](https://github.com/facebook/react/pull/12802)) <ide> * Fix a bug that prevented context propagation in some cases. ([@gaearon](https://github.com/gaearon) in [#12708](https://github.com/facebook/react/pull/12708)) <ide> * Fix re-rendering of components using `forwardRef()` on a deeper `setState()`. ([@gaearon](https://github.com/gaearon) in [#12690](https://github.com/facebook/react/pull/12690)) <ide> * Fix some attributes incorrectly getting removed from custom element nodes. ([@airamrguez](https://github.com/airamrguez) in [#12702](https://github.com/facebook/react/pull/12702))
1
Javascript
Javascript
replace "magic" numbers by constants
070a82e82c917492bf306e546cef55ffb3ca8359
<ide><path>lib/internal/constants.js <ide> module.exports = { <ide> CHAR_COLON: 58, /* : */ <ide> CHAR_QUESTION_MARK: 63, /* ? */ <ide> CHAR_UNDERSCORE: 95, /* _ */ <add> CHAR_LINE_FEED: 10, /* \n */ <add> CHAR_CARRIAGE_RETURN: 13, /* \r */ <add> CHAR_EXCLAMATION_MARK: 33, /* ! */ <add> CHAR_HASH: 35, /* # */ <ide> <ide> // Digits <ide> CHAR_0: 48, /* 0 */ <ide><path>lib/internal/module.js <ide> <ide> const errors = require('internal/errors'); <ide> <add>const { <add> CHAR_LINE_FEED, <add> CHAR_CARRIAGE_RETURN, <add> CHAR_EXCLAMATION_MARK, <add> CHAR_HASH, <add>} = require('internal/constants'); <add> <ide> // Invoke with makeRequireFunction(module) where |module| is the Module object <ide> // to use as the context for the require() function. <ide> function makeRequireFunction(mod) { <ide> function stripShebang(content) { <ide> // Remove shebang <ide> var contLen = content.length; <ide> if (contLen >= 2) { <del> if (content.charCodeAt(0) === 35/*#*/ && <del> content.charCodeAt(1) === 33/*!*/) { <add> if (content.charCodeAt(0) === CHAR_HASH && <add> content.charCodeAt(1) === CHAR_EXCLAMATION_MARK) { <ide> if (contLen === 2) { <ide> // Exact match <ide> content = ''; <ide> function stripShebang(content) { <ide> var i = 2; <ide> for (; i < contLen; ++i) { <ide> var code = content.charCodeAt(i); <del> if (code === 10/*\n*/ || code === 13/*\r*/) <add> if (code === CHAR_LINE_FEED || code === CHAR_CARRIAGE_RETURN) <ide> break; <ide> } <ide> if (i === contLen)
2
Javascript
Javascript
remove code comment
00dd8e12e50ae4afe8f2bf520a346e3891b0d477
<ide><path>lib/config/browserslistTargetHandler.js <ide> const resolve = browsers => { <ide> // Since Node.js 13.14.0 no warning about usage, but it was added 8.5.0 with some limitations and it was improved in 12.0.0 and 13.2.0 <ide> node: [13, 14] <ide> }), <del> // browserslistChecker("es6-module") && rawChecker({ node: [12, 17] }), <ide> dynamicImport: es6DynamicImport, <ide> dynamicImportInWorker: es6DynamicImport && !anyNode, <ide> // browserslist does not have info about globalThis
1
Javascript
Javascript
fix coding style in web/firefoxcom.js
6df9cc46b44ace2caa9a643a574e0e5a3036cab2
<ide><path>web/firefoxcom.js <ide> var FirefoxCom = (function FirefoxComClosure() { <ide> var request = document.createTextNode(''); <ide> if (callback) { <ide> document.addEventListener('pdf.js.response', function listener(event) { <del> var node = event.target, <del> response = event.detail.response; <add> var node = event.target; <add> var response = event.detail.response; <ide> <ide> document.documentElement.removeChild(node); <ide>
1
Go
Go
correct the help
cb7819cbc509a78d627584d18a65a4557875b516
<ide><path>commands.go <ide> func (srv *Server) Help() string { <ide> {"reset", "Reset changes to a container's filesystem"}, <ide> {"restart", "Restart a running container"}, <ide> {"rm", "Remove a container"}, <del> {"rmimage", "Remove an image"}, <add> {"rmi", "Remove an image"}, <ide> {"run", "Run a command in a new container"}, <ide> {"start", "Start a stopped container"}, <ide> {"stop", "Stop a running container"},
1
Text
Text
add guidance on order vulns are listed in
ed77955fb72b80685250ded2b5318eeaa7617aa8
<ide><path>doc/guides/security-release-process.md <ide> information described. <ide> the date in the slug so that it will move to the top of the blog list.) <ide> * [ ] pre-release: _**LINK TO PR**_ <ide> * [ ] post-release: _**LINK TO PR**_ <add> * List vulnerabilities in order of descending severity <ide> * Ask the HackerOne reporter if they would like to be credited on the <ide> security release blog page: <ide> ```text
1
Text
Text
add publish idea
8713153f01afde2f6051bdd68a23cc1b9d374623
<ide><path>docs/converting-a-text-mate-theme.md <ide> Check that you have `apm` installed by running the following command in your <ide> terminal: <ide> <ide> ```sh <del>apm -h <add>apm help init <ide> ``` <ide> <ide> You should see a message print out with all the possible `apm` commands. <ide> <ide> If you do not, launch Atom and run the _Atom > Install Shell Commmands_ menu <ide> to install the `apm` and `atom` commands. <ide> <add>You can now run `apm help init` to see all the options for initializing new <add>packages and themes. <add> <ide> ### Convert the Theme <ide> <ide> Download the theme you wish to convert, you can browse existing TextMate themes <ide> __Syntax Theme__ dropdown menu to enable your new theme. <ide> <ide> :tada: Your theme is now enabled, open an editor to see it in action! <ide> <add>:bulb: Consider using `apm publish` to publish this theme to [atom.io][atomio]. <add> <add>[atomio]: https://www.atom.io <ide> [CSS]: http://en.wikipedia.org/wiki/Cascading_Style_Sheets <ide> [LESS]: http://lesscss.org <ide> [plist]: http://en.wikipedia.org/wiki/Property_list
1
Javascript
Javascript
update version number
8f757c2ffea0184bf8f0dbf690d235b5a5970f30
<ide><path>d3.js <del>d3 = {version: "0.28.1"}; // semver <add>d3 = {version: "0.28.2"}; // semver <ide> if (!Date.now) Date.now = function() { <ide> return +new Date(); <ide> }; <ide><path>d3.min.js <del>(function(){var n=null;d3={version:"0.28.1"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.merge=function(a){return Array.prototype.concat.apply([],a)}; <add>(function(){var n=null;d3={version:"0.28.2"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.merge=function(a){return Array.prototype.concat.apply([],a)}; <ide> d3.split=function(a,b){var c=[],f=[],d,e=-1,h=a.length;if(arguments.length<2)b=aa;for(;++e<h;)if(b.call(f,d=a[e],e)){c.push(f);f=[]}else f.push(d);c.push(f);return c};function aa(a){return a==n}function E(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function ba(a,b){b=x(arguments);b[0]=this;a.apply(this,b);return this} <ide> d3.range=function(a,b,c){if(arguments.length==1){b=a;a=0}if(c==n)c=1;if((b-a)/c==Infinity)throw Error("infinite range");var f=[],d=-1,e;if(c<0)for(;(e=a+c*++d)>b;)f.push(e);else for(;(e=a+c*++d)<b;)f.push(e);return f};d3.requote=function(a){return a.replace(ca,"\\$&")};var ca=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g; <ide> d3.xhr=function(a,b,c){var f=new XMLHttpRequest;if(arguments.length<3)c=b;else b&&f.overrideMimeType(b);f.open("GET",a,true);f.onreadystatechange=function(){if(f.readyState==4)c(f.status<300?f:n)};f.send(n)};d3.text=function(a,b,c){if(arguments.length<3){c=b;b=n}d3.xhr(a,b,function(f){c(f&&f.responseText)})};d3.json=function(a,b){d3.text(a,"application/json",function(c){b(c?JSON.parse(c):n)})};
2
Java
Java
improve javadoc in sql script support classes
8fecee8c8a251209743ca109ac30559cec7dfbf0
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java <ide> * @author Chris Baldwin <ide> * @since 3.0 <ide> * @see DatabasePopulatorUtils <add> * @see ScriptUtils <ide> */ <ide> public class ResourceDatabasePopulator implements DatabasePopulator { <ide> <ide> public void setContinueOnError(boolean continueOnError) { <ide> <ide> /** <ide> * Flag to indicate that a failed SQL {@code DROP} statement can be ignored. <del> * <p>This is useful for non-embedded databases whose SQL dialect does not support an <del> * {@code IF EXISTS} clause in a {@code DROP} statement. <add> * <p>This is useful for a non-embedded database whose SQL dialect does not <add> * support an {@code IF EXISTS} clause in a {@code DROP} statement. <ide> * <p>The default is {@code false} so that if the populator runs accidentally, it will <del> * fail fast if the script starts with a {@code DROP} statement. <add> * fail fast if a script starts with a {@code DROP} statement. <ide> * @param ignoreFailedDrops {@code true} if failed drop statements should be ignored <ide> */ <ide> public void setIgnoreFailedDrops(boolean ignoreFailedDrops) { <ide> public void populate(Connection connection) throws ScriptException { <ide> } <ide> <ide> /** <del> * Execute this {@code DatabasePopulator} against the given {@link DataSource}. <add> * Execute this {@code ResourceDatabasePopulator} against the given <add> * {@link DataSource}. <ide> * <p>Delegates to {@link DatabasePopulatorUtils#execute}. <ide> * @param dataSource the {@code DataSource} to execute against <ide> * @throws ScriptException if an error occurs <ide> public void execute(DataSource dataSource) throws ScriptException { <ide> } <ide> <ide> /** <del> * {@link EncodedResource} is not a sub-type of {@link Resource}. Thus we always need <del> * to wrap each script resource in an encoded resource. <add> * {@link EncodedResource} is not a sub-type of {@link Resource}. Thus we <add> * always need to wrap each script resource in an {@code EncodedResource} <add> * using the configured {@linkplain #setSqlScriptEncoding encoding}. <add> * @param script the script to wrap <ide> */ <ide> private EncodedResource encodeScript(Resource script) { <ide> return new EncodedResource(script, this.sqlScriptEncoding); <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptUtils.java <ide> public abstract class ScriptUtils { <ide> private static final Log logger = LogFactory.getLog(ScriptUtils.class); <ide> <ide> /** <del> * Default statement separator within SQL scripts. <add> * Default statement separator within SQL scripts: {@code ";"}. <ide> */ <ide> public static final String DEFAULT_STATEMENT_SEPARATOR = ";"; <ide> <ide> /** <del> * Fallback statement separator within SQL scripts. <del> * <p>Used if neither a custom defined separator nor the <add> * Fallback statement separator within SQL scripts: {@code "\n"}. <add> * <p>Used if neither a custom separator nor the <ide> * {@link #DEFAULT_STATEMENT_SEPARATOR} is present in a given script. <ide> */ <ide> public static final String FALLBACK_STATEMENT_SEPARATOR = "\n"; <ide> <ide> /** <del> * End of file (EOF) SQL statement separator. <add> * End of file (EOF) SQL statement separator: {@code "^^^ END OF SCRIPT ^^^"}. <ide> * <p>This value may be supplied as the {@code separator} to {@link <ide> * #executeSqlScript(Connection, EncodedResource, boolean, boolean, String, String, String, String)} <ide> * to denote that an SQL script contains a single statement (potentially <ide> public abstract class ScriptUtils { <ide> public static final String EOF_STATEMENT_SEPARATOR = "^^^ END OF SCRIPT ^^^"; <ide> <ide> /** <del> * Default prefix for line comments within SQL scripts. <add> * Default prefix for single-line comments within SQL scripts: {@code "--"}. <ide> */ <ide> public static final String DEFAULT_COMMENT_PREFIX = "--"; <ide> <ide> /** <del> * Default start delimiter for block comments within SQL scripts. <add> * Default start delimiter for block comments within SQL scripts: {@code "/*"}. <ide> */ <ide> public static final String DEFAULT_BLOCK_COMMENT_START_DELIMITER = "/*"; <ide> <ide> /** <del> * Default end delimiter for block comments within SQL scripts. <add> * Default end delimiter for block comments within SQL scripts: <code>"*&#47;"</code>. <ide> */ <ide> public static final String DEFAULT_BLOCK_COMMENT_END_DELIMITER = "*/"; <ide> <ide> public static boolean containsSqlScriptDelimiters(String script, String delim) { <ide> } <ide> <ide> /** <del> * Execute the given SQL script using default settings for separator separators, <del> * comment delimiters, and exception handling flags. <add> * Execute the given SQL script using default settings for statement <add> * separators, comment delimiters, and exception handling flags. <ide> * <p>Statement separators and comments will be removed before executing <ide> * individual statements within the supplied script. <ide> * <p><b>Do not use this method to execute DDL if you expect rollback.</b> <ide> public static boolean containsSqlScriptDelimiters(String script, String delim) { <ide> * current platform's default encoding <ide> * @throws ScriptException if an error occurred while executing the SQL script <ide> * @see #executeSqlScript(Connection, EncodedResource, boolean, boolean, String, String, String, String) <del> * @see #DEFAULT_COMMENT_PREFIX <ide> * @see #DEFAULT_STATEMENT_SEPARATOR <add> * @see #DEFAULT_COMMENT_PREFIX <ide> * @see #DEFAULT_BLOCK_COMMENT_START_DELIMITER <ide> * @see #DEFAULT_BLOCK_COMMENT_END_DELIMITER <ide> */ <ide> public static void executeSqlScript(Connection connection, Resource resource) th <ide> } <ide> <ide> /** <del> * Execute the given SQL script using default settings for separator separators, <del> * comment delimiters, and exception handling flags. <add> * Execute the given SQL script using default settings for statement <add> * separators, comment delimiters, and exception handling flags. <ide> * <p>Statement separators and comments will be removed before executing <ide> * individual statements within the supplied script. <ide> * <p><b>Do not use this method to execute DDL if you expect rollback.</b> <ide> public static void executeSqlScript(Connection connection, Resource resource) th <ide> * to load the SQL script from <ide> * @throws ScriptException if an error occurred while executing the SQL script <ide> * @see #executeSqlScript(Connection, EncodedResource, boolean, boolean, String, String, String, String) <del> * @see #DEFAULT_COMMENT_PREFIX <ide> * @see #DEFAULT_STATEMENT_SEPARATOR <add> * @see #DEFAULT_COMMENT_PREFIX <ide> * @see #DEFAULT_BLOCK_COMMENT_START_DELIMITER <ide> * @see #DEFAULT_BLOCK_COMMENT_END_DELIMITER <ide> */ <ide> public static void executeSqlScript(Connection connection, EncodedResource resou <ide> * in the event of an error <ide> * @param ignoreFailedDrops whether or not to continue in the event of specifically <ide> * an error on a {@code DROP} statement <del> * @param commentPrefix the prefix that identifies comments in the SQL script &mdash; <del> * typically "--" <add> * @param commentPrefix the prefix that identifies single-line comments in the <add> * SQL script &mdash; typically "--" <ide> * @param separator the script statement separator; defaults to <ide> * {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to <ide> * {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort; may be set to
2
Text
Text
fix casing of dist files in docs
da0764a585db495c18f2f450f8b3cb32a68b374e
<ide><path>.github/ISSUE_TEMPLATE/BUG.md <ide> labels: 'type: bug' <ide> interactive example (https://codepen.io/pen?template=JXVYzq). <ide> <ide> If filing a bug against `master`, you may reference the latest code via <del> https://www.chartjs.org/dist/master/Chart.min.js (changing the filename to <add> https://www.chartjs.org/dist/master/chart.min.js (changing the filename to <ide> point at the file you need as appropriate). Do not rely on these files for <ide> production purposes as they may be removed at any time. <ide> --> <ide><path>docs/docs/developers/contributing.md <ide> Guidelines for reporting bugs: <ide> <ide> - Check the issue search to see if it has already been reported <ide> - Isolate the problem to a simple test case <del>- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)). If filing a bug against `master`, you may reference the latest code via <https://www.chartjs.org/dist/master/Chart.min.js> (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time. <add>- Please include a demonstration of the bug on a website such as [JS Bin](https://jsbin.com/), [JS Fiddle](https://jsfiddle.net/), or [Codepen](https://codepen.io/pen/). ([Template](https://codepen.io/pen?template=JXVYzq)). If filing a bug against `master`, you may reference the latest code via <https://www.chartjs.org/dist/master/chart.min.js> (changing the filename to point at the file you need as appropriate). Do not rely on these files for production purposes as they may be removed at any time. <ide> <ide> Please provide any additional details associated with the bug, if it's browser or screen density specific, or only happens with a certain configuration or data. <ide><path>docs/docs/developers/index.md <ide> Developer features allow extending and enhancing Chart.js in many different ways <ide> <ide> Latest documentation and samples, including unreleased features, are available at: <ide> <del> - https://www.chartjs.org/docs/master/ <del> - https://www.chartjs.org/samples/master/ <add>- https://www.chartjs.org/docs/master/ <add>- https://www.chartjs.org/samples/master/ <ide> <ide> ## Development releases <ide> <ide> Latest builds are available for testing at: <ide> <del> - https://www.chartjs.org/dist/master/Chart.js <del> - https://www.chartjs.org/dist/master/Chart.min.js <add>- https://www.chartjs.org/dist/master/chart.js <add>- https://www.chartjs.org/dist/master/chart.min.js <ide> <ide> **WARNING: Development builds MUST not be used for production purposes or as replacement for CDN.** <ide> <ide> ## Browser support <ide> <ide> Chart.js offers support for the following browsers: <del>* Chrome 50+ <del>* Firefox 45+ <del>* Internet Explorer 11 <del>* Edge 14+ <del>* Safari 9+ <add> <add>- Chrome 50+ <add>- Firefox 45+ <add>- Internet Explorer 11 <add>- Edge 14+ <add>- Safari 9+ <ide> <ide> Browser support for the canvas element is available in all modern & major mobile browsers. [CanIUse](https://caniuse.com/#feat=canvas) <ide>
3
Python
Python
add catch if docker lib is not in the good version
632faeb1026663e907763debe46227d8e6a0c12b
<ide><path>glances/plugins/glances_docker.py <ide> def update(self): <ide> try: <ide> self.docker_stats[c['Id']] = self.docker_client.stats(c['Id'], decode=True) <ide> logger.debug("Create Docker stats object for container {}".format(c['Id'])) <del> except AttributeError as e: <add> except (AttributeError, docker.errors.InvalidVersion) as e: <ide> logger.error("Can not call Docker stats method {}".format(e)) <ide> <ide> # Get the docker stats
1
PHP
PHP
swap the index order of morph type and id
d15ad0fdf2d1fef63600eeccf57d756d28571614
<ide><path>src/Illuminate/Database/Schema/Blueprint.php <ide> public function multiPolygon($column) <ide> */ <ide> public function morphs($name, $indexName = null) <ide> { <del> $this->unsignedInteger("{$name}_id"); <del> <ide> $this->string("{$name}_type"); <ide> <del> $this->index(["{$name}_id", "{$name}_type"], $indexName); <add> $this->unsignedInteger("{$name}_id"); <add> <add> $this->index(["{$name}_type", "{$name}_id"], $indexName); <ide> } <ide> <ide> /** <ide> public function morphs($name, $indexName = null) <ide> */ <ide> public function nullableMorphs($name, $indexName = null) <ide> { <del> $this->unsignedInteger("{$name}_id")->nullable(); <del> <ide> $this->string("{$name}_type")->nullable(); <ide> <del> $this->index(["{$name}_id", "{$name}_type"], $indexName); <add> $this->unsignedInteger("{$name}_id")->nullable(); <add> <add> $this->index(["{$name}_type", "{$name}_id"], $indexName); <ide> } <ide> <ide> /**
1
Text
Text
fix minor typo in swr
3dc4b524e79754804b8e53bd1783967d48ce5d13
<ide><path>docs/basic-features/data-fetching/client-side.md <ide> function Profile() { <ide> <ide> ## Client-side data fetching with SWR <ide> <del>The team behind Next.js has created a React hook library for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommend** if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more. <add>The team behind Next.js has created a React hook library for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommended** if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more. <ide> <ide> Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us and will revalidate the data if it becomes stale. <ide>
1
Python
Python
exclude 3.3 aswell
fafb827a461df2c32f752d3ac2e3cdb83fb3deaf
<ide><path>setup.py <ide> include_package_data=True, <ide> zip_safe=False, <ide> platforms='any', <del> python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*', <add> python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*', <ide> install_requires=[ <ide> 'Werkzeug>=0.14', <ide> 'Jinja2>=2.10',
1
Java
Java
add basic javadoc to spring-messaging annotations
cbdb99c042896cac30734440844c2c5563790cc0
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageBody.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <add>import org.springframework.messaging.Message; <add> <ide> <ide> /** <del> * Annotation indicating a method parameter should be bound to the body of a message. <add> * Annotation indicating a method parameter should be bound to the body of a <add> * {@link Message}. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageExceptionHandler.java <ide> <ide> <ide> /** <add> * Annotation for handling exceptions from message-handling methods within specific <add> * handler methods. <add> * <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageMapping.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <add>import org.springframework.messaging.Message; <add> <add> <ide> /** <add> * Annotation for mapping a {@link Message} onto specific handler handler methods based on <add> * the destination for the message. <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/ReplyTo.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <add>import org.springframework.messaging.Message; <add> <ide> <ide> /** <add> * Annotation that indicates a method's return value should be converted to <add> * a {@link Message} and sent to the specified destination. <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/ReplyToUser.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <add> <ide> <ide> /** <add> * Annotation that can be used on methods processing an input message to indicate that the <add> * method's return value should be converted to a {@link Message} and sent to the <add> * specified destination with the prefix <code>"/user/{username}"</code> automatically <add> * prepended with the user information expected to be the input message header <add> * {@link SimpMessageHeaderAccessor#USER_HEADER}. Such user destinations may need to be <add> * further resolved to actual destinations. <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <add> * <add> * @see org.springframework.messaging.handler.annotation.ReplyTo <add> * @see org.springframework.messaging.simp.handler.UserDestinationMessageHandler <ide> */ <ide> @Target(ElementType.METHOD) <ide> @Retention(RetentionPolicy.RUNTIME) <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/SubscribeEvent.java <ide> <ide> <ide> /** <add> * Annotation for mapping subscription events onto specific handler handler methods based <add> * on the destination for the message (e.g. STOMP SUBSCRIBE message). <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/UnsubscribeEvent.java <ide> <ide> <ide> /** <add> * Annotation for mapping unsubscribe events onto specific handler handler methods based <add> * on the destination for the message (e.g. STOMP UNSUBSCRIBE message). <add> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */
7
Javascript
Javascript
pass context to after-resolve hook
90daea5fdd31510e2822b0a1b0de0a6084ecbd4e
<ide><path>lib/NormalModuleFactory.js <ide> NormalModuleFactory.prototype.create = function(context, dependency, callback) { <ide> } <ide> function onDoneResolving() { <ide> this.applyPluginsAsyncWaterfall("after-resolve", { <add> context: context, <ide> request: loaders.concat([resource]).join("!"), <ide> userRequest: userRequest, <ide> rawRequest: request,
1
Ruby
Ruby
reduce allocations of pool_configs
bc951b47193639ba9d08f3b4248702e6e44fb3e7
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb <ide> def connection_pool_list(role = nil) <ide> end <ide> alias :connection_pools :connection_pool_list <ide> <add> def each_connection_pool(role = nil, &block) # :nodoc: <add> role = nil if role == :all <add> return enum_for(__method__, role) unless block_given? <add> <add> connection_name_to_pool_manager.each_value do |manager| <add> manager.each_pool_config(role) do |pool_config| <add> yield pool_config.pool <add> end <add> end <add> end <add> <ide> def establish_connection(config, owner_name: Base, role: ActiveRecord::Base.current_role, shard: Base.current_shard) <ide> owner_name = StringConnectionName.new(config.to_s) if config.is_a?(Symbol) <ide> <ide> def active_connections?(role = nil) <ide> role = ActiveRecord::Base.current_role <ide> end <ide> <del> connection_pool_list(role).any?(&:active_connection?) <add> each_connection_pool(role).any?(&:active_connection?) <ide> end <ide> <ide> # Returns any connections in use by the current thread back to the pool, <ide> def clear_active_connections!(role = nil) <ide> role = ActiveRecord::Base.current_role <ide> end <ide> <del> connection_pool_list(role).each(&:release_connection) <add> each_connection_pool(role).each(&:release_connection) <ide> end <ide> <ide> # Clears the cache which maps classes. <ide> def clear_reloadable_connections!(role = nil) <ide> role = ActiveRecord::Base.current_role <ide> end <ide> <del> connection_pool_list(role).each(&:clear_reloadable_connections!) <add> each_connection_pool(role).each(&:clear_reloadable_connections!) <ide> end <ide> <ide> def clear_all_connections!(role = nil) <ide> def clear_all_connections!(role = nil) <ide> role = ActiveRecord::Base.current_role <ide> end <ide> <del> connection_pool_list(role).each(&:disconnect!) <add> each_connection_pool(role).each(&:disconnect!) <ide> end <ide> <ide> # Disconnects all currently idle connections. <ide> def flush_idle_connections!(role = nil) <ide> role = ActiveRecord::Base.current_role <ide> end <ide> <del> connection_pool_list(role).each(&:flush!) <add> each_connection_pool(role).each(&:flush!) <ide> end <ide> <ide> # Locate the connection of the nearest super class. This can be an <ide><path>activerecord/lib/active_record/connection_adapters/pool_manager.rb <ide> def pool_configs(role = nil) <ide> end <ide> end <ide> <add> def each_pool_config(role = nil, &block) <add> if role <add> @role_to_shard_mapping[role].each_value(&block) <add> else <add> @role_to_shard_mapping.each_value do |shard_map| <add> shard_map.each_value(&block) <add> end <add> end <add> end <add> <ide> def remove_role(role) <ide> @role_to_shard_mapping.delete(role) <ide> end <ide><path>activerecord/lib/active_record/connection_handling.rb <ide> def connected_to?(role:, shard: ActiveRecord::Base.default_shard) <ide> <ide> # Clears the query cache for all connections associated with the current thread. <ide> def clear_query_caches_for_current_thread <del> connection_handler.connection_pool_list(:all).each do |pool| <add> connection_handler.each_connection_pool do |pool| <ide> pool.connection.clear_query_cache if pool.active_connection? <ide> end <ide> end <ide><path>activerecord/lib/active_record/query_cache.rb <ide> def uncached(&block) <ide> end <ide> <ide> def self.run <del> pools = [] <del> pools.concat(ActiveRecord::Base.connection_handler.connection_pool_list(:all).reject { |p| p.query_cache_enabled }.each { |p| p.enable_query_cache! }) <del> pools <add> ActiveRecord::Base.connection_handler.each_connection_pool.reject { |p| p.query_cache_enabled }.each { |p| p.enable_query_cache! } <ide> end <ide> <ide> def self.complete(pools) <ide> pools.each { |pool| pool.disable_query_cache! } <ide> <del> ActiveRecord::Base.connection_handler.connection_pool_list(:all).each do |pool| <add> ActiveRecord::Base.connection_handler.each_connection_pool do |pool| <ide> pool.release_connection if pool.active_connection? && !pool.connection.transaction_open? <ide> end <ide> end
4
Ruby
Ruby
use safe navigation on #sort_by
e604cf742bf158b9f133c14ac438822326fbbd2e
<ide><path>Library/Homebrew/dev-cmd/livecheck.rb <ide> def livecheck <ide> puts ENV["HOMEBREW_LIVECHECK_WATCHLIST"] if ENV["HOMEBREW_LIVECHECK_WATCHLIST"].present? <ide> end <ide> <del> formulae_and_casks_to_check = if args.tap <del> tap = Tap.fetch(args.tap) <del> formulae = args.cask? ? [] : tap.formula_files.map { |path| Formulary.factory(path) } <del> casks = args.formula? ? [] : tap.cask_files.map { |path| Cask::CaskLoader.load(path) } <del> formulae + casks <del> elsif args.installed? <del> formulae = args.cask? ? [] : Formula.installed <del> casks = args.formula? ? [] : Cask::Caskroom.casks <del> formulae + casks <del> elsif args.all? <del> formulae = args.cask? ? [] : Formula.to_a <del> casks = args.formula? ? [] : Cask::Cask.to_a <del> formulae + casks <del> elsif args.named.present? <del> if args.formula? <del> args.named.to_formulae <del> elsif args.cask? <del> args.named.to_casks <del> else <del> args.named.to_formulae_and_casks <del> end <del> elsif File.exist?(WATCHLIST_PATH) <del> begin <del> names = Pathname.new(WATCHLIST_PATH).read.lines <del> .reject { |line| line.start_with?("#") || line.blank? } <del> .map(&:strip) <add> formulae_and_casks_to_check = <add> if args.tap <add> tap = Tap.fetch(args.tap) <add> formulae = args.cask? ? [] : tap.formula_files.map { |path| Formulary.factory(path) } <add> casks = args.formula? ? [] : tap.cask_files.map { |path| Cask::CaskLoader.load(path) } <add> formulae + casks <add> elsif args.installed? <add> formulae = args.cask? ? [] : Formula.installed <add> casks = args.formula? ? [] : Cask::Caskroom.casks <add> formulae + casks <add> elsif args.all? <add> formulae = args.cask? ? [] : Formula.to_a <add> casks = args.formula? ? [] : Cask::Cask.to_a <add> formulae + casks <add> elsif args.named.present? <add> if args.formula? <add> args.named.to_formulae <add> elsif args.cask? <add> args.named.to_casks <add> else <add> args.named.to_formulae_and_casks <add> end <add> elsif File.exist?(WATCHLIST_PATH) <add> begin <add> names = Pathname.new(WATCHLIST_PATH).read.lines <add> .reject { |line| line.start_with?("#") || line.blank? } <add> .map(&:strip) <ide> <del> named_args = T.unsafe(CLI::NamedArgs).new(*names) <del> named_args.to_formulae_and_casks.reject do |formula_or_cask| <del> (args.formula? && !formula_or_cask.is_a?(Formula)) || <del> (args.cask? && !formula_or_cask.is_a?(Cask::Cask)) <add> named_args = T.unsafe(CLI::NamedArgs).new(*names) <add> named_args.to_formulae_and_casks.reject do |formula_or_cask| <add> (args.formula? && !formula_or_cask.is_a?(Formula)) || <add> (args.cask? && !formula_or_cask.is_a?(Cask::Cask)) <add> end <add> rescue Errno::ENOENT => e <add> onoe e <ide> end <del> rescue Errno::ENOENT => e <del> onoe e <add> end&.sort_by do |formula_or_cask| <add> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <ide> end <del> end.sort_by do |formula_or_cask| <del> formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name <del> end <ide> <ide> raise UsageError, "No formulae or casks to check." if formulae_and_casks_to_check.blank? <ide>
1
Python
Python
unify flag name for long running tests
9c8926be61207cf06e9e8d87120ac9145f64a676
<ide><path>tests/conftest.py <ide> def skip_system_test(item): <ide> def skip_long_running_test(item): <ide> for _ in item.iter_markers(name="long_running"): <ide> pytest.skip("The test is skipped because it has long_running marker. " <del> "And system tests are only run when --long-lasting flag " <add> "And system tests are only run when --include-long-running flag " <ide> "is passed to pytest. {item}". <ide> format(item=item)) <ide>
1
Javascript
Javascript
show warning when using lib/sys.js
8d70cc607cafc4c8caecd1d59727d2b2ab3fe550
<ide><path>lib/sys.js <ide> var sysWarning; <ide> if (!sysWarning) { <ide> sysWarning = 'The "sys" module is now called "util". ' + <ide> 'It should have a similar interface.'; <del> // Uncomment in 2011 <del> //util.error(sysWarning); <add> util.error(sysWarning); <ide> } <ide> <ide> exports.print = util.print;
1
Python
Python
add template fields to neo4j operator
93a6e20f43ffa4f1918974f9d394256525ec1a4b
<ide><path>airflow/providers/neo4j/example_dags/example_neo4j.py <ide> neo4j_task = Neo4jOperator( <ide> task_id='run_neo4j_query', <ide> neo4j_conn_id='neo4j_conn_id', <del> sql='MATCH (tom {name: "Tom Hanks"}) RETURN tom', <add> sql='MATCH (tom {name: "Tom Hanks", date: "{{ds}}"}) RETURN tom', <ide> dag=dag, <ide> ) <ide> <ide><path>airflow/providers/neo4j/operators/neo4j.py <ide> class Neo4jOperator(BaseOperator): <ide> :type neo4j_conn_id: str <ide> """ <ide> <add> template_fields = ['sql'] <add> <ide> def __init__( <ide> self, <ide> *,
2
Javascript
Javascript
replace console.error() with debuglog calls
83ebd7731852369fa08fb5885c7fcf7b671bce91
<ide><path>test/parallel/test-http-information-processing.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <add>const debug = require('util').debuglog('test'); <ide> <ide> const testResBody = 'other stuff!\n'; <ide> const kMessageCount = 2; <ide> <ide> const server = http.createServer((req, res) => { <ide> for (let i = 0; i < kMessageCount; i++) { <del> console.error(`Server sending informational message #${i}...`); <add> debug(`Server sending informational message #${i}...`); <ide> res.writeProcessing(); <ide> } <del> console.error('Server sending full response...'); <add> debug('Server sending full response...'); <ide> res.writeHead(200, { <ide> 'Content-Type': 'text/plain', <ide> 'ABCD': '1' <ide> server.listen(0, function() { <ide> path: '/world' <ide> }); <ide> req.end(); <del> console.error('Client sending request...'); <add> debug('Client sending request...'); <ide> <ide> let body = ''; <ide> let infoCount = 0; <ide> server.listen(0, function() { <ide> res.setEncoding('utf8'); <ide> res.on('data', function(chunk) { body += chunk; }); <ide> res.on('end', function() { <del> console.error('Got full response.'); <add> debug('Got full response.'); <ide> assert.strictEqual(body, testResBody); <ide> assert.ok('abcd' in res.headers); <ide> server.close();
1
Text
Text
add option and update the description
1917d3b958da9ffc3b738941c783e9424e3c9c2e
<ide><path>docs/reference/commandline/cli.md <ide> To list the help on any command just execute the command, followed by the <ide> <ide> Run a command in a new container <ide> <del> -a, --attach=[] Attach to STDIN, STDOUT or STDERR <del> --cpu-shares=0 CPU shares (relative weight) <add> Options: <add> --add-host value Add a custom host-to-IP mapping (host:ip) (default []) <add> -a, --attach value Attach to STDIN, STDOUT or STDERR (default []) <ide> ... <ide> <ide> ## Option types
1
Javascript
Javascript
use filter for class and title
2d660756bb14ad9e54ff7f20f805133a3a90b36e
<ide><path>examples/calendar/dji.js <ide> var rect = svg.selectAll("rect.day") <ide> .attr("width", z) <ide> .attr("height", z) <ide> .attr("x", function(d) { return week(d) * z; }) <del> .attr("y", function(d) { return day(d) * z; }); <add> .attr("y", function(d) { return day(d) * z; }) <add> .map(format); <add> <add>rect.append("title") <add> .text(function(d) { return d; }); <ide> <ide> svg.selectAll("path.month") <ide> .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) <ide> d3.csv("dji.csv", function(csv) { <ide> .rollup(function(d) { return (d[0].Close - d[0].Open) / d[0].Open; }) <ide> .map(csv); <ide> <del> rect <del> .attr("class", function(d) { <del> var dv = data[format(d)]; <del> return "day q" + (dv ? color(dv) : "X") + "-9"; }) <del> .append("title") <del> .text(function(d) { return (d = format(d)) + (d in data ? ": " + percent(data[d]) : ""); }); <add> rect.filter(function(d) { return d in data; }) <add> .attr("class", function(d) { return "day q" + color(data[d]) + "-9"; }) <add> .select("title") <add> .text(function(d) { return d + ": " + percent(data[d]); }); <ide> }); <ide> <ide> function monthPath(t0) { <ide><path>examples/calendar/vix.js <ide> var rect = svg.selectAll("rect.day") <ide> .attr("width", z) <ide> .attr("height", z) <ide> .attr("x", function(d) { return week(d) * z; }) <del> .attr("y", function(d) { return day(d) * z; }); <add> .attr("y", function(d) { return day(d) * z; }) <add> .map(format); <add> <add>rect.append("title") <add> .text(function(d) { return d; }); <ide> <ide> svg.selectAll("path.month") <ide> .data(function(d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); }) <ide> d3.csv("vix.csv", function(csv) { <ide> <ide> color.domain(d3.values(data)); <ide> <del> rect <del> .attr("class", function(d) { <del> var dv = data[format(d)]; <del> return "day q" + (dv ? color(dv) : "X") + "-9"; }) <del> .append("title") <del> .text(function(d) { return (d = format(d)) + (d in data ? ": " + data[d] : ""); }); <add> rect.filter(function(d) { return d in data; }) <add> .attr("class", function(d) { return "day q" + color(data[d]) + "-9"; }) <add> .select("title") <add> .text(function(d) { return d + ": " + data[d]; }); <ide> }); <ide> <ide> function monthPath(t0) {
2
Text
Text
fix anchor for err_tls_invalid_context
fa1fc6bf9f257f7365454dc7a28bb4cd4385919f
<ide><path>doc/api/errors.md <ide> recommended to use 2048 bits or larger for stronger security. <ide> A TLS/SSL handshake timed out. In this case, the server must also abort the <ide> connection. <ide> <del><a id="ERR_TLS_INVALID_CONTEXT"> <add><a id="ERR_TLS_INVALID_CONTEXT"></a> <ide> ### `ERR_TLS_INVALID_CONTEXT` <ide> <!-- YAML <ide> added: v13.3.0
1
PHP
PHP
fix cs error
ada53422ed7f8d72ed072c0e46600e1028fadbe7
<ide><path>src/Mailer/Email.php <ide> public function render(?string $content = null) <ide> $this->renderer = new Renderer(); <ide> } <ide> <del> list($this->_message, $this->_boundary, $this->_textMessage, $this->_htmlMessage) = $this->renderer->render($this, $content); <add> list($this->_message, <add> $this->_boundary, <add> $this->_textMessage, <add> $this->_htmlMessage <add> ) = $this->renderer->render($this, $content); <ide> } <ide> <ide> /**
1
Ruby
Ruby
make am test suite green
d74b5e440c04a1d89ae092cab7cb4d93d850f94a
<ide><path>actionmailer/test/abstract_unit.rb <ide> <ide> require 'test/unit' <ide> require 'action_mailer' <add>require 'action_mailer/test_case' <ide> <ide> # Show backtraces for deprecated behavior for quicker cleanup. <ide> ActiveSupport::Deprecation.debug = true <ide><path>actionmailer/test/base_test.rb <ide> def custom_block(include_html=false) <ide> <ide> def different_template(template_name='') <ide> mail do |format| <del> format.text { render :template => template_name } <del> format.html { render :template => template_name } <add> format.text { render :template => "#{mailer_name}/#{template_name}" } <add> format.html { render :template => "#{mailer_name}/#{template_name}" } <ide> end <ide> end <ide>
2
Javascript
Javascript
add pure notations to object calls
27411f8f0f404aa6779810726cca7dc9fac53af3
<ide><path>lib/DefinePlugin.js <ide> const stringifyObj = ( <ide> case false: <ide> return arr ? `;${code}` : `;(${code})`; <ide> default: <del> return `Object(${code})`; <add> return `/*#__PURE__*/Object(${code})`; <ide> } <ide> }; <ide> <ide><path>lib/RuntimeTemplate.js <ide> class RuntimeTemplate { <ide> ? `(0,${access})` <ide> : asiSafe === false <ide> ? `;(0,${access})` <del> : `Object(${access})`; <add> : `/*#__PURE__*/Object(${access})`; <ide> } <ide> return access; <ide> } else { <ide><path>lib/optimize/ConcatenatedModule.js <ide> const getFinalName = ( <ide> ? `(0,${reference})` <ide> : asiSafe === false <ide> ? `;(0,${reference})` <del> : `Object(${reference})`; <add> : `/*#__PURE__*/Object(${reference})`; <ide> } <ide> return reference; <ide> }
3
PHP
PHP
add another method to auth contract
3b83f3cf7209757f93f6fe466a056975b43615fa
<ide><path>src/Illuminate/Contracts/Auth/Authenticator.php <ide> public function validate(array $credentials = array()); <ide> */ <ide> public function login(User $user, $remember = false); <ide> <add> /** <add> * Log the given user ID into the application. <add> * <add> * @param mixed $id <add> * @param bool $remember <add> * @return \Illuminate\Contracts\Auth\User <add> */ <add> public function loginUsingId($id, $remember = false); <add> <ide> /** <ide> * Determine if the user was authenticated via "remember me" cookie. <ide> *
1
Mixed
Ruby
get provider_job_id from delayedjob
dd8e859829bfcfd8cb0287ce804055b827a35af1
<ide><path>activejob/CHANGELOG.md <add>* Allow `DelayedJob` to report id back to `ActiveJob::Base` as <add> `provider_job_id`. <add> <add> Fixes #18821. <add> <add> *Kevin Deisz* <add> <ide> * `assert_enqueued_jobs` and `assert_performed_jobs` in block form use the <ide> given number as expected value. This makes the error message much easier to <ide> understand. <ide><path>activejob/lib/active_job/core.rb <ide> module Core <ide> <ide> # Queue in which the job will reside. <ide> attr_writer :queue_name <add> <add> # ID optionally provided by adapter <add> attr_accessor :provider_job_id <ide> end <ide> <ide> # These methods will be included into any Active Job object, adding <ide><path>activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb <ide> module QueueAdapters <ide> # Rails.application.config.active_job.queue_adapter = :delayed_job <ide> class DelayedJobAdapter <ide> def enqueue(job) #:nodoc: <del> Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name) <add> delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name) <add> job.provider_job_id = delayed_job.id <add> delayed_job <ide> end <ide> <ide> def enqueue_at(job, timestamp) #:nodoc: <del> Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, run_at: Time.at(timestamp)) <add> delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, run_at: Time.at(timestamp)) <add> job.provider_job_id = delayed_job.id <add> delayed_job <ide> end <ide> <ide> class JobWrapper #:nodoc: <ide><path>activejob/test/integration/queuing_test.rb <ide> class QueuingTest < ActiveSupport::TestCase <ide> skip <ide> end <ide> end <add> <add> test 'should supply a provider_job_id to DelayedJob' do <add> skip unless adapter_is?(:delayed_job) <add> test_job = TestJob.perform_later @id <add> assert_kind_of Fixnum, test_job.provider_job_id <add> end <ide> end
4
Java
Java
remove duplicate separators when combining paths
76beb36e4bd1162bed6ff91f4ba5df6f9e47b528
<ide><path>spring-core/src/main/java/org/springframework/util/AntPathMatcher.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.util.regex.Pattern; <ide> <ide> /** <del> * PathMatcher implementation for Ant-style path patterns. Examples are provided below. <add> * {@link PathMatcher} implementation for Ant-style path patterns. <ide> * <ide> * <p>Part of this mapping code has been kindly borrowed from <a href="http://ant.apache.org">Apache Ant</a>. <ide> * <del> * <p>The mapping matches URLs using the following rules:<br> <ul> <li>? matches one character</li> <li>* matches zero <del> * or more characters</li> <li>** matches zero or more 'directories' in a path</li> </ul> <add> * <p>The mapping matches URLs using the following rules:<br> <add> * <ul> <add> * <li>{@code ?} matches one character</li> <add> * <li>{@code *} matches zero or more characters</li> <add> * <li>{@code **} matches zero or more <em>directories</em> in a path</li> <add> * </ul> <ide> * <del> * <p>Some examples:<br> <ul> <li>{@code com/t?st.jsp} - matches {@code com/test.jsp} but also <del> * {@code com/tast.jsp} or {@code com/txst.jsp}</li> <li>{@code com/*.jsp} - matches all <del> * {@code .jsp} files in the {@code com} directory</li> <li>{@code com/&#42;&#42;/test.jsp} - matches all <del> * {@code test.jsp} files underneath the {@code com} path</li> <li>{@code org/springframework/&#42;&#42;/*.jsp} <del> * - matches all {@code .jsp} files underneath the {@code org/springframework} path</li> <del> * <li>{@code org/&#42;&#42;/servlet/bla.jsp} - matches {@code org/springframework/servlet/bla.jsp} but also <del> * {@code org/springframework/testing/servlet/bla.jsp} and {@code org/servlet/bla.jsp}</li> </ul> <add> * <h3>Examples</h3> <add> * <ul> <add> * <li>{@code com/t?st.jsp} &mdash; matches {@code com/test.jsp} but also <add> * {@code com/tast.jsp} or {@code com/txst.jsp}</li> <add> * <li>{@code com/*.jsp} &mdash; matches all {@code .jsp} files in the <add> * {@code com} directory</li> <add> * <li><code>com/&#42;&#42;/test.jsp</code> &mdash; matches all {@code test.jsp} <add> * files underneath the {@code com} path</li> <add> * <li><code>org/springframework/&#42;&#42;/*.jsp</code> &mdash; matches all <add> * {@code .jsp} files underneath the {@code org/springframework} path</li> <add> * <li><code>org/&#42;&#42;/servlet/bla.jsp</code> &mdash; matches <add> * {@code org/springframework/servlet/bla.jsp} but also <add> * {@code org/springframework/testing/servlet/bla.jsp} and {@code org/servlet/bla.jsp}</li> <add> * </ul> <ide> * <ide> * @author Alef Arendsen <ide> * @author Juergen Hoeller <ide> * @author Rob Harrop <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <add> * @author Sam Brannen <ide> * @since 16.07.2003 <ide> */ <ide> public class AntPathMatcher implements PathMatcher { <ide> public AntPathMatcher() { <ide> } <ide> <ide> /** <del> * A convenience alternative constructor to use with a custom path separator. <add> * A convenient, alternative constructor to use with a custom path separator. <ide> * @param pathSeparator the path separator to use, must not be {@code null}. <ide> * @since 4.1 <ide> */ <ide> public AntPathMatcher(String pathSeparator) { <ide> <ide> /** <ide> * Set the path separator to use for pattern parsing. <del> * Default is "/", as in Ant. <add> * <p>Default is "/", as in Ant. <ide> */ <ide> public void setPathSeparator(String pathSeparator) { <ide> this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR); <ide> public void setPathSeparator(String pathSeparator) { <ide> <ide> /** <ide> * Specify whether to trim tokenized paths and patterns. <del> * Default is {@code true}. <add> * <p>Default is {@code true}. <ide> */ <ide> public void setTrimTokens(boolean trimTokens) { <ide> this.trimTokens = trimTokens; <ide> public void setTrimTokens(boolean trimTokens) { <ide> * <p>Default is for the cache to be on, but with the variant to automatically <ide> * turn it off when encountering too many patterns to cache at runtime <ide> * (the threshold is 65536), assuming that arbitrary permutations of patterns <del> * are coming in, with little chance for encountering a reoccurring pattern. <add> * are coming in, with little chance for encountering a recurring pattern. <ide> * @see #getStringMatcher(String) <ide> */ <ide> public void setCachePatterns(boolean cachePatterns) { <ide> protected String[] tokenizePath(String path) { <ide> } <ide> <ide> /** <del> * Tests whether or not a string matches against a pattern. <add> * Test whether or not a string matches against a pattern. <ide> * @param pattern the pattern to match against (never {@code null}) <ide> * @param str the String which must be matched against the pattern (never {@code null}) <ide> * @return {@code true} if the string matches against the pattern, or {@code false} otherwise <ide> private boolean matchStrings(String pattern, String str, Map<String, String> uri <ide> * <p>The default implementation checks this AntPathMatcher's internal cache <ide> * (see {@link #setCachePatterns}), creating a new AntPathStringMatcher instance <ide> * if no cached copy is found. <del> * When encountering too many patterns to cache at runtime (the threshold is 65536), <add> * <p>When encountering too many patterns to cache at runtime (the threshold is 65536), <ide> * it turns the default cache off, assuming that arbitrary permutations of patterns <del> * are coming in, with little chance for encountering a reoccurring pattern. <del> * <p>This method may get overridden to implement a custom cache strategy. <add> * are coming in, with little chance for encountering a recurring pattern. <add> * <p>This method may be overridden to implement a custom cache strategy. <ide> * @param pattern the pattern to match against (never {@code null}) <ide> * @return a corresponding AntPathStringMatcher (never {@code null}) <ide> * @see #setCachePatterns <ide> public Map<String, String> extractUriTemplateVariables(String pattern, String pa <ide> } <ide> <ide> /** <del> * Combines two patterns into a new pattern that is returned. <del> * <p>This implementation simply concatenates the two patterns, unless the first pattern <del> * contains a file extension match (such as {@code *.html}. In that case, the second pattern <del> * should be included in the first, or an {@code IllegalArgumentException} is thrown. <del> * <p>For example: <table> <del> * <tr><th>Pattern 1</th><th>Pattern 2</th><th>Result</th></tr> <tr><td>/hotels</td><td>{@code <del> * null}</td><td>/hotels</td></tr> <tr><td>{@code null}</td><td>/hotels</td><td>/hotels</td></tr> <del> * <tr><td>/hotels</td><td>/bookings</td><td>/hotels/bookings</td></tr> <tr><td>/hotels</td><td>bookings</td><td>/hotels/bookings</td></tr> <del> * <tr><td>/hotels/*</td><td>/bookings</td><td>/hotels/bookings</td></tr> <tr><td>/hotels/&#42;&#42;</td><td>/bookings</td><td>/hotels/&#42;&#42;/bookings</td></tr> <del> * <tr><td>/hotels</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr> <tr><td>/hotels/*</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr> <add> * Combine two patterns into a new pattern. <add> * <add> * <p>This implementation simply concatenates the two patterns, unless <add> * the first pattern contains a file extension match (e.g., {@code *.html}). <add> * In that case, the second pattern will be merged into the first. Otherwise, <add> * an {@code IllegalArgumentException} will be thrown. <add> * <add> * <h3>Examples</h3> <add> * <table border="1"> <add> * <tr><th>Pattern 1</th><th>Pattern 2</th><th>Result</th></tr> <add> * <tr><td>{@code null}</td><td>{@code null}</td><td>&nbsp;</td></tr> <add> * <tr><td>/hotels</td><td>{@code null}</td><td>/hotels</td></tr> <add> * <tr><td>{@code null}</td><td>/hotels</td><td>/hotels</td></tr> <add> * <tr><td>/hotels</td><td>/bookings</td><td>/hotels/bookings</td></tr> <add> * <tr><td>/hotels</td><td>bookings</td><td>/hotels/bookings</td></tr> <add> * <tr><td>/hotels/*</td><td>/bookings</td><td>/hotels/bookings</td></tr> <add> * <tr><td>/hotels/&#42;&#42;</td><td>/bookings</td><td>/hotels/&#42;&#42;/bookings</td></tr> <add> * <tr><td>/hotels</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr> <add> * <tr><td>/hotels/*</td><td>{hotel}</td><td>/hotels/{hotel}</td></tr> <ide> * <tr><td>/hotels/&#42;&#42;</td><td>{hotel}</td><td>/hotels/&#42;&#42;/{hotel}</td></tr> <del> * <tr><td>/*.html</td><td>/hotels.html</td><td>/hotels.html</td></tr> <tr><td>/*.html</td><td>/hotels</td><td>/hotels.html</td></tr> <del> * <tr><td>/*.html</td><td>/*.txt</td><td>IllegalArgumentException</td></tr> </table> <add> * <tr><td>/*.html</td><td>/hotels.html</td><td>/hotels.html</td></tr> <add> * <tr><td>/*.html</td><td>/hotels</td><td>/hotels.html</td></tr> <add> * <tr><td>/*.html</td><td>/*.txt</td><td>{@code IllegalArgumentException}</td></tr> <add> * </table> <add> * <ide> * @param pattern1 the first pattern <ide> * @param pattern2 the second pattern <ide> * @return the combination of the two patterns <del> * @throws IllegalArgumentException when the two patterns cannot be combined <add> * @throws IllegalArgumentException if the two patterns cannot be combined <ide> */ <ide> @Override <ide> public String combine(String pattern1, String pattern2) { <ide> public String combine(String pattern1, String pattern2) { <ide> } <ide> <ide> private String concat(String path1, String path2) { <del> if (path1.endsWith(this.pathSeparator) || path2.startsWith(this.pathSeparator)) { <add> boolean path1EndsWithSeparator = path1.endsWith(this.pathSeparator); <add> boolean path2StartsWithSeparator = path2.startsWith(this.pathSeparator); <add> <add> if (path1EndsWithSeparator && path2StartsWithSeparator) { <add> return path1 + path2.substring(1); <add> } <add> else if (path1EndsWithSeparator || path2StartsWithSeparator) { <ide> return path1 + path2; <ide> } <del> return path1 + this.pathSeparator + path2; <add> else { <add> return path1 + this.pathSeparator + path2; <add> } <ide> } <ide> <ide> /** <ide><path>spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void match() { <ide> assertFalse(pathMatcher.match("tes?", "testt")); <ide> assertFalse(pathMatcher.match("tes?", "tsst")); <ide> <del> // test matchin with *'s <add> // test matching with *'s <ide> assertTrue(pathMatcher.match("*", "test")); <ide> assertTrue(pathMatcher.match("test*", "test")); <ide> assertTrue(pathMatcher.match("test*", "testTest")); <ide> public void withMatchStart() { <ide> assertFalse(pathMatcher.matchStart("tes?", "testt")); <ide> assertFalse(pathMatcher.matchStart("tes?", "tsst")); <ide> <del> // test matchin with *'s <add> // test matching with *'s <ide> assertTrue(pathMatcher.matchStart("*", "test")); <ide> assertTrue(pathMatcher.matchStart("test*", "test")); <ide> assertTrue(pathMatcher.matchStart("test*", "testTest")); <ide> public void uniqueDeliminator() { <ide> assertFalse(pathMatcher.match("tes?", "testt")); <ide> assertFalse(pathMatcher.match("tes?", "tsst")); <ide> <del> // test matchin with *'s <add> // test matching with *'s <ide> assertTrue(pathMatcher.match("*", "test")); <ide> assertTrue(pathMatcher.match("test*", "test")); <ide> assertTrue(pathMatcher.match("test*", "testTest")); <ide> public void extractUriTemplateVariablesRegex() { <ide> assertEquals("1.0.0", result.get("version")); <ide> } <ide> <del> // SPR-7787 <del> <add> /** <add> * SPR-7787 <add> */ <ide> @Test <ide> public void extractUriTemplateVarsRegexQualifiers() { <ide> Map<String, String> result = pathMatcher.extractUriTemplateVariables( <ide> public void extractUriTemplateVarsRegexQualifiers() { <ide> assertEquals("1.0.0.{12}", result.get("version")); <ide> } <ide> <del> // SPR-8455 <del> <add> /** <add> * SPR-8455 <add> */ <ide> @Test <ide> public void extractUriTemplateVarsRegexCapturingGroups() { <ide> try { <ide> public void combine() { <ide> assertEquals("/user/user", pathMatcher.combine("/user", "/user")); // SPR-7970 <ide> assertEquals("/{foo:.*[^0-9].*}/edit/", pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")); // SPR-10062 <ide> assertEquals("/1.0/foo/test", pathMatcher.combine("/1.0", "/foo/test")); // SPR-10554 <add> assertEquals("/hotel", pathMatcher.combine("/", "/hotel")); // SPR-12975 <add> assertEquals("/hotel/booking", pathMatcher.combine("/hotel/", "/booking")); // SPR-12975 <ide> } <ide> <ide> @Test <ide> public void patternComparatorSort() { <ide> paths.clear(); <ide> } <ide> <del> // SPR-8687 <del> <add> /** <add> * SPR-8687 <add> */ <ide> @Test <ide> public void trimTokensOff() { <ide> pathMatcher.setTrimTokens(false); <ide> public void trimTokensOff() { <ide> } <ide> <ide> @Test <del> public void testDefaultCacheSetting() { <add> public void defaultCacheSetting() { <ide> match(); <ide> assertTrue(pathMatcher.stringMatcherCache.size() > 20); <ide> <ide> public void testDefaultCacheSetting() { <ide> } <ide> <ide> @Test <del> public void testCacheSetToTrue() { <add> public void cachePatternsSetToTrue() { <ide> pathMatcher.setCachePatterns(true); <ide> match(); <ide> assertTrue(pathMatcher.stringMatcherCache.size() > 20); <ide> public void testCacheSetToTrue() { <ide> } <ide> <ide> @Test <del> public void testCacheSetToFalse() { <add> public void cachePatternsSetToFalse() { <ide> pathMatcher.setCachePatterns(false); <ide> match(); <ide> assertTrue(pathMatcher.stringMatcherCache.isEmpty()); <ide> } <ide> <ide> @Test <del> public void testExtensionMappingWithDotPathSeparator() { <add> public void extensionMappingWithDotPathSeparator() { <ide> pathMatcher.setPathSeparator("."); <ide> assertEquals("Extension mapping should be disabled with \".\" as path separator", <ide> "/*.html.hotel.*", pathMatcher.combine("/*.html", "hotel.*")); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/AbstractRequestCondition.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public String toString() { <ide> return builder.toString(); <ide> } <ide> <add> /** <add> * Indicates whether this condition is empty, i.e. whether or not it <add> * contains any discrete items. <add> * @return {@code true} if empty; {@code false} otherwise <add> */ <add> public boolean isEmpty() { <add> return getContent().isEmpty(); <add> } <add> <ide> <ide> /** <ide> * Return the discrete items a request condition is composed of. <del> * For example URL patterns, HTTP request methods, param expressions, etc. <add> * <p>For example URL patterns, HTTP request methods, param expressions, etc. <ide> * @return a collection of objects, never {@code null} <ide> */ <ide> protected abstract Collection<?> getContent(); <ide> <ide> /** <ide> * The notation to use when printing discrete items of content. <del> * For example " || " for URL patterns or " && " for param expressions. <add> * <p>For example {@code " || "} for URL patterns or {@code " && "} <add> * for param expressions. <ide> */ <ide> protected abstract String getToStringInfix(); <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfo.java <ide> public int hashCode() { <ide> public String toString() { <ide> StringBuilder builder = new StringBuilder("{"); <ide> builder.append(this.patternsCondition); <del> builder.append(",methods=").append(this.methodsCondition); <del> builder.append(",params=").append(this.paramsCondition); <del> builder.append(",headers=").append(this.headersCondition); <del> builder.append(",consumes=").append(this.consumesCondition); <del> builder.append(",produces=").append(this.producesCondition); <del> builder.append(",custom=").append(this.customConditionHolder); <add> if (!this.methodsCondition.isEmpty()) { <add> builder.append(",methods=").append(this.methodsCondition); <add> } <add> if (!this.paramsCondition.isEmpty()) { <add> builder.append(",params=").append(this.paramsCondition); <add> } <add> if (!this.headersCondition.isEmpty()) { <add> builder.append(",headers=").append(this.headersCondition); <add> } <add> if (!this.consumesCondition.isEmpty()) { <add> builder.append(",consumes=").append(this.consumesCondition); <add> } <add> if (!this.producesCondition.isEmpty()) { <add> builder.append(",produces=").append(this.producesCondition); <add> } <add> if (!this.customConditionHolder.isEmpty()) { <add> builder.append(",custom=").append(this.customConditionHolder); <add> } <ide> builder.append('}'); <ide> return builder.toString(); <ide> }
4
Ruby
Ruby
add a todo so we remember to fix partial layouts
86c7b144fadf87736cf3d7e623d56eddae8e9963
<ide><path>actionpack/lib/abstract_controller/layouts.rb <ide> def render_to_body(options = {}) <ide> # This is a little bit messy. We need to explicitly handle partial <ide> # layouts here since the core lookup logic is in the view, but <ide> # we need to determine the layout based on the controller <add> # <add> # TODO: An easier way to handle this would probably be to override <add> # render_template <ide> if layout <ide> layout = _layout_for_option(layout, options[:_template].details) <ide> response = layout.render(view_context, options[:locals] || {}) { response }
1
PHP
PHP
simplify the find method
b7fa52c6abb076e6844798f793231bc2886aa0d5
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function __construct(QueryBuilder $query) <ide> * <ide> * @param mixed $id <ide> * @param array $columns <del> * @return \Illuminate\Database\Eloquent\Model|static|null <add> * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null <ide> */ <ide> public function find($id, $columns = array('*')) <ide> { <ide> public function find($id, $columns = array('*')) <ide> /** <ide> * Find a model by its primary key. <ide> * <del> * @param array $id <add> * @param array $ids <ide> * @param array $columns <del> * @return \Illuminate\Database\Eloquent\Model|Collection|static <add> * @return \Illuminate\Database\Eloquent\Collection <ide> */ <del> public function findMany($id, $columns = array('*')) <add> public function findMany($ids, $columns = array('*')) <ide> { <del> if (empty($id)) return $this->model->newCollection(); <add> if (empty($ids)) return $this->model->newCollection(); <ide> <del> $this->query->whereIn($this->model->getQualifiedKeyName(), $id); <add> $this->query->whereIn($this->model->getQualifiedKeyName(), $ids); <ide> <ide> return $this->get($columns); <ide> } <ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function all($columns = array('*')) <ide> */ <ide> public static function find($id, $columns = array('*')) <ide> { <del> $instance = new static; <del> <del> if (is_array($id) && empty($id)) return $instance->newCollection(); <del> <del> return $instance->newQuery()->find($id, $columns); <add> return static::query()->find($id, $columns); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentIntegrationTest.php <ide> public function tearDown() <ide> <ide> public function testBasicModelRetrieval() <ide> { <del> EloquentTestUser::create(['email' => '[email protected]']); <add> EloquentTestUser::create(['id' => 1, 'email' => '[email protected]']); <add> EloquentTestUser::create(['id' => 2, 'email' => '[email protected]']); <add> <ide> $model = EloquentTestUser::where('email', '[email protected]')->first(); <ide> $this->assertEquals('[email protected]', $model->email); <add> <add> $model = EloquentTestUser::find(1); <add> $this->assertInstanceOf('EloquentTestUser', $model); <add> $this->assertEquals(1, $model->id); <add> <add> $model = EloquentTestUser::find(2); <add> $this->assertInstanceOf('EloquentTestUser', $model); <add> $this->assertEquals(2, $model->id); <add> <add> $void = EloquentTestUser::find(3); <add> $this->assertNull($void); <add> <add> $collection = EloquentTestUser::find([]); <add> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection); <add> $this->assertEquals(0, $collection->count()); <add> <add> $collection = EloquentTestUser::find([1, 2, 3]); <add> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection); <add> $this->assertEquals(2, $collection->count()); <ide> } <ide> <ide>
3
Javascript
Javascript
add type check in bidirectionalindexof
aa34465ae3135adeee3fc4e120db8f13e8781404
<ide><path>lib/buffer.js <ide> const { <ide> hideStackFrames <ide> } = require('internal/errors'); <ide> const { <add> validateBuffer, <ide> validateInt32, <ide> validateString <ide> } = require('internal/validators'); <ide> Buffer.prototype.compare = function compare(target, <ide> // - encoding - an optional encoding, relevant if val is a string <ide> // - dir - true for indexOf, false for lastIndexOf <ide> function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { <add> validateBuffer(buffer); <add> <ide> if (typeof byteOffset === 'string') { <ide> encoding = byteOffset; <ide> byteOffset = undefined; <ide> function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { <ide> byteOffset = +byteOffset; <ide> // If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer. <ide> if (NumberIsNaN(byteOffset)) { <del> byteOffset = dir ? 0 : buffer.length; <add> byteOffset = dir ? 0 : (buffer.length || buffer.byteLength); <ide> } <ide> dir = !!dir; // Cast to bool. <ide> <ide><path>test/parallel/test-buffer-indexof.js <ide> assert.strictEqual(reallyLong.lastIndexOf(pattern), 0); <ide> assert.strictEqual(haystack.indexOf(needle), 2); <ide> assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3); <ide> } <add> <add>// Avoid abort because of invalid usage <add>// see https://github.com/nodejs/node/issues/32753 <add>{ <add> assert.throws(() => { <add> const buffer = require('buffer'); <add> new buffer.Buffer.prototype.lastIndexOf(1, 'str'); <add> }, { <add> code: 'ERR_INVALID_ARG_TYPE', <add> name: 'TypeError', <add> message: 'The "buffer" argument must be an instance of Buffer, ' + <add> 'TypedArray, or DataView. ' + <add> 'Received an instance of lastIndexOf' <add> }); <add>}
2
Javascript
Javascript
fix application tests
2ec0dfa472b854932061b65ca347cc636a144ba7
<ide><path>packages/ember-application/tests/system/application_test.js <ide> test('initialized application go to initial route', function() { <ide> onUpdateURL: function() {} <ide> }, <ide> <del> start: Ember.State.extend({ <add> root: Ember.State.extend({ <ide> index: Ember.State.extend({ <ide> route: '/' <ide> }) <ide> }) <ide> }); <ide> }); <ide> <del> equal(app.getPath('stateManager.currentState.path'), 'start.index', "The router moved the state into the right place"); <add> equal(app.getPath('stateManager.currentState.path'), 'root.index', "The router moved the state into the right place"); <ide> }); <ide> <ide> test("initialize application with non routable stateManager", function() { <ide> test("initialize application with stateManager via initialize call", function() <ide> app.Router = Ember.Router.extend({ <ide> location: 'hash', <ide> <del> start: Ember.State.extend({ <add> root: Ember.State.extend({ <ide> index: Ember.State.extend({ <ide> route: '/' <ide> }) <ide> test("initialize application with stateManager via initialize call", function() <ide> <ide> equal(app.getPath('stateManager') instanceof Ember.Router, true, "Router was set from initialize call"); <ide> equal(app.getPath('stateManager.location') instanceof Ember.HashLocation, true, "Location was set from location implementation name"); <del> equal(app.getPath('stateManager.currentState.path'), 'start.index', "The router moved the state into the right place"); <add> equal(app.getPath('stateManager.currentState.path'), 'root.index', "The router moved the state into the right place"); <ide> }); <ide> <ide> test("initialize application with stateManager via initialize call from Router class", function() { <ide> test("initialize application with stateManager via initialize call from Router c <ide> app.Router = Ember.Router.extend({ <ide> location: 'hash', <ide> <del> start: Ember.State.extend({ <add> root: Ember.State.extend({ <ide> index: Ember.State.extend({ <ide> route: '/' <ide> }) <ide> test("initialize application with stateManager via initialize call from Router c <ide> }); <ide> <ide> equal(app.getPath('stateManager') instanceof Ember.Router, true, "Router was set from initialize call"); <del> equal(app.getPath('stateManager.currentState.path'), 'start.index', "The router moved the state into the right place"); <add> equal(app.getPath('stateManager.currentState.path'), 'root.index', "The router moved the state into the right place"); <ide> }); <ide><path>packages/ember-states/lib/routable.js <ide> Ember.Routable = Ember.Mixin.create({ <ide> var object = state.deserialize(manager, match.hash) || {}; <ide> manager.transitionTo(get(state, 'path'), object); <ide> manager.send('routePath', match.remaining); <del> } <add> }, <add> <add> connectOutlets: Ember.K <ide> }); <ide> <ide> Ember.State.reopen(Ember.Routable);
2
Text
Text
add gh discussions to readme
52cdb12d26a42f58bdf8d1f89266dc3902a14147
<ide><path>README.md <ide> be able to provide individual support via email. We also believe that help is <ide> much more valuable if it's shared publicly, so that more people can benefit from <ide> it. <ide> <del>| Type | Platforms | <del>| ------------------------ | ------------------------------------------------------ | <del>| 🚨 **Bug Reports** | [GitHub Issue Tracker] | <del>| 🎁 **Feature Requests** | [GitHub Issue Tracker] | <del>| 👩‍💻 **Usage Questions** | [Stack Overflow] · [Gitter Chat] · [Reddit User Group] | <del>| 🗯 **General Discussion** | [Gitter Chat] · [Reddit User Group] | <add>| Type | Platforms | <add>| ------------------------ | ----------------------------------------------------------------------------- | <add>| 🚨 **Bug Reports** | [GitHub Issue Tracker] | <add>| 🎁 **Feature Requests** | [GitHub Discussions] | <add>| 👩‍💻 **Usage Questions** | [GitHub Discussions] · [Stack Overflow] · [Gitter Chat] · [Reddit User Group] | <add>| 🗯 **General Discussion** | [GitHub Discussions] · [Gitter Chat] · [Reddit User Group] | <ide> <ide> [github issue tracker]: https://github.com/explosion/spaCy/issues <add>[github discussions]: https://github.com/explosion/spaCy/discussions <ide> [stack overflow]: https://stackoverflow.com/questions/tagged/spacy <ide> [gitter chat]: https://gitter.im/explosion/spaCy <ide> [reddit user group]: https://www.reddit.com/r/spacynlp
1
Python
Python
remove whitespaces from empty lines
144bc3c2f56ffff60a45394d277e0b0b2ccc2424
<ide><path>official/recommendation/ncf_keras_benchmark.py <ide> def benchmark_2_gpus_early_stop(self): <ide> FLAGS.early_stopping = True <ide> FLAGS.num_gpus = 2 <ide> self._run_and_report_benchmark() <del> <add> <ide> def benchmark_2_gpus_early_stop_force_V2(self): <ide> self._setup() <ide> FLAGS.early_stopping = True <ide> def benchmark_8_gpu_mlperf_like(self): <ide> FLAGS.beta2 = 0.5 <ide> FLAGS.epsilon = 1e-8 <ide> self._run_and_report_benchmark_mlperf_like() <del> <add> <ide> def benchmark_8_gpu_force_v2_mlperf_like(self): <ide> """8 GPU using keras fit/compile V2 codepath.""" <ide> self._setup() <ide><path>official/resnet/keras/keras_imagenet_benchmark.py <ide> def benchmark_8_gpu(self): <ide> FLAGS.datasets_num_private_threads = 14 <ide> FLAGS.use_tensor_lr = True <ide> self._run_and_report_benchmark() <del> <add> <ide> def benchmark_8_gpu_force_v2(self): <ide> """Test Keras model with eager, dist_strat, force v2 and 8 GPUs.""" <ide> self._setup() <ide> def benchmark_8_gpu(self): <ide> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu') <ide> FLAGS.batch_size = 128 * 8 # 8 GPUs <ide> self._run_and_report_benchmark() <del> <add> <ide> def benchmark_8_gpu_force_v2(self): <ide> """Test Keras model with 8 GPUs and v2 codepath.""" <ide> self._setup()
2
Javascript
Javascript
write short strings more efficient to cache
629ac95660b18dc71a835fc13c0573fed1cfe043
<ide><path>lib/serialization/BinaryMiddleware.js <ide> class BinaryMiddleware extends SerializerMiddleware { <ide> writeU8(STRING_HEADER); <ide> writeU32(len); <ide> currentBuffer.write(thing, currentPosition); <del> } else { <add> currentPosition += len; <add> } else if (len >= 70) { <ide> allocate(len + HEADER_SIZE); <ide> writeU8(SHORT_STRING_HEADER | len); <add> <ide> currentBuffer.write(thing, currentPosition, "latin1"); <add> currentPosition += len; <add> } else { <add> allocate(len + HEADER_SIZE); <add> writeU8(SHORT_STRING_HEADER | len); <add> <add> for (let i = 0; i < len; i++) { <add> currentBuffer[currentPosition++] = thing.charCodeAt(i); <add> } <ide> } <del> currentPosition += len; <ide> break; <ide> } <ide> case "number": {
1
Text
Text
fix titles on docs.brew.sh
9a6cd9b83fc8596727df0157e89faee302907cda
<ide><path>docs/Acceptable-Formulae.md <ide> # Acceptable Formulae <add> <ide> Some formulae should not go in <ide> [homebrew/core](https://github.com/Homebrew/homebrew-core). But there are <ide> additional [Interesting Taps & Forks](Interesting-Taps-&-Forks.md) and anyone can start their <ide><path>docs/Analytics.md <ide> # Anonymous Aggregate User Behaviour Analytics <add> <ide> Homebrew has begun gathering anonymous aggregate user behaviour analytics and reporting these to Google Analytics. You will be notified the first time you run `brew update` or install Homebrew. <ide> <ide> ## Why? <ide><path>docs/Bottles.md <ide> # Bottles (binary packages) <add> <ide> Bottles are produced by installing a formula with `brew install --build-bottle $FORMULA` and then bottling it with `brew bottle $FORMULA`. This outputs the bottle DSL which should be inserted into the formula file. <ide> <ide> ## Usage <ide><path>docs/Brew-Test-Bot-For-Core-Contributors.md <ide> # Brew Test Bot For Core Contributors <add> <ide> If a build has run and passed on `brew test-bot` then it can be used to quickly bottle formulae. <ide> <ide> There are two types of Jenkins jobs you will interact with: <ide><path>docs/Brew-Test-Bot.md <ide> # Brew Test Bot <add> <ide> `brew test-bot` is the name for the automated review and testing system funded <ide> by [our Kickstarter in 2013](https://www.kickstarter.com/projects/homebrew/brew-test-bot). <ide> <ide><path>docs/C++-Standard-Libraries.md <ide> # C++ Standard Libraries <add> <ide> There are two C++ standard libraries supported by Apple compilers. <ide> <ide> The default for 10.8 and earlier is **libstdc++**, supported by Apple GCC <ide><path>docs/Checksum_Deprecation.md <ide> # MD5 and SHA-1 Deprecation <add> <ide> During early 2015 Homebrew started the process of deprecating _SHA1_ for package <ide> integrity verification. Since then every formulae under the Homebrew organisation <ide> has been moved onto _SHA256_ verification; this includes both source packages <ide><path>docs/Common-Issues.md <ide> # Common Issues <add> <ide> This is a list of commonly encountered problems, known issues, and their solutions. <ide> <ide> ### `brew` complains about absence of "Command Line Tools" <ide><path>docs/Custom-GCC-and-cross-compilers.md <ide> # Custom GCC and Cross Compilers <add> <ide> Homebrew depends on having an up-to-date version of Xcode because it comes with <ide> specific versions of build tools e.g. `clang`. <ide> <ide><path>docs/External-Commands.md <ide> # External Commands <add> <ide> Homebrew, like Git, supports *external commands*. This lets you create new commands that can be run like: <ide> <ide> ```shell <ide><path>docs/Formula-Cookbook.md <ide> # Formula Cookbook <add> <ide> A formula is a package definition written in Ruby. It can be created with `brew create $URL`, installed with `brew install $FORMULA`, and debugged with `brew install --debug --verbose $FORMULA`. Formulae use the [Formula API](http://www.rubydoc.info/github/Homebrew/brew/master/Formula) which provides various Homebrew-specific helpers. <ide> <ide> ## Homebrew Terminology <ide><path>docs/Gems,-Eggs-and-Perl-Modules.md <ide> # Gems, Eggs and Perl Modules <add> <ide> On a fresh macOS installation there are three empty directories for <ide> add-ons available to all users: <ide> <ide><path>docs/Homebrew-and-Python.md <ide> # Python <add> <ide> This page describes how Python is handled in Homebrew for users. See [Python for Formula Authors](Python-for-Formula-Authors.md) for advice on writing formulae to install packages written in Python. <ide> <ide> Homebrew should work with any [CPython](https://stackoverflow.com/questions/2324208/is-there-any-difference-between-cpython-and-python) and defaults to the macOS system Python. <ide><path>docs/How-to-Create-and-Maintain-a-Tap.md <ide> # How to Create and Maintain a Tap <add> <ide> Taps are external sources of Homebrew formulae and/or external commands. They <ide> can be created by anyone to provide their own formulae and/or external commands <ide> to any Homebrew user. <ide><path>docs/Installation.md <ide> # Installation <add> <ide> The suggested and easiest way to install Homebrew is on the <ide> [homepage](http://brew.sh). <ide> <ide><path>docs/Interesting-Taps-&-Forks.md <ide> # Interesting Taps & Forks <add> <ide> A Tap is homebrew-speak for a git repository containing extra formulae. <ide> Homebrew has the capability to add (and remove) multiple taps to your local installation with the `brew tap` and `brew untap` command. Type `man brew` in your Terminal. The main repository https://github.com/Homebrew/homebrew-core, often called `homebrew/core`, is always built-in. <ide> <ide><path>docs/Kickstarter-Supporters.md <ide> # Kickstarter Supporters <add> <ide> This file contains a list of the awesome people who gave £5 or more to <ide> [our Kickstarter](https://www.kickstarter.com/projects/homebrew/brew-test-bot). <ide> <ide><path>docs/Maintainer-Guidelines.md <ide> # Maintainer Guidelines <add> <ide> **This guide is for maintainers.** These special people have **write <ide> access** to Homebrew’s repository and help merge the contributions of <ide> others. You may find what is written here interesting, but it’s <ide><path>docs/Maintainers-Avoiding-Burnout.md <ide> # Maintainers: Avoiding Burnout <add> <ide> **This guide is for maintainers.** These special people have **write <ide> access** to Homebrew’s repository and help merge the contributions of <ide> others. You may find what is written here interesting, but it’s <ide><path>docs/Migrating-A-Formula-To-A-Tap.md <ide> # Migrating A Formula To A Tap <add> <ide> There are times when we may wish to migrate a formula from one tap into another tap. To do this: <ide> <ide> 1. Create a pull request to the new tap adding the formula file as-is from the original tap. Fix any test failures that may occur due to the stricter requirements for new formulae than existing formula (e.g. `brew audit --strict` must pass for that formula). <ide><path>docs/New-Maintainer-Checklist.md <ide> # New Maintainer Checklist <add> <ide> **This is a guide used by existing maintainers to invite new maintainers. You might find it interesting but there's nothing here users should have to know.** <ide> <ide> So, there's someone who has been making consistently high-quality contributions to Homebrew for a long time and shown themselves able to make slightly more advanced contributions than just e.g. formula updates? Let's invite them to be a maintainer! <ide><path>docs/Querying-Brew.md <ide> # Querying `brew` <add> <ide> _In this document we will be using [jq](https://stedolan.github.io/jq/) to parse JSON, available from Homebrew using `brew install jq`._ <ide> <ide> ## Overview <ide><path>docs/Versions.md <ide> # Versions <add> <ide> Now that [Homebrew/versions](https://github.com/homebrew/homebrew-versions) has been deprecated [Homebrew/core](https://github.com/homebrew/homebrew-core) supports multiple versions of formulae with a new naming format. <ide> <ide> In [Homebrew/versions](https://github.com/homebrew/homebrew-versions) the formula for GCC 6 was named `gcc6.rb` and began `class Gcc6 < Formula`. In [Homebrew/core](https://github.com/homebrew/homebrew-core) this same formula is named `[email protected]` and begins `class GccAT6 < Formula`. <ide><path>docs/brew-tap.md <ide> # Taps (third-party repositories) <add> <ide> `brew tap` adds more repos to the list of formulae that `brew` tracks, updates, <ide> and installs from. By default, `tap` assumes that the repos come from GitHub, <ide> but the command isn't limited to any one location.
24
Python
Python
add unicode declarations
da10a049a68799674559e774f67bd5f35a6caef2
<ide><path>spacy/tests/tokenizer/conftest.py <add># coding: utf-8 <add>from __future__ import unicode_literals <add> <ide> import pytest <ide> from ...en import English <ide> <ide><path>spacy/tests/tokenizer/test_contractions.py <add># coding: utf-8 <ide> from __future__ import unicode_literals <ide> <ide> import pytest <ide><path>spacy/tests/tokenizer/test_indices.py <add># coding: utf-8 <ide> """Test that token.idx correctly computes index into the original string.""" <ide> <ide> from __future__ import unicode_literals <ide><path>spacy/tests/tokenizer/test_punct.py <add># coding: utf-8 <ide> from __future__ import unicode_literals <ide> <ide> import pytest <ide><path>spacy/tests/tokenizer/test_whitespace.py <add># coding: utf-8 <ide> """Test that tokens are created correctly for whitespace.""" <ide> <ide>
5
Ruby
Ruby
improve check for 'gnubin' in path
9cab3011856d0d4308054887f7459dc91e444ed3
<ide><path>Library/Homebrew/diagnostic.rb <ide> def check_for_bad_python_symlink <ide> end <ide> <ide> def check_for_non_prefixed_coreutils <del> gnubin = "#{Formulary.factory("coreutils").prefix}/libexec/gnubin" <del> if paths.include? gnubin then <<-EOS.undent <add> coreutils = Formula["coreutils"] <add> return unless coreutils.any_version_installed? <add> <add> gnubin = %W[#{coreutils.opt_libexec}/gnubin #{coreutils.libexec}/gnubin] <add> return if (paths & gnubin).empty? <add> <add> <<-EOS.undent <ide> Putting non-prefixed coreutils in your path can cause gmp builds to fail. <del> EOS <del> end <add> EOS <ide> end <ide> <ide> def check_for_non_prefixed_findutils <del> gnubin = "#{Formulary.factory("findutils").prefix}/libexec/gnubin" <add> findutils = Formula["findutils"] <add> return unless findutils.any_version_installed? <add> <add> gnubin = %W[#{findutils.opt_libexec}/gnubin #{findutils.libexec}/gnubin] <ide> default_names = Tab.for_name("findutils").with? "default-names" <del> if paths.include?(gnubin) || default_names then <<-EOS.undent <add> return if !default_names && (paths & gnubin).empty? <add> <add> <<-EOS.undent <ide> Putting non-prefixed findutils in your path can cause python builds to fail. <del> EOS <del> end <add> EOS <ide> end <ide> <ide> def check_for_pydistutils_cfg_in_home
1
Java
Java
reimplement the "skiplast" operator with time
0fc6e2ccf82531dd93fd902437c37ffa3006676d
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> import rx.operators.OperatorSerialize; <ide> import rx.operators.OperatorSkip; <ide> import rx.operators.OperatorSkipLast; <add>import rx.operators.OperatorSkipLastTimed; <ide> import rx.operators.OperatorSkipWhile; <ide> import rx.operators.OperatorSubscribeOn; <ide> import rx.operators.OperatorSynchronize; <ide> public final Observable<T> skipLast(long time, TimeUnit unit) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211750.aspx">MSDN: Observable.SkipLast</a> <ide> */ <ide> public final Observable<T> skipLast(long time, TimeUnit unit, Scheduler scheduler) { <del> return create(new OperatorSkipLast.SkipLastTimed<T>(this, time, unit, scheduler)); <add> return lift(new OperatorSkipLastTimed<T>(time, unit, scheduler)); <ide> } <ide> <ide> /** <ide><path>rxjava-core/src/main/java/rx/operators/OperatorSkipLast.java <ide> */ <ide> package rx.operators; <ide> <del>import java.util.ArrayList; <del>import java.util.Collections; <ide> import java.util.Deque; <ide> import java.util.LinkedList; <del>import java.util.List; <del>import java.util.concurrent.TimeUnit; <ide> <del>import rx.Observable; <del>import rx.Observable.OnSubscribeFunc; <ide> import rx.Observable.Operator; <del>import rx.Observer; <del>import rx.Scheduler; <ide> import rx.Subscriber; <del>import rx.Subscription; <del>import rx.schedulers.Timestamped; <ide> <ide> /** <ide> * Bypasses a specified number of elements at the end of an observable sequence. <ide> public void onNext(T value) { <ide> }; <ide> } <ide> <del> /** <del> * Skip delivering values in the time window before the values. <del> * <del> * @param <T> <del> * the result value type <del> */ <del> public static final class SkipLastTimed<T> implements OnSubscribeFunc<T> { <del> final Observable<? extends T> source; <del> final long timeInMillis; <del> final Scheduler scheduler; <del> <del> public SkipLastTimed(Observable<? extends T> source, long time, TimeUnit unit, Scheduler scheduler) { <del> this.source = source; <del> this.timeInMillis = unit.toMillis(time); <del> this.scheduler = scheduler; <del> } <del> <del> @Override <del> public Subscription onSubscribe(Observer<? super T> t1) { <del> return source.unsafeSubscribe(new SourceObserver<T>(t1, timeInMillis, scheduler)); <del> } <del> <del> /** Observes the source. */ <del> private static final class SourceObserver<T> extends Subscriber<T> { <del> final Observer<? super T> observer; <del> final long timeInMillis; <del> final Scheduler scheduler; <del> List<Timestamped<T>> buffer = new ArrayList<Timestamped<T>>(); <del> <del> public SourceObserver(Observer<? super T> observer, <del> long timeInMillis, Scheduler scheduler) { <del> this.observer = observer; <del> this.timeInMillis = timeInMillis; <del> this.scheduler = scheduler; <del> } <del> <del> @Override <del> public void onNext(T args) { <del> buffer.add(new Timestamped<T>(scheduler.now(), args)); <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> buffer = Collections.emptyList(); <del> observer.onError(e); <del> } <del> <del> @Override <del> public void onCompleted() { <del> long limit = scheduler.now() - timeInMillis; <del> try { <del> for (Timestamped<T> v : buffer) { <del> if (v.getTimestampMillis() < limit) { <del> try { <del> observer.onNext(v.getValue()); <del> } catch (Throwable t) { <del> observer.onError(t); <del> return; <del> } <del> } else { <del> observer.onCompleted(); <del> break; <del> } <del> } <del> } finally { <del> buffer = Collections.emptyList(); <del> } <del> } <del> <del> } <del> } <ide> } <ide><path>rxjava-core/src/main/java/rx/operators/OperatorSkipLastTimed.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package rx.operators; <add> <add>import rx.Observable.Operator; <add>import rx.Scheduler; <add>import rx.Subscriber; <add>import rx.schedulers.Timestamped; <add> <add>import java.util.ArrayList; <add>import java.util.Collections; <add>import java.util.List; <add>import java.util.concurrent.TimeUnit; <add> <add>/** <add> * Skip delivering values in the time window before the values. <add> */ <add>public class OperatorSkipLastTimed<T> implements Operator<T, T> { <add> <add> private final long timeInMillis; <add> private final Scheduler scheduler; <add> <add> public OperatorSkipLastTimed(long time, TimeUnit unit, Scheduler scheduler) { <add> this.timeInMillis = unit.toMillis(time); <add> this.scheduler = scheduler; <add> } <add> <add> @Override <add> public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { <add> return new Subscriber<T>(subscriber) { <add> <add> private List<Timestamped<T>> buffer = new ArrayList<Timestamped<T>>(); <add> <add> @Override <add> public void onNext(T value) { <add> buffer.add(new Timestamped<T>(scheduler.now(), value)); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> buffer = Collections.emptyList(); <add> subscriber.onError(e); <add> } <add> <add> @Override <add> public void onCompleted() { <add> long limit = scheduler.now() - timeInMillis; <add> try { <add> for (Timestamped<T> v : buffer) { <add> if (v.getTimestampMillis() < limit) { <add> try { <add> subscriber.onNext(v.getValue()); <add> } catch (Throwable t) { <add> subscriber.onError(t); <add> return; <add> } <add> } else { <add> break; <add> } <add> } <add> subscriber.onCompleted(); <add> } finally { <add> buffer = Collections.emptyList(); <add> } <add> } <add> <add> }; <add> } <add>} <ide><path>rxjava-core/src/test/java/rx/operators/OperatorSkipLastTest.java <ide> import static org.mockito.Mockito.verify; <ide> <ide> import java.util.Arrays; <del>import java.util.concurrent.TimeUnit; <ide> <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <ide> <ide> import rx.Observable; <ide> import rx.Observer; <del>import rx.operators.OperationSkipTest.CustomException; <del>import rx.schedulers.TestScheduler; <del>import rx.subjects.PublishSubject; <ide> <ide> public class OperatorSkipLastTest { <ide> <ide> public void testSkipLastWithNegativeCount() { <ide> Observable.from("one").skipLast(-1); <ide> } <ide> <del> @Test <del> public void testSkipLastTimed() { <del> TestScheduler scheduler = new TestScheduler(); <del> <del> PublishSubject<Integer> source = PublishSubject.create(); <del> <del> Observable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); <del> <del> Observer<Object> o = mock(Observer.class); <del> <del> result.subscribe(o); <del> <del> source.onNext(1); <del> source.onNext(2); <del> source.onNext(3); <del> <del> scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); <del> <del> source.onNext(4); <del> source.onNext(5); <del> source.onNext(6); <del> <del> scheduler.advanceTimeBy(950, TimeUnit.MILLISECONDS); <del> source.onCompleted(); <del> <del> InOrder inOrder = inOrder(o); <del> inOrder.verify(o).onNext(1); <del> inOrder.verify(o).onNext(2); <del> inOrder.verify(o).onNext(3); <del> inOrder.verify(o, never()).onNext(4); <del> inOrder.verify(o, never()).onNext(5); <del> inOrder.verify(o, never()).onNext(6); <del> inOrder.verify(o).onCompleted(); <del> inOrder.verifyNoMoreInteractions(); <del> <del> verify(o, never()).onError(any(Throwable.class)); <del> } <del> <del> @Test <del> public void testSkipLastTimedErrorBeforeTime() { <del> TestScheduler scheduler = new TestScheduler(); <del> <del> PublishSubject<Integer> source = PublishSubject.create(); <del> <del> Observable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); <del> <del> Observer<Object> o = mock(Observer.class); <del> <del> result.subscribe(o); <del> <del> source.onNext(1); <del> source.onNext(2); <del> source.onNext(3); <del> source.onError(new OperationSkipTest.CustomException()); <del> <del> scheduler.advanceTimeBy(1050, TimeUnit.MILLISECONDS); <del> <del> verify(o).onError(any(CustomException.class)); <del> <del> verify(o, never()).onCompleted(); <del> verify(o, never()).onNext(any()); <del> } <del> <del> @Test <del> public void testSkipLastTimedCompleteBeforeTime() { <del> TestScheduler scheduler = new TestScheduler(); <del> <del> PublishSubject<Integer> source = PublishSubject.create(); <del> <del> Observable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); <del> <del> Observer<Object> o = mock(Observer.class); <del> <del> result.subscribe(o); <del> <del> source.onNext(1); <del> source.onNext(2); <del> source.onNext(3); <del> <del> scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); <del> <del> source.onCompleted(); <del> <del> InOrder inOrder = inOrder(o); <del> inOrder.verify(o).onCompleted(); <del> inOrder.verifyNoMoreInteractions(); <del> <del> verify(o, never()).onNext(any()); <del> verify(o, never()).onError(any(Throwable.class)); <del> } <ide> } <ide><path>rxjava-core/src/test/java/rx/operators/OperatorSkipLastTimedTest.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package rx.operators; <add> <add>import org.junit.Test; <add>import org.mockito.InOrder; <add>import rx.Observable; <add>import rx.Observer; <add>import rx.operators.OperationSkipTest.CustomException; <add>import rx.schedulers.TestScheduler; <add>import rx.subjects.PublishSubject; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import static org.mockito.Matchers.any; <add>import static org.mockito.Mockito.*; <add> <add>public class OperatorSkipLastTimedTest { <add> <add> @Test <add> public void testSkipLastTimed() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); <add> <add> Observer<Object> o = mock(Observer.class); <add> <add> result.subscribe(o); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); <add> <add> source.onNext(4); <add> source.onNext(5); <add> source.onNext(6); <add> <add> scheduler.advanceTimeBy(950, TimeUnit.MILLISECONDS); <add> source.onCompleted(); <add> <add> InOrder inOrder = inOrder(o); <add> inOrder.verify(o).onNext(1); <add> inOrder.verify(o).onNext(2); <add> inOrder.verify(o).onNext(3); <add> inOrder.verify(o, never()).onNext(4); <add> inOrder.verify(o, never()).onNext(5); <add> inOrder.verify(o, never()).onNext(6); <add> inOrder.verify(o).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> verify(o, never()).onError(any(Throwable.class)); <add> } <add> <add> @Test <add> public void testSkipLastTimedErrorBeforeTime() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); <add> <add> Observer<Object> o = mock(Observer.class); <add> <add> result.subscribe(o); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> source.onError(new CustomException()); <add> <add> scheduler.advanceTimeBy(1050, TimeUnit.MILLISECONDS); <add> <add> verify(o).onError(any(CustomException.class)); <add> <add> verify(o, never()).onCompleted(); <add> verify(o, never()).onNext(any()); <add> } <add> <add> @Test <add> public void testSkipLastTimedCompleteBeforeTime() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> result = source.skipLast(1, TimeUnit.SECONDS, scheduler); <add> <add> Observer<Object> o = mock(Observer.class); <add> <add> result.subscribe(o); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); <add> <add> source.onCompleted(); <add> <add> InOrder inOrder = inOrder(o); <add> inOrder.verify(o).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> <add> verify(o, never()).onNext(any()); <add> verify(o, never()).onError(any(Throwable.class)); <add> } <add> <add> @Test <add> public void testSkipLastTimedWhenAllElementsAreValid() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> PublishSubject<Integer> source = PublishSubject.create(); <add> <add> Observable<Integer> result = source.skipLast(1, TimeUnit.MILLISECONDS, scheduler); <add> <add> Observer<Object> o = mock(Observer.class); <add> <add> result.subscribe(o); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onNext(3); <add> <add> scheduler.advanceTimeBy(500, TimeUnit.MILLISECONDS); <add> <add> source.onCompleted(); <add> <add> InOrder inOrder = inOrder(o); <add> inOrder.verify(o).onNext(1); <add> inOrder.verify(o).onNext(2); <add> inOrder.verify(o).onNext(3); <add> inOrder.verify(o).onCompleted(); <add> inOrder.verifyNoMoreInteractions(); <add> } <add>}
5
Javascript
Javascript
remove custom template override
e87d19507a4189257c16fc211341ca54d4401fbe
<ide><path>packages/ember-handlebars/lib/ext.js <ide> import { <ide> } from "ember-metal/streams/read"; <ide> <ide> var slice = [].slice; <del>var originalTemplate = EmberHandlebars.template; <ide> <ide> /** <ide> Lookup both on root and on window. If the path starts with <ide> function makeBoundHelper(fn) { <ide> return helper; <ide> } <ide> <del>/** <del> Overrides Handlebars.template so that we can distinguish <del> user-created, top-level templates from inner contexts. <del> <del> @private <del> @method template <del> @for Ember.Handlebars <del> @param {String} spec <del>*/ <del>export function template(spec) { <del> var t = originalTemplate(spec); <del> t.isTop = true; <del> return t; <del>} <del> <ide> export { <ide> makeBoundHelper, <ide> handlebarsGetView, <ide><path>packages/ember-handlebars/lib/main.js <ide> import { runLoadHooks } from "ember-runtime/system/lazy_load"; <ide> import bootstrap from "ember-handlebars/loader"; <ide> <ide> import { <del> template, <ide> makeBoundHelper, <ide> registerBoundHelper, <ide> helperMissingHelper, <ide> Ember Handlebars <ide> <ide> // Ember.Handlebars.Globals <ide> EmberHandlebars.bootstrap = bootstrap; <del>EmberHandlebars.template = template; <ide> EmberHandlebars.makeBoundHelper = makeBoundHelper; <ide> EmberHandlebars.registerBoundHelper = registerBoundHelper; <ide> EmberHandlebars.resolveHelper = resolveHelper;
2
Python
Python
add tests for adding parser actions
dde87e6b0d2de331e536d335ead00db5d181ee96
<ide><path>spacy/tests/parser/test_add_label.py <add>'''Test the ability to add a label to a (potentially trained) parsing model.''' <add>from __future__ import unicode_literals <add>import pytest <add>import numpy.random <add>from thinc.neural.optimizers import Adam <add>from thinc.neural.ops import NumpyOps <add> <add>from ...attrs import NORM <add>from ...gold import GoldParse <add>from ...vocab import Vocab <add>from ...tokens import Doc <add>from ...pipeline import NeuralDependencyParser <add> <add>numpy.random.seed(0) <add> <add> <add>@pytest.fixture <add>def vocab(): <add> return Vocab(lex_attr_getters={NORM: lambda s: s}) <add> <add> <add>@pytest.fixture <add>def parser(vocab): <add> parser = NeuralDependencyParser(vocab) <add> parser.cfg['token_vector_width'] = 4 <add> parser.cfg['hidden_width'] = 6 <add> parser.cfg['hist_size'] = 0 <add> parser.add_label('left') <add> parser.begin_training([], **parser.cfg) <add> sgd = Adam(NumpyOps(), 0.001) <add> <add> for i in range(30): <add> losses = {} <add> doc = Doc(vocab, words=['a', 'b', 'c', 'd']) <add> gold = GoldParse(doc, heads=[1, 1, 3, 3], <add> deps=['left', 'ROOT', 'left', 'ROOT']) <add> parser.update([doc], [gold], sgd=sgd, losses=losses) <add> return parser <add> <add> <add>def test_add_label(parser): <add> doc = Doc(parser.vocab, words=['a', 'b', 'c', 'd']) <add> doc = parser(doc) <add> assert doc[0].head.i == 1 <add> assert doc[0].dep_ == 'left' <add> assert doc[1].head.i == 1 <add> assert doc[2].head.i == 3 <add> assert doc[2].head.i == 3 <add> parser.add_label('right') <add> doc = Doc(parser.vocab, words=['a', 'b', 'c', 'd']) <add> doc = parser(doc) <add> assert doc[0].head.i == 1 <add> assert doc[0].dep_ == 'left' <add> assert doc[1].head.i == 1 <add> assert doc[2].head.i == 3 <add> assert doc[2].head.i == 3 <add> sgd = Adam(NumpyOps(), 0.001) <add> for i in range(10): <add> losses = {} <add> doc = Doc(parser.vocab, words=['a', 'b', 'c', 'd']) <add> gold = GoldParse(doc, heads=[1, 1, 3, 3], <add> deps=['right', 'ROOT', 'left', 'ROOT']) <add> parser.update([doc], [gold], sgd=sgd, losses=losses) <add> doc = Doc(parser.vocab, words=['a', 'b', 'c', 'd']) <add> doc = parser(doc) <add> assert doc[0].dep_ == 'right' <add> assert doc[2].dep_ == 'left' <add>
1
Ruby
Ruby
override unsafe methods only if defined on string
9c4fe308b6da76711adffeff24d62acb013680ea
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb <ide> def to_yaml(*args) <ide> end <ide> <ide> UNSAFE_STRING_METHODS.each do |unsafe_method| <del> class_eval <<-EOT, __FILE__, __LINE__ + 1 <del> def #{unsafe_method}(*args, &block) # def capitalize(*args, &block) <del> to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block) <del> end # end <del> <del> def #{unsafe_method}!(*args) # def capitalize!(*args) <del> @dirty = true # @dirty = true <del> super # super <del> end # end <del> EOT <add> if 'String'.respond_to?(unsafe_method) <add> class_eval <<-EOT, __FILE__, __LINE__ + 1 <add> def #{unsafe_method}(*args, &block) # def capitalize(*args, &block) <add> to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block) <add> end # end <add> <add> def #{unsafe_method}!(*args) # def capitalize!(*args) <add> @dirty = true # @dirty = true <add> super # super <add> end # end <add> EOT <add> end <ide> end <ide> <ide> protected
1
Python
Python
resolve issue by simplifying url pattern
3452d6ce521943fb0bb02f59d3d9e3a1bac218c4
<ide><path>spacy/language_data/tokenizer_exceptions.py <ide> r"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))" <ide> r"|" <ide> # host name <del> r"(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)" <add> r"(?:(?:[a-z0-9\-]*)?[a-z0-9]+)" <ide> # domain name <del> r"(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*" <add> r"(?:\.(?:[a-z0-9\-])*[a-z0-9]+)*" <ide> # TLD identifier <del> r"(?:\.(?:[a-z\u00a1-\uffff]{2,}))" <add> r"(?:\.(?:[a-z]{2,}))" <ide> r")" <ide> # port number <ide> r"(?::\d{2,5})?" <ide><path>spacy/tests/tokenizer/test_urls.py <ide> "http://userid:[email protected]/", <ide> "http://142.42.1.1/", <ide> "http://142.42.1.1:8080/", <del> "http://⌘.ws", <del> "http://⌘.ws/", <ide> "http://foo.com/blah_(wikipedia)#cite-1", <ide> "http://foo.com/blah_(wikipedia)_blah#cite-1", <ide> "http://foo.com/unicode_(✪)_in_parens", <ide> "http://foo.com/(something)?after=parens", <del> "http://☺.damowmow.com/", <ide> "http://code.google.com/events/#&product=browser", <ide> "http://j.mp", <ide> "ftp://foo.bar/baz", <ide> "http://a.b-c.de", <ide> "http://223.255.255.254", <ide> "http://a.b--c.de/", # this is a legit domain name see: https://gist.github.com/dperini/729294 comment on 9/9/2014 <del> "http://✪df.ws/123", <del> "http://➡.ws/䨹", <del> "http://مثال.إختبار", <del> "http://例子.测试", <del> "http://उदाहरण.परीक्षा", <ide> <ide> pytest.mark.xfail("http://foo.com/blah_blah_(wikipedia)"), <ide> pytest.mark.xfail("http://foo.com/blah_blah_(wikipedia)_(again)"), <add> pytest.mark.xfail("http://⌘.ws"), <add> pytest.mark.xfail("http://⌘.ws/"), <add> pytest.mark.xfail("http://☺.damowmow.com/"), <add> pytest.mark.xfail("http://✪df.ws/123"), <add> pytest.mark.xfail("http://➡.ws/䨹"), <add> pytest.mark.xfail("http://مثال.إختبار"), <add> pytest.mark.xfail("http://例子.测试"), <add> pytest.mark.xfail("http://उदाहरण.परीक्षा"), <ide> ] <ide> <ide> URLS_SHOULD_NOT_MATCH = [ <ide> "http://foo.bar/foo(bar)baz quux", <ide> "ftps://foo.bar/", <ide> "http://-error-.invalid/", <del> "http://-a.b.co", <ide> "http://a.b-.co", <ide> "http://0.0.0.0", <ide> "http://10.1.1.0", <ide> pytest.mark.xfail("foo.com"), <ide> pytest.mark.xfail("http://1.1.1.1.1"), <ide> pytest.mark.xfail("http://www.foo.bar./"), <add> pytest.mark.xfail("http://-a.b.co"), <ide> ] <ide> <ide>
2
Text
Text
add swisscom to inthewild.md
219df18414185e426aab9bb8f297785d6f54f6a5
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Strongmind](https://www.strongmind.com) [[@tomchapin](https://github.com/tomchapin) & [@wongstein](https://github.com/wongstein)] <ide> 1. [Ströer Labs](https://stroeer-labs.com) [[@mbrtargeting](https://github.com/mbrtargeting/)] <ide> 1. [Surfline](https://www.surfline.com/) [[@jawang35](https://github.com/jawang35)] <add>1. [Swisscom](https://www.swisscom.ch) [[@JulesTriomphe](https://github.com/JulesTriomphe)] <ide> 1. [Syapse](https://www.syapse.com/) [[@zedmor](https://github.com/zedmor)] <ide> 1. [T2 Systems](http://t2systems.com) [[@unclaimedpants](https://github.com/unclaimedpants)] <ide> 1. [Tails.com](https://tails.com/) [[@alanmcruickshank](https://github.com/alanmcruickshank)]
1
Javascript
Javascript
fix typo in uselegacypromise var
929ec6ba5a60e926654583033a90aebe716123c0
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> return useApplyAsync; <ide> }; <ide> <del> var useLegacyPromse = true; <add> var useLegacyPromise = true; <ide> /** <ide> * @ngdoc method <ide> * @name $httpProvider#useLegacyPromiseExtensions <ide> function $HttpProvider() { <ide> **/ <ide> this.useLegacyPromiseExtensions = function(value) { <ide> if (isDefined(value)) { <del> useLegacyPromse = !!value; <add> useLegacyPromise = !!value; <ide> return this; <ide> } <del> return useLegacyPromse; <add> return useLegacyPromise; <ide> }; <ide> <ide> /** <ide> function $HttpProvider() { <ide> promise = promise.then(thenFn, rejectFn); <ide> } <ide> <del> if (useLegacyPromse) { <add> if (useLegacyPromise) { <ide> promise.success = function(fn) { <ide> assertArgFn(fn, 'fn'); <ide>
1
Python
Python
fix flaskr import in flaskr/__init__.py
cd13a5cf6215914ba4c3e0963d2189fe19fed508
<ide><path>examples/flaskr/flaskr/__init__.py <del>from flaskr import app <ide>\ No newline at end of file <add>from flaskr.flaskr import app <ide>\ No newline at end of file
1
Mixed
Python
fix documentation for checkpoint arg
e156b5b70f48c4fff575d89e551683def6bdbcc9
<ide><path>research/object_detection/export_tflite_graph_tf2.py <ide> -------------- <ide> python object_detection/export_tflite_graph_tf2.py \ <ide> --pipeline_config_path path/to/ssd_model/pipeline.config \ <del> --trained_checkpoint_prefix path/to/ssd_model/checkpoint \ <add> --trained_checkpoint_dir path/to/ssd_model/checkpoint \ <ide> --output_directory path/to/exported_model_directory <ide> <ide> The expected output SavedModel would be in the directory <ide> NMS score_threshold to be 0.0): <ide> python object_detection/export_tflite_model_tf2.py \ <ide> --pipeline_config_path path/to/ssd_model/pipeline.config \ <del> --trained_checkpoint_prefix path/to/ssd_model/checkpoint \ <add> --trained_checkpoint_dir path/to/ssd_model/checkpoint \ <ide> --output_directory path/to/exported_model_directory <ide> --config_override " \ <ide> model{ \ <ide><path>research/object_detection/g3doc/running_on_mobile_tf2.md <ide> To use the script: <ide> # From the tensorflow/models/research/ directory <ide> python object_detection/export_tflite_graph_tf2.py \ <ide> --pipeline_config_path path/to/ssd_model/pipeline.config \ <del> --trained_checkpoint_prefix path/to/ssd_model/checkpoint \ <add> --trained_checkpoint_dir path/to/ssd_model/checkpoint \ <ide> --output_directory path/to/exported_model_directory <ide> ``` <ide>
2
Javascript
Javascript
extract validatenumber validator
3e44b8c91ef717913364ac67a12cb7cd638630db
<ide><path>lib/dgram.js <ide> const { <ide> ERR_SOCKET_DGRAM_NOT_RUNNING, <ide> ERR_INVALID_FD_TYPE <ide> } = errors.codes; <del>const { isInt32, validateString } = require('internal/validators'); <add>const { <add> isInt32, <add> validateString, <add> validateNumber <add>} = require('internal/validators'); <ide> const { Buffer } = require('buffer'); <ide> const util = require('util'); <ide> const { isUint8Array } = require('internal/util/types'); <ide> Socket.prototype.sendto = function(buffer, <ide> port, <ide> address, <ide> callback) { <del> if (typeof offset !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset); <del> } <del> <del> if (typeof length !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('length', 'number', length); <del> } <del> <del> if (typeof port !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('port', 'number', port); <del> } <del> <add> validateNumber(offset, 'offset'); <add> validateNumber(length, 'length'); <add> validateNumber(port, 'port'); <ide> validateString(address, 'address'); <ide> <ide> this.send(buffer, offset, length, port, address, callback); <ide> Socket.prototype.setBroadcast = function(arg) { <ide> <ide> <ide> Socket.prototype.setTTL = function(ttl) { <del> if (typeof ttl !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('ttl', 'number', ttl); <del> } <add> validateNumber(ttl, 'ttl'); <ide> <ide> var err = this[kStateSymbol].handle.setTTL(ttl); <ide> if (err) { <ide> Socket.prototype.setTTL = function(ttl) { <ide> <ide> <ide> Socket.prototype.setMulticastTTL = function(ttl) { <del> if (typeof ttl !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('ttl', 'number', ttl); <del> } <add> validateNumber(ttl, 'ttl'); <ide> <ide> var err = this[kStateSymbol].handle.setMulticastTTL(ttl); <ide> if (err) { <ide><path>lib/internal/buffer.js <ide> const { <ide> ERR_INVALID_ARG_TYPE, <ide> ERR_OUT_OF_RANGE <ide> } = require('internal/errors').codes; <add>const { validateNumber } = require('internal/validators'); <ide> const { setupBufferJS } = binding; <ide> <ide> // Remove from the binding so that function is only available as exported here. <ide> function checkInt(value, min, max, buf, offset, byteLength) { <ide> } <ide> <ide> function checkNumberType(value, type) { <del> if (typeof value !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE(type || 'offset', 'number', value); <del> } <add> validateNumber(value, type || 'offset'); <ide> } <ide> <ide> function boundsError(value, length, type) { <ide><path>lib/internal/crypto/random.js <ide> const { <ide> ERR_INVALID_CALLBACK, <ide> ERR_OUT_OF_RANGE <ide> } = require('internal/errors').codes; <add>const { validateNumber } = require('internal/validators'); <ide> const { isArrayBufferView } = require('internal/util/types'); <ide> <ide> const kMaxUint32 = 2 ** 32 - 1; <ide> const kMaxPossibleLength = Math.min(kMaxLength, kMaxUint32); <ide> <ide> function assertOffset(offset, elementSize, length) { <del> if (typeof offset !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('offset', 'number', offset); <del> } <del> <add> validateNumber(offset, 'offset'); <ide> offset *= elementSize; <ide> <ide> const maxLength = Math.min(length, kMaxPossibleLength); <ide> function assertOffset(offset, elementSize, length) { <ide> } <ide> <ide> function assertSize(size, elementSize, offset, length) { <del> if (typeof size !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('size', 'number', size); <del> } <del> <add> validateNumber(size, 'size'); <ide> size *= elementSize; <ide> <ide> if (Number.isNaN(size) || size > kMaxPossibleLength || size < 0) { <ide><path>lib/internal/fs/streams.js <ide> const { <ide> ERR_INVALID_ARG_TYPE, <ide> ERR_OUT_OF_RANGE <ide> } = require('internal/errors').codes; <add>const { validateNumber } = require('internal/validators'); <ide> const fs = require('fs'); <ide> const { Buffer } = require('buffer'); <ide> const { <ide> function ReadStream(path, options) { <ide> <ide> if (this.start !== undefined) { <ide> if (!Number.isSafeInteger(this.start)) { <del> if (typeof this.start !== 'number') <del> throw new ERR_INVALID_ARG_TYPE('start', 'number', this.start); <add> validateNumber(this.start, 'start'); <ide> if (!Number.isInteger(this.start)) <ide> throw new ERR_OUT_OF_RANGE('start', 'an integer', this.start); <ide> throw new ERR_OUT_OF_RANGE( <ide><path>lib/internal/http2/core.js <ide> const { <ide> ERR_SOCKET_CLOSED <ide> } <ide> } = require('internal/errors'); <add>const { validateNumber } = require('internal/validators'); <ide> const { utcDate } = require('internal/http'); <ide> const { onServerStream, <ide> Http2ServerRequest, <ide> class Http2Session extends EventEmitter { <ide> if (this.destroyed) <ide> throw new ERR_HTTP2_INVALID_SESSION(); <ide> <del> if (typeof id !== 'number') <del> throw new ERR_INVALID_ARG_TYPE('id', 'number', id); <add> validateNumber(id, 'id'); <ide> if (id <= 0 || id > kMaxStreams) <ide> throw new ERR_OUT_OF_RANGE('id', `> 0 and <= ${kMaxStreams}`, id); <ide> this[kHandle].setNextStreamID(id); <ide> class Http2Session extends EventEmitter { <ide> ['Buffer', 'TypedArray', 'DataView'], <ide> opaqueData); <ide> } <del> if (typeof code !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('code', 'number', code); <del> } <del> if (typeof lastStreamID !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('lastStreamID', 'number', lastStreamID); <del> } <add> validateNumber(code, 'code'); <add> validateNumber(lastStreamID, 'lastStreamID'); <ide> <ide> const goawayFn = submitGoaway.bind(this, code, lastStreamID, opaqueData); <ide> if (this.connecting) { <ide> class Http2Stream extends Duplex { <ide> // close, it is still possible to queue up PRIORITY and RST_STREAM frames, <ide> // but no DATA and HEADERS frames may be sent. <ide> close(code = NGHTTP2_NO_ERROR, callback) { <del> if (typeof code !== 'number') <del> throw new ERR_INVALID_ARG_TYPE('code', 'number', code); <add> validateNumber(code, 'code'); <ide> if (code < 0 || code > kMaxInt) <ide> throw new ERR_OUT_OF_RANGE('code', `>= 0 && <= ${kMaxInt}`, code); <ide> if (callback !== undefined && typeof callback !== 'function') <ide> class ServerHttp2Stream extends Http2Stream { <ide> this[kState].flags |= STREAM_FLAGS_HAS_TRAILERS; <ide> } <ide> <del> if (typeof fd !== 'number') <del> throw new ERR_INVALID_ARG_TYPE('fd', 'number', fd); <add> validateNumber(fd, 'fd'); <ide> <ide> debug(`Http2Stream ${this[kID]} [Http2Session ` + <ide> `${sessionName(session[kType])}]: initiating response from fd`); <ide><path>lib/internal/timers.js <ide> const async_id_symbol = Symbol('asyncId'); <ide> const trigger_async_id_symbol = Symbol('triggerId'); <ide> <ide> const { <del> ERR_INVALID_ARG_TYPE, <ide> ERR_INVALID_CALLBACK, <ide> ERR_OUT_OF_RANGE <ide> } = require('internal/errors').codes; <add>const { validateNumber } = require('internal/validators'); <ide> <ide> // Timeout values > TIMEOUT_MAX are set to 1. <ide> const TIMEOUT_MAX = 2 ** 31 - 1; <ide> function setUnrefTimeout(callback, after, arg1, arg2, arg3) { <ide> <ide> // Type checking used by timers.enroll() and Socket#setTimeout() <ide> function validateTimerDuration(msecs) { <del> if (typeof msecs !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('msecs', 'number', msecs); <del> } <del> <add> validateNumber(msecs, 'msecs'); <ide> if (msecs < 0 || !isFinite(msecs)) { <ide> throw new ERR_OUT_OF_RANGE('msecs', 'a non-negative finite number', msecs); <ide> } <ide><path>lib/internal/validators.js <ide> function validateString(value, name) { <ide> throw new ERR_INVALID_ARG_TYPE(name, 'string', value); <ide> } <ide> <add>function validateNumber(value, name) { <add> if (typeof value !== 'number') <add> throw new ERR_INVALID_ARG_TYPE(name, 'number', value); <add>} <add> <ide> module.exports = { <ide> isInt32, <ide> isUint32, <ide> validateMode, <ide> validateInteger, <ide> validateInt32, <ide> validateUint32, <del> validateString <add> validateString, <add> validateNumber <ide> }; <ide><path>lib/util.js <ide> const { <ide> ERR_INVALID_ARG_TYPE, <ide> ERR_OUT_OF_RANGE <ide> } = errors.codes; <add>const { validateNumber } = require('internal/validators'); <ide> const { TextDecoder, TextEncoder } = require('internal/encoding'); <ide> const { isBuffer } = require('buffer').Buffer; <ide> <ide> function callbackify(original) { <ide> } <ide> <ide> function getSystemErrorName(err) { <del> if (typeof err !== 'number') { <del> throw new ERR_INVALID_ARG_TYPE('err', 'number', err); <del> } <add> validateNumber(err, 'err'); <ide> if (err >= 0 || !Number.isSafeInteger(err)) { <ide> throw new ERR_OUT_OF_RANGE('err', 'a negative integer', err); <ide> }
8
Text
Text
fix the mistake of present
6e1339bbc624711c992e27ebf368d53599c97a2d
<ide><path>man/docker-run.1.md <ide> You would have to write policy defining a `svirt_apache_t` type. <ide> If you want to set `/dev/sda` device weight to `200`, you can specify the device <ide> weight by `--blkio-weight-device` flag. Use the following command: <ide> <del> # docker run -it --blkio-weight-device "/dev/sda:200" ubuntu <add> # docker run -it --blkio-weight-device "/dev/sda:200" ubuntu <ide> <ide> ## Specify isolation technology for container (--isolation) <ide>
1
PHP
PHP
move hiddenfield handling to formhelper
b0a3fe8d378ac4666f7d4900fd9d2fcaecaafd96
<ide><path>src/View/Helper/FormHelper.php <ide> public function multiCheckbox($fieldName, $options, array $attributes = []) <ide> ]; <ide> $hidden = $this->hidden($fieldName, $hiddenAttributes); <ide> } <add> unset($attributes['hiddenField']); <ide> <ide> return $hidden . $this->widget('multicheckbox', $attributes); <ide> } <ide><path>src/View/Widget/MultiCheckboxWidget.php <ide> protected function _renderInput($checkbox, $context) <ide> 'templateVars' => $checkbox['templateVars'], <ide> 'attrs' => $this->_templates->formatAttributes( <ide> $checkbox, <del> ['name', 'value', 'text', 'options', 'label', 'val', 'type', 'hiddenField'] <add> ['name', 'value', 'text', 'options', 'label', 'val', 'type'] <ide> ) <ide> ]); <ide>
2
Text
Text
add more info about the link env vars created
61387427cb9b1ed6a4c34e0a7960183159ee305d
<ide><path>docs/sources/userguide/dockerlinks.md <ide> recipient container in two ways: <ide> * Environment variables, <ide> * Updating the `/etc/hosts` file. <ide> <del>Docker can set a number of environment variables. You run the `env` <add>### Environment Variables <add> <add>When two containers are linked, Docker will set some envrionment variables <add>in the target container to enable programmatic discovery of information <add>related to the source container. <add> <add>First, Docker will set a `<alias>_NAME` environment variable specifying the <add>alias of each target container that was given in a `--link` parameter. So, <add>for example, if a new container called `web` is being linked to a database <add>container called `db` via `--link db:webdb` then in the `web` container <add>would be `WEBDB_NAME=/web/webdb`. <add> <add>Docker will then also define a set of environment variables for each <add>port that is exposed by the source container. The pattern followed is: <add> <add>* `<name>_PORT_<port>_<protocol>` will contain a URL reference to the <add>port. Where `<name>` is the alias name specified in the `--link` parameter <add>(e.g. `webdb`), `<port>` is the port number being exposed, and `<protocol>` <add>is either `TCP` or `UDP`. The format of the URL will be: <add>`<protocol>://<container_ip_address>:<port>` <add>(e.g. `tcp://172.17.0.82:8080`). This URL will then be <add>split into the following 3 environment variables for convinience: <add>* `<name>_PORT_<port>_<protocol>_ADDR` will contain just the IP address <add>from the URL (e.g. `WEBDB_PORT_8080_TCP_ADDR=172.17.0.82`). <add>* `<name>_PORT_<port>_<protocol>_PORT` will contain just the port number <add>from the URL (e.g. `WEBDB_PORT_8080_TCP_PORT=8080`). <add>* `<name>_PORT_<port>_<protocol>_PROTO` will contain just the protocol <add>from the URL (e.g. `WEBDB_PORT_8080_TCP_PROTO=tcp`). <add> <add>If there are multiple ports exposed then the above set of environment <add>variables will be defined for each one. <add> <add>Finally, there will be an environment variable called `<alias>_PORT` that will <add>contain the URL of the first exposed port of the source container. <add>For example, `WEBDB_PORT=tcp://172.17.0.82:8080`. In this case, 'first' <add>is defined as the lowest numbered port that is exposed. If that port is <add>used for both tcp and udp, then the tcp one will be specified. <add> <add>Returning back to our database example, you can run the `env` <ide> command to list the specified container's environment variables. <ide> <ide> ``` <ide> environment variables to configure your applications to connect to the database <ide> on the `db` container. The connection will be secure and private; only the <ide> linked `web` container will be able to talk to the `db` container. <ide> <add>### Updating the `/etc/hosts` file <add> <ide> In addition to the environment variables, Docker adds a host entry for the <ide> source container to the `/etc/hosts` file. Here's an entry for the `web` <ide> container:
1
Javascript
Javascript
remove object.observe from tests
b4313cf9a2ac4e56397a5c6049a6a9e143ab7696
<ide><path>test/parallel/test-microtask-queue-integration-domain.js <ide> require('domain'); <ide> var implementations = [ <ide> function(fn) { <ide> Promise.resolve().then(fn); <del> }, <del> function(fn) { <del> var obj = {}; <del> <del> Object.observe(obj, fn); <del> <del> obj.a = 1; <ide> } <ide> ]; <ide> <ide><path>test/parallel/test-microtask-queue-integration.js <ide> var assert = require('assert'); <ide> var implementations = [ <ide> function(fn) { <ide> Promise.resolve().then(fn); <del> }, <del> function(fn) { <del> var obj = {}; <del> <del> Object.observe(obj, fn); <del> <del> obj.a = 1; <ide> } <ide> ]; <ide>
2