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
|
|---|---|---|---|---|---|
PHP
|
PHP
|
fix docblock to what its interface contracts says
|
2f765a486c58d57fd95c87bfc05a01dfbc6458cb
|
<ide><path>src/ORM/Table.php
<ide> public function exists($conditions)
<ide> *
<ide> * @param \Cake\Datasource\EntityInterface $entity
<ide> * @param array $options
<del> * @return bool|\Cake\Datasource\EntityInterface|mixed
<add> * @return \Cake\Datasource\EntityInterface|false
<ide> * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction is aborted in the afterSave event.
<ide> */
<ide> public function save(EntityInterface $entity, $options = [])
| 1
|
Python
|
Python
|
fix bug in protm script
|
36cc3cae1caf4190b8c7fe8e773886cad04d2712
|
<ide><path>dev/stats/get_important_pr_candidates.py
<ide> def __init__(self, g, pull_request: PullRequest):
<ide> self.len_issue_comments = 0
<ide> self.num_issue_comments = 0
<ide> self.num_issue_reactions = 0
<add> self.protm_score = 0
<ide>
<ide> @property
<ide> def label_score(self) -> float:
<ide> """assigns label score"""
<del> for label in self.pull_request.labels:
<add> labels = self.pull_request.labels
<add> for label in labels:
<ide> if "provider" in label.name:
<ide> return PrStat.PROVIDER_SCORE
<ide> return PrStat.REGULAR_SCORE
<ide>
<ide> @cached_property
<ide> def num_comments(self):
<del> """counts reviewer comments"""
<del> comments = 0
<add> """counts reviewer comments & checks for #protm tag"""
<add> num_comments = 0
<add> num_protm = 0
<ide> for comment in self.pull_request.get_comments():
<ide> self._users.add(comment.user.login)
<del> comments += 1
<del> return comments
<add> lowercase_body = comment.body.lower()
<add> if 'protm' in lowercase_body:
<add> num_protm += 1
<add> num_comments += 1
<add> self.protm_score = num_protm
<add> return num_comments
<ide>
<ide> @cached_property
<ide> def num_conv_comments(self) -> int:
<del> """counts conversational comments"""
<del> conv_comments = 0
<add> """counts conversational comments & checks for #protm tag"""
<add> num_conv_comments = 0
<add> num_protm = 0
<ide> for conv_comment in self.pull_request.get_issue_comments():
<ide> self._users.add(conv_comment.user.login)
<del> conv_comments += 1
<del> return conv_comments
<add> lowercase_body = conv_comment.body.lower()
<add> if 'protm' in lowercase_body:
<add> num_protm += 1
<add> num_conv_comments += 1
<add> self.protm_score = num_protm
<add> return num_conv_comments
<ide>
<ide> @cached_property
<ide> def num_reactions(self) -> int:
<ide> def num_conv_reactions(self) -> int:
<ide> @cached_property
<ide> def num_reviews(self) -> int:
<ide> """counts reviews"""
<del> reviews = 0
<add> num_reviews = 0
<ide> for review in self.pull_request.get_reviews():
<ide> self._users.add(review.user.login)
<del> reviews += 1
<del> return reviews
<add> num_reviews += 1
<add> return num_reviews
<ide>
<ide> @cached_property
<ide> def issues(self):
<ide> def issue_reactions(self) -> int:
<ide> @cached_property
<ide> def issue_comments(self) -> int:
<ide> """counts issue comments and calculates comment length"""
<del> issues = self.issues
<del> if issues:
<add> if self.issue_nums:
<ide> repo = self.g.get_repo("apache/airflow")
<ide> issue_comments = 0
<ide> len_issue_comments = 0
<del> for num in issues:
<add> for num in self.issue_nums:
<ide> issue = repo.get_issue(number=num)
<del> for issue_comment in issue.get_comments():
<add> issues = issue.get_comments()
<add> for issue_comment in issues:
<ide> issue_comments += 1
<ide> self._users.add(issue_comment.user.login)
<ide> if issue_comment.body is not None:
<ide> def score(self):
<ide> # If the body contains over 2000 characters, the PR should matter 40% more.
<ide> # If the body contains fewer than 1000 characters, the PR should matter 20% less.
<ide> #
<add> # Weight PRs with protm tags more heavily:
<add> # If there is at least one protm tag, multiply the interaction score by the number of tags, up to 3.
<add> interaction_score = self.interaction_score
<add> interaction_score *= min(self.protm_score + 1, 3)
<ide> return round(
<ide> 1.0
<del> * self.interaction_score
<add> * interaction_score
<ide> * self.label_score
<ide> * self.length_score
<ide> * self.change_score
<ide> def score(self):
<ide> )
<ide>
<ide> def __str__(self) -> str:
<del> return (
<del> f"Score: {self.score:.2f}: PR{self.pull_request.number} by @{self.pull_request.user.login}: "
<del> f"\"{self.pull_request.title}\". "
<del> f"Merged at {self.pull_request.merged_at}: {self.pull_request.html_url}"
<del> )
<add> if self.protm_score > 0:
<add> return (
<add> '[magenta]##Tagged PR## [/]'
<add> f"Score: {self.score:.2f}: PR{self.pull_request.number} by @{self.pull_request.user.login}: "
<add> f"\"{self.pull_request.title}\". "
<add> f"Merged at {self.pull_request.merged_at}: {self.pull_request.html_url}"
<add> )
<add> else:
<add> return (
<add> f"Score: {self.score:.2f}: PR{self.pull_request.number} by @{self.pull_request.user.login}: "
<add> f"\"{self.pull_request.title}\". "
<add> f"Merged at {self.pull_request.merged_at}: {self.pull_request.html_url}"
<add> )
<ide>
<ide> def verboseStr(self) -> str:
<add> if self.protm_score > 0:
<add> console.print("********************* Tagged with '#protm' *********************", style="magenta")
<ide> return (
<ide> f'-- Created at [bright_blue]{self.pull_request.created_at}[/], '
<ide> f'merged at [bright_blue]{self.pull_request.merged_at}[/]\n'
<ide> def main(
<ide> )
<ide> continue
<ide>
<del> if pr.created_at < date_start:
<add> if pr.merged_at < date_start:
<ide> console.print("[bright_blue]Completed selecting candidates")
<ide> break
<ide>
| 1
|
Javascript
|
Javascript
|
add code example for emberarray reject
|
c20639593b23463cb5ca48446335bd4eb80045da
|
<ide><path>packages/@ember/-internals/runtime/lib/mixins/array.js
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide>
<ide> ```javascript
<ide> let peopleToMoon = ['Armstrong', 'Aldrin'];
<del>
<add>
<ide> peopleToMoon.get('[]'); // ['Armstrong', 'Aldrin']
<ide>
<ide> peopleToMoon.set('[]', ['Collins']); // ['Collins']
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide>
<ide> vowels.reverseObjects();
<ide> vowels.firstObject; // 'u'
<del>
<add>
<ide> vowels.clear();
<ide> vowels.firstObject; // undefined
<ide> ```
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> Returns the index if found, -1 if no match is found.
<ide>
<ide> The optional `startAt` argument can be used to pass a starting
<del> index to search from, effectively slicing the searchable portion
<add> index to search from, effectively slicing the searchable portion
<ide> of the array. If it's negative it will add the array length to
<ide> the startAt value passed in as the index to search from. If less
<ide> than or equal to `-1 * array.length` the entire array is searched.
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> editPost(post, newContent) {
<ide> let oldContent = post.body,
<ide> postIndex = this.posts.indexOf(post);
<del>
<add>
<ide> this.posts.arrayContentWillChange(postIndex, 0, 0); // attemptsToModify = 1
<ide> post.set('body', newContent);
<ide>
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide>
<ide> ```javascript
<ide> let people = [{name: 'Joe'}, {name: 'Matt'}];
<del>
<add>
<ide> people.setEach('zipCode', '10011);
<ide> // [{name: 'Joe', zipCode: '10011'}, {name: 'Matt', zipCode: '10011'}];
<ide> ```
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> object that will be set as "this" on the context. This is a good way
<ide> to give your iterator function access to the current object.
<ide>
<add> Example Usage:
<add>
<add> ```javascript
<add> const food = Ember.A().addObjects([{food: 'apple', isFruit: true}, {food: 'bread', isFruit: false}, food: 'banana', isFruit: true}]);
<add> const nonFruits = food.reject(function(thing) {
<add> return thing.isFruit;
<add> }); // [{food: 'beans', isFruit: false}]
<add> ```
<add>
<ide> @method reject
<ide> @param {Function} callback The callback to execute
<ide> @param {Object} [target] The target object to use
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> Note that in addition to a callback, you can also pass an optional target
<ide> object that will be set as `this` on the context. This is a good way
<ide> to give your iterator function access to the current object.
<del>
<add>
<ide> Example Usage:
<ide>
<ide> ```javascript
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> greet(prefix='Hello') {
<ide> return `${prefix} ${this.name}`;
<ide> },
<del>
<add>
<ide> });
<ide> let people = [Person.create('Joe'), Person.create('Matt')];
<ide>
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> Returns `true` if found, `false` otherwise.
<ide>
<ide> The optional `startAt` argument can be used to pass a starting
<del> index to search from, effectively slicing the searchable portion
<add> index to search from, effectively slicing the searchable portion
<ide> of the array. If it's negative it will add the array length to
<ide> the startAt value passed in as the index to search from. If less
<ide> than or equal to `-1 * array.length` the entire array is searched.
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> { name: 'green', weight: 600 },
<ide> { name: 'blue', weight: 500 }
<ide> ];
<del>
<add>
<ide> colors.sortBy('name');
<ide> // [{name: 'blue', weight: 500}, {name: 'green', weight: 600}, {name: 'red', weight: 500}]
<del>
<add>
<ide> colors.sortBy('weight', 'name');
<ide> // [{name: 'blue', weight: 500}, {name: 'red', weight: 500}, {name: 'green', weight: 600}]
<ide> ```
| 1
|
Text
|
Text
|
update doc files for ticks.minrotation
|
691a7c6a4bef0c6e0b8d1c82bafd4e2807239fac
|
<ide><path>docs/01-Scales.md
<ide> afterUpdate | Function | undefined | Callback that runs at the end of the update
<ide> *ticks*.fontFamily | String | "Helvetica Neue" | Font family for the tick labels, follows CSS font-family options.
<ide> *ticks*.fontSize | Number | 12 | Font size for the tick labels.
<ide> *ticks*.fontStyle | String | "normal" | Font style for the tick labels, follows CSS font-style options (i.e. normal, italic, oblique, initial, inherit).
<add>*ticks*.minRotation | Number | 0 | Minimum rotation for tick labels
<ide> *ticks*.maxRotation | Number | 90 | Maximum rotation for tick labels when rotating to condense labels. Note: Rotation doesn't occur until necessary. *Note: Only applicable to horizontal scales.*
<ide> *ticks*.minRotation | Number | 20 | *currently not-implemented* Minimum rotation for tick labels when condensing is necessary. *Note: Only applicable to horizontal scales.*
<ide> *ticks*.maxTicksLimit | Number | 11 | Maximum number of ticks and gridlines to show. If not defined, it will limit to 11 ticks but will show all gridlines.
| 1
|
Javascript
|
Javascript
|
restore the `btoa`/`atob` polyfills for node.js
|
0e1b5589e7a54f979e5e572024b71222c9444ebc
|
<ide><path>examples/node/domstubs.js
<ide> DOMElementSerializer.prototype = {
<ide> },
<ide> };
<ide>
<del>function btoa (chars) {
<del> return Buffer.from(chars, 'binary').toString('base64');
<del>}
<del>
<ide> const document = {
<ide> childNodes : [],
<ide>
<ide> Image.prototype = {
<ide> }
<ide> }
<ide>
<del>exports.btoa = btoa;
<ide> exports.document = document;
<ide> exports.Image = Image;
<ide>
<ide><path>gulpfile.js
<ide> gulp.task('lib', ['buildnumber'], function () {
<ide> var licenseHeaderLibre =
<ide> fs.readFileSync('./src/license_header_libre.js').toString();
<ide> var preprocessor2 = require('./external/builder/preprocessor2.js');
<add> var sharedFiles = [
<add> 'compatibility',
<add> 'global_scope',
<add> 'is_node',
<add> 'streams_polyfill',
<add> 'util',
<add> ];
<ide> var buildLib = merge([
<ide> gulp.src([
<ide> 'src/{core,display}/*.js',
<del> 'src/shared/{compatibility,util,streams_polyfill,global_scope}.js',
<add> 'src/shared/{' + sharedFiles.join() + '}.js',
<ide> 'src/{pdf,pdf.worker}.js',
<ide> ], { base: 'src/', }),
<ide> gulp.src([
<ide><path>src/core/worker.js
<ide>
<ide> import {
<ide> arrayByteLength, arraysToBytes, assert, createPromiseCapability, info,
<del> InvalidPDFException, isNodeJS, MessageHandler, MissingPDFException,
<del> PasswordException, setVerbosityLevel, UnexpectedResponseException,
<del> UnknownErrorException, UNSUPPORTED_FEATURES, warn, XRefParseException
<add> InvalidPDFException, MessageHandler, MissingPDFException, PasswordException,
<add> setVerbosityLevel, UnexpectedResponseException, UnknownErrorException,
<add> UNSUPPORTED_FEATURES, warn, XRefParseException
<ide> } from '../shared/util';
<ide> import { LocalPdfManager, NetworkPdfManager } from './pdf_manager';
<add>import isNodeJS from '../shared/is_node';
<ide> import { Ref } from './primitives';
<ide>
<ide> var WorkerTask = (function WorkerTaskClosure() {
<ide><path>src/display/svg.js
<ide> /* globals __non_webpack_require__ */
<ide>
<ide> import {
<del> createObjectURL, FONT_IDENTITY_MATRIX, IDENTITY_MATRIX, ImageKind, isNodeJS,
<del> isNum, OPS, Util, warn
<add> createObjectURL, FONT_IDENTITY_MATRIX, IDENTITY_MATRIX, ImageKind, isNum, OPS,
<add> Util, warn
<ide> } from '../shared/util';
<ide> import { DOMSVGFactory } from './dom_utils';
<add>import isNodeJS from '../shared/is_node';
<ide>
<ide> var SVGGraphics = function() {
<ide> throw new Error('Not implemented: SVGGraphics');
<ide><path>src/pdf.js
<ide> var pdfjsDisplaySVG = require('./display/svg.js');
<ide>
<ide> if (typeof PDFJSDev === 'undefined' ||
<ide> !PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<del> if (pdfjsSharedUtil.isNodeJS()) {
<add> const isNodeJS = require('./shared/is_node.js');
<add> if (isNodeJS()) {
<ide> var PDFNodeStream = require('./display/node_stream.js').PDFNodeStream;
<ide> pdfjsDisplayAPI.setPDFNetworkStreamClass(PDFNodeStream);
<ide> } else if (typeof Response !== 'undefined' && 'body' in Response.prototype &&
<ide><path>src/shared/compatibility.js
<ide> if ((typeof PDFJSDev === 'undefined' ||
<ide> (typeof PDFJS === 'undefined' || !PDFJS.compatibilityChecked)) {
<ide>
<ide> var globalScope = require('./global_scope');
<add>const isNodeJS = require('./is_node');
<ide>
<ide> var userAgent = (typeof navigator !== 'undefined' && navigator.userAgent) || '';
<ide> var isAndroid = /Android/.test(userAgent);
<ide> if (typeof PDFJS === 'undefined') {
<ide>
<ide> PDFJS.compatibilityChecked = true;
<ide>
<add>// Support: Node.js
<add>(function checkNodeBtoa() {
<add> if (globalScope.btoa || !isNodeJS()) {
<add> return;
<add> }
<add> globalScope.btoa = function(chars) {
<add> // eslint-disable-next-line no-undef
<add> return Buffer.from(chars, 'binary').toString('base64');
<add> };
<add>})();
<add>
<add>// Support: Node.js
<add>(function checkNodeAtob() {
<add> if (globalScope.atob || !isNodeJS()) {
<add> return;
<add> }
<add> globalScope.atob = function(input) {
<add> // eslint-disable-next-line no-undef
<add> return Buffer.from(input, 'base64').toString('binary');
<add> };
<add>})();
<add>
<ide> // Checks if possible to use URL.createObjectURL()
<ide> // Support: IE, Chrome on iOS
<ide> (function checkOnBlobSupport() {
<ide><path>src/shared/is_node.js
<add>/* Copyright 2018 Mozilla Foundation
<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>/* globals module, process */
<add>
<add>module.exports = function isNodeJS() {
<add> return typeof process === 'object' && process + '' === '[object process]';
<add>};
<ide><path>src/shared/util.js
<ide> function isSpace(ch) {
<ide> return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A);
<ide> }
<ide>
<del>function isNodeJS() {
<del> // eslint-disable-next-line no-undef
<del> return typeof process === 'object' && process + '' === '[object process]';
<del>}
<del>
<ide> /**
<ide> * Promise Capability object.
<ide> *
<ide> export {
<ide> isNum,
<ide> isString,
<ide> isSpace,
<del> isNodeJS,
<ide> isSameOrigin,
<ide> createValidAbsoluteUrl,
<ide> isLittleEndian,
<ide><path>test/unit/api_spec.js
<ide> import {
<ide> buildGetDocumentParams, NodeFileReaderFactory, TEST_PDFS_PATH
<ide> } from './test_utils';
<ide> import {
<del> createPromiseCapability, FontType, InvalidPDFException, isNodeJS,
<del> MissingPDFException, PasswordException, PasswordResponses, StreamType,
<del> stringToBytes
<add> createPromiseCapability, FontType, InvalidPDFException, MissingPDFException,
<add> PasswordException, PasswordResponses, StreamType, stringToBytes
<ide> } from '../../src/shared/util';
<ide> import {
<ide> DOMCanvasFactory, RenderingCancelledException
<ide> } from '../../src/display/dom_utils';
<ide> import {
<ide> getDocument, PDFDocumentProxy, PDFPageProxy
<ide> } from '../../src/display/api';
<add>import isNodeJS from '../../src/shared/is_node';
<ide> import { PDFJS } from '../../src/display/global';
<ide>
<ide> describe('api', function() {
<ide><path>test/unit/cmap_spec.js
<ide>
<ide> import { CMap, CMapFactory, IdentityCMap } from '../../src/core/cmap';
<ide> import { DOMCMapReaderFactory } from '../../src/display/dom_utils';
<del>import { isNodeJS } from '../../src/shared/util';
<add>import isNodeJS from '../../src/shared/is_node';
<ide> import { Name } from '../../src/core/primitives';
<ide> import { NodeCMapReaderFactory } from './test_utils';
<ide> import { StringStream } from '../../src/core/stream';
<ide><path>test/unit/custom_spec.js
<ide> import { buildGetDocumentParams } from './test_utils';
<ide> import { DOMCanvasFactory } from '../../src/display/dom_utils';
<ide> import { getDocument } from '../../src/display/api';
<del>import { isNodeJS } from '../../src/shared/util';
<add>import isNodeJS from '../../src/shared/is_node';
<ide>
<ide> function getTopLeftPixel(canvasContext) {
<ide> let imgData = canvasContext.getImageData(0, 0, 1, 1);
<ide><path>test/unit/display_svg_spec.js
<ide> */
<ide> /* globals __non_webpack_require__ */
<ide>
<del>import { isNodeJS, NativeImageDecoding } from '../../src/shared/util';
<ide> import { setStubs, unsetStubs } from '../../examples/node/domstubs';
<ide> import { buildGetDocumentParams } from './test_utils';
<ide> import { getDocument } from '../../src/display/api';
<add>import isNodeJS from '../../src/shared/is_node';
<add>import { NativeImageDecoding } from '../../src/shared/util';
<ide> import { SVGGraphics } from '../../src/display/svg';
<ide>
<ide> const XLINK_NS = 'http://www.w3.org/1999/xlink';
<ide><path>test/unit/dom_utils_spec.js
<ide> import {
<ide> DOMSVGFactory, getFilenameFromUrl, isExternalLinkTargetSet, LinkTarget
<ide> } from '../../src/display/dom_utils';
<del>import { isNodeJS } from '../../src/shared/util';
<add>import isNodeJS from '../../src/shared/is_node';
<ide> import { PDFJS } from '../../src/display/global';
<ide>
<ide> describe('dom_utils', function() {
<ide><path>test/unit/node_stream_spec.js
<ide> */
<ide> /* globals __non_webpack_require__ */
<ide>
<del>import { assert, isNodeJS } from '../../src/shared/util';
<add>import { assert } from '../../src/shared/util';
<add>import isNodeJS from '../../src/shared/is_node';
<ide> import { PDFNodeStream } from '../../src/display/node_stream';
<ide>
<ide> // Make sure that we only running this script is Node.js environments.
<ide><path>test/unit/test_utils.js
<ide> * limitations under the License.
<ide> */
<ide>
<del>import { CMapCompressionType, isNodeJS } from '../../src/shared/util';
<add>import { CMapCompressionType } from '../../src/shared/util';
<add>import isNodeJS from '../../src/shared/is_node';
<ide> import { isRef } from '../../src/core/primitives';
<ide>
<ide> class NodeFileReaderFactory {
<ide><path>test/unit/ui_utils_spec.js
<ide> import {
<ide> binarySearchFirstItem, EventBus, getPDFFileNameFromURL, isValidRotation,
<ide> waitOnEventOrTimeout, WaitOnType
<ide> } from '../../web/ui_utils';
<del>import { createObjectURL, isNodeJS } from '../../src/shared/util';
<add>import { createObjectURL } from '../../src/shared/util';
<add>import isNodeJS from '../../src/shared/is_node';
<ide>
<ide> describe('ui_utils', function() {
<ide> describe('binary search', function() {
| 16
|
Javascript
|
Javascript
|
add tests for attribute hook/helper
|
df4e1723ae290cd38876fd4e50b6157208db84d3
|
<ide><path>packages/ember-htmlbars/lib/helpers/attribute.js
<add>import run from "ember-metal/run_loop";
<add>
<add>export function attributeHelper(params, hash, options, env) {
<add> var dom = env.dom;
<add> var name = params[0];
<add> var value = params[1];
<add>
<add> var isDirty, lastRenderedValue;
<add>
<add> value.subscribe(function(lazyValue) {
<add> isDirty = true;
<add>
<add> run.schedule('render', this, function() {
<add> var value = lazyValue.value();
<add>
<add> if (isDirty) {
<add> isDirty = false;
<add> if (value !== lastRenderedValue) {
<add> lastRenderedValue = value;
<add> dom.setAttribute(options.element, name, value);
<add> }
<add> }
<add> });
<add> });
<add>
<add> lastRenderedValue = value.value();
<add>
<add> dom.setAttribute(options.element, name, lastRenderedValue);
<add>}
<ide><path>packages/ember-htmlbars/lib/helpers/concat.js
<add>import Stream from "ember-metal/streams/stream";
<add>import {readArray} from "ember-metal/streams/read";
<add>
<add>export function concatHelper(params, hash, options, env) {
<add> var stream = new Stream(function() {
<add> return readArray(params).join('');
<add> });
<add>
<add> for (var i = 0, l = params.length; i < l; i++) {
<add> var param = params[i];
<add>
<add> if (param && param.isStream) {
<add> param.subscribe(stream.notifyAll, stream);
<add> }
<add> }
<add>
<add> return stream;
<add>}
<add>
<ide><path>packages/ember-htmlbars/lib/helpers/unbound.js
<del>import { lookupHelper } from 'ember-htmlbars/system/lookup-helper';
<add>import lookupHelper from 'ember-htmlbars/system/lookup-helper';
<ide> import { read } from 'ember-metal/streams/read';
<ide> import EmberError from "ember-metal/error";
<ide> import merge from "ember-metal/merge";
<ide><path>packages/ember-htmlbars/lib/hooks.js
<ide> import Ember from "ember-metal/core";
<del>import { lookupHelper } from "ember-htmlbars/system/lookup-helper";
<add>import lookupHelper from "ember-htmlbars/system/lookup-helper";
<ide> import { sanitizeOptionsForHelper } from "ember-htmlbars/system/sanitize-for-helper";
<ide>
<ide> function streamifyArgs(view, params, hash, options, env, helper) {
<ide><path>packages/ember-htmlbars/lib/main.js
<ide> import {
<ide> helper,
<ide> default as helpers
<ide> } from "ember-htmlbars/helpers";
<add>import { attributeHelper} from "ember-htmlbars/helpers/attribute";
<add>import { concatHelper } from "ember-htmlbars/helpers/concat";
<ide> import { bindHelper } from "ember-htmlbars/helpers/binding";
<ide> import { viewHelper } from "ember-htmlbars/helpers/view";
<ide> import { yieldHelper } from "ember-htmlbars/helpers/yield";
<ide> import "ember-htmlbars/system/bootstrap";
<ide> // Ember.Handlebars global if htmlbars is enabled
<ide> import "ember-htmlbars/compat";
<ide>
<add>registerHelper('attribute', attributeHelper);
<add>registerHelper('concat', concatHelper);
<ide> registerHelper('bindHelper', bindHelper);
<ide> registerHelper('bind', bindHelper);
<ide> registerHelper('view', viewHelper);
<ide><path>packages/ember-htmlbars/lib/system/lookup-helper.js
<ide> import Ember from "ember-metal/core";
<ide> import Cache from "ember-metal/cache";
<ide> import makeViewHelper from "ember-htmlbars/system/make-view-helper";
<ide> import HandlebarsCompatibleHelper from "ember-htmlbars/compat/helper";
<del>import Stream from "ember-metal/streams/stream";
<del>import {readArray} from "ember-metal/streams/read";
<del>import Helper from "ember-htmlbars/system/helper";
<ide>
<ide> export var ISNT_HELPER_CACHE = new Cache(1000, function(key) {
<ide> return key.indexOf('-') === -1;
<ide> });
<ide>
<del>export function attribute(params, hash, options, env) {
<del> var dom = env.dom;
<del> var name = params[0];
<del> var value = params[1];
<del>
<del> value.subscribe(function(lazyValue) {
<del> dom.setAttribute(options.element, name, lazyValue.value());
<del> });
<del>
<del> dom.setAttribute(options.element, name, value.value());
<del>}
<del>
<del>var attributeHelper = new Helper(attribute);
<del>
<del>export function concat(params, hash, options, env) {
<del> var stream = new Stream(function() {
<del> return readArray(params).join('');
<del> });
<del>
<del> for (var i = 0, l = params.length; i < l; i++) {
<del> var param = params[i];
<del>
<del> if (param && param.isStream) {
<del> param.subscribe(stream.notifyAll, stream);
<del> }
<del> }
<del>
<del> return stream;
<del>}
<del>
<del>var concatHelper = new Helper(concat);
<del>
<ide> /**
<ide> Used to lookup/resolve handlebars helpers. The lookup order is:
<ide>
<ide> var concatHelper = new Helper(concat);
<ide> @param {String} name the name of the helper to lookup
<ide> @return {Handlebars Helper}
<ide> */
<del>export function lookupHelper(name, view, env) {
<del> if (name === 'concat') {
<del> return concatHelper;
<del> }
<del>
<del> if (name === 'attribute') {
<del> return attributeHelper;
<del> }
<del>
<add>export default function lookupHelper(name, view, env) {
<ide> if (env.helpers[name]) {
<ide> return env.helpers[name];
<ide> }
<ide><path>packages/ember-htmlbars/tests/helpers/attribute_test.js
<add>import EmberView from "ember-views/views/view";
<add>import run from "ember-metal/run_loop";
<add>import EmberObject from "ember-runtime/system/object";
<add>import { compile } from "htmlbars-compiler/compiler";
<add>import { equalInnerHTML } from "htmlbars-test-helpers";
<add>import { defaultEnv } from "ember-htmlbars";
<add>
<add>var view, originalSetAttribute, setAttributeCalls;
<add>var dom = defaultEnv.dom;
<add>
<add>function appendView(view) {
<add> run(function() { view.appendTo('#qunit-fixture'); });
<add>}
<add>
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add> QUnit.module("ember-htmlbars: attribute", {
<add> teardown: function(){
<add> if (view) {
<add> run(view, view.destroy);
<add> }
<add> }
<add> });
<add>
<add> test("property is output", function() {
<add> view = EmberView.create({
<add> context: {name: 'erik'},
<add> template: compile("<div data-name={{name}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> equalInnerHTML(view.element, '<div data-name="erik">Hi!</div>', "attribute is output");
<add> });
<add>
<add> test("property value is directly added to attribute", function() {
<add> view = EmberView.create({
<add> context: {name: '"" data-foo="blah"'},
<add> template: compile("<div data-name={{name}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> equalInnerHTML(view.element, '<div data-name=""" data-foo="blah"">Hi!</div>', "attribute is output");
<add> });
<add>
<add> test("path is output", function() {
<add> view = EmberView.create({
<add> context: {name: {firstName: 'erik'}},
<add> template: compile("<div data-name={{name.firstName}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> equalInnerHTML(view.element, '<div data-name="erik">Hi!</div>', "attribute is output");
<add> });
<add>
<add> test("changed property updates", function() {
<add> var context = EmberObject.create({name: 'erik'});
<add> view = EmberView.create({
<add> context: context,
<add> template: compile("<div data-name={{name}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> equalInnerHTML(view.element, '<div data-name="erik">Hi!</div>', "precond - attribute is output");
<add>
<add> run(context, context.set, 'name', 'mmun');
<add>
<add> equalInnerHTML(view.element, '<div data-name="mmun">Hi!</div>', "attribute is updated output");
<add> });
<add>
<add> test("updates are scheduled in the render queue", function() {
<add> expect(4);
<add>
<add> var context = EmberObject.create({name: 'erik'});
<add> view = EmberView.create({
<add> context: context,
<add> template: compile("<div data-name={{name}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> equalInnerHTML(view.element, '<div data-name="erik">Hi!</div>', "precond - attribute is output");
<add>
<add> run(function() {
<add> run.schedule('render', function() {
<add> equalInnerHTML(view.element, '<div data-name="erik">Hi!</div>', "precond - attribute is not updated sync");
<add> });
<add>
<add> context.set('name', 'mmun');
<add>
<add> run.schedule('render', function() {
<add> equalInnerHTML(view.element, '<div data-name="mmun">Hi!</div>', "attribute is updated output");
<add> });
<add> });
<add>
<add> equalInnerHTML(view.element, '<div data-name="mmun">Hi!</div>', "attribute is updated output");
<add> });
<add>
<add> QUnit.module('ember-htmlbars: {{attribute}} helper -- setAttribute', {
<add> setup: function() {
<add> originalSetAttribute = dom.setAttribute;
<add> dom.setAttribute = function(element, name, value) {
<add> setAttributeCalls.push([name, value]);
<add>
<add> originalSetAttribute.call(dom, element, name, value);
<add> };
<add>
<add> setAttributeCalls = [];
<add> },
<add>
<add> teardown: function() {
<add> dom.setAttribute = originalSetAttribute;
<add>
<add> if (view) {
<add> run(view, view.destroy);
<add> }
<add> }
<add> });
<add>
<add> test('calls setAttribute for new values', function() {
<add> var context = EmberObject.create({name: 'erik'});
<add> view = EmberView.create({
<add> context: context,
<add> template: compile("<div data-name={{name}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> run(context, context.set, 'name', 'mmun');
<add>
<add> var expected = [
<add> ['data-name', 'erik'],
<add> ['data-name', 'mmun']
<add> ];
<add>
<add> deepEqual(setAttributeCalls, expected);
<add> });
<add>
<add> test('does not call setAttribute if the same value is set', function() {
<add> var context = EmberObject.create({name: 'erik'});
<add> view = EmberView.create({
<add> context: context,
<add> template: compile("<div data-name={{name}}>Hi!</div>")
<add> });
<add> appendView(view);
<add>
<add> run(function() {
<add> context.set('name', 'mmun');
<add> context.set('name', 'erik');
<add> });
<add>
<add> var expected = [
<add> ['data-name', 'erik']
<add> ];
<add>
<add> deepEqual(setAttributeCalls, expected);
<add> });
<add>}
<ide><path>packages/ember-htmlbars/tests/system/lookup-helper_test.js
<del>import {
<del> concat,
<del> attribute,
<del> lookupHelper
<del>} from "ember-htmlbars/system/lookup-helper";
<add>import lookupHelper from "ember-htmlbars/system/lookup-helper";
<ide> import ComponentLookup from "ember-views/component_lookup";
<ide> import Container from "container";
<ide> import Component from "ember-views/views/component";
<ide> function generateContainer() {
<ide>
<ide> QUnit.module('ember-htmlbars: lookupHelper hook');
<ide>
<del>test('returns concat when helper is `concat`', function() {
<del> var actual = lookupHelper('concat');
<del>
<del> equal(actual.helperFunction, concat, 'concat is a hard-coded helper');
<del>});
<del>
<del>test('returns attribute when helper is `attribute`', function() {
<del> var actual = lookupHelper('attribute');
<del>
<del> equal(actual.helperFunction, attribute, 'attribute is a hard-coded helper');
<del>});
<del>
<ide> test('looks for helpers in the provided `env.helpers`', function() {
<ide> var env = generateEnv({
<ide> 'flubarb': function() { }
| 8
|
Text
|
Text
|
update maintainer info [ci skip]
|
3e3d87a068019fd66625ef4f1686f0ad616f7ab5
|
<ide><path>CONTRIBUTING.md
<ide>
<ide> # Contribute to spaCy
<ide>
<del>Thanks for your interest in contributing to spaCy 🎉 The project is maintained
<del>by **[@honnibal](https://github.com/honnibal)**,
<del>**[@ines](https://github.com/ines)**, **[@svlandeg](https://github.com/svlandeg)** and
<del>**[@adrianeboyd](https://github.com/adrianeboyd)**,
<del>and we'll do our best to help you get started. This page will give you a quick
<add>Thanks for your interest in contributing to spaCy 🎉 This page will give you a quick
<ide> overview of how things are organized and most importantly, how to get involved.
<ide>
<ide> ## Table of contents
<ide><path>README.md
<ide> open-source software, released under the MIT license.
<ide> ## 💬 Where to ask questions
<ide>
<ide> The spaCy project is maintained by **[@honnibal](https://github.com/honnibal)**,
<del>**[@ines](https://github.com/ines)**, **[@svlandeg](https://github.com/svlandeg)** and
<del>**[@adrianeboyd](https://github.com/adrianeboyd)**. Please understand that we won't
<del>be able to provide individual support via email. We also believe that help is
<del>much more valuable if it's shared publicly, so that more people can benefit from
<del>it.
<add>**[@ines](https://github.com/ines)**, **[@svlandeg](https://github.com/svlandeg)**,
<add>**[@adrianeboyd](https://github.com/adrianeboyd)** and **[@polm](https://github.com/polm)**.
<add>Please understand that we won't be able to provide individual support via email.
<add>We also believe that help is much more valuable if it's shared publicly, so that
<add>more people can benefit from it.
<ide>
<ide> | Type | Platforms |
<ide> | ------------------------------- | --------------------------------------- |
| 2
|
Ruby
|
Ruby
|
add fake controllers for url rewriter tests
|
2ae84e04aa18f6b35c628349c8c816fe1538cd70
|
<ide><path>actionpack/test/controller/url_rewriter_test.rb
<ide> require 'abstract_unit'
<add>require 'controller/fake_controllers'
<ide>
<ide> ActionController::UrlRewriter
<ide>
<ide><path>actionpack/test/lib/controller/fake_controllers.rb
<ide> class NewsFeedController < ActionController::Base; end
<ide> class ElsewhereController < ActionController::Base; end
<ide> class AddressesController < ActionController::Base; end
<ide> class SessionsController < ActionController::Base; end
<add>class FooController < ActionController::Base; end
<add>class CController < ActionController::Base; end
<add>class HiController < ActionController::Base; end
<add>class BraveController < ActionController::Base; end
<add>class ImageController < ActionController::Base; end
<ide>
<ide> # For speed test
<ide> class SpeedController < ActionController::Base; end
| 2
|
Python
|
Python
|
add bigquery to google cloud storage operator
|
1790a8ed364744ad97b84c61fdd6f4c2ec015af9
|
<ide><path>airflow/contrib/hooks/bigquery_hook.py
<ide> def get_conn(self):
<ide>
<ide> def get_pandas_df(self, bql, parameters=None):
<ide> """
<del> Returns a Pandas DataFrame for the results produced by a BigQuery query.
<add> Returns a Pandas DataFrame for the results produced by a BigQuery
<add> query.
<add>
<add> :param bql: The BigQuery SQL to execute.
<add> :type bql: string
<ide> """
<ide> service = self.get_conn()
<ide> connection_info = self.get_connection(self.bigquery_conn_id)
<ide> def get_pandas_df(self, bql, parameters=None):
<ide> else:
<ide> return gbq_parse_data(schema, [])
<ide>
<del> def run(self, bql, destination_dataset_table = False):
<add> def run(self, bql, destination_dataset_table = False, write_disposition = 'WRITE_EMPTY'):
<ide> """
<ide> Executes a BigQuery SQL query. Either returns results and schema, or
<del> stores results in a BigQuery table, if destination is set.
<add> stores results in a BigQuery table, if destination is set. See here:
<add>
<add> https://cloud.google.com/bigquery/docs/reference/v2/jobs
<add>
<add> For more details about these parameters.
<add>
<add> :param bql: The BigQuery SQL to execute.
<add> :type bql: string
<add> :param destination_dataset_table: The dotted <dataset>.<table>
<add> BigQuery table to save the query results.
<add> :param write_disposition: What to do if the table already exists in
<add> BigQuery.
<ide> """
<ide> connection_info = self.get_connection(self.bigquery_conn_id)
<ide> connection_extras = connection_info.extra_dejson
<ide> project = connection_extras['project']
<ide> configuration = {
<ide> 'query': {
<del> 'query': bql
<add> 'query': bql,
<add> 'writeDisposition': write_disposition,
<ide> }
<ide> }
<ide>
<ide> def run(self, bql, destination_dataset_table = False):
<ide> 'tableId': destination_table,
<ide> }
<ide>
<del> return self.run_with_configuration(configuration)
<add> self.run_with_configuration(configuration)
<add>
<add> def run_extract(self, source_dataset_table, destination_cloud_storage_uris, compression='NONE', export_format='CSV', field_delimiter=',', print_header=True):
<add> """
<add> Executes a BigQuery extract command to copy data from BigQuery to
<add> Google Cloud Storage. See here:
<add>
<add> https://cloud.google.com/bigquery/docs/reference/v2/jobs
<add>
<add> For more details about these parameters.
<add>
<add> :param source_dataset_table: The dotted <dataset>.<table> BigQuery table to use as the source data.
<add> :type source_dataset_table: string
<add> :param destination_cloud_storage_uris: The destination Google Cloud
<add> Storage URI (e.g. gs://some-bucket/some-file.txt). Follows
<add> convention defined here:
<add> https://cloud.google.com/bigquery/exporting-data-from-bigquery#exportingmultiple
<add> :type destination_cloud_storage_uris: list
<add> :param compression: Type of compression to use.
<add> :type compression: string
<add> :param export_format: File format to export.
<add> :type field_delimiter: string
<add> :param field_delimiter: The delimiter to use when extracting to a CSV.
<add> :type field_delimiter: string
<add> :param print_header: Whether to print a header for a CSV file extract.
<add> :type print_header: boolean
<add> """
<add> assert '.' in source_dataset_table, \
<add> 'Expected source_dataset_table in the format of <dataset>.<table>. Got: {}'.format(source_dataset_table)
<add>
<add> connection_info = self.get_connection(self.bigquery_conn_id)
<add> connection_extras = connection_info.extra_dejson
<add> project = connection_extras['project']
<add> source_dataset, source_table = source_dataset_table.split('.', 1)
<add> configuration = {
<add> 'extract': {
<add> 'sourceTable': {
<add> 'projectId': project,
<add> 'datasetId': source_dataset,
<add> 'tableId': source_table,
<add> },
<add> 'compression': compression,
<add> 'destinationUris': destination_cloud_storage_uris,
<add> 'destinationFormat': export_format,
<add> 'fieldDelimiter': field_delimiter,
<add> 'printHeader': print_header,
<add> }
<add> }
<add>
<add> self.run_with_configuration(configuration)
<ide>
<ide> def run_with_configuration(self, configuration):
<ide> """
<del> Executes a BigQuery SQL query.
<add> Executes a BigQuery SQL query. See here:
<add>
<add> https://cloud.google.com/bigquery/docs/reference/v2/jobs
<add>
<add> For more details about the configuration parameter.
<ide>
<ide> :param configuration: The configuration parameter maps directly to
<ide> BigQuery's configuration field in the job object. See
<ide> def run_with_configuration(self, configuration):
<ide> connection_info = self.get_connection(self.bigquery_conn_id)
<ide> connection_extras = connection_info.extra_dejson
<ide> project = connection_extras['project']
<del> job_collection = service.jobs()
<add> jobs = service.jobs()
<ide> job_data = {
<ide> 'configuration': configuration
<ide> }
<ide>
<ide> # Send query and wait for reply.
<del> query_reply = job_collection \
<add> query_reply = jobs \
<ide> .insert(projectId=project, body=job_data) \
<ide> .execute()
<del> job_reference = query_reply['jobReference']
<add> job_id = query_reply['jobReference']['jobId']
<add> job = jobs.get(projectId=project, jobId=job_id).execute()
<ide>
<ide> # Wait for query to finish.
<del> while not query_reply.get('jobComplete', False):
<del> logging.info('Waiting for job to complete: %s', job_reference)
<add> while not job['status']['state'] == 'DONE':
<add> logging.info('Waiting for job to complete: %s, %s', project, job_id)
<ide> time.sleep(5)
<del> query_reply = job_collection \
<del> .getQueryResults(projectId=job_reference['projectId'], jobId=job_reference['jobId']) \
<del> .execute()
<del>
<del> total_rows = int(query_reply['totalRows'])
<del> results = list()
<del> seen_page_tokens = set()
<del> current_row = 0
<del> schema = query_reply['schema']
<del>
<del> # Loop through each page of data, and stuff it into the results variable.
<del> while 'rows' in query_reply and current_row < total_rows:
<del> page = query_reply['rows']
<del> results.extend(page)
<del> current_row += len(page)
<del> page_token = query_reply.get('pageToken', None)
<del>
<del> if not page_token and current_row < total_rows:
<del> raise Exception('Required pageToken was missing. Received {0} of {1} rows.'.format(current_row, total_rows))
<del> elif page_token in seen_page_tokens:
<del> raise Exception('A duplicate pageToken was returned. This is unexpected.')
<del>
<del> seen_page_tokens.add(page_token)
<del>
<del> query_reply = job_collection \
<del> .getQueryResults(projectId=job_reference['projectId'], jobId=job_reference['jobId'], pageToken=page_token) \
<del> .execute()
<del>
<del> if current_row < total_rows:
<del> raise Exception('Didn\'t get complete result set. Something went wrong. Aborting.')
<del>
<del> return schema, results
<add> job = jobs.get(projectId=project, jobId=job_id).execute()
<add>
<add> # Check if job had errors.
<add> if 'errorResult' in job['status']:
<add> raise Exception('BigQuery job failed. Final error was: %s', job['status']['errorResult'])
<ide>
<ide> class BigQueryPandasConnector(GbqConnector):
<ide> """
<ide><path>airflow/contrib/operators/bigquery_operator.py
<ide> from airflow.models import BaseOperator
<ide> from airflow.utils import apply_defaults
<ide>
<del>
<ide> class BigQueryOperator(BaseOperator):
<ide> """
<ide> Executes BigQuery SQL queries in a specific BigQuery database
<ide> """
<ide>
<ide> template_fields = ('bql',)
<ide> template_ext = ('.sql',)
<del> ui_color = '#b4e0ff'
<add> ui_color = '#e4f0e8'
<ide>
<ide> @apply_defaults
<del> def __init__(self, bql, destination_dataset_table = False, bigquery_conn_id='bigquery_default', *args, **kwargs):
<add> def __init__(self, bql, destination_dataset_table = False, write_disposition = 'WRITE_EMPTY', bigquery_conn_id='bigquery_default', *args, **kwargs):
<ide> """
<ide> Create a new BigQueryOperator.
<ide>
<ide> def __init__(self, bql, destination_dataset_table = False, bigquery_conn_id='big
<ide> :param destination_dataset_table: A dotted dataset.table that, if set,
<ide> will store the results of the query.
<ide> :type destination_dataset_table: string
<del> :param bigquery_conn_id: reference to a specific Vertica database
<add> :param bigquery_conn_id: reference to a specific BigQuery hook.
<ide> :type bigquery_conn_id: string
<ide> """
<ide> super(BigQueryOperator, self).__init__(*args, **kwargs)
<ide><path>airflow/contrib/operators/bigquery_to_gcs.py
<add>import logging
<add>
<add>from airflow.contrib.hooks.bigquery_hook import BigQueryHook
<add>from airflow.models import BaseOperator
<add>from airflow.utils import apply_defaults
<add>
<add>class BigQueryToCloudStorageOperator(BaseOperator):
<add> """
<add> Executes BigQuery SQL queries in a specific BigQuery database
<add> """
<add>
<add> template_fields = ('source_dataset_table','destination_cloud_storage_uris',)
<add> template_ext = ('.sql',)
<add> ui_color = '#e4e6f0'
<add>
<add> @apply_defaults
<add> def __init__(
<add> self,
<add> source_dataset_table,
<add> destination_cloud_storage_uris,
<add> compression='NONE',
<add> export_format='CSV',
<add> field_delimiter=',',
<add> print_header=True,
<add> bigquery_conn_id='bigquery_default',
<add> *args,
<add> **kwargs):
<add> """
<add> Create a new BigQueryToCloudStorage to move data from BigQuery to
<add> Google Cloud Storage.
<add>
<add> TODO: more params to doc
<add> :param bigquery_conn_id: reference to a specific BigQuery hook.
<add> :type bigquery_conn_id: string
<add> """
<add> super(BigQueryToCloudStorageOperator, self).__init__(*args, **kwargs)
<add> self.source_dataset_table = source_dataset_table
<add> self.destination_cloud_storage_uris = destination_cloud_storage_uris
<add> self.compression = compression
<add> self.export_format = export_format
<add> self.field_delimiter = field_delimiter
<add> self.print_header = print_header
<add> self.bigquery_conn_id = bigquery_conn_id
<add>
<add> def execute(self, context):
<add> logging.info('Executing extract of %s into: %s', self.source_dataset_table, self.destination_cloud_storage_uris)
<add> hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id)
<add> hook.run_extract(
<add> self.source_dataset_table,
<add> self.destination_cloud_storage_uris,
<add> self.compression,
<add> self.export_format,
<add> self.field_delimiter,
<add> self.print_header)
| 3
|
Text
|
Text
|
remove reference to forum from readme.md
|
24884999321a00b140bc58271ddb503e1723c199
|
<ide><path>README.md
<ide> Free Code Camp!
<ide>
<ide> We're a community of busy people learning to code by collaborating on projects for nonprofits. We learn, then use, the JavaScript MEAN stack - MongoDB, Express.js, Angular.js and Node.js.
<ide>
<del>This app is live at [FreeCodeCamp.com](http://www.FreeCodeCamp.com), and we have a [chat room](https://gitter.im/FreeCodeCamp/FreeCodeCamp), [blog](http://blog.freecodecamp.com) and [forum](http://forum.freecodecamp.com), too. Join us!
<add>This app is live at [FreeCodeCamp.com](http://www.FreeCodeCamp.com), and we have a [chat room](https://gitter.im/FreeCodeCamp/FreeCodeCamp) and [blog](http://blog.freecodecamp.com), too. Join us!
<ide>
<ide> Prerequisites
<ide> -------------
| 1
|
PHP
|
PHP
|
remove type attributes from script and link tags
|
5c49e139f1d94cd0c24555a41975b8216b4f6cc8
|
<ide><path>src/View/Helper/HtmlHelper.php
<ide> class HtmlHelper extends Helper {
<ide> 'tagselfclosing' => '<{{tag}}{{attrs}}/>',
<ide> 'para' => '<p{{attrs}}>{{content}}</p>',
<ide> 'parastart' => '<p{{attrs}}>',
<del> 'css' => '<link rel="{{rel}}" type="text/css" href="{{url}}"{{attrs}}/>',
<add> 'css' => '<link rel="{{rel}}" href="{{url}}"{{attrs}}/>',
<ide> 'style' => '<style type="text/css"{{attrs}}>{{content}}</style>',
<ide> 'charset' => '<meta http-equiv="Content-Type" content="text/html; charset={{charset}}" />',
<ide> 'ul' => '<ul{{attrs}}>{{content}}</ul>',
<ide> 'ol' => '<ol{{attrs}}>{{content}}</ol>',
<ide> 'li' => '<li{{attrs}}>{{content}}</li>',
<ide> 'javascriptblock' => '<script{{attrs}}>{{content}}</script>',
<ide> 'javascriptstart' => '<script>',
<del> 'javascriptlink' => '<script type="text/javascript" src="{{url}}"{{attrs}}></script>',
<add> 'javascriptlink' => '<script src="{{url}}"{{attrs}}></script>',
<ide> 'javascriptend' => '</script>'
<ide> ];
<ide>
<ide> public function script($url, $options = array()) {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#HtmlHelper::scriptBlock
<ide> */
<ide> public function scriptBlock($script, $options = array()) {
<del> $options += array('type' => 'text/javascript', 'safe' => true, 'inline' => true);
<add> $options += array('safe' => true, 'inline' => true);
<ide> if ($options['safe']) {
<ide> $script = "\n" . '//<![CDATA[' . "\n" . $script . "\n" . '//]]>' . "\n";
<ide> }
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testThemeAssetsInMainWebrootPath() {
<ide> $this->Html->theme = 'test_theme';
<ide> $result = $this->Html->css('webroot_test');
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'preg:/.*theme\/test_theme\/css\/webroot_test\.css/')
<add> 'link' => array('rel' => 'stylesheet', 'href' => 'preg:/.*theme\/test_theme\/css\/webroot_test\.css/')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $this->Html->theme = 'test_theme';
<ide> $result = $this->Html->css('theme_webroot');
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'preg:/.*theme\/test_theme\/css\/theme_webroot\.css/')
<add> 'link' => array('rel' => 'stylesheet', 'href' => 'preg:/.*theme\/test_theme\/css\/theme_webroot\.css/')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> }
<ide> public function testStyle() {
<ide> public function testCssLink() {
<ide> $result = $this->Html->css('screen');
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'preg:/.*css\/screen\.css/')
<add> 'link' => array('rel' => 'stylesheet', 'href' => 'preg:/.*css\/screen\.css/')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> public function testCssLinkBC() {
<ide> $expected = array(
<ide> 'link' => array(
<ide> 'rel' => 'stylesheet',
<del> 'type' => 'text/css',
<ide> 'href' => 'preg:/.*css\/TestPlugin\.style\.css/'
<ide> )
<ide> );
<ide> public function testCssWithFullBase() {
<ide>
<ide> $result = $this->Html->css('screen', null, array('fullBase' => true));
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => $here . 'css/screen.css')
<add> 'link' => array('rel' => 'stylesheet', 'href' => $here . 'css/screen.css')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> }
<ide> public function testPluginCssLink() {
<ide>
<ide> $result = $this->Html->css('TestPlugin.test_plugin_asset');
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => 'preg:/.*test_plugin\/css\/test_plugin_asset\.css/')
<add> 'link' => array('rel' => 'stylesheet', 'href' => 'preg:/.*test_plugin\/css\/test_plugin_asset\.css/')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> public function testCssTimestamping() {
<ide> Configure::write('Asset.timestamp', true);
<ide>
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => '')
<add> 'link' => array('rel' => 'stylesheet', 'href' => '')
<ide> );
<ide>
<ide> $result = $this->Html->css('cake.generic');
<ide> public function testPluginCssTimestamping() {
<ide> Configure::write('Asset.timestamp', true);
<ide>
<ide> $expected = array(
<del> 'link' => array('rel' => 'stylesheet', 'type' => 'text/css', 'href' => '')
<add> 'link' => array('rel' => 'stylesheet', 'href' => '')
<ide> );
<ide>
<ide> $result = $this->Html->css('TestPlugin.test_plugin_asset');
<ide> public function testPluginScriptTimestamping() {
<ide> public function testScript() {
<ide> $result = $this->Html->script('foo');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'js/foo.js')
<add> 'script' => array('src' => 'js/foo.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script(array('foobar', 'bar'));
<ide> $expected = array(
<del> array('script' => array('type' => 'text/javascript', 'src' => 'js/foobar.js')),
<add> array('script' => array('src' => 'js/foobar.js')),
<ide> '/script',
<del> array('script' => array('type' => 'text/javascript', 'src' => 'js/bar.js')),
<add> array('script' => array('src' => 'js/bar.js')),
<ide> '/script',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('jquery-1.3');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'js/jquery-1.3.js')
<add> 'script' => array('src' => 'js/jquery-1.3.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('test.json');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'js/test.json.js')
<add> 'script' => array('src' => 'js/test.json.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('http://example.com/test.json');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'http://example.com/test.json')
<add> 'script' => array('src' => 'http://example.com/test.json')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('/plugin/js/jquery-1.3.2.js?someparam=foo');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => '/plugin/js/jquery-1.3.2.js?someparam=foo')
<add> 'script' => array('src' => '/plugin/js/jquery-1.3.2.js?someparam=foo')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('test.json.js?foo=bar');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'js/test.json.js?foo=bar')
<add> 'script' => array('src' => 'js/test.json.js?foo=bar')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('test.json.js?foo=bar&other=test');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'js/test.json.js?foo=bar&other=test')
<add> 'script' => array('src' => 'js/test.json.js?foo=bar&other=test')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('foo2', array('pathPrefix' => '/my/custom/path/'));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => '/my/custom/path/foo2.js')
<add> 'script' => array('src' => '/my/custom/path/foo2.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('foo3', array('pathPrefix' => 'http://cakephp.org/assets/js/'));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'http://cakephp.org/assets/js/foo3.js')
<add> 'script' => array('src' => 'http://cakephp.org/assets/js/foo3.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $previousConfig = Configure::read('App.jsBaseUrl');
<ide> Configure::write('App.jsBaseUrl', '//cdn.cakephp.org/js/');
<ide> $result = $this->Html->script('foo4');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => '//cdn.cakephp.org/js/foo4.js')
<add> 'script' => array('src' => '//cdn.cakephp.org/js/foo4.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> Configure::write('App.jsBaseUrl', $previousConfig);
<ide> public function testScript() {
<ide>
<ide> $result = $this->Html->script('jquery-1.3.2', array('defer' => true, 'encoding' => 'utf-8'));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'js/jquery-1.3.2.js', 'defer' => 'defer', 'encoding' => 'utf-8')
<add> 'script' => array('src' => 'js/jquery-1.3.2.js', 'defer' => 'defer', 'encoding' => 'utf-8')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> }
<ide> public function testPluginScript() {
<ide>
<ide> $result = $this->Html->script('TestPlugin.foo');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/foo.js')
<add> 'script' => array('src' => 'test_plugin/js/foo.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script(array('TestPlugin.foobar', 'TestPlugin.bar'));
<ide> $expected = array(
<del> array('script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/foobar.js')),
<add> array('script' => array('src' => 'test_plugin/js/foobar.js')),
<ide> '/script',
<del> array('script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/bar.js')),
<add> array('script' => array('src' => 'test_plugin/js/bar.js')),
<ide> '/script',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('TestPlugin.jquery-1.3');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/jquery-1.3.js')
<add> 'script' => array('src' => 'test_plugin/js/jquery-1.3.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('TestPlugin.test.json');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/test.json.js')
<add> 'script' => array('src' => 'test_plugin/js/test.json.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('TestPlugin./jquery-1.3.2.js?someparam=foo');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'test_plugin/jquery-1.3.2.js?someparam=foo')
<add> 'script' => array('src' => 'test_plugin/jquery-1.3.2.js?someparam=foo')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script('TestPlugin.test.json.js?foo=bar');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/test.json.js?foo=bar')
<add> 'script' => array('src' => 'test_plugin/js/test.json.js?foo=bar')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> public function testPluginScript() {
<ide>
<ide> $result = $this->Html->script('TestPlugin.jquery-1.3.2', array('defer' => true, 'encoding' => 'utf-8'));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => 'test_plugin/js/jquery-1.3.2.js', 'defer' => 'defer', 'encoding' => 'utf-8')
<add> 'script' => array('src' => 'test_plugin/js/jquery-1.3.2.js', 'defer' => 'defer', 'encoding' => 'utf-8')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> public function testScriptWithFullBase() {
<ide>
<ide> $result = $this->Html->script('foo', array('fullBase' => true));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'src' => $here . 'js/foo.js')
<add> 'script' => array('src' => $here . 'js/foo.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->script(array('foobar', 'bar'), array('fullBase' => true));
<ide> $expected = array(
<del> array('script' => array('type' => 'text/javascript', 'src' => $here . 'js/foobar.js')),
<add> array('script' => array('src' => $here . 'js/foobar.js')),
<ide> '/script',
<del> array('script' => array('type' => 'text/javascript', 'src' => $here . 'js/bar.js')),
<add> array('script' => array('src' => $here . 'js/bar.js')),
<ide> '/script',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testScriptInTheme() {
<ide> $this->Html->theme = 'test_theme';
<ide> $result = $this->Html->script('__test_js.js');
<ide> $expected = array(
<del> 'script' => array('src' => '/theme/test_theme/js/__test_js.js', 'type' => 'text/javascript')
<add> 'script' => array('src' => '/theme/test_theme/js/__test_js.js')
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> }
<ide> public function testScriptInTheme() {
<ide> public function testScriptBlock() {
<ide> $result = $this->Html->scriptBlock('window.foo = 2;');
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript'),
<add> '<script',
<ide> $this->cDataStart,
<ide> 'window.foo = 2;',
<ide> $this->cDataEnd,
<ide> public function testScriptBlock() {
<ide>
<ide> $result = $this->Html->scriptBlock('window.foo = 2;', array('safe' => false));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript'),
<add> '<script',
<ide> 'window.foo = 2;',
<ide> '/script',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Html->scriptBlock('window.foo = 2;', array('safe' => true));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript'),
<add> '<script',
<ide> $this->cDataStart,
<ide> 'window.foo = 2;',
<ide> $this->cDataEnd,
<ide> public function testScriptBlock() {
<ide>
<ide> $result = $this->Html->scriptBlock('window.foo = 2;', array('safe' => false, 'encoding' => 'utf-8'));
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript', 'encoding' => 'utf-8'),
<add> 'script' => array('encoding' => 'utf-8'),
<ide> 'window.foo = 2;',
<ide> '/script',
<ide> );
<ide> public function testScriptStartAndScriptEnd() {
<ide>
<ide> $result = $this->Html->scriptEnd();
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript'),
<add> '<script',
<ide> $this->cDataStart,
<ide> 'this is some javascript',
<ide> $this->cDataEnd,
<ide> public function testScriptStartAndScriptEnd() {
<ide>
<ide> $result = $this->Html->scriptEnd();
<ide> $expected = array(
<del> 'script' => array('type' => 'text/javascript'),
<add> '<script',
<ide> 'this is some javascript',
<ide> '/script'
<ide> );
| 2
|
Python
|
Python
|
add warning message to np.npv docs
|
58dc45505b3d3e2b9de1a6961a749c8bd1165548
|
<ide><path>numpy/lib/financial.py
<ide> def npv(rate, values):
<ide> The NPV of the input cash flow series `values` at the discount
<ide> `rate`.
<ide>
<add> Warnings
<add> --------
<add> ``npv`` considers a series of cashflows starting in the present (t = 0).
<add> NPV can also be defined with a series of future cashflows, paid at the
<add> end, rather than the start, of each period. If future cashflows are used,
<add> the first cashflow `values[0]` must be zeroed and added to the net
<add> present value of the future cashflows. This is demonstrated in the
<add> examples.
<add>
<ide> Notes
<ide> -----
<ide> Returns the result of: [G]_
<ide> def npv(rate, values):
<ide>
<ide> (Compare with the Example given for numpy.lib.financial.irr)
<ide>
<add> Consider a potential project with an initial investment of $40 000 and
<add> projected cashflows of $5 000, $8 000, $12 000 and $30 000 at the end of
<add> each period discounted at a rate of 8% per period. To find the project's
<add> net present value:
<add>
<add> >>> rate, cashflows = 0.08, [-40_000, 5_000, 8_000, 12_000, 30_000]
<add> >>> np.npv(rate, cashflows).round(5)
<add> 3065.22267
<add>
<add> It may be preferable to split the projected cashflow into an initial
<add> investment and expected future cashflows. In this case, the value of
<add> the initial cashflow is zero and the initial investment is later added
<add> to the future cashflows net present value:
<add>
<add> >>> initial_cashflow = cashflows[0]
<add> >>> cashflows[0] = 0
<add> >>> np.round(np.npv(rate, cashflows) + initial_cashflow, 5)
<add> 3065.22267
<add>
<ide> """
<ide> values = np.asarray(values)
<ide> return (values / (1+rate)**np.arange(0, len(values))).sum(axis=0)
| 1
|
Java
|
Java
|
fix checkstyle violation
|
facdbdb7b62f6b62011934a758e29c5481af4a0b
|
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/server/support/WebSocketHttpRequestHandlerTests.java
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.verify;
<ide> import static org.mockito.Mockito.verifyNoMoreInteractions;
<del>import static org.mockito.Mockito.when;
<ide>
<ide> /**
<ide> * Unit tests for {@link WebSocketHttpRequestHandler}.
| 1
|
Java
|
Java
|
use stream#toarray in testcompiler
|
b6c463676afac813d078681a6b5ab48cf24b8c39
|
<ide><path>spring-context-indexer/src/test/java/org/springframework/context/index/test/TestCompiler.java
<ide> public TestCompiler(JavaCompiler compiler, Path tempDir) throws IOException {
<ide>
<ide>
<ide> public TestCompilationTask getTask(Class<?>... types) {
<del> List<String> names = Arrays.stream(types).map(Class::getName).collect(Collectors.toList());
<del> return getTask(names.toArray(new String[names.size()]));
<add> return getTask(Arrays.stream(types).map(Class::getName).toArray(String[]::new));
<ide> }
<ide>
<ide> public TestCompilationTask getTask(String... types) {
| 1
|
Ruby
|
Ruby
|
update virtualenv to 16.0.0
|
db56b1add5eddfe1413b3d8828635757a977ea39
|
<ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<del>PYTHON_VIRTUALENV_URL = "https://files.pythonhosted.org/packages/b1/72/2d70c5a1de409ceb3a27ff2ec007ecdd5cc52239e7c74990e32af57affe9/virtualenv-15.2.0.tar.gz".freeze
<del>PYTHON_VIRTUALENV_SHA256 = "1d7e241b431e7afce47e77f8843a276f652699d1fa4f93b9d8ce0076fd7b0b54".freeze
<add>PYTHON_VIRTUALENV_URL = "https://files.pythonhosted.org/packages/33/bc/fa0b5347139cd9564f0d44ebd2b147ac97c36b2403943dbee8a25fd74012/virtualenv-16.0.0.tar.gz".freeze
<add>PYTHON_VIRTUALENV_SHA256 = "ca07b4c0b54e14a91af9f34d0919790b016923d157afda5efdde55c96718f752".freeze
| 1
|
Text
|
Text
|
add 2.17.0-beta.2 to changelog
|
8bfa2013de2c15108b123f41b6a407a56f64108e
|
<ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.17.0-beta.2 (October 17, 2017)
<add>- [#15613](https://github.com/emberjs/ember.js/pull/15613) [BUGFIX] Don't throw an error, when not all query params are passed to routerService.transitionTo
<add>- [#15707](https://github.com/emberjs/ember.js/pull/15707) [BUGFIX] Fix `canInvoke` for edge cases
<add>- [#15722](https://github.com/emberjs/ember.js/pull/15722) [BUGFIX] empty path in `get` helper should not throw assertion
<add>- [#15733](https://github.com/emberjs/ember.js/pull/15733) [BUGFIX] Fix computed sort regression when array prop initially null
<add>
<ide> ### 2.17.0-beta.1 (October 9, 2017)
<ide>
<ide> - [#15265](https://github.com/emberjs/ember.js/pull/15265) [BUGFIX] fixed issue when passing `false` to `activeClass` for `{{link-to}}`
| 1
|
PHP
|
PHP
|
fix missed case for midnight in 12 hour format
|
27eb5e0291da6cd915a661746ffbd3f392e33a52
|
<ide><path>src/View/Widget/DateTime.php
<ide> protected function _hourSelect($options = []) {
<ide> $is24 = $options['format'] == 24;
<ide>
<ide> $defaultEnd = $is24 ? 24 : 12;
<del>
<ide> $options['start'] = max(1, $options['start']);
<ide>
<ide> $options['end'] = min($defaultEnd, $options['end']);
<ide> protected function _hourSelect($options = []) {
<ide> if (!$is24 && $options['val'] > 12) {
<ide> $options['val'] = sprintf('%02d', $options['val'] - 12);
<ide> }
<add> if (!$is24 && $options['val'] == 0) {
<add> $options['val'] = 12;
<add> }
<ide>
<ide> if (empty($options['options'])) {
<ide> $options['options'] = $this->_generateNumbers(
<ide><path>tests/TestCase/View/Widget/DateTimeTest.php
<ide> public function testRenderHourWidget12() {
<ide> $this->assertContains('<option value="pm" selected="selected">pm</option>', $result);
<ide> }
<ide>
<add>/**
<add> * Test rendering hour widget in 12 hour mode at midnight.
<add> *
<add> * @return void
<add> */
<add> public function testRenderHourWidget12Midnight() {
<add> $now = new \DateTime('2010-09-09 00:30:45');
<add> $result = $this->DateTime->render([
<add> 'name' => 'date',
<add> 'year' => false,
<add> 'month' => false,
<add> 'day' => false,
<add> 'hour' => [
<add> 'format' => 12,
<add> ],
<add> 'minute' => false,
<add> 'second' => false,
<add> 'val' => $now,
<add> ]);
<add> $this->assertContains(
<add> '<option value="12" selected="selected">12</option>',
<add> $result,
<add> '12 is selected'
<add> );
<add> }
<add>
<ide> /**
<ide> * Test rendering the hour picker in 12 hour mode.
<ide> *
| 2
|
Ruby
|
Ruby
|
handle id attribute in primarykey module
|
d7942d4230e7cfa0c0c7c96c9a10dee49f612155
|
<ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def arel_attributes_values(include_primary_key = true, include_readonly_attribut
<ide> end
<ide>
<ide> def attribute_method?(attr_name)
<del> attr_name == 'id' || (defined?(@attributes) && @attributes.include?(attr_name))
<add> defined?(@attributes) && @attributes.include?(attr_name)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/attribute_methods/primary_key.rb
<ide> def id?
<ide> query_attribute(self.class.primary_key)
<ide> end
<ide>
<add> protected
<add>
<add> def attribute_method?(attr_name)
<add> attr_name == 'id' || super
<add> end
<add>
<ide> module ClassMethods
<ide> def define_method_attribute(attr_name)
<ide> super
| 2
|
Python
|
Python
|
add namespaces to digitize tests + one more test
|
54746848f313ba1ee22a812e8b500d4bcc334910
|
<ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_basic(self):
<ide>
<ide> tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)
<ide> assert_array_equal(np.cumsum(a, axis=0), tgt)
<del>
<add>
<ide> tgt = np.array([[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)
<ide> assert_array_equal(np.cumsum(a2, axis=0), tgt)
<del>
<add>
<ide> tgt = np.array([[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)
<ide> assert_array_equal(np.cumsum(a2, axis=1), tgt)
<ide>
<ide> def test_random(self):
<ide> bin = np.linspace(x.min(), x.max(), 10)
<ide> assert_(np.all(digitize(x, bin) != 0))
<ide>
<add> def test_right_basic(self):
<add> x = [1,5,4,10,8,11,0]
<add> bins = [1,5,10]
<add> default_answer = [1,2,1,3,2,3,0]
<add> assert_array_equal(digitize(x, bins), default_answer)
<add> right_answer = [0,1,1,2,2,3,0]
<add> assert_array_equal(digitize(x, bins, True), right_answer)
<add>
<ide> def test_right_open(self):
<del> x = arange(-6, 5)
<del> bins = arange(-6, 4)
<del> assert_array_equal(digitize(x,bins,True), arange(11))
<add> x = np.arange(-6, 5)
<add> bins = np.arange(-6, 4)
<add> assert_array_equal(digitize(x,bins,True), np.arange(11))
<ide>
<ide> def test_right_open_reverse(self):
<del> x = arange(5, -6, -1)
<del> bins = arange(4, -6, -1)
<del> assert_array_equal(digitize(x, bins, True), arange(11))
<add> x = np.arange(5, -6, -1)
<add> bins = np.arange(4, -6, -1)
<add> assert_array_equal(digitize(x, bins, True), np.arange(11))
<ide>
<ide> def test_right_open_random(self):
<ide> x = rand(10)
<del> bins = linspace(x.min(), x.max(), 10)
<add> bins = np.linspace(x.min(), x.max(), 10)
<ide> assert_(all(digitize(x, bins, True) != 10))
<ide>
<ide>
| 1
|
PHP
|
PHP
|
add type check before validating url
|
052e9a51bbbbbe3247d6e080bec2dc222faa3974
|
<ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php
<ide> protected function validateTimezone($attribute, $value)
<ide> */
<ide> protected function validateUrl($attribute, $value)
<ide> {
<add> if (! is_string($value)) {
<add> return false;
<add> }
<add>
<ide> /*
<ide> * This pattern is derived from Symfony\Component\Validator\Constraints\UrlValidator (2.7.4).
<ide> *
| 1
|
PHP
|
PHP
|
fix double semicolon
|
adcdb9abf287b7fdc418ef2b73daff367f654c11
|
<ide><path>src/Illuminate/Foundation/Providers/PublisherServiceProvider.php
<ide> protected function registerViewPublisher()
<ide>
<ide> $this->app->bindShared('view.publisher', function($app)
<ide> {
<del> $viewPath = $app['path.base'].'/resources/views';;
<add> $viewPath = $app['path.base'].'/resources/views';
<ide>
<ide> // Once we have created the view publisher, we will set the default packages
<ide> // path on this object so that it knows where to find all of the packages
| 1
|
PHP
|
PHP
|
use explicit flag as default sorting
|
3b515cea9cab30e2832ca7b7b9be7923d732cb5e
|
<ide><path>src/Illuminate/Collections/Collection.php
<ide> public function sort($callback = null)
<ide>
<ide> $callback && is_callable($callback)
<ide> ? uasort($items, $callback)
<del> : asort($items, $callback);
<add> : asort($items, $callback ?? SORT_REGULAR);
<ide>
<ide> return new static($items);
<ide> }
| 1
|
Javascript
|
Javascript
|
remove unneeded arguments checks
|
112af1e7ec00d88e4281ad71857d2dc7c83f7450
|
<ide><path>lib/BannerPlugin.js
<ide> const wrapComment = str => {
<ide> };
<ide>
<ide> class BannerPlugin {
<del> constructor(options) {
<del> if (arguments.length > 1) {
<del> throw new Error(
<del> "BannerPlugin only takes one argument (pass an options object)"
<del> );
<del> }
<del>
<add> constructor(options = {}) {
<ide> validateOptions(schema, options, "Banner Plugin");
<ide>
<ide> if (typeof options === "string" || typeof options === "function") {
<ide> class BannerPlugin {
<ide> };
<ide> }
<ide>
<del> this.options = options || {};
<add> this.options = options;
<ide>
<ide> if (typeof options.banner === "function") {
<ide> const getBanner = this.options.banner;
<ide><path>lib/EvalSourceMapDevToolPlugin.js
<ide> const EvalSourceMapDevToolModuleTemplatePlugin = require("./EvalSourceMapDevToolModuleTemplatePlugin");
<ide> const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
<ide>
<add>/** @typedef {import("./Compiler")} Compiler */
<add>
<ide> class EvalSourceMapDevToolPlugin {
<del> constructor(options) {
<del> if (arguments.length > 1) {
<del> throw new Error(
<del> "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)"
<del> );
<del> }
<add> /**
<add> * @param {TODO} options Options object
<add> */
<add> constructor(options = {}) {
<ide> if (typeof options === "string") {
<ide> options = {
<ide> append: options
<ide> };
<ide> }
<del> if (!options) options = {};
<ide> this.options = options;
<ide> }
<ide>
<add> /**
<add> * @param {Compiler} compiler Webpack Compiler
<add> * @returns {void}
<add> */
<ide> apply(compiler) {
<ide> const options = this.options;
<ide> compiler.hooks.compilation.tap(
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> const getTaskForFile = (file, chunk, options, compilation) => {
<ide> };
<ide>
<ide> class SourceMapDevToolPlugin {
<del> constructor(options) {
<del> if (arguments.length > 1) {
<del> throw new Error(
<del> "SourceMapDevToolPlugin only takes one argument (pass an options object)"
<del> );
<del> }
<del>
<del> validateOptions(schema, options || {}, "SourceMap DevTool Plugin");
<add> constructor(options = {}) {
<add> validateOptions(schema, options, "SourceMap DevTool Plugin");
<ide>
<del> if (!options) options = {};
<ide> this.sourceMapFilename = options.filename;
<ide> this.sourceMappingURLComment =
<ide> options.append === false
| 3
|
Go
|
Go
|
add unit tests for remote api
|
ede0793d94e0bafcddc65b1fcb683169accffea3
|
<ide><path>api_test.go
<ide> func TestInfo(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>// func TestHistory(t *testing.T) {
<del>// runtime, err := newTestRuntime()
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// defer nuke(runtime)
<del>
<del>// srv := &Server{runtime: runtime}
<del>
<del>// req, err := http.NewRequest("GET", "/images/"+unitTestImageName+"/history", nil)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>
<del>// router := mux.NewRouter()
<del>// router.Path("/images/{name:.*}/history")
<del>// vars := mux.Vars(req)
<del>// router.
<del>// vars["name"] = unitTestImageName
<del>
<del>// body, err := getImagesHistory(srv, nil, req)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// var outs []ApiHistory
<del>// err = json.Unmarshal(body, &outs)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// if len(outs) != 1 {
<del>// t.Errorf("Excepted 1 line, %d found", len(outs))
<del>// }
<del>// }
<del>
<del>// func TestImagesSearch(t *testing.T) {
<del>// body, _, err := call("GET", "/images/search?term=redis", nil)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// var outs []ApiSearch
<del>// err = json.Unmarshal(body, &outs)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// if len(outs) < 2 {
<del>// t.Errorf("Excepted at least 2 lines, %d found", len(outs))
<del>// }
<del>// }
<del>
<del>// func TestGetImage(t *testing.T) {
<del>// obj, _, err := call("GET", "/images/"+unitTestImageName+"/json", nil)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// var out Image
<del>// err = json.Unmarshal(obj, &out)
<del>// if err != nil {
<del>// t.Fatal(err)
<del>// }
<del>// if out.Comment != "Imported from http://get.docker.io/images/busybox" {
<del>// t.Errorf("Error inspecting image")
<del>// }
<del>// }
<add>func TestHistory(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<add>
<add> srv := &Server{runtime: runtime}
<add>
<add> body, err := getImagesHistory(srv, nil, nil, map[string]string{"name": unitTestImageName})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> history := []ApiHistory{}
<add>
<add> err = json.Unmarshal(body, &history)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(history) != 1 {
<add> t.Errorf("Excepted 1 line, %d found", len(history))
<add> }
<add>}
<add>
<add>func TestImagesSearch(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<add>
<add> srv := &Server{runtime: runtime}
<add>
<add> req, err := http.NewRequest("GET", "/images/search?term=redis", nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> body, err := getImagesSearch(srv, nil, req, nil)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> results := []ApiSearch{}
<add>
<add> err = json.Unmarshal(body, &results)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(results) < 2 {
<add> t.Errorf("Excepted at least 2 lines, %d found", len(results))
<add> }
<add>}
<add>
<add>func TestGetImage(t *testing.T) {
<add> runtime, err := newTestRuntime()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer nuke(runtime)
<add>
<add> srv := &Server{runtime: runtime}
<add>
<add> body, err := getImagesByName(srv, nil, nil, map[string]string{"name": unitTestImageName})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> img := &Image{}
<add>
<add> err = json.Unmarshal(body, img)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if img.Comment != "Imported from http://get.docker.io/images/busybox" {
<add> t.Errorf("Error inspecting image")
<add> }
<add>}
<ide>
<ide> func TestCreateListStartStopRestartKillWaitDelete(t *testing.T) {
<ide>
| 1
|
Javascript
|
Javascript
|
improve dev and beginner experience
|
19ebc0dda52ff6b6a6f7e11a3dc181262cddb804
|
<ide><path>build/grunt.js
<ide> module.exports = function(grunt) {
<ide> }
<ide> },
<ide> babel: {
<del> command: 'npm run babel -- --watch',
<add> command: 'npm run babel -- --watch --quiet',
<ide> options: {
<ide> preferLocal: true
<ide> }
<ide> module.exports = function(grunt) {
<ide> });
<ide>
<ide> // Run while developing
<del> grunt.registerTask('dev', ['connect:dev', 'concurrent:dev']);
<add> grunt.registerTask('dev', ['sandbox', 'connect:dev', 'concurrent:dev']);
<ide> grunt.registerTask('watchAll', ['build', 'connect:dev', 'concurrent:watchAll']);
<ide> grunt.registerTask('test-a11y', ['copy:a11y', 'accessibility']);
<ide>
<ide><path>build/rollup.js
<ide> const args = minimist(process.argv.slice(2), {
<ide> }
<ide> });
<ide>
<add>if (args.watch) {
<add> args.progress = false;
<add>}
<add>
<ide> const compiledLicense = _.template(fs.readFileSync('./build/license-header.txt', 'utf8'));
<ide> const bannerData = _.pick(pkg, ['version', 'copyright']);
<ide>
<ide><path>build/tasks/sandbox.js
<add>const fs = require('fs');
<add>const path = require('path');
<add>const klawSync = require('klaw-sync');
<add>
<add>module.exports = function(grunt) {
<add> grunt.registerTask('sandbox', 'copy over sandbox example files if necessary', function() {
<add> const files = klawSync('sandbox/').filter((file) => path.extname(file.path) === '.example');
<add>
<add> const changes = files.map(function(file) {
<add> const p = path.parse(file.path);
<add> const nonExample = path.join(p.dir, p.name);
<add> return {
<add> file: file.path,
<add> copy: nonExample
<add> };
<add> })
<add> .filter(function(change) {
<add> return !fs.existsSync(change.copy);
<add> });
<add>
<add> changes.forEach(function(change) {
<add> grunt.file.copy(change.file, change.copy);
<add> });
<add>
<add> if (changes.length) {
<add> grunt.log.writeln("Updated Sandbox files for:");
<add> grunt.log.writeln('\t' + changes.map((chg) => chg.copy).join('\n\t'));
<add> } else {
<add> grunt.log.writeln("No sandbox updates necessary");
<add> }
<add>
<add> });
<add>};
| 3
|
Javascript
|
Javascript
|
add test for handling of null env load setting
|
6bbe60ab712bb47d7a717b8ba01f5ead618e7863
|
<ide><path>spec/environment-helpers-spec.js
<ide> describe('updateProcessEnv(launchEnv)', function () {
<ide> TERM: 'xterm-something',
<ide> PATH: '/usr/bin:/bin:/usr/sbin:/sbin:/crazy/path'
<ide> })
<add>
<add> // Doesn't error
<add> updateProcessEnv(null)
<ide> })
<ide> })
<ide>
| 1
|
Javascript
|
Javascript
|
convert layout phase to depth-first traversal
|
6132919bf2b8851382547b34a442e7e0c09c5697
|
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js
<ide> import {
<ide> ChildDeletion,
<ide> Snapshot,
<ide> Update,
<add> Callback,
<add> Ref,
<ide> Passive,
<ide> PassiveMask,
<add> LayoutMask,
<ide> PassiveUnmountPendingDev,
<ide> } from './ReactFiberFlags';
<ide> import getComponentName from 'shared/getComponentName';
<ide> export function commitPassiveEffectDurations(
<ide> }
<ide> }
<ide>
<del>function commitLifeCycles(
<add>function commitLayoutEffectOnFiber(
<ide> finishedRoot: FiberRoot,
<ide> current: Fiber | null,
<ide> finishedWork: Fiber,
<ide> committedLanes: Lanes,
<ide> ): void {
<del> switch (finishedWork.tag) {
<del> case FunctionComponent:
<del> case ForwardRef:
<del> case SimpleMemoComponent: {
<del> // At this point layout effects have already been destroyed (during mutation phase).
<del> // This is done to prevent sibling component effects from interfering with each other,
<del> // e.g. a destroy function in one component should never override a ref set
<del> // by a create function in another component during the same commit.
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<add> if ((finishedWork.flags & (Update | Callback)) !== NoFlags) {
<add> switch (finishedWork.tag) {
<add> case FunctionComponent:
<add> case ForwardRef:
<add> case SimpleMemoComponent: {
<add> // At this point layout effects have already been destroyed (during mutation phase).
<add> // This is done to prevent sibling component effects from interfering with each other,
<add> // e.g. a destroy function in one component should never override a ref set
<add> // by a create function in another component during the same commit.
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<add> } finally {
<add> recordLayoutEffectDuration(finishedWork);
<add> }
<add> } else {
<ide> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<del> } finally {
<del> recordLayoutEffectDuration(finishedWork);
<ide> }
<del> } else {
<del> commitHookEffectListMount(HookLayout | HookHasEffect, finishedWork);
<del> }
<ide>
<del> schedulePassiveEffects(finishedWork);
<del> return;
<del> }
<del> case ClassComponent: {
<del> const instance = finishedWork.stateNode;
<del> if (finishedWork.flags & Update) {
<del> if (current === null) {
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> if (__DEV__) {
<add> schedulePassiveEffects(finishedWork);
<add> break;
<add> }
<add> case ClassComponent: {
<add> const instance = finishedWork.stateNode;
<add> if (finishedWork.flags & Update) {
<add> if (current === null) {
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'componentDidMount. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentName(finishedWork.type) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'componentDidMount. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentName(finishedWork.type) || 'instance',
<add> );
<add> }
<add> }
<add> }
<ide> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<ide> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'componentDidMount. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentName(finishedWork.type) || 'instance',
<del> );
<add> try {
<add> startLayoutEffectTimer();
<add> instance.componentDidMount();
<add> } finally {
<add> recordLayoutEffectDuration(finishedWork);
<ide> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'componentDidMount. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentName(finishedWork.type) || 'instance',
<del> );
<del> }
<del> }
<del> }
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<add> } else {
<ide> instance.componentDidMount();
<del> } finally {
<del> recordLayoutEffectDuration(finishedWork);
<ide> }
<ide> } else {
<del> instance.componentDidMount();
<add> const prevProps =
<add> finishedWork.elementType === finishedWork.type
<add> ? current.memoizedProps
<add> : resolveDefaultProps(finishedWork.type, current.memoizedProps);
<add> const prevState = current.memoizedState;
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> if (__DEV__) {
<add> if (
<add> finishedWork.type === finishedWork.elementType &&
<add> !didWarnAboutReassigningProps
<add> ) {
<add> if (instance.props !== finishedWork.memoizedProps) {
<add> console.error(
<add> 'Expected %s props to match memoized props before ' +
<add> 'componentDidUpdate. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.props`. ' +
<add> 'Please file an issue.',
<add> getComponentName(finishedWork.type) || 'instance',
<add> );
<add> }
<add> if (instance.state !== finishedWork.memoizedState) {
<add> console.error(
<add> 'Expected %s state to match memoized state before ' +
<add> 'componentDidUpdate. ' +
<add> 'This might either be because of a bug in React, or because ' +
<add> 'a component reassigns its own `this.state`. ' +
<add> 'Please file an issue.',
<add> getComponentName(finishedWork.type) || 'instance',
<add> );
<add> }
<add> }
<add> }
<add> if (
<add> enableProfilerTimer &&
<add> enableProfilerCommitHooks &&
<add> finishedWork.mode & ProfileMode
<add> ) {
<add> try {
<add> startLayoutEffectTimer();
<add> instance.componentDidUpdate(
<add> prevProps,
<add> prevState,
<add> instance.__reactInternalSnapshotBeforeUpdate,
<add> );
<add> } finally {
<add> recordLayoutEffectDuration(finishedWork);
<add> }
<add> } else {
<add> instance.componentDidUpdate(
<add> prevProps,
<add> prevState,
<add> instance.__reactInternalSnapshotBeforeUpdate,
<add> );
<add> }
<ide> }
<del> } else {
<del> const prevProps =
<del> finishedWork.elementType === finishedWork.type
<del> ? current.memoizedProps
<del> : resolveDefaultProps(finishedWork.type, current.memoizedProps);
<del> const prevState = current.memoizedState;
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<add> }
<add>
<add> // TODO: I think this is now always non-null by the time it reaches the
<add> // commit phase. Consider removing the type check.
<add> const updateQueue: UpdateQueue<
<add> *,
<add> > | null = (finishedWork.updateQueue: any);
<add> if (updateQueue !== null) {
<ide> if (__DEV__) {
<ide> if (
<ide> finishedWork.type === finishedWork.elementType &&
<ide> function commitLifeCycles(
<ide> if (instance.props !== finishedWork.memoizedProps) {
<ide> console.error(
<ide> 'Expected %s props to match memoized props before ' +
<del> 'componentDidUpdate. ' +
<add> 'processing the update queue. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> 'a component reassigns its own `this.props`. ' +
<ide> 'Please file an issue.',
<ide> function commitLifeCycles(
<ide> if (instance.state !== finishedWork.memoizedState) {
<ide> console.error(
<ide> 'Expected %s state to match memoized state before ' +
<del> 'componentDidUpdate. ' +
<add> 'processing the update queue. ' +
<ide> 'This might either be because of a bug in React, or because ' +
<ide> 'a component reassigns its own `this.state`. ' +
<ide> 'Please file an issue.',
<ide> function commitLifeCycles(
<ide> }
<ide> }
<ide> }
<del> if (
<del> enableProfilerTimer &&
<del> enableProfilerCommitHooks &&
<del> finishedWork.mode & ProfileMode
<del> ) {
<del> try {
<del> startLayoutEffectTimer();
<del> instance.componentDidUpdate(
<del> prevProps,
<del> prevState,
<del> instance.__reactInternalSnapshotBeforeUpdate,
<del> );
<del> } finally {
<del> recordLayoutEffectDuration(finishedWork);
<del> }
<del> } else {
<del> instance.componentDidUpdate(
<del> prevProps,
<del> prevState,
<del> instance.__reactInternalSnapshotBeforeUpdate,
<del> );
<del> }
<add> // We could update instance props and state here,
<add> // but instead we rely on them being set during last render.
<add> // TODO: revisit this when we implement resuming.
<add> commitUpdateQueue(finishedWork, updateQueue, instance);
<ide> }
<add> break;
<ide> }
<del>
<del> // TODO: I think this is now always non-null by the time it reaches the
<del> // commit phase. Consider removing the type check.
<del> const updateQueue: UpdateQueue<
<del> *,
<del> > | null = (finishedWork.updateQueue: any);
<del> if (updateQueue !== null) {
<del> if (__DEV__) {
<del> if (
<del> finishedWork.type === finishedWork.elementType &&
<del> !didWarnAboutReassigningProps
<del> ) {
<del> if (instance.props !== finishedWork.memoizedProps) {
<del> console.error(
<del> 'Expected %s props to match memoized props before ' +
<del> 'processing the update queue. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.props`. ' +
<del> 'Please file an issue.',
<del> getComponentName(finishedWork.type) || 'instance',
<del> );
<del> }
<del> if (instance.state !== finishedWork.memoizedState) {
<del> console.error(
<del> 'Expected %s state to match memoized state before ' +
<del> 'processing the update queue. ' +
<del> 'This might either be because of a bug in React, or because ' +
<del> 'a component reassigns its own `this.state`. ' +
<del> 'Please file an issue.',
<del> getComponentName(finishedWork.type) || 'instance',
<del> );
<add> case HostRoot: {
<add> // TODO: I think this is now always non-null by the time it reaches the
<add> // commit phase. Consider removing the type check.
<add> const updateQueue: UpdateQueue<
<add> *,
<add> > | null = (finishedWork.updateQueue: any);
<add> if (updateQueue !== null) {
<add> let instance = null;
<add> if (finishedWork.child !== null) {
<add> switch (finishedWork.child.tag) {
<add> case HostComponent:
<add> instance = getPublicInstance(finishedWork.child.stateNode);
<add> break;
<add> case ClassComponent:
<add> instance = finishedWork.child.stateNode;
<add> break;
<ide> }
<ide> }
<add> commitUpdateQueue(finishedWork, updateQueue, instance);
<ide> }
<del> // We could update instance props and state here,
<del> // but instead we rely on them being set during last render.
<del> // TODO: revisit this when we implement resuming.
<del> commitUpdateQueue(finishedWork, updateQueue, instance);
<add> break;
<ide> }
<del> return;
<del> }
<del> case HostRoot: {
<del> // TODO: I think this is now always non-null by the time it reaches the
<del> // commit phase. Consider removing the type check.
<del> const updateQueue: UpdateQueue<
<del> *,
<del> > | null = (finishedWork.updateQueue: any);
<del> if (updateQueue !== null) {
<del> let instance = null;
<del> if (finishedWork.child !== null) {
<del> switch (finishedWork.child.tag) {
<del> case HostComponent:
<del> instance = getPublicInstance(finishedWork.child.stateNode);
<del> break;
<del> case ClassComponent:
<del> instance = finishedWork.child.stateNode;
<del> break;
<del> }
<add> case HostComponent: {
<add> const instance: Instance = finishedWork.stateNode;
<add>
<add> // Renderers may schedule work to be done after host components are mounted
<add> // (eg DOM renderer may schedule auto-focus for inputs and form controls).
<add> // These effects should only be committed when components are first mounted,
<add> // aka when there is no current/alternate.
<add> if (current === null && finishedWork.flags & Update) {
<add> const type = finishedWork.type;
<add> const props = finishedWork.memoizedProps;
<add> commitMount(instance, type, props, finishedWork);
<ide> }
<del> commitUpdateQueue(finishedWork, updateQueue, instance);
<del> }
<del> return;
<del> }
<del> case HostComponent: {
<del> const instance: Instance = finishedWork.stateNode;
<ide>
<del> // Renderers may schedule work to be done after host components are mounted
<del> // (eg DOM renderer may schedule auto-focus for inputs and form controls).
<del> // These effects should only be committed when components are first mounted,
<del> // aka when there is no current/alternate.
<del> if (current === null && finishedWork.flags & Update) {
<del> const type = finishedWork.type;
<del> const props = finishedWork.memoizedProps;
<del> commitMount(instance, type, props, finishedWork);
<add> break;
<ide> }
<add> case HostText: {
<add> // We have no life-cycles associated with text.
<add> break;
<add> }
<add> case HostPortal: {
<add> // We have no life-cycles associated with portals.
<add> break;
<add> }
<add> case Profiler: {
<add> if (enableProfilerTimer) {
<add> const {onCommit, onRender} = finishedWork.memoizedProps;
<add> const {effectDuration} = finishedWork.stateNode;
<ide>
<del> return;
<del> }
<del> case HostText: {
<del> // We have no life-cycles associated with text.
<del> return;
<del> }
<del> case HostPortal: {
<del> // We have no life-cycles associated with portals.
<del> return;
<del> }
<del> case Profiler: {
<del> if (enableProfilerTimer) {
<del> const {onCommit, onRender} = finishedWork.memoizedProps;
<del> const {effectDuration} = finishedWork.stateNode;
<del>
<del> const commitTime = getCommitTime();
<del>
<del> let phase = current === null ? 'mount' : 'update';
<del> if (enableProfilerNestedUpdatePhase) {
<del> if (isCurrentUpdateNested()) {
<del> phase = 'nested-update';
<del> }
<del> }
<add> const commitTime = getCommitTime();
<ide>
<del> if (typeof onRender === 'function') {
<del> if (enableSchedulerTracing) {
<del> onRender(
<del> finishedWork.memoizedProps.id,
<del> phase,
<del> finishedWork.actualDuration,
<del> finishedWork.treeBaseDuration,
<del> finishedWork.actualStartTime,
<del> commitTime,
<del> finishedRoot.memoizedInteractions,
<del> );
<del> } else {
<del> onRender(
<del> finishedWork.memoizedProps.id,
<del> phase,
<del> finishedWork.actualDuration,
<del> finishedWork.treeBaseDuration,
<del> finishedWork.actualStartTime,
<del> commitTime,
<del> );
<add> let phase = current === null ? 'mount' : 'update';
<add> if (enableProfilerNestedUpdatePhase) {
<add> if (isCurrentUpdateNested()) {
<add> phase = 'nested-update';
<add> }
<ide> }
<del> }
<ide>
<del> if (enableProfilerCommitHooks) {
<del> if (typeof onCommit === 'function') {
<add> if (typeof onRender === 'function') {
<ide> if (enableSchedulerTracing) {
<del> onCommit(
<add> onRender(
<ide> finishedWork.memoizedProps.id,
<ide> phase,
<del> effectDuration,
<add> finishedWork.actualDuration,
<add> finishedWork.treeBaseDuration,
<add> finishedWork.actualStartTime,
<ide> commitTime,
<ide> finishedRoot.memoizedInteractions,
<ide> );
<ide> } else {
<del> onCommit(
<add> onRender(
<ide> finishedWork.memoizedProps.id,
<ide> phase,
<del> effectDuration,
<add> finishedWork.actualDuration,
<add> finishedWork.treeBaseDuration,
<add> finishedWork.actualStartTime,
<ide> commitTime,
<ide> );
<ide> }
<ide> }
<ide>
<del> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<del> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<del> // because the effect is also where times bubble to parent Profilers.
<del> enqueuePendingPassiveProfilerEffect(finishedWork);
<add> if (enableProfilerCommitHooks) {
<add> if (typeof onCommit === 'function') {
<add> if (enableSchedulerTracing) {
<add> onCommit(
<add> finishedWork.memoizedProps.id,
<add> phase,
<add> effectDuration,
<add> commitTime,
<add> finishedRoot.memoizedInteractions,
<add> );
<add> } else {
<add> onCommit(
<add> finishedWork.memoizedProps.id,
<add> phase,
<add> effectDuration,
<add> commitTime,
<add> );
<add> }
<add> }
<ide>
<del> // Propagate layout effect durations to the next nearest Profiler ancestor.
<del> // Do not reset these values until the next render so DevTools has a chance to read them first.
<del> let parentFiber = finishedWork.return;
<del> while (parentFiber !== null) {
<del> if (parentFiber.tag === Profiler) {
<del> const parentStateNode = parentFiber.stateNode;
<del> parentStateNode.effectDuration += effectDuration;
<del> break;
<add> // Schedule a passive effect for this Profiler to call onPostCommit hooks.
<add> // This effect should be scheduled even if there is no onPostCommit callback for this Profiler,
<add> // because the effect is also where times bubble to parent Profilers.
<add> enqueuePendingPassiveProfilerEffect(finishedWork);
<add>
<add> // Propagate layout effect durations to the next nearest Profiler ancestor.
<add> // Do not reset these values until the next render so DevTools has a chance to read them first.
<add> let parentFiber = finishedWork.return;
<add> while (parentFiber !== null) {
<add> if (parentFiber.tag === Profiler) {
<add> const parentStateNode = parentFiber.stateNode;
<add> parentStateNode.effectDuration += effectDuration;
<add> break;
<add> }
<add> parentFiber = parentFiber.return;
<ide> }
<del> parentFiber = parentFiber.return;
<ide> }
<ide> }
<add> break;
<ide> }
<del> return;
<add> case SuspenseComponent: {
<add> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
<add> break;
<add> }
<add> case SuspenseListComponent:
<add> case IncompleteClassComponent:
<add> case FundamentalComponent:
<add> case ScopeComponent:
<add> case OffscreenComponent:
<add> case LegacyHiddenComponent:
<add> break;
<add> default:
<add> invariant(
<add> false,
<add> 'This unit of work tag should not have side-effects. This error is ' +
<add> 'likely caused by a bug in React. Please file an issue.',
<add> );
<ide> }
<del> case SuspenseComponent: {
<del> commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
<del> return;
<add> }
<add>
<add> if (enableScopeAPI) {
<add> // TODO: This is a temporary solution that allowed us to transition away
<add> // from React Flare on www.
<add> if (finishedWork.flags & Ref && finishedWork.tag !== ScopeComponent) {
<add> commitAttachRef(finishedWork);
<add> }
<add> } else {
<add> if (finishedWork.flags & Ref) {
<add> commitAttachRef(finishedWork);
<ide> }
<del> case SuspenseListComponent:
<del> case IncompleteClassComponent:
<del> case FundamentalComponent:
<del> case ScopeComponent:
<del> case OffscreenComponent:
<del> case LegacyHiddenComponent:
<del> return;
<ide> }
<del> invariant(
<del> false,
<del> 'This unit of work tag should not have side-effects. This error is ' +
<del> 'likely caused by a bug in React. Please file an issue.',
<del> );
<ide> }
<ide>
<ide> function hideOrUnhideAllChildren(finishedWork, isHidden) {
<ide> function commitResetTextContent(current: Fiber) {
<ide> resetTextContent(current.stateNode);
<ide> }
<ide>
<add>export function commitLayoutEffects(
<add> finishedWork: Fiber,
<add> root: FiberRoot,
<add> committedLanes: Lanes,
<add>): void {
<add> nextEffect = finishedWork;
<add> commitLayoutEffects_begin(finishedWork, root, committedLanes);
<add>}
<add>
<add>function commitLayoutEffects_begin(
<add> subtreeRoot: Fiber,
<add> root: FiberRoot,
<add> committedLanes: Lanes,
<add>) {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> const firstChild = fiber.child;
<add> if ((fiber.subtreeFlags & LayoutMask) !== NoFlags && firstChild !== null) {
<add> ensureCorrectReturnPointer(firstChild, fiber);
<add> nextEffect = firstChild;
<add> } else {
<add> commitLayoutMountEffects_complete(subtreeRoot, root, committedLanes);
<add> }
<add> }
<add>}
<add>
<add>function commitLayoutMountEffects_complete(
<add> subtreeRoot: Fiber,
<add> root: FiberRoot,
<add> committedLanes: Lanes,
<add>) {
<add> while (nextEffect !== null) {
<add> const fiber = nextEffect;
<add> if ((fiber.flags & LayoutMask) !== NoFlags) {
<add> const current = fiber.alternate;
<add> if (__DEV__) {
<add> setCurrentDebugFiberInDEV(fiber);
<add> invokeGuardedCallback(
<add> null,
<add> commitLayoutEffectOnFiber,
<add> null,
<add> root,
<add> current,
<add> fiber,
<add> committedLanes,
<add> );
<add> if (hasCaughtError()) {
<add> const error = clearCaughtError();
<add> captureCommitPhaseError(fiber, error);
<add> }
<add> resetCurrentDebugFiberInDEV();
<add> } else {
<add> try {
<add> commitLayoutEffectOnFiber(root, current, fiber, committedLanes);
<add> } catch (error) {
<add> captureCommitPhaseError(fiber, error);
<add> }
<add> }
<add> }
<add>
<add> if (fiber === subtreeRoot) {
<add> nextEffect = null;
<add> return;
<add> }
<add>
<add> const sibling = fiber.sibling;
<add> if (sibling !== null) {
<add> ensureCorrectReturnPointer(sibling, fiber.return);
<add> nextEffect = sibling;
<add> return;
<add> }
<add>
<add> nextEffect = fiber.return;
<add> }
<add>}
<add>
<ide> export function commitPassiveMountEffects(
<ide> root: FiberRoot,
<del> firstChild: Fiber,
<add> finishedWork: Fiber,
<ide> ): void {
<del> nextEffect = firstChild;
<del> commitPassiveMountEffects_begin(firstChild, root);
<add> nextEffect = finishedWork;
<add> commitPassiveMountEffects_begin(finishedWork, root);
<ide> }
<ide>
<ide> function commitPassiveMountEffects_begin(subtreeRoot: Fiber, root: FiberRoot) {
<ide> export {
<ide> commitPlacement,
<ide> commitDeletion,
<ide> commitWork,
<del> commitLifeCycles,
<ide> commitAttachRef,
<ide> commitDetachRef,
<ide> };
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> Ref,
<ide> ContentReset,
<ide> Snapshot,
<del> Callback,
<ide> Passive,
<ide> PassiveStatic,
<ide> Incomplete,
<ide> import {
<ide> } from './ReactFiberThrow.new';
<ide> import {
<ide> commitBeforeMutationLifeCycles as commitBeforeMutationEffectOnFiber,
<del> commitLifeCycles as commitLayoutEffectOnFiber,
<add> commitLayoutEffects,
<ide> commitPlacement,
<ide> commitWork,
<ide> commitDeletion,
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> // The next phase is the layout phase, where we call effects that read
<ide> // the host tree after it's been mutated. The idiomatic use case for this is
<ide> // layout, but class component lifecycles also fire here for legacy reasons.
<del> nextEffect = firstEffect;
<del> do {
<del> if (__DEV__) {
<del> invokeGuardedCallback(null, commitLayoutEffects, null, root, lanes);
<del> if (hasCaughtError()) {
<del> invariant(nextEffect !== null, 'Should be working on an effect.');
<del> const error = clearCaughtError();
<del> captureCommitPhaseError(nextEffect, error);
<del> nextEffect = nextEffect.nextEffect;
<del> }
<del> } else {
<del> try {
<del> commitLayoutEffects(root, lanes);
<del> } catch (error) {
<del> invariant(nextEffect !== null, 'Should be working on an effect.');
<del> captureCommitPhaseError(nextEffect, error);
<del> nextEffect = nextEffect.nextEffect;
<del> }
<add> if (__DEV__) {
<add> if (enableDebugTracing) {
<add> logLayoutEffectsStarted(lanes);
<ide> }
<del> } while (nextEffect !== null);
<add> }
<add> if (enableSchedulingProfiler) {
<add> markLayoutEffectsStarted(lanes);
<add> }
<add> commitLayoutEffects(finishedWork, root, lanes);
<add> if (__DEV__) {
<add> if (enableDebugTracing) {
<add> logLayoutEffectsStopped();
<add> }
<add> }
<ide>
<del> nextEffect = null;
<add> if (enableSchedulingProfiler) {
<add> markLayoutEffectsStopped();
<add> }
<ide>
<ide> if (enableProfilerTimer && enableProfilerNestedUpdateScheduledHook) {
<ide> rootCommittingMutationOrLayoutEffects = null;
<ide> function commitMutationEffects(
<ide> }
<ide> }
<ide>
<del>function commitLayoutEffects(root: FiberRoot, committedLanes: Lanes) {
<del> if (__DEV__) {
<del> if (enableDebugTracing) {
<del> logLayoutEffectsStarted(committedLanes);
<del> }
<del> }
<del>
<del> if (enableSchedulingProfiler) {
<del> markLayoutEffectsStarted(committedLanes);
<del> }
<del>
<del> // TODO: Should probably move the bulk of this function to commitWork.
<del> while (nextEffect !== null) {
<del> setCurrentDebugFiberInDEV(nextEffect);
<del>
<del> const flags = nextEffect.flags;
<del>
<del> if (flags & (Update | Callback)) {
<del> const current = nextEffect.alternate;
<del> commitLayoutEffectOnFiber(root, current, nextEffect, committedLanes);
<del> }
<del>
<del> if (enableScopeAPI) {
<del> // TODO: This is a temporary solution that allowed us to transition away
<del> // from React Flare on www.
<del> if (flags & Ref && nextEffect.tag !== ScopeComponent) {
<del> commitAttachRef(nextEffect);
<del> }
<del> } else {
<del> if (flags & Ref) {
<del> commitAttachRef(nextEffect);
<del> }
<del> }
<del>
<del> resetCurrentDebugFiberInDEV();
<del> nextEffect = nextEffect.nextEffect;
<del> }
<del>
<del> if (__DEV__) {
<del> if (enableDebugTracing) {
<del> logLayoutEffectsStopped();
<del> }
<del> }
<del>
<del> if (enableSchedulingProfiler) {
<del> markLayoutEffectsStopped();
<del> }
<del>}
<del>
<ide> export function flushPassiveEffects(): boolean {
<ide> // Returns whether passive effects were flushed.
<ide> if (pendingPassiveEffectsRenderPriority !== NoSchedulerPriority) {
<ide><path>packages/react/src/__tests__/ReactDOMTracing-test.internal.js
<ide> describe('ReactDOMTracing', () => {
<ide> onInteractionScheduledWorkCompleted,
<ide> ).toHaveBeenLastNotifiedOfInteraction(interaction);
<ide>
<del> if (gate(flags => flags.dfsEffectsRefactor)) {
<add> if (gate(flags => flags.enableUseJSStackToTrackPassiveDurations)) {
<ide> expect(onRender).toHaveBeenCalledTimes(3);
<ide> } else {
<ide> // TODO: This is 4 instead of 3 because this update was scheduled at
<ide> describe('ReactDOMTracing', () => {
<ide> expect(
<ide> onInteractionScheduledWorkCompleted,
<ide> ).toHaveBeenLastNotifiedOfInteraction(interaction);
<del> if (gate(flags => flags.dfsEffectsRefactor)) {
<add> if (gate(flags => flags.enableUseJSStackToTrackPassiveDurations)) {
<ide> expect(onRender).toHaveBeenCalledTimes(3);
<ide> } else {
<ide> // TODO: This is 4 instead of 3 because this update was scheduled at
<ide><path>packages/react/src/__tests__/ReactProfiler-test.internal.js
<ide> describe('Profiler', () => {
<ide>
<ide> renderer.update(<App />);
<ide>
<del> if (gate(flags => flags.dfsEffectsRefactor)) {
<add> if (gate(flags => flags.enableUseJSStackToTrackPassiveDurations)) {
<ide> // None of the Profiler's subtree was rendered because App bailed out before the Profiler.
<ide> // So we expect onRender not to be called.
<ide> expect(callback).not.toHaveBeenCalled();
<ide> describe('Profiler', () => {
<ide> // because the resolved suspended subtree doesn't contain any passive effects.
<ide> // If <AsyncComponentWithCascadingWork> or its decendents had a passive effect,
<ide> // onPostCommit would be called again.
<del> if (gate(flags => flags.dfsEffectsRefactor)) {
<add> if (gate(flags => flags.enableUseJSStackToTrackPassiveDurations)) {
<ide> expect(Scheduler).toFlushAndYield([]);
<ide> } else {
<ide> expect(Scheduler).toFlushAndYield(['onPostCommit']);
<ide> describe('Profiler', () => {
<ide> });
<ide>
<ide> if (__DEV__) {
<del> // @gate dfsEffectsRefactor
<add> // @gate enableUseJSStackToTrackPassiveDurations
<ide> // @gate enableDoubleInvokingEffects
<ide> it('double invoking does not disconnect wrapped async work', () => {
<ide> ReactFeatureFlags.enableDoubleInvokingEffects = true;
<ide><path>scripts/jest/TestFlags.js
<ide> const environmentFlags = {
<ide> // Use this for tests that are known to be broken.
<ide> FIXME: false,
<ide>
<del> // Turn this flag back on (or delete) once the effect list is removed in favor
<del> // of a depth-first traversal using `subtreeTags`.
<del> dfsEffectsRefactor: false,
<add> // Turn these flags back on (or delete) once the effect list is removed in
<add> // favor of a depth-first traversal using `subtreeTags`.
<add> dfsEffectsRefactor: __VARIANT__,
<add> enableUseJSStackToTrackPassiveDurations: false,
<ide> };
<ide>
<ide> function getTestFlags() {
| 5
|
Go
|
Go
|
replace magic consts for golang.org/x/sys consts
|
89de943401bb23e09047f3c2c8f64f8aec247bc3
|
<ide><path>pkg/pidfile/pidfile_windows.go
<ide> import (
<ide> "golang.org/x/sys/windows"
<ide> )
<ide>
<del>const (
<del> processQueryLimitedInformation = 0x1000
<del>
<del> stillActive = 259
<del>)
<del>
<ide> func processExists(pid int) bool {
<del> h, err := windows.OpenProcess(processQueryLimitedInformation, false, uint32(pid))
<add> h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
<ide> if err != nil {
<ide> return false
<ide> }
<ide> var c uint32
<ide> err = windows.GetExitCodeProcess(h, &c)
<ide> windows.Close(h)
<ide> if err != nil {
<del> return c == stillActive
<add> // From the GetExitCodeProcess function (processthreadsapi.h) API docs:
<add> // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess
<add> //
<add> // The GetExitCodeProcess function returns a valid error code defined by the
<add> // application only after the thread terminates. Therefore, an application should
<add> // not use STILL_ACTIVE (259) as an error code (STILL_ACTIVE is a macro for
<add> // STATUS_PENDING (minwinbase.h)). If a thread returns STILL_ACTIVE (259) as
<add> // an error code, then applications that test for that value could interpret it
<add> // to mean that the thread is still running, and continue to test for the
<add> // completion of the thread after the thread has terminated, which could put
<add> // the application into an infinite loop.
<add> return c == uint32(windows.STATUS_PENDING)
<ide> }
<ide> return true
<ide> }
| 1
|
Python
|
Python
|
add choices to options metadata for choicefield
|
a38d9d5b24501ae0e279c9afbea08e423112ba34
|
<ide><path>rest_framework/fields.py
<ide> def _set_choices(self, value):
<ide>
<ide> choices = property(_get_choices, _set_choices)
<ide>
<add> def metadata(self):
<add> data = super(ChoiceField, self).metadata()
<add> data['choices'] = self.choices
<add> return data
<add>
<ide> def validate(self, value):
<ide> """
<ide> Validates that the input is in self.choices.
| 1
|
Javascript
|
Javascript
|
remove main template hooks for hmrplugin
|
c006675dd9ed4375942405023a623fb1605a8599
|
<ide><path>lib/HotModuleReplacementPlugin.js
<ide>
<ide> "use strict";
<ide>
<del>const { SyncBailHook, SyncWaterfallHook } = require("tapable");
<add>const { SyncBailHook } = require("tapable");
<ide> const { RawSource } = require("webpack-sources");
<ide> const HotUpdateChunk = require("./HotUpdateChunk");
<ide> const JavascriptParser = require("./JavascriptParser");
<ide> const {
<ide> evaluateToString,
<ide> toConstantDependency
<ide> } = require("./JavascriptParserHelpers");
<del>const MainTemplate = require("./MainTemplate");
<ide> const NormalModule = require("./NormalModule");
<ide> const NullFactory = require("./NullFactory");
<ide> const RuntimeGlobals = require("./RuntimeGlobals");
<ide> const { compareModulesById } = require("./util/comparators");
<ide> * @property {SyncBailHook<TODO, string[]>} hotAcceptWithoutCallback
<ide> */
<ide>
<del>/** @type {WeakMap<MainTemplate, HMRMainTemplateHooks>} */
<del>const mainTemplateHooksMap = new WeakMap();
<del>
<ide> /** @type {WeakMap<JavascriptParser, HMRJavascriptParserHooks>} */
<ide> const parserHooksMap = new WeakMap();
<ide>
<ide> class HotModuleReplacementPlugin {
<del> /**
<del> * @param {MainTemplate} mainTemplate the main template
<del> * @returns {HMRMainTemplateHooks} the attached hooks
<del> */
<del> static getMainTemplateHooks(mainTemplate) {
<del> if (!(mainTemplate instanceof MainTemplate)) {
<del> throw new TypeError(
<del> "The 'mainTemplate' argument must be an instance of MainTemplate"
<del> );
<del> }
<del> let hooks = mainTemplateHooksMap.get(mainTemplate);
<del> if (hooks === undefined) {
<del> hooks = {
<del> hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"])
<del> };
<del> mainTemplateHooksMap.set(mainTemplate, hooks);
<del> }
<del> return hooks;
<del> }
<del>
<ide> /**
<ide> * @param {JavascriptParser} parser the parser
<ide> * @returns {HMRJavascriptParserHooks} the attached hooks
| 1
|
Python
|
Python
|
use strict type checking (not isinstance)
|
07a3f43cd6406433c2132e7bd14ad43b23677ecd
|
<ide><path>numpy/core/shape_base.py
<ide> def _block_check_depths_match(arrays, index=[]):
<ide> def format_index(index):
<ide> idx_str = ''.join('[{}]'.format(i) for i in index if i is not None)
<ide> return 'arrays' + idx_str
<del> if isinstance(arrays, tuple):
<add> if type(arrays) is tuple:
<ide> raise TypeError(
<ide> '{} is a tuple. '
<ide> 'Only lists can be used to arrange blocks, and np.block does '
<ide> 'not allow implicit conversion from tuple to ndarray.'.format(
<ide> format_index(index)
<ide> )
<ide> )
<del> elif isinstance(arrays, list) and len(arrays) > 0:
<add> elif type(arrays) is list and len(arrays) > 0:
<ide> indexes = [_block_check_depths_match(arr, index + [i])
<ide> for i, arr in enumerate(arrays)]
<ide>
<ide> def format_index(index):
<ide> )
<ide> )
<ide> return first_index
<del> elif isinstance(arrays, list) and len(arrays) == 0:
<add> elif type(arrays) is list and len(arrays) == 0:
<ide> # We've 'bottomed out' on an empty list
<ide> return index + [None]
<ide> else:
<ide> def format_index(index):
<ide>
<ide>
<ide> def _block(arrays, depth=0):
<del> if isinstance(arrays, list):
<add> if type(arrays) is list:
<ide> if len(arrays) == 0:
<ide> raise ValueError('Lists cannot be empty')
<ide> arrs, list_ndims = zip(*(_block(arr, depth+1) for arr in arrays))
| 1
|
Java
|
Java
|
fix cglib memory leak for method injection
|
8028eae786ff36ea58df9a385319bf045795fa77
|
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.beans.BeanInstantiationException;
<add>import org.springframework.beans.BeanUtils;
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.cglib.core.SpringNamingPolicy;
<ide> import org.springframework.cglib.proxy.Callback;
<ide> import org.springframework.cglib.proxy.CallbackFilter;
<ide> import org.springframework.cglib.proxy.Enhancer;
<add>import org.springframework.cglib.proxy.Factory;
<ide> import org.springframework.cglib.proxy.MethodInterceptor;
<ide> import org.springframework.cglib.proxy.MethodProxy;
<ide> import org.springframework.cglib.proxy.NoOp;
<ide>
<ide> /**
<ide> * Default object instantiation strategy for use in BeanFactories.
<del> * Uses CGLIB to generate subclasses dynamically if methods need to be
<del> * overridden by the container, to implement Method Injection.
<add> *
<add> * <p>Uses CGLIB to generate subclasses dynamically if methods need to be
<add> * overridden by the container to implement <em>Method Injection</em>.
<ide> *
<ide> * @author Rod Johnson
<ide> * @author Juergen Hoeller
<add> * @author Sam Brannen
<ide> * @since 1.1
<ide> */
<ide> public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
<ide> public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationSt
<ide>
<ide> /**
<ide> * Index in the CGLIB callback array for a method that should
<del> * be overridden to provide method lookup.
<add> * be overridden to provide <em>method lookup</em>.
<ide> */
<ide> private static final int LOOKUP_OVERRIDE = 1;
<ide>
<ide> public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationSt
<ide>
<ide>
<ide> @Override
<del> protected Object instantiateWithMethodInjection(
<del> RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
<add> protected Object instantiateWithMethodInjection(RootBeanDefinition beanDefinition, String beanName,
<add> BeanFactory owner) {
<ide>
<del> // Must generate CGLIB subclass.
<del> return new CglibSubclassCreator(beanDefinition, owner).instantiate(null, null);
<add> return instantiateWithMethodInjection(beanDefinition, beanName, owner, null, null);
<ide> }
<ide>
<ide> @Override
<del> protected Object instantiateWithMethodInjection(
<del> RootBeanDefinition beanDefinition, String beanName, BeanFactory owner,
<del> Constructor<?> ctor, Object[] args) {
<add> protected Object instantiateWithMethodInjection(RootBeanDefinition beanDefinition, String beanName,
<add> BeanFactory owner, Constructor<?> ctor, Object[] args) {
<ide>
<add> // Must generate CGLIB subclass.
<ide> return new CglibSubclassCreator(beanDefinition, owner).instantiate(ctor, args);
<ide> }
<ide>
<ide> protected Object instantiateWithMethodInjection(
<ide> */
<ide> private static class CglibSubclassCreator {
<ide>
<del> private static final Log logger = LogFactory.getLog(CglibSubclassCreator.class);
<add> private static final Class<?>[] CALLBACK_TYPES = new Class<?>[] { NoOp.class,
<add> LookupOverrideMethodInterceptor.class, ReplaceOverrideMethodInterceptor.class };
<ide>
<ide> private final RootBeanDefinition beanDefinition;
<ide>
<ide> private final BeanFactory owner;
<ide>
<del> public CglibSubclassCreator(RootBeanDefinition beanDefinition, BeanFactory owner) {
<add>
<add> CglibSubclassCreator(RootBeanDefinition beanDefinition, BeanFactory owner) {
<ide> this.beanDefinition = beanDefinition;
<ide> this.owner = owner;
<ide> }
<ide> public CglibSubclassCreator(RootBeanDefinition beanDefinition, BeanFactory owner
<ide> * @param ctor constructor to use. If this is {@code null}, use the
<ide> * no-arg constructor (no parameterization, or Setter Injection)
<ide> * @param args arguments to use for the constructor.
<del> * Ignored if the ctor parameter is {@code null}.
<add> * Ignored if the {@code ctor} parameter is {@code null}.
<ide> * @return new instance of the dynamically generated subclass
<ide> */
<del> public Object instantiate(Constructor<?> ctor, Object[] args) {
<add> Object instantiate(Constructor<?> ctor, Object[] args) {
<add> Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
<add>
<add> Object instance;
<add> if (ctor == null) {
<add> instance = BeanUtils.instantiate(subclass);
<add> }
<add> else {
<add> try {
<add> Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
<add> instance = enhancedSubclassConstructor.newInstance(args);
<add> }
<add> catch (Exception e) {
<add> throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format(
<add> "Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e);
<add> }
<add> }
<add>
<add> // SPR-10785: set callbacks directly on the instance instead of in the
<add> // enhanced class (via the Enhancer) in order to avoid memory leaks.
<add> Factory factory = (Factory) instance;
<add> factory.setCallbacks(new Callback[] { NoOp.INSTANCE,//
<add> new LookupOverrideMethodInterceptor(beanDefinition, owner),//
<add> new ReplaceOverrideMethodInterceptor(beanDefinition, owner) });
<add>
<add> return instance;
<add> }
<add>
<add> /**
<add> * Create an enhanced subclass of the bean class for the provided bean
<add> * definition, using CGLIB.
<add> */
<add> private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
<ide> Enhancer enhancer = new Enhancer();
<del> enhancer.setSuperclass(this.beanDefinition.getBeanClass());
<add> enhancer.setSuperclass(beanDefinition.getBeanClass());
<ide> enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
<del> enhancer.setCallbackFilter(new CallbackFilterImpl());
<del> enhancer.setCallbacks(new Callback[] {
<del> NoOp.INSTANCE,
<del> new LookupOverrideMethodInterceptor(),
<del> new ReplaceOverrideMethodInterceptor()
<del> });
<del>
<del> return (ctor != null ? enhancer.create(ctor.getParameterTypes(), args) : enhancer.create());
<add> enhancer.setCallbackFilter(new CallbackFilterImpl(beanDefinition));
<add> enhancer.setCallbackTypes(CALLBACK_TYPES);
<add> return enhancer.createClass();
<ide> }
<add> }
<add>
<add> /**
<add> * Class providing hashCode and equals methods required by CGLIB to
<add> * ensure that CGLIB doesn't generate a distinct class per bean.
<add> * Identity is based on class and bean definition.
<add> */
<add> private static class CglibIdentitySupport {
<ide>
<add> private final RootBeanDefinition beanDefinition;
<add>
<add>
<add> CglibIdentitySupport(RootBeanDefinition beanDefinition) {
<add> this.beanDefinition = beanDefinition;
<add> }
<ide>
<ide> /**
<del> * Class providing hashCode and equals methods required by CGLIB to
<del> * ensure that CGLIB doesn't generate a distinct class per bean.
<del> * Identity is based on class and bean definition.
<add> * Exposed for equals method to allow access to enclosing class field
<ide> */
<del> private class CglibIdentitySupport {
<del>
<del> /**
<del> * Exposed for equals method to allow access to enclosing class field
<del> */
<del> protected RootBeanDefinition getBeanDefinition() {
<del> return beanDefinition;
<del> }
<add> protected RootBeanDefinition getBeanDefinition() {
<add> return beanDefinition;
<add> }
<ide>
<del> @Override
<del> public boolean equals(Object other) {
<del> return (other.getClass().equals(getClass()) &&
<del> ((CglibIdentitySupport) other).getBeanDefinition().equals(beanDefinition));
<del> }
<add> @Override
<add> public boolean equals(Object other) {
<add> return (other.getClass().equals(getClass()) && ((CglibIdentitySupport) other).getBeanDefinition().equals(
<add> beanDefinition));
<add> }
<ide>
<del> @Override
<del> public int hashCode() {
<del> return beanDefinition.hashCode();
<del> }
<add> @Override
<add> public int hashCode() {
<add> return beanDefinition.hashCode();
<ide> }
<add> }
<ide>
<add> /**
<add> * CGLIB object to filter method interception behavior.
<add> */
<add> private static class CallbackFilterImpl extends CglibIdentitySupport implements CallbackFilter {
<add>
<add> private static final Log logger = LogFactory.getLog(CallbackFilterImpl.class);
<ide>
<del> /**
<del> * CGLIB MethodInterceptor to override methods, replacing them with an
<del> * implementation that returns a bean looked up in the container.
<del> */
<del> private class LookupOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor {
<ide>
<del> @Override
<del> public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {
<del> // Cast is safe, as CallbackFilter filters are used selectively.
<del> LookupOverride lo = (LookupOverride) beanDefinition.getMethodOverrides().getOverride(method);
<del> return owner.getBean(lo.getBeanName());
<add> CallbackFilterImpl(RootBeanDefinition beanDefinition) {
<add> super(beanDefinition);
<add> }
<add>
<add> @Override
<add> public int accept(Method method) {
<add> MethodOverride methodOverride = getBeanDefinition().getMethodOverrides().getOverride(method);
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Override for '" + method.getName() + "' is [" + methodOverride + "]");
<add> }
<add> if (methodOverride == null) {
<add> return PASSTHROUGH;
<ide> }
<add> else if (methodOverride instanceof LookupOverride) {
<add> return LOOKUP_OVERRIDE;
<add> }
<add> else if (methodOverride instanceof ReplaceOverride) {
<add> return METHOD_REPLACER;
<add> }
<add> throw new UnsupportedOperationException("Unexpected MethodOverride subclass: "
<add> + methodOverride.getClass().getName());
<ide> }
<add> }
<ide>
<add> /**
<add> * CGLIB MethodInterceptor to override methods, replacing them with an
<add> * implementation that returns a bean looked up in the container.
<add> */
<add> private static class LookupOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor {
<ide>
<del> /**
<del> * CGLIB MethodInterceptor to override methods, replacing them with a call
<del> * to a generic MethodReplacer.
<del> */
<del> private class ReplaceOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor {
<del>
<del> @Override
<del> public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {
<del> ReplaceOverride ro = (ReplaceOverride) beanDefinition.getMethodOverrides().getOverride(method);
<del> // TODO could cache if a singleton for minor performance optimization
<del> MethodReplacer mr = (MethodReplacer) owner.getBean(ro.getMethodReplacerBeanName());
<del> return mr.reimplement(obj, method, args);
<del> }
<add> private final BeanFactory owner;
<add>
<add>
<add> LookupOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner) {
<add> super(beanDefinition);
<add> this.owner = owner;
<ide> }
<ide>
<add> @Override
<add> public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {
<add> // Cast is safe, as CallbackFilter filters are used selectively.
<add> LookupOverride lo = (LookupOverride) getBeanDefinition().getMethodOverrides().getOverride(method);
<add> return this.owner.getBean(lo.getBeanName());
<add> }
<add> }
<ide>
<del> /**
<del> * CGLIB object to filter method interception behavior.
<del> */
<del> private class CallbackFilterImpl extends CglibIdentitySupport implements CallbackFilter {
<add> /**
<add> * CGLIB MethodInterceptor to override methods, replacing them with a call
<add> * to a generic MethodReplacer.
<add> */
<add> private static class ReplaceOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor {
<ide>
<del> @Override
<del> public int accept(Method method) {
<del> MethodOverride methodOverride = beanDefinition.getMethodOverrides().getOverride(method);
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Override for '" + method.getName() + "' is [" + methodOverride + "]");
<del> }
<del> if (methodOverride == null) {
<del> return PASSTHROUGH;
<del> }
<del> else if (methodOverride instanceof LookupOverride) {
<del> return LOOKUP_OVERRIDE;
<del> }
<del> else if (methodOverride instanceof ReplaceOverride) {
<del> return METHOD_REPLACER;
<del> }
<del> throw new UnsupportedOperationException(
<del> "Unexpected MethodOverride subclass: " + methodOverride.getClass().getName());
<del> }
<add> private final BeanFactory owner;
<add>
<add>
<add> ReplaceOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner) {
<add> super(beanDefinition);
<add> this.owner = owner;
<add> }
<add>
<add> @Override
<add> public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {
<add> ReplaceOverride ro = (ReplaceOverride) getBeanDefinition().getMethodOverrides().getOverride(method);
<add> // TODO could cache if a singleton for minor performance optimization
<add> MethodReplacer mr = owner.getBean(ro.getMethodReplacerBeanName(), MethodReplacer.class);
<add> return mr.reimplement(obj, method, args);
<ide> }
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java
<ide> import org.springframework.util.FileCopyUtils;
<ide> import org.springframework.util.SerializationTestUtils;
<ide> import org.springframework.util.StopWatch;
<del>
<ide> import org.xml.sax.InputSource;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<ide> public void testAutowireModeNotInherited() {
<ide> XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
<ide> reader.loadBeanDefinitions(OVERRIDES_CONTEXT);
<ide>
<del> TestBean david = (TestBean)xbf.getBean("magicDavid");
<add> TestBean david = (TestBean) xbf.getBean("magicDavid");
<ide> // the parent bean is autowiring
<ide> assertNotNull(david.getSpouse());
<ide>
<del> TestBean derivedDavid = (TestBean)xbf.getBean("magicDavidDerived");
<add> TestBean derivedDavid = (TestBean) xbf.getBean("magicDavidDerived");
<ide> // this fails while it inherits from the child bean
<ide> assertNull("autowiring not propagated along child relationships", derivedDavid.getSpouse());
<ide> }
<ide> public void testSingletonInheritsFromParentFactoryPrototype() throws Exception {
<ide> DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
<ide> new XmlBeanDefinitionReader(child).loadBeanDefinitions(CHILD_CONTEXT);
<ide> TestBean inherits = (TestBean) child.getBean("singletonInheritsFromParentFactoryPrototype");
<del> // Name property value is overriden
<add> // Name property value is overridden
<ide> assertTrue(inherits.getName().equals("prototype-override"));
<ide> // Age property is inherited from bean in parent factory
<ide> assertTrue(inherits.getAge() == 2);
<ide> public void testComplexFactoryReferenceCircle() {
<ide> assertEquals(5, xbf.getSingletonCount());
<ide> }
<ide>
<del> @Test
<del> public void testNoSuchFactoryBeanMethod() {
<del> try {
<del> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(NO_SUCH_FACTORY_METHOD_CONTEXT);
<del> assertNotNull(xbf.getBean("defaultTestBean"));
<del> fail("Should not get invalid bean");
<del> }
<del> catch (BeanCreationException ex) {
<del> // Ok
<del> }
<add> @Test(expected = BeanCreationException.class)
<add> public void noSuchFactoryBeanMethod() {
<add> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(NO_SUCH_FACTORY_METHOD_CONTEXT);
<add> assertNotNull(xbf.getBean("defaultTestBean"));
<ide> }
<ide>
<ide> @Test
<ide> public void testDefaultLazyInit() throws Exception {
<ide> }
<ide> }
<ide>
<del> @Test
<del> public void testNoSuchXmlFile() throws Exception {
<add> @Test(expected = BeanDefinitionStoreException.class)
<add> public void noSuchXmlFile() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> try {
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT);
<del> fail("Must not create factory from missing XML");
<del> }
<del> catch (BeanDefinitionStoreException expected) {
<del> }
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT);
<ide> }
<ide>
<del> @Test
<del> public void testInvalidXmlFile() throws Exception {
<add> @Test(expected = BeanDefinitionStoreException.class)
<add> public void invalidXmlFile() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> try {
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT);
<del> fail("Must not create factory from invalid XML");
<del> }
<del> catch (BeanDefinitionStoreException expected) {
<del> }
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT);
<ide> }
<ide>
<del> @Test
<del> public void testUnsatisfiedObjectDependencyCheck() throws Exception {
<add> @Test(expected = UnsatisfiedDependencyException.class)
<add> public void unsatisfiedObjectDependencyCheck() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> try {
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_OBJECT_DEP_CONTEXT);
<del> xbf.getBean("a", DependenciesBean.class);
<del> fail("Must have thrown an UnsatisfiedDependencyException");
<del> }
<del> catch (UnsatisfiedDependencyException ex) {
<del> }
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_OBJECT_DEP_CONTEXT);
<add> xbf.getBean("a", DependenciesBean.class);
<ide> }
<ide>
<del> @Test
<del> public void testUnsatisfiedSimpleDependencyCheck() throws Exception {
<add> @Test(expected = UnsatisfiedDependencyException.class)
<add> public void unsatisfiedSimpleDependencyCheck() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> try {
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_SIMPLE_DEP_CONTEXT);
<del> xbf.getBean("a", DependenciesBean.class);
<del> fail("Must have thrown an UnsatisfiedDependencyException");
<del> }
<del> catch (UnsatisfiedDependencyException expected) {
<del> }
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_SIMPLE_DEP_CONTEXT);
<add> xbf.getBean("a", DependenciesBean.class);
<ide> }
<ide>
<ide> @Test
<ide> public void testSatisfiedSimpleDependencyCheck() throws Exception {
<ide> assertEquals(a.getAge(), 33);
<ide> }
<ide>
<del> @Test
<del> public void testUnsatisfiedAllDependencyCheck() throws Exception {
<add> @Test(expected = UnsatisfiedDependencyException.class)
<add> public void unsatisfiedAllDependencyCheck() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> try {
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_ALL_DEP_CONTEXT);
<del> xbf.getBean("a", DependenciesBean.class);
<del> fail("Must have thrown an UnsatisfiedDependencyException");
<del> }
<del> catch (UnsatisfiedDependencyException expected) {
<del> }
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_ALL_DEP_CONTEXT);
<add> xbf.getBean("a", DependenciesBean.class);
<ide> }
<ide>
<ide> @Test
<ide> public void testConstructorArgWithSingleMatch() {
<ide> assertEquals(File.separator + "test", file.getPath());
<ide> }
<ide>
<del> @Test
<del> public void testThrowsExceptionOnTooManyArguments() throws Exception {
<add> @Test(expected = BeanCreationException.class)
<add> public void throwsExceptionOnTooManyArguments() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<ide> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
<del> try {
<del> xbf.getBean("rod7", ConstructorDependenciesBean.class);
<del> fail("Should have thrown BeanCreationException");
<del> }
<del> catch (BeanCreationException expected) {
<del> }
<add> xbf.getBean("rod7", ConstructorDependenciesBean.class);
<ide> }
<ide>
<del> @Test
<del> public void testThrowsExceptionOnAmbiguousResolution() throws Exception {
<add> @Test(expected = UnsatisfiedDependencyException.class)
<add> public void throwsExceptionOnAmbiguousResolution() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<ide> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT);
<del> try {
<del> xbf.getBean("rod8", ConstructorDependenciesBean.class);
<del> fail("Must have thrown UnsatisfiedDependencyException");
<del> }
<del> catch (UnsatisfiedDependencyException expected) {
<del> }
<add> xbf.getBean("rod8", ConstructorDependenciesBean.class);
<ide> }
<ide>
<ide> @Test
<ide> public void testFileSystemResourceWithImport() throws URISyntaxException {
<ide> xbf.getBean("resource2", ResourceTestBean.class);
<ide> }
<ide>
<del> @Test
<del> public void testRecursiveImport() {
<add> @Test(expected = BeanDefinitionStoreException.class)
<add> public void recursiveImport() {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<del> try {
<del> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT);
<del> fail("Should have thrown BeanDefinitionStoreException");
<del> }
<del> catch (BeanDefinitionStoreException ex) {
<del> // expected
<del> ex.printStackTrace();
<del> }
<add> new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT);
<ide> }
<ide>
<ide> /**
<ide> public void testRecursiveImport() {
<ide> public void methodInjectedBeanMustBeOfSameEnhancedCglibSubclassTypeAcrossBeanFactories() {
<ide> Class<?> firstClass = null;
<ide>
<del> for (int i = 1; i <= 10; i++) {
<add> for (int i = 0; i < 10; i++) {
<ide> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<ide> new XmlBeanDefinitionReader(bf).loadBeanDefinitions(OVERRIDES_CONTEXT);
<ide>
<ide> public void methodInjectedBeanMustBeOfSameEnhancedCglibSubclassTypeAcrossBeanFac
<ide> }
<ide>
<ide> @Test
<del> public void testLookupOverrideMethodsWithSetterInjection() {
<add> public void lookupOverrideMethodsWithSetterInjection() {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<ide> XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
<ide> reader.loadBeanDefinitions(OVERRIDES_CONTEXT);
<ide>
<del> testLookupOverrideMethodsWithSetterInjection(xbf, "overrideOneMethod", true);
<add> lookupOverrideMethodsWithSetterInjection(xbf, "overrideOneMethod", true);
<ide> // Should work identically on subclass definition, in which lookup
<ide> // methods are inherited
<del> testLookupOverrideMethodsWithSetterInjection(xbf, "overrideInheritedMethod", true);
<add> lookupOverrideMethodsWithSetterInjection(xbf, "overrideInheritedMethod", true);
<ide>
<ide> // Check cost of repeated construction of beans with method overrides
<ide> // Will pick up misuse of CGLIB
<ide> int howMany = 100;
<ide> StopWatch sw = new StopWatch();
<ide> sw.start("Look up " + howMany + " prototype bean instances with method overrides");
<ide> for (int i = 0; i < howMany; i++) {
<del> testLookupOverrideMethodsWithSetterInjection(xbf, "overrideOnPrototype", false);
<add> lookupOverrideMethodsWithSetterInjection(xbf, "overrideOnPrototype", false);
<ide> }
<ide> sw.stop();
<del> System.out.println(sw);
<add> // System.out.println(sw);
<ide> if (!LogFactory.getLog(DefaultListableBeanFactory.class).isDebugEnabled()) {
<ide> assertTrue(sw.getTotalTimeMillis() < 2000);
<ide> }
<ide> public void testLookupOverrideMethodsWithSetterInjection() {
<ide> assertEquals("Jenny", tb.getName());
<ide> }
<ide>
<del> private void testLookupOverrideMethodsWithSetterInjection(BeanFactory xbf, String beanName, boolean singleton) {
<add> private void lookupOverrideMethodsWithSetterInjection(BeanFactory xbf,
<add> String beanName, boolean singleton) {
<ide> OverrideOneMethod oom = (OverrideOneMethod) xbf.getBean(beanName);
<ide>
<ide> if (singleton) {
<ide> public void testReplaceMethodOverrideWithSetterInjection() {
<ide> }
<ide>
<ide> @Test
<del> public void testLookupOverrideOneMethodWithConstructorInjection() {
<add> public void lookupOverrideOneMethodWithConstructorInjection() {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<ide> XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
<ide> reader.loadBeanDefinitions(CONSTRUCTOR_OVERRIDES_CONTEXT);
<ide> public void testRejectsOverrideOfBogusMethodName() {
<ide> }
<ide> }
<ide>
<del> /**
<del> * Assert the presence of this bug until we resolve it.
<del> */
<ide> @Test
<del> public void testSerializabilityOfMethodReplacer() throws Exception {
<del> try {
<del> BUGtestSerializableMethodReplacerAndSuperclass();
<del> fail();
<del> }
<del> catch (AssertionError ex) {
<del> System.err.println("****** SPR-356: Objects with MethodReplace overrides are not serializable");
<del> }
<del> }
<del>
<del> public void BUGtestSerializableMethodReplacerAndSuperclass() throws IOException, ClassNotFoundException {
<add> public void serializableMethodReplacerAndSuperclass() throws Exception {
<ide> DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
<ide> XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf);
<ide> reader.loadBeanDefinitions(DELEGATION_OVERRIDES_CONTEXT);
<ide> SerializableMethodReplacerCandidate s = (SerializableMethodReplacerCandidate) xbf.getBean("serializableReplacer");
<ide> String forwards = "this is forwards";
<ide> String backwards = new StringBuffer(forwards).reverse().toString();
<ide> assertEquals(backwards, s.replaceMe(forwards));
<del> assertTrue(SerializationTestUtils.isSerializable(s));
<del> s = (SerializableMethodReplacerCandidate) SerializationTestUtils.serializeAndDeserialize(s);
<del> assertEquals("Method replace still works after serialization and deserialization", backwards, s.replaceMe(forwards));
<add> // SPR-356: lookup methods & method replacers are not serializable.
<add> assertFalse(
<add> "Lookup methods and method replacers are not meant to be serializable.",
<add> SerializationTestUtils.isSerializable(s));
<ide> }
<ide>
<ide> @Test
| 2
|
Javascript
|
Javascript
|
make regular elements like identity elements
|
ca436a2b1d4d488a6aeadd9ba7e6ab170e3a5e49
|
<ide><path>packages/ember-htmlbars/lib/hooks/component.js
<ide> export default function componentHook(renderNode, env, scope, _tagName, params,
<ide>
<ide> let tagName = _tagName;
<ide> let isAngleBracket = false;
<del> let isTopLevel;
<add> let isTopLevel = false;
<add> let isDasherized = false;
<ide>
<ide> let angles = tagName.match(/^(@?)<(.*)>$/);
<ide>
<ide> export default function componentHook(renderNode, env, scope, _tagName, params,
<ide> isTopLevel = !!angles[1];
<ide> }
<ide>
<add> if (tagName.indexOf('-') !== -1) {
<add> isDasherized = true;
<add> }
<add>
<ide> var parentView = env.view;
<ide>
<del> if (isTopLevel && tagName === env.view.tagName) {
<add> if (isTopLevel && tagName === env.view.tagName || !isDasherized) {
<ide> let component = env.view;
<ide> let templateOptions = {
<ide> component,
<add> tagName,
<ide> isAngleBracket: true,
<ide> isComponentElement: true,
<ide> outerAttrs: scope.attrs,
<ide><path>packages/ember-htmlbars/tests/integration/component_invocation_test.js
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$().html(), '<div>This is a</div><div>fragment</div>', 'Just the fragment was used');
<ide> });
<ide>
<del> QUnit.skip('non-block without properties replaced with a div', function() {
<add> QUnit.test('non-block without properties replaced with a div', function() {
<ide> // The whitespace is added intentionally to verify that the heuristic is not "a single node" but
<ide> // rather "a single non-whitespace, non-comment node"
<ide> registry.register('template:components/non-block', compile(' <div>In layout</div> '));
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equalsElement(node.firstElementChild, 'non-block', { such: 'changed!!!', class: 'ember-view', id: regex(/^ember\d*$/) }, '<p>In layout</p>');
<ide> });
<ide>
<del> QUnit.skip('non-block with class replaced with a div merges classes', function() {
<add> QUnit.test('non-block with class replaced with a div merges classes', function() {
<ide> registry.register('template:components/non-block', compile('<div class="inner-class" />'));
<ide>
<ide> view = appendViewFor('<non-block class="{{view.outer}}" />', {
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$('non-block').attr('class'), 'inner-class new-outer ember-view', 'the classes are merged');
<ide> });
<ide>
<del> QUnit.skip('non-block with outer attributes replaced with a div shadows inner attributes', function() {
<add> QUnit.test('non-block with outer attributes replaced with a div shadows inner attributes', function() {
<ide> registry.register('template:components/non-block', compile('<div data-static="static" data-dynamic="{{internal}}" />'));
<ide>
<ide> view = appendViewFor('<non-block data-static="outer" data-dynamic="outer" />');
<ide><path>packages/ember-template-compiler/lib/plugins/transform-top-level-components.js
<ide> function TransformTopLevelComponents() {
<ide> @param {AST} The AST to be transformed.
<ide> */
<ide> TransformTopLevelComponents.prototype.transform = function TransformTopLevelComponents_transform(ast) {
<add> let b = this.syntax.builders;
<add>
<ide> hasSingleComponentNode(ast.body, component => {
<del> component.tag = `@${component.tag}`;
<add> if (component.type === 'ComponentNode') {
<add> component.tag = `@${component.tag}`;
<add> }
<add> }, element => {
<add> // TODO: Properly copy loc from children
<add> let program = b.program(element.children);
<add> return b.component(`@<${element.tag}>`, element.attributes, program, element.loc);
<ide> });
<ide>
<ide> return ast;
<ide> };
<ide>
<del>function hasSingleComponentNode(body, callback) {
<add>function hasSingleComponentNode(body, componentCallback, elementCallback) {
<ide> let lastComponentNode;
<ide> let lastIndex;
<ide> let nodeCount = 0;
<ide> function hasSingleComponentNode(body, callback) {
<ide> if (!lastComponentNode) { return; }
<ide>
<ide> if (lastComponentNode.type === 'ComponentNode') {
<del> callback(lastComponentNode);
<add> componentCallback(lastComponentNode);
<add> } else {
<add> let component = elementCallback(lastComponentNode);
<add> body.splice(lastIndex, 1, component);
<ide> }
<ide> }
<ide>
<ide><path>packages/ember-views/lib/system/build-component-template.js
<ide> import { internal, render } from 'htmlbars-runtime';
<ide> import getValue from 'ember-htmlbars/hooks/get-value';
<ide> import { isStream } from 'ember-metal/streams/utils';
<ide>
<del>export default function buildComponentTemplate({ component, layout, isAngleBracket, isComponentElement, outerAttrs }, attrs, content) {
<del> var blockToRender, tagName, meta;
<add>export default function buildComponentTemplate({ component, tagName, layout, isAngleBracket, isComponentElement, outerAttrs }, attrs, content) {
<add> var blockToRender, meta;
<ide>
<ide> if (component === undefined) {
<ide> component = null;
<ide> export default function buildComponentTemplate({ component, layout, isAngleBrack
<ide> }
<ide>
<ide> if (component && !component._isAngleBracket || isComponentElement) {
<del> tagName = tagNameFor(component);
<add> tagName = tagName || tagNameFor(component);
<ide>
<ide> // If this is not a tagless component, we need to create the wrapping
<ide> // element. We use `manualElement` to create a template that represents
| 4
|
Python
|
Python
|
remove duplicated code
|
0cdafbf7ecfe0f13335c2ea10fd92391e30c79f0
|
<ide><path>src/transformers/tokenization_marian.py
<ide> def prepare_seq2seq_batch(
<ide> if max_target_length is not None:
<ide> tokenizer_kwargs["max_length"] = max_target_length
<ide>
<del> if max_target_length is not None:
<del> tokenizer_kwargs["max_length"] = max_target_length
<del>
<ide> self.current_spm = self.spm_target
<ide> model_inputs["labels"] = self(tgt_texts, **tokenizer_kwargs)["input_ids"]
<ide> self.current_spm = self.spm_source
| 1
|
Text
|
Text
|
add link to exercises
|
38898201d9d176ca22f50ce349024d32644ff8bf
|
<ide><path>guide/english/css/css3-grid-layout/index.md
<ide> Though Grid Layout isn't fully supported by all browsers, it's the most advanced
<ide> - [Grid by Example](https://gridbyexample.com/)
<ide> - [Wes Bos - Free CSS Grid Course](https://cssgrid.io/)
<ide> - [YouTube - CSS Grid Playlist](https://www.youtube.com/watch?v=FEnRpy9Xfes&list=PLbSquHt1VCf1x_-1ytlVMT0AMwADlWtc1)
<add>- [CSS Grid Garden Exercises](https://cssgridgarden.com) - [Guide](https://github.com/thomaspark/gridgarden).
<ide> - [Scrimba - Learn CSS Grid for free - screencast](https://scrimba.com/g/gR8PTE)
<ide>
<add>
<ide> More info about browser support can be read at <a href="https://caniuse.com/#feat=css-grid" target="_blank">https://caniuse.com</a>.
| 1
|
Python
|
Python
|
add test for broadcast with one argument
|
361c0d5ce1dc3d9b68bad42ec05ef7a4b33285ce
|
<ide><path>numpy/core/tests/test_indexing.py
<ide> def _get_multi_index(self, arr, indices):
<ide> + arr.shape[ax + len(indx[1:]):]))
<ide>
<ide> # Check if broadcasting works
<del> if len(indx[1:]) != 1:
<del> res = np.broadcast(*indx[1:]) # raises ValueError...
<del> else:
<del> res = indx[1]
<add> res = np.broadcast(*indx[1:])
<ide> # unfortunately the indices might be out of bounds. So check
<ide> # that first, and use mode='wrap' then. However only if
<ide> # there are any indices...
<ide><path>numpy/core/tests/test_numeric.py
<ide> def test_broadcast_in_args(self):
<ide> for a, ia in zip(arrs, mit.iters):
<ide> assert_(a is ia.base)
<ide>
<add> def test_broadcast_single_arg(self):
<add> # gh-6899
<add> arrs = [np.empty((5, 6, 7))]
<add> mit = np.broadcast(*arrs)
<add> assert_equal(mit.shape, (5, 6, 7))
<add> assert_equal(mit.nd, 3)
<add> assert_equal(mit.numiter, 1)
<add> assert_(arrs[0] is mit.iters[0].base)
<add>
<ide> def test_number_of_arguments(self):
<ide> arr = np.empty((5,))
<ide> for j in range(35):
<ide> arrs = [arr] * j
<del> if j < 2 or j > 32:
<add> if j < 1 or j > 32:
<ide> assert_raises(ValueError, np.broadcast, *arrs)
<ide> else:
<ide> mit = np.broadcast(*arrs)
| 2
|
PHP
|
PHP
|
add missing type to api docs
|
52c2674e45b775d9252eedfc1f9c4060a88974b5
|
<ide><path>src/Routing/Route/Route.php
<ide> public function __construct($template, $defaults = [], array $options = []) {
<ide> /**
<ide> * Get/Set the supported extensions for this route.
<ide> *
<del> * @param null|array $extensions The extensions to set. Use null to get.
<add> * @param null|string|array $extensions The extensions to set. Use null to get.
<ide> * @return array|void The extensions or null.
<ide> */
<ide> public function extensions($extensions = null) {
<ide><path>src/Routing/RouteCollection.php
<ide> public function addExtensions(array $extensions) {
<ide> /**
<ide> * Get/set the extensions that the route collection could handle.
<ide> *
<del> * @param null|array $extensions Either the list of extensions to set, or null to get.
<add> * @param null|string|array $extensions Either the list of extensions to set, or null to get.
<ide> * @return array The valid extensions.
<ide> */
<ide> public function extensions($extensions = null) {
| 2
|
Javascript
|
Javascript
|
handle multi-file solutions
|
063145fe90aaae94e45a132015f19418438c68c1
|
<ide><path>tools/challenge-md-parser/challengeSeed-to-data.js
<ide> function defaultFile(lang) {
<ide> };
<ide> }
<ide> function createCodeGetter(key, regEx, seeds) {
<del> console.log('seeds');
<del> console.log(seeds);
<ide> return container => {
<ide> const {
<ide> properties: { id }
<ide> function createPlugin() {
<ide> };
<ide> }
<ide>
<del>module.exports = createPlugin;
<add>exports.challengeSeedToData = createPlugin;
<add>exports.createCodeGetter = createCodeGetter;
<ide><path>tools/challenge-md-parser/challengeSeed-to-data.test.js
<ide> /* global describe it expect beforeEach */
<del>const mockAST = require('./fixtures/challenge-html-ast.json');
<del>const challengeSeedToData = require('./challengeSeed-to-data');
<ide> const isArray = require('lodash/isArray');
<ide>
<add>const mockAST = require('./fixtures/challenge-html-ast.json');
<add>const { challengeSeedToData } = require('./challengeSeed-to-data');
<add>
<ide> describe('challengeSeed-to-data plugin', () => {
<ide> const plugin = challengeSeedToData();
<ide> let file = { data: {} };
<ide><path>tools/challenge-md-parser/index.js
<ide> const raw = require('rehype-raw');
<ide> const frontmatterToData = require('./frontmatter-to-data');
<ide> const textToData = require('./text-to-data');
<ide> const testsToData = require('./tests-to-data');
<del>const challengeSeedToData = require('./challengeSeed-to-data');
<add>const { challengeSeedToData } = require('./challengeSeed-to-data');
<ide> const solutionsToData = require('./solution-to-data');
<ide>
<ide> const processor = unified()
<ide><path>tools/challenge-md-parser/solution-to-data.js
<ide> const visit = require('unist-util-visit');
<ide> const { selectAll } = require('hast-util-select');
<ide>
<ide> const { sectionFilter } = require('./utils');
<add>const { createCodeGetter } = require('./challengeSeed-to-data');
<add>
<add>const solutionRE = /(.+)-solution$/;
<ide>
<ide> function createPlugin() {
<ide> return function transformer(tree, file) {
<ide> function visitor(node) {
<ide> if (sectionFilter(node, 'solution')) {
<add> // fallback for single-file challenges
<ide> const solutions = selectAll('code', node).map(
<ide> element => element.children[0].value
<ide> );
<ide> file.data = {
<ide> ...file.data,
<ide> solutions
<ide> };
<add> const solutionFiles = {};
<add> const codeDivs = selectAll('div', node);
<add> const solutionContainers = codeDivs.filter(({ properties: { id } }) =>
<add> solutionRE.test(id)
<add> );
<add> solutionContainers.forEach(
<add> createCodeGetter('contents', solutionRE, solutionFiles)
<add> );
<add>
<add> file.data = {
<add> ...file.data,
<add> solutionFiles: Object.keys(solutionFiles).map(
<add> lang => solutionFiles[lang]
<add> )
<add> };
<ide> }
<ide> }
<ide> visit(tree, 'element', visitor);
| 4
|
Go
|
Go
|
remove unused repoinfo
|
c1040b222c2520f8a0ebe14e81b5b7fe188e8dc6
|
<ide><path>api/client/build.go
<ide> import (
<ide> "github.com/docker/docker/pkg/ulimit"
<ide> "github.com/docker/docker/pkg/urlutil"
<ide> "github.com/docker/docker/reference"
<del> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/utils"
<ide> "github.com/docker/go-units"
<ide> )
<ide> func (td *trustedDockerfile) Close() error {
<ide> // resolvedTag records the repository, tag, and resolved digest reference
<ide> // from a Dockerfile rewrite.
<ide> type resolvedTag struct {
<del> repoInfo *registry.RepositoryInfo
<ide> digestRef reference.Canonical
<ide> tagRef reference.NamedTagged
<ide> }
<ide> func rewriteDockerfileFrom(dockerfileName string, translator func(reference.Name
<ide> }
<ide> }
<ide>
<del> repoInfo, err := registry.ParseRepositoryInfo(ref)
<del> if err != nil {
<del> return nil, nil, fmt.Errorf("unable to parse repository info %q: %v", ref.String(), err)
<del> }
<del>
<ide> if !digested && isTrusted() {
<ide> trustedRef, err := translator(ref.(reference.NamedTagged))
<ide> if err != nil {
<ide> func rewriteDockerfileFrom(dockerfileName string, translator func(reference.Name
<ide>
<ide> line = dockerfileFromLinePattern.ReplaceAllLiteralString(line, fmt.Sprintf("FROM %s", trustedRef.String()))
<ide> resolvedTags = append(resolvedTags, &resolvedTag{
<del> repoInfo: repoInfo,
<ide> digestRef: trustedRef,
<ide> tagRef: ref.(reference.NamedTagged),
<ide> })
| 1
|
Python
|
Python
|
add smart lib in dep
|
bcea4d1cdc083ab698634bbff926b798d03e20ed
|
<ide><path>setup.py
<ide> def run(self):
<ide> 'graph': ['pygal'],
<ide> 'ip': ['netifaces'],
<ide> 'raid': ['pymdstat'],
<add> 'smart': ['pySMART.smartx'],
<ide> 'snmp': ['pysnmp'],
<ide> 'web': ['bottle', 'requests'],
<ide> 'wifi': ['wifi']
| 1
|
Python
|
Python
|
remove unused set_input method
|
92e8a20761bedbde8fd56a02a165884e8132f045
|
<ide><path>keras/engine/topology.py
<ide> def input(self):
<ide> return self._get_node_attribute_at_index(0, 'input_tensors',
<ide> 'input')
<ide>
<del> def set_input(self, input_tensor, shape=None):
<del> if len(self.inbound_nodes) > 1:
<del> raise Exception('Cannot `set_input` for layer ' + self.name +
<del> ' because it has more than one inbound connection.')
<del> if len(self.inbound_nodes) == 1:
<del> # Check that the inbound node is an Input node.
<del> if self.inbound_nodes[0].inbound_layers:
<del> warnings.warn('You are manually setting the input for layer ' +
<del> self.name + ' but it is not an Input layer. '
<del> 'This will cause part of your model '
<del> 'to be disconnected.')
<del> if self.outbound_nodes:
<del> warnings.warn('You are manually setting the input for layer ' +
<del> self.name + ' but it has ' +
<del> str(len(self.outbound_nodes)) +
<del> ' outbound layers. '
<del> 'This will cause part of your model '
<del> 'to be disconnected.')
<del> if hasattr(K, 'int_shape'):
<del> # Auto-infered shape takes priority.
<del> shape = K.int_shape(input_tensor)
<del> elif not shape:
<del> raise Exception('`set_input` needs to know the shape '
<del> 'of the `input_tensor` it receives, but '
<del> 'Keras was not able to infer it automatically.'
<del> ' Specify it via: '
<del> '`model.set_input(input_tensor, shape)`')
<del> # Reset layer connections.
<del> self.inbound_nodes = []
<del> self.outbound_nodes = []
<del> input_shape = tuple(shape)
<del> self.build(input_shape=input_shape)
<del>
<del> # Set Keras tensor metadata.
<del> input_tensor._uses_learning_phase = False
<del> input_tensor._keras_history = (None, 0, 0)
<del> input_tensor._keras_shape = input_shape
<del>
<del> output_tensors = to_list(self.call(input_tensor))
<del> output_shapes = to_list(self.get_output_shape_for(input_shape))
<del> output_masks = to_list(self.compute_mask(input_tensor, None))
<del>
<del> for i, output_tensor in enumerate(output_tensors):
<del> output_tensor._keras_history = (self, 0, i)
<del> output_tensor._keras_shape = output_shapes[i]
<del> output_tensor._uses_learning_phase = self.uses_learning_phase
<del>
<del> # Create node.
<del> Node(self,
<del> inbound_layers=[],
<del> node_indices=[],
<del> tensor_indices=[],
<del> input_tensors=[input_tensor],
<del> output_tensors=output_tensors,
<del> input_masks=[None],
<del> output_masks=output_masks,
<del> input_shapes=[input_shape],
<del> output_shapes=output_shapes)
<del>
<ide> @property
<ide> def output(self):
<ide> '''Retrieves the output tensor(s) of a layer (only applicable if
| 1
|
Text
|
Text
|
add pref to using draft pr versus wip label
|
4a7a18bbbe6444c425221f6327ddd072bd07194f
|
<ide><path>doc/guides/contributing/pull-requests.md
<ide> details, but feel free to skip parts if you're not sure what to put.
<ide>
<ide> Once opened, pull requests are usually reviewed within a few days.
<ide>
<add>To get feedback on your proposed change even though it is not ready
<add>to land, use the `Convert to draft` option in the GitHub UI.
<add>Do not use the `wip` label as it might not prevent the PR
<add>from landing before you are ready.
<add>
<ide> ### Step 9: Discuss and update
<ide>
<ide> You will probably get feedback or requests for changes to your pull request.
| 1
|
Ruby
|
Ruby
|
remove a defensive to_s call
|
22d1f6516f977520ed67601ffde2bfecea746757
|
<ide><path>Library/Homebrew/build_options.rb
<ide> def initialize_copy(other)
<ide> end
<ide>
<ide> def add(name, description)
<del> description ||= case name.to_s
<add> description ||= case name
<ide> when "universal" then "Build a universal binary"
<ide> when "32-bit" then "Build 32-bit only"
<ide> when "c++11" then "Build using C++11 mode"
| 1
|
Text
|
Text
|
fix typo on test.md
|
3048c3a7682919297d8d7d26897a59dc91b3be09
|
<ide><path>docs/contributing/test.md
<ide> $ TESTDIRS='opts' make test-unit
<ide>
<ide> You can also use the `TESTFLAGS` environment variable to run a single test. The
<ide> flag's value is passed as arguments to the `go test` command. For example, from
<del>your local host you can run the `TestBuild` test with this command:
<add>your local host you can run the `TestValidateIPAddress` test with this command:
<ide>
<ide> ```bash
<ide> $ TESTFLAGS='-test.run ^TestValidateIPAddress$' make test-unit
| 1
|
Text
|
Text
|
modify styles and typo of readme
|
66bfea679fa782418d9158aea8b1b0ec578eb37b
|
<ide><path>test/README.md
<ide> Basically you don't need to write any expected behaviors your self. The assumpti
<ide>
<ide> Please follow the approach described bellow:
<ide>
<del>* write your test code in ```statsCases/``` folder by creating a separate folder for it, for example
<del>```statsCases/some-file-import-stats/index.js```
<del>```
<del> import(./someModule);
<add>* write your test code in `statsCases/` folder by creating a separate folder for it, for example `statsCases/some-file-import-stats/index.js`
<add>
<add>```javascript
<add>import(./someModule);
<ide> ```
<del>** dont's forget the ```webpack.config.js```
<add>* don't forget the `webpack.config.js`
<ide> * run the test
<del>* jest will automatically add the output from your test code to ```StatsTestCases.test.js.snap``` and you can always check your results there
<add>* jest will automatically add the output from your test code to `StatsTestCases.test.js.snap` and you can always check your results there
<ide> * Next time test will run -> runner will compare results against your output written to snapshot previously
<ide>
<ide> You can read more about SnapShot testing [right here](https://jestjs.io/docs/snapshot-testing)
| 1
|
PHP
|
PHP
|
add failing test for new custom statement handler
|
73c88939d7b5e554741f6913a1d94cd441678e51
|
<ide><path>tests/View/ViewBladeCompilerTest.php
<ide> public function testCustomExtensionsAreCompiled()
<ide> }
<ide>
<ide>
<add> public function testCustomStatements()
<add> {
<add> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
<add> $compiler->addStatement('customControl', function($expression) {
<add> return "<?php echo custom_control{$expression}; ?>";
<add> });
<add>
<add> $string = '@if($foo)
<add>@customControl(10, $foo, \'bar\')
<add>@endif';
<add> $expected = '<?php if($foo): ?>
<add><?php echo custom_control(10, $foo, \'bar\'); ?>
<add><?php endif; ?>';
<add> $this->assertEquals($expected, $compiler->compileString($string));
<add> }
<add>
<add>
<ide> public function testConfiguringContentTags()
<ide> {
<ide> $compiler = new BladeCompiler($this->getFiles(), __DIR__);
| 1
|
Javascript
|
Javascript
|
remove dead code in favor of unit tests
|
2db57bdecc9a0c3cedbd3883d9ee3e8a20232608
|
<ide><path>lib/path.js
<ide> function win32SplitPath(filename) {
<ide> // Separate device+slash from tail
<ide> var result = splitDeviceRe.exec(filename),
<ide> device = (result[1] || '') + (result[2] || ''),
<del> tail = result[3] || '';
<add> tail = result[3];
<ide> // Split the tail into dir, basename and extension
<ide> var result2 = splitTailRe.exec(tail),
<ide> dir = result2[1],
<ide> win32.parse = function(pathString) {
<ide> assertPath(pathString);
<ide>
<ide> var allParts = win32SplitPath(pathString);
<del> if (!allParts || allParts.length !== 4) {
<del> throw new TypeError("Invalid path '" + pathString + "'");
<del> }
<ide> return {
<ide> root: allParts[0],
<ide> dir: allParts[0] + allParts[1].slice(0, -1),
<ide> posix.parse = function(pathString) {
<ide> assertPath(pathString);
<ide>
<ide> var allParts = posixSplitPath(pathString);
<del> if (!allParts || allParts.length !== 4) {
<del> throw new TypeError("Invalid path '" + pathString + "'");
<del> }
<del> allParts[1] = allParts[1] || '';
<del> allParts[2] = allParts[2] || '';
<del> allParts[3] = allParts[3] || '';
<del>
<ide> return {
<ide> root: allParts[0],
<ide> dir: allParts[0] + allParts[1].slice(0, -1),
<ide><path>test/parallel/test-path-parse-format.js
<ide> var winPaths = [
<ide> '\\foo\\C:',
<ide> 'file',
<ide> '.\\file',
<add> '',
<ide>
<ide> // unc
<ide> '\\\\server\\share\\file_path',
<ide> var unixPaths = [
<ide> 'file',
<ide> '.\\file',
<ide> './file',
<del> 'C:\\foo'
<add> 'C:\\foo',
<add> ''
<ide> ];
<ide>
<ide> var unixSpecialCaseFormatTests = [
<ide> var errors = [
<ide> message: /Path must be a string. Received 1/},
<ide> {method: 'parse', input: [],
<ide> message: /Path must be a string. Received undefined/},
<del> // {method: 'parse', input: [''],
<del> // message: /Invalid path/}, // omitted because it's hard to trigger!
<ide> {method: 'format', input: [null],
<ide> message: /Parameter 'pathObject' must be an object, not/},
<ide> {method: 'format', input: [''],
<ide> function checkErrors(path) {
<ide> }
<ide>
<ide> function checkParseFormat(path, paths) {
<del> paths.forEach(function(element, index, array) {
<add> paths.forEach(function(element) {
<ide> var output = path.parse(element);
<add> assert.strictEqual(typeof output.root, 'string');
<add> assert.strictEqual(typeof output.dir, 'string');
<add> assert.strictEqual(typeof output.base, 'string');
<add> assert.strictEqual(typeof output.ext, 'string');
<add> assert.strictEqual(typeof output.name, 'string');
<ide> assert.strictEqual(path.format(output), element);
<ide> assert.strictEqual(output.dir, output.dir ? path.dirname(element) : '');
<ide> assert.strictEqual(output.base, path.basename(element));
| 2
|
Python
|
Python
|
add deprecate with doc
|
94e351cbda3fb151af4ae18d6ebfc9b409e27022
|
<ide><path>utils.py
<ide> from numpy.core import product, ndarray
<ide>
<ide> __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype',
<del> 'issubdtype', 'deprecate', 'get_numarray_include',
<add> 'issubdtype', 'deprecate', 'deprecate_with_doc',
<add> 'get_numarray_include',
<ide> 'get_include', 'info', 'source', 'who',
<ide> 'byte_bounds', 'may_share_memory']
<ide>
<ide> def _set_function_name(func, name):
<ide> func.__name__ = name
<ide> return func
<ide>
<del>def deprecate(func, oldname, newname):
<add>def deprecate(func, oldname=None, newname=None):
<ide> import warnings
<add> if oldname is None:
<add> oldname = func.func_name
<add> if newname is None:
<add> str1 = "%s is deprecated" % (oldname,)
<add> depdoc = "%s is DEPRECATED!" % (oldname,)
<add> else:
<add> str1 = "%s is deprecated, use %s" % (oldname, newname),
<add> depdoc = '%s is DEPRECATED! -- use %s instead' % (oldname, newname,)
<add>
<ide> def newfunc(*args,**kwds):
<del> warnings.warn("%s is deprecated, use %s" % (oldname, newname),
<del> DeprecationWarning)
<add> warnings.warn(str1, DeprecationWarning)
<ide> return func(*args, **kwds)
<ide> newfunc = _set_function_name(newfunc, oldname)
<ide> doc = func.__doc__
<del> depdoc = '%s is DEPRECATED: use %s instead' % (oldname, newname,)
<ide> if doc is None:
<ide> doc = depdoc
<ide> else:
<ide> def newfunc(*args,**kwds):
<ide> newfunc.__dict__.update(d)
<ide> return newfunc
<ide>
<add>def deprecate_with_doc(somestr):
<add> def _decorator(func):
<add> newfunc = deprecate(func)
<add> newfunc.__doc__ += "\n" + somestr
<add> return newfunc
<add> return _decorator
<add>
<ide> get_numpy_include = deprecate(get_include, 'get_numpy_include', 'get_include')
<ide>
<ide>
| 1
|
Java
|
Java
|
update @controlleradvice javadoc
|
fce8ed62cef7df6aaffe5699dc64bf1a0c4faf3a
|
<ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/ControllerAdvice.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2017 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 org.springframework.core.annotation.AliasFor;
<ide> import org.springframework.stereotype.Component;
<ide>
<add>
<ide> /**
<del> * Indicates the annotated class assists a "Controller".
<del> *
<del> * <p>Serves as a specialization of {@link Component @Component}, allowing for
<del> * implementation classes to be autodetected through classpath scanning.
<del> *
<del> * <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
<del> * {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
<del> * methods that apply to all {@link RequestMapping @RequestMapping} methods.
<del> *
<del> * <p>One of {@link #annotations()}, {@link #basePackageClasses()},
<del> * {@link #basePackages()} or its alias {@link #value()}
<del> * may be specified to define specific subsets of Controllers
<del> * to assist. When multiple selectors are applied, OR logic is applied -
<del> * meaning selected Controllers should match at least one selector.
<add> * Specialization of {@link Component @Component} for classes that declare
<add> * {@link ExceptionHandler @ExceptionHandler}, {@link InitBinder @InitBinder}, or
<add> * {@link ModelAttribute @ModelAttribute} methods to be shared across
<add> * multiple {@code @Controller} classes.
<ide> *
<del> * <p>The default behavior (i.e. if used without any selector),
<del> * the {@code @ControllerAdvice} annotated class will
<del> * assist all known Controllers.
<add> * <p>Classes with {@code @ControllerAdvice} can be declared explicitly as Spring
<add> * beans or auto-detected via classpath scanning. All such beans are sorted via
<add> * {@link org.springframework.core.annotation.AnnotationAwareOrderComparator
<add> * AnnotationAwareOrderComparator}, i.e. based on
<add> * {@link org.springframework.core.annotation.Order @Order} and
<add> * {@link org.springframework.core.Ordered Ordered}, and applied in that order
<add> * at runtime. For handling exceptions the first {@code @ExceptionHandler} to
<add> * match the exception is used. For model attributes and {@code InitBinder}
<add> * initialization, {@code @ModelAttribute} and {@code @InitBinder} methods will
<add> * also follow {@code @ControllerAdvice} order.
<ide> *
<del> * <p>Note that those checks are done at runtime, so adding many attributes and using
<del> * multiple strategies may have negative impacts (complexity, performance).
<add> * <p>By default the methods in an {@code @ControllerAdvice} apply globally to
<add> * all Controllers. Use selectors {@link #annotations()},
<add> * {@link #basePackageClasses()}, and {@link #basePackages()} (or its alias
<add> * {@link #value()}) to define a more narrow subset of targeted Controllers.
<add> * If multiple selectors are declared, OR logic is applied, meaning selected
<add> * Controllers should match at least one selector. Note that selector checks
<add> * are performed at runtime and so adding many selectors may negatively impact
<add> * performance and add complexity.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Brian Clozel
| 1
|
Javascript
|
Javascript
|
improve transferable abort controller exec
|
367ac71894a70c068da51945edb06052b595bce5
|
<ide><path>lib/internal/abort_controller.js
<ide> class AbortController {
<ide>
<ide> static [kMakeTransferable]() {
<ide> const controller = new AbortController();
<del> controller.#signal = transferableAbortSignal(controller.#signal);
<add> controller.#signal = createAbortSignal({ transferable: true });
<ide> return controller;
<ide> }
<ide> }
| 1
|
Ruby
|
Ruby
|
add cask options to `brew reinstall`
|
e40eece17bdf83b6d93fc8fff36f94938db22cd3
|
<ide><path>Library/Homebrew/cli/named_args.rb
<ide> def initialize(*args, parent: Args.new, override_spec: nil, force_bottle: false,
<ide> super(@args)
<ide> end
<ide>
<add> def to_casks
<add> @to_casks ||= to_formulae_and_casks(only: :cask).freeze
<add> end
<add>
<ide> def to_formulae
<ide> @to_formulae ||= to_formulae_and_casks(only: :formula).freeze
<ide> end
<ide>
<del> def to_formulae_and_casks(only: nil)
<add> def to_formulae_and_casks(only: nil, method: nil)
<ide> @to_formulae_and_casks ||= {}
<ide> @to_formulae_and_casks[only] ||= begin
<del> to_objects(only: only).reject { |o| o.is_a?(Tap) }.freeze
<add> to_objects(only: only, method: method).reject { |o| o.is_a?(Tap) }.freeze
<ide> end
<ide> end
<ide>
<del> def load_formula_or_cask(name, only: nil)
<add> def load_formula_or_cask(name, only: nil, method: nil)
<ide> if only != :cask
<ide> begin
<del> formula = Formulary.factory(name, spec, force_bottle: @force_bottle, flags: @flags)
<add> formula = case method
<add> when nil, :factory
<add> Formulary.factory(name, *spec, force_bottle: @force_bottle, flags: @flags)
<add> when :resolve
<add> Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags)
<add> else
<add> raise
<add> end
<add>
<ide> warn_if_cask_conflicts(name, "formula") unless only == :formula
<ide> return formula
<ide> rescue FormulaUnavailableError => e
<ide> def load_formula_or_cask(name, only: nil)
<ide>
<ide> if only != :formula
<ide> begin
<del> return Cask::CaskLoader.load(name)
<add> return Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent))
<ide> rescue Cask::CaskUnavailableError
<ide> raise e if only == :cask
<ide> end
<ide> def load_formula_or_cask(name, only: nil)
<ide> private :load_formula_or_cask
<ide>
<ide> def resolve_formula(name)
<del> Formulary.resolve(name, spec: spec(nil), force_bottle: @force_bottle, flags: @flags)
<add> Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags)
<ide> end
<ide> private :resolve_formula
<ide>
<ide> def to_resolved_formulae
<del> @to_resolved_formulae ||= (downcased_unique_named - homebrew_tap_cask_names).map do |name|
<del> resolve_formula(name)
<del> end.uniq(&:name).freeze
<add> @to_resolved_formulae ||= to_formulae_and_casks(only: :formula, method: :resolve)
<add> .freeze
<ide> end
<ide>
<ide> def to_resolved_formulae_to_casks
<del> @to_resolved_formulae_to_casks ||= begin
<del> resolved_formulae = []
<del> casks = []
<del>
<del> downcased_unique_named.each do |name|
<del> resolved_formulae << resolve_formula(name)
<del>
<del> warn_if_cask_conflicts(name, "formula")
<del> rescue FormulaUnavailableError
<del> begin
<del> casks << Cask::CaskLoader.load(name)
<del> rescue Cask::CaskUnavailableError
<del> raise "No available formula or cask with the name \"#{name}\""
<del> end
<del> end
<del>
<del> [resolved_formulae.freeze, casks.freeze].freeze
<del> end
<add> @to_resolved_formulae_to_casks ||= to_formulae_and_casks(method: :resolve)
<add> .partition { |o| o.is_a?(Formula) }
<add> .map(&:freeze).freeze
<ide> end
<ide>
<ide> # Convert named arguments to `Tap`, `Formula` or `Cask` objects.
<ide> # If both a formula and cask exist with the same name, returns the
<ide> # formula and prints a warning unless `only` is specified.
<del> def to_objects(only: nil)
<add> def to_objects(only: nil, method: nil)
<ide> @to_objects ||= {}
<ide> @to_objects[only] ||= downcased_unique_named.flat_map do |name|
<ide> next Tap.fetch(name) if only == :tap || (only.nil? && name.count("/") == 1 && !name.start_with?("./", "/"))
<ide>
<del> load_formula_or_cask(name, only: only)
<add> load_formula_or_cask(name, only: only, method: method)
<ide> end.uniq.freeze
<ide> end
<ide>
<ide> def to_paths(only: nil)
<ide> end.uniq.freeze
<ide> end
<ide>
<del> def to_casks
<del> @to_casks ||= downcased_unique_named
<del> .map { |name| Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent)) }
<del> .freeze
<del> end
<del>
<ide> def to_kegs
<ide> @to_kegs ||= downcased_unique_named.map do |name|
<ide> resolve_keg name
<ide> def downcased_unique_named
<ide> end.uniq
<ide> end
<ide>
<del> def spec(default = :stable)
<del> @override_spec || default
<add> def spec
<add> @override_spec
<ide> end
<add> private :spec
<ide>
<ide> def resolve_keg(name)
<ide> raise UsageError if name.blank?
<ide><path>Library/Homebrew/cmd/reinstall.rb
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def reinstall_args
<add> cask_only_options = [
<add> [:switch, "--cask", "--casks", {
<add> description: "Treat all named arguments as casks.",
<add> }],
<add> *Cask::Cmd::OPTIONS,
<add> *Cask::Cmd::AbstractCommand::OPTIONS,
<add> ]
<add>
<add> formula_only_options = [
<add> [:switch, "--formula", "--formulae", {
<add> description: "Treat all named arguments as formulae.",
<add> }],
<add> [:switch, "-s", "--build-from-source", {
<add> description: "Compile <formula> from source even if a bottle is available.",
<add> }],
<add> [:switch, "-i", "--interactive", {
<add> description: "Download and patch <formula>, then open a shell. This allows the user to "\
<add> "run `./configure --help` and otherwise determine how to turn the software "\
<add> "package into a Homebrew package.",
<add> }],
<add> [:switch, "--force-bottle", {
<add> description: "Install from a bottle if it exists for the current or newest version of "\
<add> "macOS, even if it would not normally be used for installation.",
<add> }],
<add> [:switch, "--keep-tmp", {
<add> description: "Retain the temporary files created during installation.",
<add> }],
<add> [:switch, "--display-times", {
<add> env: :display_install_times,
<add> description: "Print install times for each formula at the end of the run.",
<add> }],
<add> ]
<add>
<ide> Homebrew::CLI::Parser.new do
<ide> usage_banner <<~EOS
<ide> `reinstall` [<options>] <formula>|<cask>
<ide> def reinstall_args
<ide> switch "-d", "--debug",
<ide> description: "If brewing fails, open an interactive debugging session with access to IRB "\
<ide> "or a shell inside the temporary build directory."
<del> switch "-s", "--build-from-source",
<del> description: "Compile <formula> from source even if a bottle is available."
<del> switch "-i", "--interactive",
<del> description: "Download and patch <formula>, then open a shell. This allows the user to "\
<del> "run `./configure --help` and otherwise determine how to turn the software "\
<del> "package into a Homebrew package."
<del> switch "--force-bottle",
<del> description: "Install from a bottle if it exists for the current or newest version of "\
<del> "macOS, even if it would not normally be used for installation."
<del> switch "--keep-tmp",
<del> description: "Retain the temporary files created during installation."
<ide> switch "-f", "--force",
<ide> description: "Install without checking for previously installed keg-only or "\
<ide> "non-migrated versions."
<ide> switch "-v", "--verbose",
<ide> description: "Print the verification and postinstall steps."
<del> switch "--display-times",
<del> env: :display_install_times,
<del> description: "Print install times for each formula at the end of the run."
<ide> conflicts "--build-from-source", "--force-bottle"
<add>
<add> formula_only_options.each do |options|
<add> send(*options)
<add> conflicts "--cask", options[-2]
<add> end
<add>
<add> cask_only_options.each do |options|
<add> send(*options)
<add> conflicts "--formula", options[-2]
<add> end
<add>
<ide> formula_options
<ide> min_named 1
<ide> end
<ide> def reinstall
<ide>
<ide> Install.perform_preinstall_checks
<ide>
<del> resolved_formulae, casks = args.named.to_resolved_formulae_to_casks
<del> resolved_formulae.each do |f|
<add> only = :cask if args.cask? && !args.formula?
<add> only = :formula if !args.cask? && args.formula?
<add>
<add> formulae, casks = args.named.to_formulae_and_casks(only: only, method: :resolve)
<add> .partition { |o| o.is_a?(Formula) }
<add>
<add> formulae.each do |f|
<ide> if f.pinned?
<ide> onoe "#{f.full_name} is pinned. You must unpin it to reinstall."
<ide> next
<ide> def reinstall
<ide>
<ide> Upgrade.check_installed_dependents(args: args)
<ide>
<del> Homebrew.messages.display_messages(display_times: args.display_times?)
<add> if casks.any?
<add> Cask::Cmd::Reinstall.reinstall_casks(
<add> *casks,
<add> binaries: EnvConfig.cask_opts_binaries?,
<add> verbose: args.verbose?,
<add> force: args.force?,
<add> require_sha: EnvConfig.cask_opts_require_sha?,
<add> skip_cask_deps: args.skip_cask_deps?,
<add> quarantine: EnvConfig.cask_opts_quarantine?,
<add> )
<add> end
<ide>
<del> return if casks.blank?
<del>
<del> Cask::Cmd::Reinstall.reinstall_casks(
<del> *casks,
<del> binaries: EnvConfig.cask_opts_binaries?,
<del> verbose: args.verbose?,
<del> force: args.force?,
<del> require_sha: EnvConfig.cask_opts_require_sha?,
<del> skip_cask_deps: args.skip_cask_deps?,
<del> quarantine: EnvConfig.cask_opts_quarantine?,
<del> )
<add> Homebrew.messages.display_messages(display_times: args.display_times?)
<ide> end
<ide> end
| 2
|
PHP
|
PHP
|
use alternative for array_add
|
01541893d20a5540d1f8e911e780f907103bfb60
|
<ide><path>src/Illuminate/Container/Container.php
<ide> public function tag($abstracts, $tags)
<ide>
<ide> foreach ($tags as $tag)
<ide> {
<del> array_add($this->tags, $tag, []);
<add> if ( ! isset($this->tags[$tag])) $this->tags[$tag] = [];
<ide>
<ide> foreach ((array) $abstracts as $abstract)
<ide> {
| 1
|
Python
|
Python
|
add unit tests for trapping executor errors
|
f0eeb151106f9b179f8d8ea27f3fc0066b968404
|
<ide><path>tests/core.py
<ide> from email.mime.multipart import MIMEMultipart
<ide> from email.mime.application import MIMEApplication
<ide> import errno
<add>import signal
<ide> from time import sleep
<ide>
<ide> from dateutil.relativedelta import relativedelta
<ide>
<ide> NUM_EXAMPLE_DAGS = 14
<ide> DEV_NULL = '/dev/null'
<add>TEST_DAG_FOLDER = os.path.join(
<add> os.path.dirname(os.path.realpath(__file__)), 'dags')
<ide> DEFAULT_DATE = datetime(2015, 1, 1)
<ide> DEFAULT_DATE_ISO = DEFAULT_DATE.isoformat()
<ide> DEFAULT_DATE_DS = DEFAULT_DATE_ISO[:10]
<ide> import pickle
<ide>
<ide>
<add>class timeout:
<add> """
<add> A context manager used to limit execution time.
<add>
<add> Note -- won't work on Windows (based on signal, like Airflow timeouts)
<add>
<add> Based on: http://stackoverflow.com/a/22348885
<add> """
<add> def __init__(self, seconds=1, error_message='Timeout'):
<add> self.seconds = seconds
<add> self.error_message = error_message
<add>
<add> def handle_timeout(self, signum, frame):
<add> raise ValueError(self.error_message)
<add>
<add> def __enter__(self):
<add> signal.signal(signal.SIGALRM, self.handle_timeout)
<add> signal.alarm(self.seconds)
<add>
<add> def __exit__(self, type, value, traceback):
<add> signal.alarm(0)
<add>
<add>
<ide> class FakeDatetime(datetime):
<ide> "A fake replacement for datetime that can be mocked for testing."
<ide>
<ide> def test_backfill_examples(self):
<ide> end_date=DEFAULT_DATE)
<ide> job.run()
<ide>
<add> def test_trap_executor_error(self):
<add> """
<add> Test for https://github.com/airbnb/airflow/pull/1220
<add>
<add> Test that errors setting up tasks (before tasks run) are properly
<add> caught
<add> """
<add> self.dagbag = models.DagBag(dag_folder=TEST_DAG_FOLDER)
<add> dags = [
<add> dag for dag in self.dagbag.dags.values()
<add> if dag.dag_id in ('test_raise_executor_error',)]
<add> for dag in dags:
<add> dag.clear(
<add> start_date=DEFAULT_DATE,
<add> end_date=DEFAULT_DATE)
<add> for dag in dags:
<add> job = jobs.BackfillJob(
<add> dag=dag,
<add> start_date=DEFAULT_DATE,
<add> end_date=DEFAULT_DATE)
<add> # run with timeout because this creates an infinite loop if not
<add> # caught
<add> def run_with_timeout():
<add> with timeout(seconds=15):
<add> job.run()
<add> self.assertRaises(AirflowException, run_with_timeout)
<add>
<ide> def test_pickling(self):
<ide> dp = self.dag.pickle()
<ide> assert self.dag.dag_id == dp.pickle.dag_id
<ide><path>tests/dags/test_raise_executor_error.py
<add># -*- coding: utf-8 -*-
<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>
<add>"""
<add>DAG designed to test what happens when running a DAG fails before
<add>a task runs -- prior to a fix, this could actually cause an Executor to report
<add>SUCCESS. Since the task never reports any status, this can lead to an infinite
<add>rescheduling loop.
<add>"""
<add>from datetime import datetime
<add>
<add>from airflow.models import DAG
<add>from airflow.operators import SubDagOperator
<add>from airflow.example_dags.subdags.subdag import subdag
<add>
<add>args = {
<add> 'owner': 'airflow',
<add> 'start_date': datetime(2016, 1, 1),
<add>}
<add>
<add>dag = DAG(
<add> dag_id='test_raise_executor_error',
<add> default_args=args,
<add> schedule_interval="@daily",
<add>)
<add>
<add>section_1 = SubDagOperator(
<add> task_id='subdag_op',
<add> subdag=subdag('test_raise_executor_error', 'subdag_op', args),
<add> default_args=args,
<add> dag=dag,
<add>)
<add>
<add># change the subdag name -- this creates an error because the subdag
<add># won't be found, but it'll do it in a way that causes the executor to report
<add># success
<add>section_1.subdag.dag_id = 'bad_id'
| 2
|
Text
|
Text
|
add 2.13.1 to changelog
|
f7615bd2817563226d699824e5487b21c84abb97
|
<ide><path>CHANGELOG.md
<ide> - [#15178](https://github.com/emberjs/ember.js/pull/15178) Refactor route to lookup controller for QPs.
<ide> - [#15129](https://github.com/emberjs/ember.js/pull/15129) Fix access to service:-document in ember-engines
<ide>
<add>### 2.13.1 (May 17, 2017)
<add>
<add>- [#15129](https://github.com/emberjs/ember.js/pull/15129) Fix access to document service in `ember-engines`.
<add>- [#15138](https://github.com/emberjs/ember.js/pull/15138) [BUGFIX] Fix mocha blueprint service test filename
<add>- [#15204](https://github.com/emberjs/ember.js/pull/15204) [DEPRECATION] `Ember.MODEL_FACTORY_INJECTIONS` is now always false, deprecate setting it.
<add>- [#15207](https://github.com/emberjs/ember.js/pull/15207) [BUGFIX] Ensure child engines do not have their container destroyed twice.
<add>- [#15242](https://github.com/emberjs/ember.js/pull/15242) [BUGFIX] Fix `EmberError` import in system/router.
<add>- [#15247](https://github.com/emberjs/ember.js/pull/15247) [BUGFIX] Ensure nested custom elements render properly.
<ide>
<ide> ### 2.13.0 (April 27, 2017)
<ide>
| 1
|
Python
|
Python
|
run db shells in pty
|
67268a00cf1f197eb6a943c37b96521ead481073
|
<ide><path>airflow/cli/commands/db_command.py
<ide> # under the License.
<ide> """Database sub-commands"""
<ide> import os
<del>import subprocess
<ide> import textwrap
<ide> from tempfile import NamedTemporaryFile
<ide>
<ide> from airflow import settings
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.utils import cli as cli_utils, db
<add>from airflow.utils.process_utils import execute_interactive
<ide>
<ide>
<ide> def initdb(args):
<ide> def shell(args):
<ide> """).strip()
<ide> f.write(content.encode())
<ide> f.flush()
<del> subprocess.Popen(["mysql", f"--defaults-extra-file={f.name}"]).wait()
<add> execute_interactive(["mysql", f"--defaults-extra-file={f.name}"])
<ide> elif url.get_backend_name() == 'sqlite':
<del> subprocess.Popen(["sqlite3", url.database]).wait()
<add> execute_interactive(["sqlite3", url.database]).wait()
<ide> elif url.get_backend_name() == 'postgresql':
<ide> env = os.environ.copy()
<ide> env['PGHOST'] = url.host or ""
<ide> def shell(args):
<ide> # PostgreSQL does not allow the use of PGPASSFILE if the current user is root.
<ide> env["PGPASSWORD"] = url.password or ""
<ide> env['PGDATABASE'] = url.database
<del> subprocess.Popen(["psql"], env=env).wait()
<add> execute_interactive(["psql"], env=env)
<ide> else:
<ide> raise AirflowException(f"Unknown driver: {url.drivername}")
<ide>
<ide><path>airflow/utils/process_utils.py
<ide> import errno
<ide> import logging
<ide> import os
<add>import pty
<add>import select
<ide> import shlex
<ide> import signal
<ide> import subprocess
<add>import sys
<add>import termios
<add>import tty
<ide> from contextlib import contextmanager
<ide> from typing import Dict, List
<ide>
<ide> def execute_in_subprocess(cmd: List[str]):
<ide> raise subprocess.CalledProcessError(exit_code, cmd)
<ide>
<ide>
<add>def execute_interactive(cmd: List[str], **kwargs):
<add> """
<add> Runs the new command as a subprocess and ensures that the terminal's state is restored to its original
<add> state after the process is completed e.g. if the subprocess hides the cursor, it will be restored after
<add> the process is completed.
<add> """
<add> log.info("Executing cmd: %s", " ".join([shlex.quote(c) for c in cmd]))
<add>
<add> old_tty = termios.tcgetattr(sys.stdin)
<add> tty.setraw(sys.stdin.fileno())
<add>
<add> # open pseudo-terminal to interact with subprocess
<add> master_fd, slave_fd = pty.openpty()
<add> try: # pylint: disable=too-many-nested-blocks
<add> # use os.setsid() make it run in a new process group, or bash job control will not be enabled
<add> proc = subprocess.Popen(
<add> cmd,
<add> stdin=slave_fd,
<add> stdout=slave_fd,
<add> stderr=slave_fd,
<add> universal_newlines=True,
<add> **kwargs
<add> )
<add>
<add> while proc.poll() is None:
<add> readable_fbs, _, _ = select.select([sys.stdin, master_fd], [], [])
<add> if sys.stdin in readable_fbs:
<add> input_data = os.read(sys.stdin.fileno(), 10240)
<add> os.write(master_fd, input_data)
<add> if master_fd in readable_fbs:
<add> output_data = os.read(master_fd, 10240)
<add> if output_data:
<add> os.write(sys.stdout.fileno(), output_data)
<add> finally:
<add> # restore tty settings back
<add> termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
<add>
<add>
<ide> def kill_child_processes_by_pids(pids_to_kill: List[int], timeout: int = 5) -> None:
<ide> """
<ide> Kills child processes for the current process.
<ide><path>tests/cli/commands/test_db_command.py
<ide> def test_cli_upgradedb(self, mock_upgradedb):
<ide>
<ide> mock_upgradedb.assert_called_once_with()
<ide>
<del> @mock.patch("airflow.cli.commands.db_command.subprocess")
<add> @mock.patch("airflow.cli.commands.db_command.execute_interactive")
<ide> @mock.patch("airflow.cli.commands.db_command.NamedTemporaryFile")
<ide> @mock.patch(
<ide> "airflow.cli.commands.db_command.settings.engine.url",
<ide> make_url("mysql://root@mysql/airflow")
<ide> )
<del> def test_cli_shell_mysql(self, mock_tmp_file, mock_subprocess):
<add> def test_cli_shell_mysql(self, mock_tmp_file, mock_execute_interactive):
<ide> mock_tmp_file.return_value.__enter__.return_value.name = "/tmp/name"
<ide> db_command.shell(self.parser.parse_args(['db', 'shell']))
<del> mock_subprocess.Popen.assert_called_once_with(
<add> mock_execute_interactive.assert_called_once_with(
<ide> ['mysql', '--defaults-extra-file=/tmp/name']
<ide> )
<ide> mock_tmp_file.return_value.__enter__.return_value.write.assert_called_once_with(
<ide> b'[client]\nhost = mysql\nuser = root\npassword = \nport = '
<ide> b'\ndatabase = airflow'
<ide> )
<ide>
<del> @mock.patch("airflow.cli.commands.db_command.subprocess")
<add> @mock.patch("airflow.cli.commands.db_command.execute_interactive")
<ide> @mock.patch(
<ide> "airflow.cli.commands.db_command.settings.engine.url",
<ide> make_url("sqlite:////root/airflow/airflow.db")
<ide> )
<del> def test_cli_shell_sqlite(self, mock_subprocess):
<add> def test_cli_shell_sqlite(self, mock_execute_interactive):
<ide> db_command.shell(self.parser.parse_args(['db', 'shell']))
<del> mock_subprocess.Popen.assert_called_once_with(
<add> mock_execute_interactive.assert_called_once_with(
<ide> ['sqlite3', '/root/airflow/airflow.db']
<ide> )
<ide>
<del> @mock.patch("airflow.cli.commands.db_command.subprocess")
<add> @mock.patch("airflow.cli.commands.db_command.execute_interactive")
<ide> @mock.patch(
<ide> "airflow.cli.commands.db_command.settings.engine.url",
<ide> make_url("postgresql+psycopg2://postgres:airflow@postgres/airflow")
<ide> )
<del> def test_cli_shell_postgres(self, mock_subprocess):
<add> def test_cli_shell_postgres(self, mock_execute_interactive):
<ide> db_command.shell(self.parser.parse_args(['db', 'shell']))
<del> mock_subprocess.Popen.assert_called_once_with(
<add> mock_execute_interactive.assert_called_once_with(
<ide> ['psql'], env=mock.ANY
<ide> )
<del> _, kwargs = mock_subprocess.Popen.call_args
<add> _, kwargs = mock_execute_interactive.call_args
<ide> env = kwargs['env']
<ide> postgres_env = {k: v for k, v in env.items() if k.startswith('PG')}
<ide> self.assertEqual({
| 3
|
Ruby
|
Ruby
|
add tests to serialize and deserialze individually
|
b59c7c7e69144bafd6d45f1be68f885e8995b6f1
|
<ide><path>activejob/test/cases/argument_serialization_test.rb
<ide> class ArgumentSerializationTest < ActiveSupport::TestCase
<ide> assert_arguments_roundtrip([a: 1, "b" => 2])
<ide> end
<ide>
<add> test "serialize a hash" do
<add> symbol_key = { a: 1 }
<add> string_key = { "a" => 1 }
<add> indifferent_access = { a: 1 }.with_indifferent_access
<add>
<add> assert_equal(
<add> { "a" => 1, "_aj_symbol_keys" => ["a"] },
<add> ActiveJob::Arguments.serialize([symbol_key]).first
<add> )
<add> assert_equal(
<add> { "a" => 1, "_aj_symbol_keys" => [] },
<add> ActiveJob::Arguments.serialize([string_key]).first
<add> )
<add> assert_equal(
<add> { "a" => 1, "_aj_hash_with_indifferent_access" => true },
<add> ActiveJob::Arguments.serialize([indifferent_access]).first
<add> )
<add> end
<add>
<add> test "deserialize a hash" do
<add> symbol_key = { "a" => 1, "_aj_symbol_keys" => ["a"] }
<add> string_key = { "a" => 1, "_aj_symbol_keys" => [] }
<add> another_string_key = { "a" => 1 }
<add> indifferent_access = { "a" => 1, "_aj_hash_with_indifferent_access" => true }
<add>
<add> assert_equal(
<add> { a: 1 },
<add> ActiveJob::Arguments.deserialize([symbol_key]).first
<add> )
<add> assert_equal(
<add> { "a" => 1 },
<add> ActiveJob::Arguments.deserialize([string_key]).first
<add> )
<add> assert_equal(
<add> { "a" => 1 },
<add> ActiveJob::Arguments.deserialize([another_string_key]).first
<add> )
<add> assert_equal(
<add> { "a" => 1 },
<add> ActiveJob::Arguments.deserialize([indifferent_access]).first
<add> )
<add> end
<add>
<ide> test "should maintain hash with indifferent access" do
<ide> symbol_key = { a: 1 }
<ide> string_key = { "a" => 1 }
| 1
|
Javascript
|
Javascript
|
add cluster 'bind twice' test
|
cacd3ae004d9796c746472433b83252cf5edb7e7
|
<ide><path>test/simple/test-cluster-bind-twice.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>// This test starts two clustered HTTP servers on the same port. It expects the
<add>// first cluster to succeed and the second cluster to fail with EADDRINUSE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var cluster = require('cluster');
<add>var fork = require('child_process').fork;
<add>var http = require('http');
<add>
<add>var id = process.argv[2];
<add>
<add>if (!id) {
<add> var a = fork(__filename, ['one']);
<add> var b = fork(__filename, ['two']);
<add>
<add> a.on('message', function(m) {
<add> assert.equal(m, 'READY');
<add> b.send('START');
<add> });
<add>
<add> var ok = false;
<add>
<add> b.on('message', function(m) {
<add> assert.equal(m, 'EADDRINUSE');
<add> a.kill();
<add> b.kill();
<add> ok = true;
<add> });
<add>
<add> process.on('exit', function() {
<add> a.kill();
<add> b.kill();
<add> assert(ok);
<add> });
<add>}
<add>else if (id === 'one') {
<add> if (cluster.isMaster) cluster.fork();
<add> http.createServer(assert.fail).listen(common.PORT, function() {
<add> process.send('READY');
<add> });
<add>}
<add>else if (id === 'two') {
<add> if (cluster.isMaster) cluster.fork();
<add> process.on('message', function(m) {
<add> assert.equal(m, 'START');
<add> var server = http.createServer(assert.fail);
<add> server.listen(common.PORT, assert.fail);
<add> server.on('error', function(e) {
<add> assert.equal(e.code, 'EADDRINUSE');
<add> process.send(e.code);
<add> });
<add> });
<add>}
<add>else {
<add> assert(0); // bad command line argument
<add>}
| 1
|
Ruby
|
Ruby
|
use +/<tt> instead of ` in the rdoc [ci skip]
|
94554514fe8c03fae6b9fa389c6288415cb9e717
|
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def cache_key_with_version
<ide> # end
<ide> # # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1
<ide> #
<del> # If `all_queries: true` is passed, scoping will apply to all queries
<del> # for the relation including `update` and `delete` on instances.
<del> # Once `all_queries` is set to true it cannot be set to false in a
<add> # If <tt>all_queries: true</tt> is passed, scoping will apply to all queries
<add> # for the relation including +update+ and +delete+ on instances.
<add> # Once +all_queries+ is set to true it cannot be set to false in a
<ide> # nested block.
<ide> #
<ide> # Please check unscoped if you want to remove all previous scopes (including
| 1
|
Python
|
Python
|
use unicodecsv to make it py3 compatible
|
5603afa5f706347f939757a1e7a5cd30d51bfd8a
|
<ide><path>airflow/hooks/hive_hooks.py
<ide> from __future__ import print_function
<ide> from builtins import zip
<ide> from past.builtins import basestring
<del>import csv
<add>import unicodecsv as csv
<ide> import logging
<ide> import re
<ide> import subprocess
<ide> def to_csv(
<ide> schema = cur.description
<ide> with open(csv_filepath, 'wb') as f:
<ide> writer = csv.writer(f, delimiter=delimiter,
<del> lineterminator=lineterminator)
<add> lineterminator=lineterminator, encoding='utf-8')
<ide> if output_header:
<ide> writer.writerow([c[0]
<ide> for c in cur.description])
<ide><path>setup.py
<ide> def run(self):
<ide> 'hive-thrift-py>=0.0.1',
<ide> 'pyhive>=0.1.3',
<ide> 'impyla>=0.13.3',
<add> 'unicodecsv>=0.14.1'
<ide> ]
<ide> jdbc = ['jaydebeapi>=0.2.0']
<del>mssql = ['pymssql>=2.1.1', 'unicodecsv>=0.13.0']
<add>mssql = ['pymssql>=2.1.1', 'unicodecsv>=0.14.1']
<ide> mysql = ['mysqlclient>=1.3.6']
<ide> optional = ['librabbitmq>=1.6.1']
<ide> oracle = ['cx_Oracle>=5.1.2']
| 2
|
Javascript
|
Javascript
|
fix a bug with item controllers
|
8714394fd9ced690512b2b5ae9a795b6ff2d5136
|
<ide><path>packages/ember-runtime/lib/controllers/array_controller.js
<ide> Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin,
<ide> },
<ide>
<ide> arrayContentDidChange: function(idx, removedCnt, addedCnt) {
<del> this._super(idx, removedCnt, addedCnt);
<del>
<ide> var subContainers = get(this, 'subContainers'),
<ide> subContainersToRemove = subContainers.slice(idx, idx+removedCnt);
<ide>
<ide> Ember.ArrayController = Ember.ArrayProxy.extend(Ember.ControllerMixin,
<ide> });
<ide>
<ide> replace(subContainers, idx, removedCnt, new Array(addedCnt));
<add>
<add> // The shadow array of subcontainers must be updated before we trigger
<add> // observers, otherwise observers will get the wrong subcontainer when
<add> // calling `objectAt`
<add> this._super(idx, removedCnt, addedCnt);
<ide> },
<ide>
<ide> init: function() {
<ide><path>packages/ember-runtime/tests/controllers/item_controller_class_test.js
<ide> test("if `lookupItemController` returns a string, it must be resolvable by the c
<ide> /NonExistant/,
<ide> "`lookupItemController` must return either null or a valid controller name");
<ide> });
<add>
<add>test("array observers can invoke `objectAt` without overwriting existing item controllers", function() {
<add> createArrayController();
<add>
<add> var tywinController = arrayController.objectAtContent(0),
<add> arrayObserverCalled = false;
<add>
<add> arrayController.reopen({
<add> lannistersWillChange: Ember.K,
<add> lannistersDidChange: function(_, idx, removedAmt, addedAmt) {
<add> arrayObserverCalled = true;
<add> equal(this.objectAt(idx).get('name'), "Tyrion", "Array observers get the right object via `objectAt`");
<add> }
<add> });
<add> arrayController.addArrayObserver(arrayController, {
<add> willChange: 'lannistersWillChange',
<add> didChange: 'lannistersDidChange'
<add> });
<add>
<add> Ember.run(function() {
<add> lannisters.unshiftObject(tyrion);
<add> });
<add>
<add> equal(arrayObserverCalled, true, "Array observers are called normally");
<add> equal(tywinController.get('name'), "Tywin", "Array observers calling `objectAt` does not overwrite existing controllers' content");
<add>});
<add>
| 2
|
Java
|
Java
|
fix duplicate invoke method of transformedbeanname
|
ab8e388412858339099e299f7db34dffcbde8460
|
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
<ide> protected Object getObjectForBeanInstance(
<ide> return beanInstance;
<ide> }
<ide> if (!(beanInstance instanceof FactoryBean)) {
<del> throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
<add> throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
<ide> }
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
check server status in test-tls-psk-client
|
0ee6643d36d357da833b9c6b1462227463c765bd
|
<ide><path>test/sequential/test-tls-psk-client.js
<ide> const server = spawn(common.opensslCli, [
<ide> '-psk_hint', IDENTITY,
<ide> '-nocert',
<ide> '-rev',
<del>]);
<add>], { encoding: 'utf8' });
<add>let serverErr = '';
<add>let serverOut = '';
<add>server.stderr.on('data', (data) => serverErr += data);
<add>server.stdout.on('data', (data) => serverOut += data);
<add>server.on('error', common.mustNotCall());
<add>server.on('exit', (code, signal) => {
<add> // Server is expected to be terminated by cleanUp().
<add> assert.strictEqual(code, null,
<add> `'${server.spawnfile} ${server.spawnargs.join(' ')}' unexpected exited with output:\n${serverOut}\n${serverErr}`);
<add> assert.strictEqual(signal, 'SIGTERM');
<add>});
<ide>
<ide> const cleanUp = (err) => {
<ide> clearTimeout(timeout);
| 1
|
Python
|
Python
|
fix comment typos under models/research
|
94be38c75f8946fabb35e2ac5c09050262d17aa9
|
<ide><path>research/attention_ocr/python/inception_preprocessing.py
<ide> def distort_color(image, color_ordering=0, fast_mode=True, scope=None):
<ide>
<ide> Each color distortion is non-commutative and thus ordering of the color ops
<ide> matters. Ideally we would randomly permute the ordering of the color ops.
<del> Rather then adding that level of complication, we select a distinct ordering
<add> Rather than adding that level of complication, we select a distinct ordering
<ide> of color ops for each preprocessing thread.
<ide>
<ide> Args:
<ide><path>research/inception/inception/image_processing.py
<ide> def distort_color(image, thread_id=0, scope=None):
<ide>
<ide> Each color distortion is non-commutative and thus ordering of the color ops
<ide> matters. Ideally we would randomly permute the ordering of the color ops.
<del> Rather then adding that level of complication, we select a distinct ordering
<add> Rather than adding that level of complication, we select a distinct ordering
<ide> of color ops for each preprocessing thread.
<ide>
<ide> Args:
<ide><path>research/slim/preprocessing/inception_preprocessing.py
<ide> def distort_color(image, color_ordering=0, fast_mode=True, scope=None):
<ide>
<ide> Each color distortion is non-commutative and thus ordering of the color ops
<ide> matters. Ideally we would randomly permute the ordering of the color ops.
<del> Rather then adding that level of complication, we select a distinct ordering
<add> Rather than adding that level of complication, we select a distinct ordering
<ide> of color ops for each preprocessing thread.
<ide>
<ide> Args:
<ide><path>research/tcn/preprocessing.py
<ide> def distort_color(image, color_ordering=0, fast_mode=True, scope=None):
<ide>
<ide> Each color distortion is non-commutative and thus ordering of the color ops
<ide> matters. Ideally we would randomly permute the ordering of the color ops.
<del> Rather then adding that level of complication, we select a distinct ordering
<add> Rather than adding that level of complication, we select a distinct ordering
<ide> of color ops for each preprocessing thread.
<ide> Args:
<ide> image: 3-D Tensor containing single image in [0, 1].
| 4
|
Ruby
|
Ruby
|
add homepage and desc into regex
|
3c418cfb4eaa5eeafb3613172954c01aca831af1
|
<ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def merge
<ide> indent = s.slice(/^ +stable do/).length - "stable do".length
<ide> string = s.sub!(/^ {#{indent}}stable do(.|\n)+?^ {#{indent}}end\n/m, '\0' + output + "\n")
<ide> else
<del> string = s.sub!(/(
<del> \ {2}( # two spaces at the beginning
<del> url\ ['"][\S\ ]+['"] # url with a string
<del> (
<del> ,[\S\ ]*$ # url may have options
<del> (\n^\ {3}[\S\ ]+$)* # options can be in multiple lines
<del> )?|
<del> (sha1|sha256|head|version|mirror)\ ['"][\S\ ]+['"]| # specs with a string
<del> revision\ \d+ # revision with a number
<del> )\n+ # multiple empty lines
<del> )+
<del> /mx, '\0' + output + "\n")
<add> string = s.sub!(
<add> /(
<add> \ {2}( # two spaces at the beginning
<add> url\ ['"][\S\ ]+['"] # url with a string
<add> (
<add> ,[\S\ ]*$ # url may have options
<add> (\n^\ {3}[\S\ ]+$)* # options can be in multiple lines
<add> )?|
<add> (homepage|desc|sha1|sha256|head|version|mirror)\ ['"][\S\ ]+['"]| # specs with a string
<add> revision\ \d+ # revision with a number
<add> )\n+ # multiple empty lines
<add> )+
<add> /mx, '\0' + output + "\n")
<ide> end
<ide> odie 'Bottle block addition failed!' unless string
<ide> end
| 1
|
Ruby
|
Ruby
|
correct doc typo [ci skip]
|
07c4f253704d398506d433adce0f40b53927d2b5
|
<ide><path>activerecord/lib/active_record/database_configurations.rb
<ide> def initialize(configurations = {})
<ide> # the returned list. Most of the time we're only iterating over the write
<ide> # connection (i.e. migrations don't need to run for the write and read connection).
<ide> # Defaults to +false+.
<del> # * <tt>include_hidden:</tte Determines whether to include replicas and configurations
<add> # * <tt>include_hidden:</tt> Determines whether to include replicas and configurations
<ide> # hidden by +database_tasks: false+ in the returned list. Most of the time we're only
<ide> # iterating over the primary connections (i.e. migrations don't need to run for the
<ide> # write and read connection). Defaults to +false+.
| 1
|
Python
|
Python
|
fix all is_torch_tpu_available issues
|
7c4c6f60849fa8c8fa5904e2c6a6e1a21c981f56
|
<ide><path>examples/pytorch/question-answering/trainer_qa.py
<ide> from transformers.trainer_utils import PredictionOutput
<ide>
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide> import torch_xla.debug.metrics as met
<ide>
<ide><path>examples/pytorch/question-answering/trainer_seq2seq_qa.py
<ide> from transformers.trainer_utils import PredictionOutput
<ide>
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide> import torch_xla.debug.metrics as met
<ide>
<ide><path>examples/research_projects/quantization-qdqbert/trainer_quant_qa.py
<ide>
<ide> logger = logging.getLogger(__name__)
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide> import torch_xla.debug.metrics as met
<ide>
<ide><path>src/transformers/benchmark/benchmark_args.py
<ide> if is_torch_available():
<ide> import torch
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide>
<ide>
<ide><path>src/transformers/testing_utils.py
<ide> def require_torch_tpu(test_case):
<ide> """
<ide> Decorator marking a test that requires a TPU (in PyTorch).
<ide> """
<del> return unittest.skipUnless(is_torch_tpu_available(), "test requires PyTorch TPU")(test_case)
<add> return unittest.skipUnless(is_torch_tpu_available(check_device=False), "test requires PyTorch TPU")(test_case)
<ide>
<ide>
<ide> if is_torch_available():
<ide><path>src/transformers/trainer.py
<ide> if is_datasets_available():
<ide> import datasets
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide> import torch_xla.debug.metrics as met
<ide> import torch_xla.distributed.parallel_loader as pl
<ide><path>src/transformers/trainer_pt_utils.py
<ide> if is_training_run_on_sagemaker():
<ide> logging.add_handler(StreamHandler(sys.stdout))
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide>
<ide> # this is used to suppress an undesired warning emitted by pytorch versions 1.4.2-1.7.0
<ide><path>src/transformers/trainer_utils.py
<ide> def is_main_process(local_rank):
<ide> Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on
<ide> `local_rank`.
<ide> """
<del> if is_torch_tpu_available():
<add> if is_torch_tpu_available(check_device=True):
<ide> import torch_xla.core.xla_model as xm
<ide>
<ide> return xm.get_ordinal() == 0
<ide> def total_processes_number(local_rank):
<ide> """
<ide> Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs.
<ide> """
<del> if is_torch_tpu_available():
<add> if is_torch_tpu_available(check_device=True):
<ide> import torch_xla.core.xla_model as xm
<ide>
<ide> return xm.xrt_world_size()
<ide><path>src/transformers/training_args.py
<ide> import torch
<ide> import torch.distributed as dist
<ide>
<del>if is_torch_tpu_available():
<add>if is_torch_tpu_available(check_device=False):
<ide> import torch_xla.core.xla_model as xm
<ide>
<ide>
<ide><path>src/transformers/utils/import_utils.py
<ide> def is_ftfy_available():
<ide> return _ftfy_available
<ide>
<ide>
<del>def is_torch_tpu_available():
<add>def is_torch_tpu_available(check_device=True):
<add> "Checks if `torch_xla` is installed and potentially if a TPU is in the environment"
<ide> if not _torch_available:
<ide> return False
<del> if importlib.util.find_spec("torch_xla") is None:
<del> return False
<del> import torch_xla.core.xla_model as xm
<add> if importlib.util.find_spec("torch_xla") is not None:
<add> if check_device:
<add> # We need to check if `xla_device` can be found, will raise a RuntimeError if not
<add> try:
<add> import torch_xla.core.xla_model as xm
<ide>
<del> # We need to check if `xla_device` can be found, will raise a RuntimeError if not
<del> try:
<del> xm.xla_device()
<add> _ = xm.xla_device()
<add> return True
<add> except RuntimeError:
<add> return False
<ide> return True
<del> except RuntimeError:
<del> return False
<add> return False
<ide>
<ide>
<ide> def is_torchdynamo_available():
| 10
|
PHP
|
PHP
|
add more assertions
|
cda64c05ca73c0f9421589a5bcdf4fabfe7543da
|
<ide><path>src/Illuminate/Database/Eloquent/Relations/Pivot.php
<ide> protected function setKeysForSaveQuery(Builder $query)
<ide> ));
<ide>
<ide> return $query->where($this->relatedKey, $this->getOriginal(
<del> $this->relatedKey, $this->getAttribute($this->foreignKey)
<add> $this->relatedKey, $this->getAttribute($this->relatedKey)
<ide> ));
<ide> }
<ide>
<ide><path>tests/Integration/Database/EloquentBelongsToManyTest.php
<ide> public function custom_pivot_class()
<ide>
<ide> $post->tagsWithCustomPivot()->attach($tag->id);
<ide>
<del> $post->tagsWithCustomAccessor()->attach($tag->id);
<del>
<ide> $this->assertInstanceOf(CustomPivot::class, $post->tagsWithCustomPivot[0]->pivot);
<ide>
<ide> $this->assertEquals([
<ide> 'post_id' => '1',
<ide> 'tag_id' => '1',
<ide> ], $post->tagsWithCustomAccessor[0]->tag->toArray());
<add>
<add> $pivot = $post->tagsWithCustomPivot[0]->pivot;
<add> $pivot->tag_id = 2;
<add> $pivot->save();
<add>
<add> $this->assertEquals(1, CustomPivot::count());
<add> $this->assertEquals(1, CustomPivot::first()->post_id);
<add> $this->assertEquals(2, CustomPivot::first()->tag_id);
<ide> }
<ide>
<ide> /**
<ide> public function posts()
<ide>
<ide> class CustomPivot extends Pivot
<ide> {
<add> protected $table = 'posts_tags';
<ide> }
| 2
|
Javascript
|
Javascript
|
use error code rather than message in test
|
4f0ab76b6c29da74b29125a3ec83bb06e77c2aad
|
<ide><path>test/parallel/test-child-process-fork-closed-channel-segfault.js
<ide> const server = net
<ide> send(function(err) {
<ide> // Ignore errors when sending the second handle because the worker
<ide> // may already have exited.
<del> if (err && err.message !== 'Channel closed') {
<add> if (err && err.code !== 'ERR_IPC_CHANNEL_CLOSED') {
<ide> throw err;
<ide> }
<ide> });
| 1
|
Javascript
|
Javascript
|
move nulldependencytemplate within nulldependency
|
c934d2644d3149d572cf1896bd6326b46835ecaf
|
<ide><path>lib/dependencies/NullDependency.js
<ide> class NullDependency extends Dependency {
<ide> }
<ide> }
<ide>
<add>NullDependency.Template = class NullDependencyTemplate {
<add> apply() {}
<add>}
<add>
<ide> module.exports = NullDependency;
<ide><path>lib/dependencies/NullDependencyTemplate.js
<del>/*
<del> MIT License http://www.opensource.org/licenses/mit-license.php
<del> Author Tobias Koppers @sokra
<del>*/
<del>"use strict";
<del>class NullDependencyTemplate {
<del> apply() {}
<del>}
<del>
<del>module.exports = NullDependencyTemplate;
<ide><path>lib/dependencies/RequireEnsureItemDependency.js
<ide> Author Tobias Koppers @sokra
<ide> */
<ide> var ModuleDependency = require("./ModuleDependency");
<add>var NullDependency = require("./NullDependency");
<ide>
<ide> function RequireEnsureItemDependency(request) {
<ide> ModuleDependency.call(this, request);
<ide> RequireEnsureItemDependency.prototype = Object.create(ModuleDependency.prototype
<ide> RequireEnsureItemDependency.prototype.constructor = RequireEnsureItemDependency;
<ide> RequireEnsureItemDependency.prototype.type = "require.ensure item";
<ide>
<del>RequireEnsureItemDependency.Template = require("./NullDependencyTemplate");
<add>RequireEnsureItemDependency.Template = NullDependency.Template;
| 3
|
PHP
|
PHP
|
add missing file block
|
eeae636ff12a670bc1e223283bd89691438bb04f
|
<ide><path>src/Error/Renderer/TextRenderer.php
<ide> <?php
<ide> declare(strict_types=1);
<ide>
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.4.0
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<ide> namespace Cake\Error\Renderer;
<ide>
<ide> use Cake\Error\ErrorRendererInterface;
| 1
|
Text
|
Text
|
update build requirements in readme
|
86b7fec0bb0cb1ce5a77a32bad1c12ea4408d272
|
<ide><path>README.md
<ide> Atom will automatically update when a new release is available.
<ide>
<ide> ### OS X Requirements
<ide> * OS X 10.8 or later
<del> * [node.js](http://nodejs.org/)
<del> * Command Line Tools for [Xcode](https://developer.apple.com/xcode/downloads/) (Run `xcode-select --install`)
<add> * [node.js](http://nodejs.org/download/) v0.10.x
<add> * Command Line Tools for [Xcode](https://developer.apple.com/xcode/downloads/) (run `xcode-select --install` to install)
<ide>
<ide> ```sh
<ide> git clone https://github.com/atom/atom
<ide> Atom will automatically update when a new release is available.
<ide> ### Linux Requirements
<ide> * Ubuntu LTS 12.04 64-bit is the recommended platform
<ide> * OS with 64-bit architecture
<del> * [node.js](http://nodejs.org/) v0.10.x
<add> * [node.js](http://nodejs.org/download/) v0.10.x
<ide> * [npm](http://www.npmjs.org/) v1.4.x
<ide> * `sudo apt-get install libgnome-keyring-dev`
<ide> * `npm config set python /usr/bin/python2 -g` to ensure that gyp uses Python 2
<ide> Atom will automatically update when a new release is available.
<ide> ### Windows Requirements
<ide> * Windows 7 or later
<ide> * [Visual C++ 2010 Express](http://www.microsoft.com/visualstudio/eng/products/visual-studio-2010-express)
<del> * [node.js - 32bit](http://nodejs.org/)
<add> * [node.js - 32bit](http://nodejs.org/download/) v0.10.x
<ide> * [Python 2.7.x](http://www.python.org/download/)
<ide> * [GitHub for Windows](http://windows.github.com/)
<ide> * [Git for Windows](http://git-scm.com/download/win)
| 1
|
PHP
|
PHP
|
fix code style
|
354a94ee6a379a4a4fa4fad0b090aea05d795fcb
|
<ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> public function compileSavepointRollBack($name)
<ide> *
<ide> * @return string
<ide> */
<del> public function compileRandom(){
<add> public function compileRandom()
<add> {
<ide> return "RANDOM()";
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Query/Grammars/MySqlGrammar.php
<ide> protected function wrapJsonSelector($value)
<ide> *
<ide> * @return string
<ide> */
<del> public function compileRandom(){
<add> public function compileRandom()
<add> {
<ide> return "RAND()";
<ide> }
<ide> }
<ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php
<ide> protected function wrapTableValuedFunction($table)
<ide> *
<ide> * @return string
<ide> */
<del> public function compileRandom(){
<add> public function compileRandom()
<add> {
<ide> return "NEWID()";
<ide> }
<ide> }
| 3
|
Javascript
|
Javascript
|
add link to photo
|
2d9c0d9900adf26c8cb1e408e2a7fda843f399bc
|
<ide><path>app.js
<ide> app.use(helmet.contentSecurityPolicy({
<ide> scriptSrc: ['*.optimizely.com'].concat(trusted),
<ide> 'connect-src': process.env.NODE_ENV === 'development' ? ['ws://localhost:3001/', 'http://localhost:3001/'] : [],
<ide> styleSrc: trusted,
<del> imgSrc: ['*.evernote.com', '*.amazonaws.com', "data:"].concat(trusted),
<add> imgSrc: ['*.evernote.com', '*.amazonaws.com', "data:", '*.licdn.com'].concat(trusted),
<ide> fontSrc: ["'self", '*.googleapis.com'].concat(trusted),
<ide> mediaSrc: ['*.amazonaws.com', '*.twitter.com'],
<ide> frameSrc: ['*.gitter.im', '*.vimeo.com', '*.twitter.com'],
| 1
|
Python
|
Python
|
allow lazy logging
|
ea7a8f7d808319f91c0e0ae41ea7b159891eef2b
|
<ide><path>airflow/settings.py
<ide> TIMEZONE = pendulum.tz.timezone(tz)
<ide> except Exception:
<ide> pass
<del>log.info("Configured default timezone %s" % TIMEZONE)
<add>log.info("Configured default timezone %s", TIMEZONE)
<ide>
<ide>
<ide> HEADER = '\n'.join([
<ide> def configure_vars():
<ide>
<ide>
<ide> def configure_orm(disable_connection_pool=False):
<del> log.debug("Setting up DB connection pool (PID %s)" % os.getpid())
<add> log.debug("Setting up DB connection pool (PID %s)", os.getpid())
<ide> global engine
<ide> global Session
<ide> engine_args = {}
<ide> def import_local_settings():
<ide> if not k.startswith("__"):
<ide> globals()[k] = v
<ide>
<del> log.info("Loaded airflow_local_settings from " + airflow_local_settings.__file__ + ".")
<add> log.info("Loaded airflow_local_settings from %s .", airflow_local_settings.__file__)
<ide> except ImportError:
<ide> log.debug("Failed to import airflow_local_settings.", exc_info=True)
<ide>
| 1
|
Javascript
|
Javascript
|
add dev/start timing to pr stats
|
9222ca9f3f225469f9d1840cbfe7af365664b829
|
<ide><path>.github/actions/next-stats-action/src/run/collect-stats.js
<ide> module.exports = async function collectStats(
<ide> (hasPagesToFetch || hasPagesToBench)
<ide> ) {
<ide> const port = await getPort()
<add> const startTime = Date.now()
<ide> const child = spawn(statsConfig.appStartCommand, {
<ide> cwd: curDir,
<ide> env: {
<ide> module.exports = async function collectStats(
<ide> })
<ide> let exitCode = null
<ide> let logStderr = true
<del> child.stdout.on('data', (data) => process.stdout.write(data))
<add>
<add> let serverReadyResolve
<add> let serverReadyResolved = false
<add> const serverReadyPromise = new Promise((resolve) => {
<add> serverReadyResolve = resolve
<add> })
<add>
<add> child.stdout.on('data', (data) => {
<add> if (data.toString().includes('started server') && !serverReadyResolved) {
<add> serverReadyResolved = true
<add> serverReadyResolve()
<add> }
<add> process.stdout.write(data)
<add> })
<ide> child.stderr.on('data', (data) => logStderr && process.stderr.write(data))
<ide>
<ide> child.on('exit', (code) => {
<add> if (!serverReadyResolved) {
<add> serverReadyResolve()
<add> serverReadyResolved = true
<add> }
<ide> exitCode = code
<ide> })
<del> // give app a second to start up
<del> await new Promise((resolve) => setTimeout(() => resolve(), 1500))
<add>
<add> await serverReadyPromise
<add> if (!orderedStats['General']) {
<add> orderedStats['General'] = {}
<add> }
<add> orderedStats['General']['nextStartReadyDuration (ms)'] =
<add> Date.now() - startTime
<ide>
<ide> if (exitCode !== null) {
<ide> throw new Error(
<ide><path>.github/actions/next-stats-action/src/run/index.js
<ide> const path = require('path')
<ide> const fs = require('fs-extra')
<add>const getPort = require('get-port')
<ide> const glob = require('../util/glob')
<ide> const exec = require('../util/exec')
<ide> const logger = require('../util/logger')
<ide> async function runConfigs(
<ide> }
<ide>
<ide> const collectedStats = await collectStats(config, statsConfig)
<del> curStats = {
<del> ...curStats,
<del> ...collectedStats,
<add>
<add> for (const key of Object.keys(collectedStats)) {
<add> curStats[key] = Object.assign({}, curStats[key], collectedStats[key])
<ide> }
<ide>
<ide> const applyRenames = (renames, stats) => {
<ide> async function runConfigs(
<ide> env: yarnEnvValues,
<ide> })
<ide> curStats.General.buildDurationCached = Date.now() - secondBuildStart
<add>
<add> if (statsConfig.appDevCommand) {
<add> const port = await getPort()
<add> const startTime = Date.now()
<add> const child = exec.spawn(statsConfig.appDevCommand, {
<add> cwd: statsAppDir,
<add> env: {
<add> PORT: port,
<add> },
<add> stdio: 'pipe',
<add> })
<add>
<add> let serverReadyResolve
<add> let serverReadyResolved = false
<add> const serverReadyPromise = new Promise((resolve) => {
<add> serverReadyResolve = resolve
<add> })
<add>
<add> child.stdout.on('data', (data) => {
<add> if (
<add> data.toString().includes('started server') &&
<add> !serverReadyResolved
<add> ) {
<add> serverReadyResolved = true
<add> serverReadyResolve()
<add> }
<add> process.stdout.write(data)
<add> })
<add> child.stderr.on('data', (data) => process.stderr.write(data))
<add>
<add> child.on('exit', (code) => {
<add> if (!serverReadyResolved) {
<add> serverReadyResolve()
<add> serverReadyResolved = true
<add> }
<add> exitCode = code
<add> })
<add>
<add> setTimeout(() => {
<add> if (!serverReadyResolved) {
<add> child.kill()
<add> }
<add> }, 3 * 1000)
<add>
<add> await serverReadyPromise
<add> child.kill()
<add>
<add> curStats['General']['nextDevReadyDuration'] = Date.now() - startTime
<add> }
<ide> }
<ide>
<ide> logger(`Finished running: ${config.title}`)
<ide><path>test/.stats-app/stats-config.js
<ide> module.exports = {
<ide> commentReleaseHeading: 'Stats from current release',
<ide> appBuildCommand: 'NEXT_TELEMETRY_DISABLED=1 yarn next build',
<ide> appStartCommand: 'NEXT_TELEMETRY_DISABLED=1 yarn next start --port $PORT',
<add> appDevCommand: 'NEXT_TELEMETRY_DISABLED=1 yarn next --port $PORT',
<ide> mainRepo: 'vercel/next.js',
<ide> mainBranch: 'canary',
<ide> autoMergeMain: true,
| 3
|
Python
|
Python
|
resolve typeerror on `.get` from nested groups
|
dd2cdd9c4f8688f965d7b5658fa4956d083a7b8b
|
<ide><path>celery/result.py
<ide> def iterate(self, timeout=None, propagate=True, interval=0.5):
<ide>
<ide> def get(self, timeout=None, propagate=True, interval=0.5,
<ide> callback=None, no_ack=True, on_message=None,
<del> disable_sync_subtasks=True):
<add> disable_sync_subtasks=True, on_interval=None):
<ide> """See :meth:`join`.
<ide>
<ide> This is here for API compatibility with :class:`AsyncResult`,
<ide> def get(self, timeout=None, propagate=True, interval=0.5,
<ide> return (self.join_native if self.supports_native_join else self.join)(
<ide> timeout=timeout, propagate=propagate,
<ide> interval=interval, callback=callback, no_ack=no_ack,
<del> on_message=on_message, disable_sync_subtasks=disable_sync_subtasks
<add> on_message=on_message, disable_sync_subtasks=disable_sync_subtasks,
<add> on_interval=on_interval,
<ide> )
<ide>
<ide> def join(self, timeout=None, propagate=True, interval=0.5,
<ide><path>t/integration/test_canvas.py
<ide> def test_parent_ids(self, manager):
<ide> assert parent_id == expected_parent_id
<ide> assert value == i + 2
<ide>
<add> @flaky
<add> def test_nested_group(self, manager):
<add> assert manager.inspect().ping()
<add>
<add> c = group(
<add> add.si(1, 10),
<add> group(
<add> add.si(1, 100),
<add> group(
<add> add.si(1, 1000),
<add> add.si(1, 2000),
<add> ),
<add> ),
<add> )
<add> res = c()
<add>
<add> assert res.get(timeout=TIMEOUT) == [11, 101, 1001, 2001]
<add>
<ide>
<ide> def assert_ids(r, expected_value, expected_root_id, expected_parent_id):
<ide> root_id, parent_id, value = r.get(timeout=TIMEOUT)
<ide> def test_group_chain(self, manager):
<ide> res = c()
<ide> assert res.get(timeout=TIMEOUT) == [12, 13, 14, 15]
<ide>
<add> @flaky
<add> def test_nested_group_chain(self, manager):
<add> try:
<add> manager.app.backend.ensure_chords_allowed()
<add> except NotImplementedError as e:
<add> raise pytest.skip(e.args[0])
<add>
<add> if not manager.app.backend.supports_native_join:
<add> raise pytest.skip('Requires native join support.')
<add> c = chain(
<add> add.si(1, 0),
<add> group(
<add> add.si(1, 100),
<add> chain(
<add> add.si(1, 200),
<add> group(
<add> add.si(1, 1000),
<add> add.si(1, 2000),
<add> ),
<add> ),
<add> ),
<add> add.si(1, 10),
<add> )
<add> res = c()
<add> assert res.get(timeout=TIMEOUT) == 11
<add>
<ide> @flaky
<ide> def test_parent_ids(self, manager):
<ide> if not manager.app.conf.result_backend.startswith('redis'):
<ide><path>t/unit/tasks/test_result.py
<ide> def get(self, propagate=True, **kwargs):
<ide> class MockAsyncResultSuccess(AsyncResult):
<ide> forgotten = False
<ide>
<add> def __init__(self, *args, **kwargs):
<add> self._result = kwargs.pop('result', 42)
<add> super(MockAsyncResultSuccess, self).__init__(*args, **kwargs)
<add>
<ide> def forget(self):
<ide> self.forgotten = True
<ide>
<ide> @property
<ide> def result(self):
<del> return 42
<add> return self._result
<ide>
<ide> @property
<ide> def state(self):
<ide> def test_forget(self):
<ide> for sub in subs:
<ide> assert sub.forgotten
<ide>
<add> def test_get_nested_without_native_join(self):
<add> backend = SimpleBackend()
<add> backend.supports_native_join = False
<add> ts = self.app.GroupResult(uuid(), [
<add> MockAsyncResultSuccess(uuid(), result='1.1',
<add> app=self.app, backend=backend),
<add> self.app.GroupResult(uuid(), [
<add> MockAsyncResultSuccess(uuid(), result='2.1',
<add> app=self.app, backend=backend),
<add> self.app.GroupResult(uuid(), [
<add> MockAsyncResultSuccess(uuid(), result='3.1',
<add> app=self.app, backend=backend),
<add> MockAsyncResultSuccess(uuid(), result='3.2',
<add> app=self.app, backend=backend),
<add> ]),
<add> ]),
<add> ])
<add> ts.app.backend = backend
<add>
<add> vals = ts.get()
<add> assert vals == [
<add> '1.1',
<add> [
<add> '2.1',
<add> [
<add> '3.1',
<add> '3.2',
<add> ]
<add> ],
<add> ]
<add>
<ide> def test_getitem(self):
<ide> subs = [MockAsyncResultSuccess(uuid(), app=self.app),
<ide> MockAsyncResultSuccess(uuid(), app=self.app)]
| 3
|
Javascript
|
Javascript
|
add missing var declaration for
|
c0389e3e37447aa7eb70cfb4837f4df6cdec5bba
|
<ide><path>src/core.js
<ide> jQuery.extend({
<ide>
<ide> // arg is for internal usage only
<ide> map: function( elems, callback, arg ) {
<del> var value, ret = [],
<add> var value, key, ret = [],
<ide> i = 0,
<ide> length = elems.length,
<ide> // jquery objects are treated as arrays
| 1
|
Javascript
|
Javascript
|
remove unused enqueuesetprops methods
|
cf4255445e7c1f0ce3061fbd2466d5da0877d714
|
<ide><path>src/isomorphic/classic/element/ReactElement.js
<ide> ReactElement.cloneAndReplaceKey = function(oldElement, newKey) {
<ide> return newElement;
<ide> };
<ide>
<del>ReactElement.cloneAndReplaceProps = function(oldElement, newProps) {
<del> var newElement = ReactElement(
<del> oldElement.type,
<del> oldElement.key,
<del> oldElement.ref,
<del> oldElement._self,
<del> oldElement._source,
<del> oldElement._owner,
<del> newProps
<del> );
<del>
<del> if (__DEV__) {
<del> // If the key on the original is valid, then the clone is valid
<del> newElement._store.validated = oldElement._store.validated;
<del> }
<del>
<del> return newElement;
<del>};
<del>
<ide> ReactElement.cloneElement = function(element, config, children) {
<ide> var propName;
<ide>
<ide><path>src/renderers/shared/reconciler/ReactUpdateQueue.js
<ide> 'use strict';
<ide>
<ide> var ReactCurrentOwner = require('ReactCurrentOwner');
<del>var ReactElement = require('ReactElement');
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<ide> var ReactUpdates = require('ReactUpdates');
<ide>
<del>var assign = require('Object.assign');
<ide> var invariant = require('invariant');
<ide> var warning = require('warning');
<ide>
<ide> var ReactUpdateQueue = {
<ide> enqueueUpdate(internalInstance);
<ide> },
<ide>
<del> /**
<del> * Sets a subset of the props.
<del> *
<del> * @param {ReactClass} publicInstance The instance that should rerender.
<del> * @param {object} partialProps Subset of the next props.
<del> * @internal
<del> */
<del> enqueueSetProps: function(publicInstance, partialProps) {
<del> var internalInstance = getInternalInstanceReadyForUpdate(
<del> publicInstance,
<del> 'setProps'
<del> );
<del> if (!internalInstance) {
<del> return;
<del> }
<del> ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps);
<del> },
<del>
<del> enqueueSetPropsInternal: function(internalInstance, partialProps) {
<del> var topLevelWrapper = internalInstance._topLevelWrapper;
<del> invariant(
<del> topLevelWrapper,
<del> 'setProps(...): You called `setProps` on a ' +
<del> 'component with a parent. This is an anti-pattern since props will ' +
<del> 'get reactively updated when rendered. Instead, change the owner\'s ' +
<del> '`render` method to pass the correct value as props to the component ' +
<del> 'where it is created.'
<del> );
<del>
<del> // Merge with the pending element if it exists, otherwise with existing
<del> // element props.
<del> var wrapElement = topLevelWrapper._pendingElement ||
<del> topLevelWrapper._currentElement;
<del> var element = wrapElement.props;
<del> var props = assign({}, element.props, partialProps);
<del> topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(
<del> wrapElement,
<del> ReactElement.cloneAndReplaceProps(element, props)
<del> );
<del>
<del> enqueueUpdate(topLevelWrapper);
<del> },
<del>
<del> /**
<del> * Replaces all of the props.
<del> *
<del> * @param {ReactClass} publicInstance The instance that should rerender.
<del> * @param {object} props New props.
<del> * @internal
<del> */
<del> enqueueReplaceProps: function(publicInstance, props) {
<del> var internalInstance = getInternalInstanceReadyForUpdate(
<del> publicInstance,
<del> 'replaceProps'
<del> );
<del> if (!internalInstance) {
<del> return;
<del> }
<del> ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props);
<del> },
<del>
<del> enqueueReplacePropsInternal: function(internalInstance, props) {
<del> var topLevelWrapper = internalInstance._topLevelWrapper;
<del> invariant(
<del> topLevelWrapper,
<del> 'replaceProps(...): You called `replaceProps` on a ' +
<del> 'component with a parent. This is an anti-pattern since props will ' +
<del> 'get reactively updated when rendered. Instead, change the owner\'s ' +
<del> '`render` method to pass the correct value as props to the component ' +
<del> 'where it is created.'
<del> );
<del>
<del> // Merge with the pending element if it exists, otherwise with existing
<del> // element props.
<del> var wrapElement = topLevelWrapper._pendingElement ||
<del> topLevelWrapper._currentElement;
<del> var element = wrapElement.props;
<del> topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(
<del> wrapElement,
<del> ReactElement.cloneAndReplaceProps(element, props)
<del> );
<del>
<del> enqueueUpdate(topLevelWrapper);
<del> },
<del>
<ide> enqueueElementInternal: function(internalInstance, newElement) {
<ide> internalInstance._pendingElement = newElement;
<ide> enqueueUpdate(internalInstance);
| 2
|
Ruby
|
Ruby
|
mark another duration test failing with ruby 1.9
|
f3560d5a956f13df0571471c63f05369b85ba67d
|
<ide><path>activesupport/test/core_ext/numeric_ext_test.rb
<ide> def setup
<ide> }
<ide> end
<ide>
<add> # FIXME: ruby 1.9
<ide> def test_units
<ide> @seconds.each do |actual, expected|
<ide> assert_equal expected, actual
| 1
|
PHP
|
PHP
|
use consistent config paths
|
63dc985f2f02705598e4e8a76946904e4b174ecd
|
<ide><path>config/view.php
<ide> */
<ide>
<ide> 'paths' => [
<del> realpath(base_path('resources/views')),
<add> resource_path('views'),
<ide> ],
<ide>
<ide> /*
| 1
|
Text
|
Text
|
synchronize api docs
|
53b1dcb25ca937c61bd47a29ba7be6e68abc25a5
|
<ide><path>docs/reference/api/docker_remote_api_v1.18.md
<ide> Attach to the container `id`
<ide> - **404** – no such container
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **200** – no error
<ide> - **404** – no such exec instance
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.19.md
<ide> Attach to the container `id`
<ide> - **404** – no such container
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **200** – no error
<ide> - **404** – no such exec instance
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.20.md
<ide> Attach to the container `id`
<ide> - **404** – no such container
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **200** – no error
<ide> - **404** – no such exec instance
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.21.md
<ide> Attach to the container `id`
<ide> - **404** – no such container
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **404** – no such exec instance
<ide> - **409** - container is paused
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.22.md
<ide> Attach to the container `id`
<ide> - **409** - container is paused
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **404** – no such exec instance
<ide> - **409** - container is paused
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.23.md
<ide> Attach to the container `id`
<ide> - **409** - container is paused
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> Show the docker version information
<ide> Content-Type: application/json
<ide>
<ide> {
<del> "Version": "1.10.0",
<add> "Version": "1.11.0",
<ide> "Os": "linux",
<ide> "KernelVersion": "3.19.0-23-generic",
<ide> "GoVersion": "go1.4.2",
<ide> interactive session with the `exec` command.
<ide> - **404** – no such exec instance
<ide> - **409** - container is paused
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.24.md
<ide> Attach to the container `id`
<ide> - **409** - container is paused
<ide> - **500** – server error
<ide>
<del> **Stream details**:
<add>**Stream details**:
<ide>
<del> When using the TTY setting is enabled in
<del> [`POST /containers/create`
<del> ](#create-a-container),
<del> the stream is the raw data from the process PTY and client's `stdin`.
<del> When the TTY is disabled, then the stream is multiplexed to separate
<del> `stdout` and `stderr`.
<add>When using the TTY setting is enabled in
<add>[`POST /containers/create`
<add>](#create-a-container),
<add>the stream is the raw data from the process PTY and client's `stdin`.
<add>When the TTY is disabled, then the stream is multiplexed to separate
<add>`stdout` and `stderr`.
<ide>
<del> The format is a **Header** and a **Payload** (frame).
<add>The format is a **Header** and a **Payload** (frame).
<ide>
<del> **HEADER**
<add>**HEADER**
<ide>
<del> The header contains the information which the stream writes (`stdout` or
<del> `stderr`). It also contains the size of the associated frame encoded in the
<del> last four bytes (`uint32`).
<add>The header contains the information which the stream writes (`stdout` or
<add>`stderr`). It also contains the size of the associated frame encoded in the
<add>last four bytes (`uint32`).
<ide>
<del> It is encoded on the first eight bytes like this:
<add>It is encoded on the first eight bytes like this:
<ide>
<del> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<del> `STREAM_TYPE` can be:
<add>`STREAM_TYPE` can be:
<ide>
<ide> - 0: `stdin` (is written on `stdout`)
<ide> - 1: `stdout`
<ide> - 2: `stderr`
<ide>
<del> `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<del> the `uint32` size encoded as big endian.
<add>`SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of
<add>the `uint32` size encoded as big endian.
<ide>
<del> **PAYLOAD**
<add>**PAYLOAD**
<ide>
<del> The payload is the raw stream.
<add>The payload is the raw stream.
<ide>
<del> **IMPLEMENTATION**
<add>**IMPLEMENTATION**
<ide>
<del> The simplest way to implement the Attach protocol is the following:
<add>The simplest way to implement the Attach protocol is the following:
<ide>
<ide> 1. Read eight bytes.
<ide> 2. Choose `stdout` or `stderr` depending on the first byte.
<ide> Create an image either by pulling it from the registry or by importing it
<ide>
<ide> **Example request**:
<ide>
<del> POST /images/create?fromImage=ubuntu HTTP/1.1
<add> POST /images/create?fromImage=busybox&tag=latest HTTP/1.1
<ide>
<ide> **Example response**:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **404** – no such exec instance
<ide> - **409** - container is paused
<ide>
<del> **Stream details**:
<del> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<add>**Stream details**:
<add>
<add>Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide>
<ide> Return low-level information on the node `id`
<ide> ### Remove a node
<ide>
<ide>
<del>`DELETE /nodes/<id>`
<add>`DELETE /nodes/(id)`
<ide>
<ide> Remove a node [`id`] from the swarm.
<ide>
<ide> Remove a node [`id`] from the swarm.
<ide> ### Update a node
<ide>
<ide>
<del>`POST /nodes/<id>/update`
<add>`POST /nodes/(id)/update`
<ide>
<ide> Update the node `id`.
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.25.md
<ide> Create a container
<ide> "AutoRemove": true,
<ide> "NetworkMode": "bridge",
<ide> "Devices": [],
<add> "Sysctls": { "net.ipv4.ip_forward": "1" },
<ide> "Ulimits": [{}],
<ide> "LogConfig": { "Type": "json-file", "Config": {} },
<ide> "SecurityOpt": [],
<ide> last four bytes (`uint32`).
<ide>
<ide> It is encoded on the first eight bytes like this:
<ide>
<del>header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<add> header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}
<ide>
<ide> `STREAM_TYPE` can be:
<ide>
<ide> interactive session with the `exec` command.
<ide> - **409** - container is paused
<ide>
<ide> **Stream details**:
<add>
<ide> Similar to the stream behavior of `POST /containers/(id or name)/attach` API
<ide>
<ide> ### Exec Resize
<ide> Inspect swarm
<ide>
<ide> `POST /swarm/init`
<ide>
<del>Initialize a new swarm
<add>Initialize a new swarm. The body of the HTTP response includes the node ID.
<ide>
<ide> **Example request**:
<ide>
<ide> Initialize a new swarm
<ide> **Example response**:
<ide>
<ide> HTTP/1.1 200 OK
<del> Content-Length: 0
<del> Content-Type: text/plain; charset=utf-8
<add> Content-Length: 28
<add> Content-Type: application/json
<add> Date: Thu, 01 Sep 2016 21:49:13 GMT
<add> Server: Docker/1.12.0 (linux)
<add>
<add> "7v2t30z9blmxuhnyo6s4cpenp"
<ide>
<ide> **Status codes**:
<ide>
| 8
|
Python
|
Python
|
fix ui flash when triggering with dup logical date
|
6a8f0167436b8b582aeb92a93d3f69d006b36f7b
|
<ide><path>airflow/www/views.py
<ide> def trigger(self, session=None):
<ide> form=form,
<ide> is_dag_run_conf_overrides_params=is_dag_run_conf_overrides_params,
<ide> )
<del> # if run_id is not None, filter dag runs based on run id and ignore execution date
<add>
<ide> dr = DagRun.find_duplicate(dag_id=dag_id, run_id=run_id, execution_date=execution_date)
<ide> if dr:
<del> flash(f"The run_id {dr.run_id} already exists", "error")
<add> if dr.run_id == run_id:
<add> message = f"The run ID {run_id} already exists"
<add> else:
<add> message = f"The logical date {execution_date} already exists"
<add> flash(message, "error")
<ide> return redirect(origin)
<ide>
<ide> # Flash a warning when slash is used, but still allow it to continue on.
<ide><path>tests/www/views/test_views_trigger_dag.py
<ide> def test_duplicate_run_id(admin_client):
<ide> run_id = 'test_run'
<ide> admin_client.post(f'trigger?dag_id={test_dag_id}&run_id={run_id}', follow_redirects=True)
<ide> response = admin_client.post(f'trigger?dag_id={test_dag_id}&run_id={run_id}', follow_redirects=True)
<del> check_content_in_response(f'The run_id {run_id} already exists', response)
<add> check_content_in_response(f'The run ID {run_id} already exists', response)
<ide>
<ide>
<ide> def test_trigger_dag_conf(admin_client):
| 2
|
Javascript
|
Javascript
|
add regression test for
|
f55795c8ee37ba882fc69192da9478a8a1f8ce1a
|
<ide><path>packages/react-dom/src/__tests__/ReactDOMSuspensePlaceholder-test.internal.js
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> ReactCache = require('react-cache');
<ide> Suspense = React.Suspense;
<ide> container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<ide> TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
<ide> return new Promise((resolve, reject) =>
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> }, ([text, ms]) => text);
<ide> });
<ide>
<add> afterEach(() => {
<add> document.body.removeChild(container);
<add> });
<add>
<ide> function advanceTimers(ms) {
<ide> // Note: This advances Jest's virtual time but not React's. Use
<ide> // ReactNoop.expire for that.
<ide> describe('ReactDOMSuspensePlaceholder', () => {
<ide> );
<ide> },
<ide> );
<add>
<add> // Regression test for https://github.com/facebook/react/issues/14188
<add> it('can call findDOMNode() in a suspended component commit phase', async () => {
<add> const log = [];
<add> const Lazy = React.lazy(
<add> () =>
<add> new Promise(resolve =>
<add> resolve({
<add> default() {
<add> return 'lazy';
<add> },
<add> }),
<add> ),
<add> );
<add>
<add> class Child extends React.Component {
<add> componentDidMount() {
<add> log.push('cDM ' + this.props.id);
<add> ReactDOM.findDOMNode(this);
<add> }
<add> componentDidUpdate() {
<add> log.push('cDU ' + this.props.id);
<add> ReactDOM.findDOMNode(this);
<add> }
<add> render() {
<add> return 'child';
<add> }
<add> }
<add>
<add> const buttonRef = React.createRef();
<add> class App extends React.Component {
<add> state = {
<add> suspend: false,
<add> };
<add> handleClick = () => {
<add> this.setState({suspend: true});
<add> };
<add> render() {
<add> return (
<add> <React.Suspense fallback="Loading">
<add> <Child id="first" />
<add> <button ref={buttonRef} onClick={this.handleClick}>
<add> Suspend
<add> </button>
<add> <Child id="second" />
<add> {this.state.suspend && <Lazy />}
<add> </React.Suspense>
<add> );
<add> }
<add> }
<add>
<add> ReactDOM.render(<App />, container);
<add>
<add> expect(log).toEqual(['cDM first', 'cDM second']);
<add> log.length = 0;
<add>
<add> buttonRef.current.dispatchEvent(new MouseEvent('click', {bubbles: true}));
<add> await Lazy;
<add> expect(log).toEqual(['cDU first', 'cDU second']);
<add> });
<ide> });
| 1
|
PHP
|
PHP
|
remove pseudo instanceconfig defaults
|
e60797a8229822497f7712690f9f28b293f0ea0e
|
<ide><path>src/Log/Engine/SyslogLog.php
<ide> class SyslogLog extends BaseLog {
<ide>
<ide> /**
<add> * Default config for this class
<add> *
<ide> * By default messages are formatted as:
<ide> * level: message
<ide> *
<ide> class SyslogLog extends BaseLog {
<ide> *
<ide> * @var array
<ide> */
<del> protected $_defaults = array(
<add> protected $_defaultConfig = [
<add> 'levels' => [],
<add> 'scopes' => [],
<ide> 'format' => '%s: %s',
<ide> 'flag' => LOG_ODELAY,
<ide> 'prefix' => '',
<ide> 'facility' => LOG_USER
<del> );
<add> ];
<ide>
<ide> /**
<ide> * Used to map the string names back to their LOG_* constants
<ide> class SyslogLog extends BaseLog {
<ide> */
<ide> protected $_open = false;
<ide>
<del>/**
<del> * Make sure the configuration contains the format parameter, by default it uses
<del> * the error number and the type as a prefix to the message
<del> *
<del> * @param array $config
<del> */
<del> public function __construct($config = array()) {
<del> $config += $this->_defaults;
<del> parent::__construct($config);
<del> }
<del>
<ide> /**
<ide> * Writes a message to syslog
<ide> *
| 1
|
Text
|
Text
|
update big brand examples in wordpress guide
|
ac66dcf052dd33e60f1bb86da9deebb29f226a6f
|
<ide><path>guide/english/wordpress/index.md
<ide> In this instance, you could create a custom post type for products, a custom pos
<ide> The free and open-source version of wordpress is found at [https://wordpress.org](https://wordpress.org) and must be self-hosted on a server or local development machine. This is also the version of WordPress that is frequently available as a simple installation through cPanel on the majority of hosting providers. Meanwhile, a hosted version of WordPress is available [wordpress.com](https://wordpress.com), but this is not an open-source version. Users of the WordPress.com site may need to pay subscription fees to access many of the features and benefits of the open-source WordPress.
<ide>
<ide> Here are some examples of big name brands using WordPress:
<del>* Sony Music
<del>* The New Yorker
<del>* MTV News
<del>* BBC America
<del>* Techcrunch
<add>* [Sony Music](https://www.sonymusic.com/)
<add>* [TechCrunch](https://techcrunch.com/)
<add>* [BBC America](http://www.bbcamerica.com/)
<add>* [Bloomberg Professional](https://www.bloomberg.com/professional/)
<add>* [The Walt Disney Company](https://www.thewaltdisneycompany.com/)
<ide>
<ide> Note: WordPress's ease of use may encourage new users to forget about website security. However, the popularity of WordPress increases the activity of malware and other issues.
<ide> It is important to choose extremely difficult or random passwords for the administrators and for the database. This guards against random brute-force attacks.
| 1
|
PHP
|
PHP
|
use a tag
|
8b1c43036b3d09d65ed4a6fef11918edae4f2058
|
<ide><path>templates/layout/dev_error.php
<ide> font-size: 30px;
<ide> margin: 0;
<ide> }
<del> .header-title small {
<add> .header-title a {
<ide> font-size: 18px;
<ide> cursor: pointer;
<ide> margin-left: 10px;
<ide> <header>
<ide> <h1 class="header-title">
<ide> <?= Debugger::formatHtmlMessage($this->fetch('title')) ?>
<del> <small>📋</small>
<add> <a>📋</a>
<ide> </h1>
<ide> <span class="header-type"><?= get_class($error) ?></span>
<ide> </header>
<ide> function each(els, cb) {
<ide> event.preventDefault();
<ide> });
<ide>
<del> bindEvent('.header-title small', 'click', function(event) {
<add> bindEvent('.header-title a', 'click', function(event) {
<ide> event.preventDefault();
<ide> var text = '';
<ide> each(this.parentNode.childNodes, function(el) {
<del> if (el.nodeName !== 'SMALL') {
<add> if (el.nodeName !== 'A') {
<ide> text += el.textContent.trim();
<ide> }
<ide> });
<ide> function each(els, cb) {
<ide> var original = el.innerText;
<ide> el.innerText = '\ud83c\udf70';
<ide> setTimeout(function () {
<del> el.textContent = original;
<add> el.innerText = original;
<ide> }, 1000);
<ide> } catch (err) {
<ide> alert('Unable to update clipboard ' + err);
| 1
|
Mixed
|
Ruby
|
add an after_bundle callback in rails templates
|
097b2101897af447591d00fb2809d91894572b87
|
<ide><path>guides/source/rails_application_templates.md
<ide> generate(:scaffold, "person name:string")
<ide> route "root to: 'people#index'"
<ide> rake("db:migrate")
<ide>
<del>git :init
<del>git add: "."
<del>git commit: %Q{ -m 'Initial commit' }
<add>after_bundle do
<add> git :init
<add> git add: "."
<add> git commit: %Q{ -m 'Initial commit' }
<add>end
<ide> ```
<ide>
<ide> The following sections outline the primary methods provided by the API:
<ide> git add: "."
<ide> git commit: "-a -m 'Initial commit'"
<ide> ```
<ide>
<add>### after_bundle(&block)
<add>
<add>Registers a callback to be executed after bundler and binstub generation have
<add>run. Useful for adding the binstubs to version control:
<add>
<add>```ruby
<add>after_bundle do
<add> git :init
<add> git add: '.'
<add> git commit: "-a -m 'Initial commit'"
<add>end
<add>```
<add>
<add>The callbacks gets executed even if `--skip-bundle` and/or `--skip-spring` has
<add>been passed.
<add>
<ide> Advanced Usage
<ide> --------------
<ide>
<ide><path>railties/CHANGELOG.md
<add>* Add `after_bundle` callbacks in Rails templates. Useful for allowing the
<add> generated binstubs to be added to version control.
<add>
<add> Fixes #16292.
<add>
<add> *Stefan Kanev*
<add>
<ide> * Scaffold generator `_form` partial adds `class="field"` for password
<ide> confirmation fields.
<ide>
<ide><path>railties/lib/rails/generators/actions.rb
<ide> module Actions
<ide> def initialize(*) # :nodoc:
<ide> super
<ide> @in_group = nil
<add> @after_bundle_callbacks = []
<ide> end
<ide>
<ide> # Adds an entry into +Gemfile+ for the supplied gem.
<ide> def readme(path)
<ide> log File.read(find_in_source_paths(path))
<ide> end
<ide>
<add> # Registers a callback to be executed after bundle and spring binstubs
<add> # have run.
<add> #
<add> # after_bundle do
<add> # git add: '.'
<add> # end
<add> def after_bundle(&block)
<add> @after_bundle_callbacks << block
<add> end
<add>
<ide> protected
<ide>
<ide> # Define log for backwards compatibility. If just one argument is sent,
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def finish_template
<ide> public_task :apply_rails_template, :run_bundle
<ide> public_task :generate_spring_binstubs
<ide>
<add> def run_after_bundle_callbacks
<add> @after_bundle_callbacks.each do |callback|
<add> callback.call
<add> end
<add> end
<add>
<ide> protected
<ide>
<ide> def self.banner
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_psych_gem
<ide> end
<ide> end
<ide>
<add> def test_after_bundle_callback
<add> path = 'http://example.org/rails_template'
<add> template = %{ after_bundle { run 'echo ran after_bundle' } }
<add> template.instance_eval "def read; self; end" # Make the string respond to read
<add>
<add> generator([destination_root], template: path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
<add>
<add> bundler_first = sequence('bundle, binstubs, after_bundle')
<add> generator.expects(:bundle_command).with('install').once.in_sequence(bundler_first)
<add> generator.expects(:bundle_command).with('exec spring binstub --all').in_sequence(bundler_first)
<add> generator.expects(:run).with('echo ran after_bundle').in_sequence(bundler_first)
<add>
<add> quietly { generator.invoke_all }
<add> end
<add>
<ide> protected
<ide>
<ide> def action(*args, &block)
| 5
|
Text
|
Text
|
add mention to changelog
|
36f17c92627564af12e839c84422b3f327afa27e
|
<ide><path>CHANGELOG.md
<ide> ## Bug Fixes
<ide> - **angular.merge:** do not merge __proto__ property
<ide> ([726f49](https://github.com/angular/angular.js/commit/726f49dcf6c23106ddaf5cfd5e2e592841db743a))
<del> ([Thanks to the Snyk Security Research Team](https://snyk.io/blog/snyk-research-team-discovers-severe-prototype-pollution-security-vulnerabilities-affecting-all-versions-of-lodash/) for identifyng this issue.)
<add> <br>(Thanks to the [Snyk Security Research Team](https://snyk.io/blog/snyk-research-team-discovers-severe-prototype-pollution-security-vulnerabilities-affecting-all-versions-of-lodash/) for identifyng this issue.)
<ide> - **ngStyle:** correctly remove old style when new style value is invalid
<ide> ([5edd25](https://github.com/angular/angular.js/commit/5edd25364f617083363dc2bd61f9230b38267578),
<ide> [#16860](https://github.com/angular/angular.js/issues/16860),
| 1
|
Go
|
Go
|
fix inhibitipv4 nil panic
|
41a91e9a5d6525cf7e19baa511873c7f7f29df4d
|
<ide><path>libnetwork/drivers/bridge/bridge_store.go
<ide> func (ncfg *networkConfiguration) UnmarshalJSON(b []byte) error {
<ide> ncfg.EnableIPv6 = nMap["EnableIPv6"].(bool)
<ide> ncfg.EnableIPMasquerade = nMap["EnableIPMasquerade"].(bool)
<ide> ncfg.EnableICC = nMap["EnableICC"].(bool)
<del> ncfg.InhibitIPv4 = nMap["InhibitIPv4"].(bool)
<add> if v, ok := nMap["InhibitIPv4"]; ok {
<add> ncfg.InhibitIPv4 = v.(bool)
<add> }
<add>
<ide> ncfg.Mtu = int(nMap["Mtu"].(float64))
<ide> if v, ok := nMap["Internal"]; ok {
<ide> ncfg.Internal = v.(bool)
| 1
|
Ruby
|
Ruby
|
fix alias and versioned symlink handling
|
128aeba3a4d255c31066541f9828fe211b8e1f9d
|
<ide><path>Library/Homebrew/keg.rb
<ide> def remove_old_aliases
<ide> # versioned aliases are handled below
<ide> next if a.match?(/.+@./)
<ide>
<del> alias_opt_symlink = opt/a
<del> if alias_opt_symlink.symlink? && alias_opt_symlink.exist?
<del> alias_opt_symlink.delete if alias_opt_symlink.realpath == opt_record.realpath
<del> elsif alias_opt_symlink.symlink? || alias_opt_symlink.exist?
<del> alias_opt_symlink.delete
<del> end
<del>
<del> alias_linkedkegs_symlink = linkedkegs/a
<del> alias_linkedkegs_symlink.delete if alias_linkedkegs_symlink.symlink? || alias_linkedkegs_symlink.exist?
<add> remove_alias_symlink(opt/a, opt_record)
<add> remove_alias_symlink(linkedkegs/a, linked_keg_record)
<ide> end
<ide>
<ide> Pathname.glob("#{opt_record}@*").each do |a|
<ide> a = a.basename.to_s
<ide> next if aliases.include?(a)
<ide>
<del> alias_opt_symlink = opt/a
<del> if alias_opt_symlink.symlink? && alias_opt_symlink.exist? && rack == alias_opt_symlink.realpath.parent
<del> alias_opt_symlink.delete
<del> end
<del>
<del> alias_linkedkegs_symlink = linkedkegs/a
<del> alias_linkedkegs_symlink.delete if alias_linkedkegs_symlink.symlink? || alias_linkedkegs_symlink.exist?
<add> remove_alias_symlink(opt/a, rack)
<add> remove_alias_symlink(linkedkegs/a, rack)
<ide> end
<ide> end
<ide>
<ide> def uninstall
<ide> path.rmtree
<ide> path.parent.rmdir_if_possible
<ide> remove_opt_record if optlinked?
<add> remove_linked_keg_record if linked?
<ide> remove_old_aliases
<ide> remove_oldname_opt_record
<ide> rescue Errno::EACCES, Errno::ENOTEMPTY
<ide> def unlink(**options)
<ide>
<ide> dst.uninstall_info if dst.to_s.match?(INFOFILE_RX)
<ide> dst.unlink
<del> remove_old_aliases
<ide> Find.prune if src.directory?
<ide> end
<ide> end
<ide>
<ide> unless options[:dry_run]
<add> remove_old_aliases
<ide> remove_linked_keg_record if linked?
<ide> dirs.reverse_each(&:rmdir_if_possible)
<ide> end
<ide> def make_relative_symlink(dst, src, **options)
<ide> raise LinkError.new(self, src.relative_path_from(path), dst, e)
<ide> end
<ide>
<add> def remove_alias_symlink(alias_symlink, alias_match_path)
<add> if alias_symlink.symlink? && alias_symlink.exist?
<add> alias_symlink.delete if alias_symlink.realpath == alias_match_path.realpath
<add> elsif alias_symlink.symlink? || alias_symlink.exist?
<add> alias_symlink.delete
<add> end
<add> end
<add>
<ide> protected
<ide>
<ide> # symlinks the contents of path+relative_dir recursively into #{HOMEBREW_PREFIX}/relative_dir
| 1
|
Python
|
Python
|
improve keras graph performance for resnet56
|
dd5a91d3c0c5df38e78c2700d997c9b7dc56d268
|
<ide><path>official/resnet/cifar10_main.py
<ide> def input_fn(is_training,
<ide> dtype=tf.float32,
<ide> datasets_num_private_threads=None,
<ide> parse_record_fn=parse_record,
<del> input_context=None):
<add> input_context=None,
<add> drop_remainder=False):
<ide> """Input function which provides batches for train or eval.
<ide>
<ide> Args:
<ide> def input_fn(is_training,
<ide> parse_record_fn: Function to use for parsing the records.
<ide> input_context: A `tf.distribute.InputContext` object passed in by
<ide> `tf.distribute.Strategy`.
<add> drop_remainder: A boolean indicates whether to drop the remainder of the
<add> batches. If True, the batch dimension will be static.
<ide>
<ide> Returns:
<ide> A dataset that can be used for iteration.
<ide> def input_fn(is_training,
<ide> parse_record_fn=parse_record_fn,
<ide> num_epochs=num_epochs,
<ide> dtype=dtype,
<del> datasets_num_private_threads=datasets_num_private_threads
<add> datasets_num_private_threads=datasets_num_private_threads,
<add> drop_remainder=drop_remainder
<ide> )
<ide>
<ide>
<ide><path>official/resnet/keras/keras_cifar_main.py
<ide> def run(flags_obj):
<ide> Returns:
<ide> Dictionary of training and eval stats.
<ide> """
<del> keras_utils.set_session_config(enable_eager=flags_obj.enable_eager,
<del> enable_xla=flags_obj.enable_xla)
<add> keras_utils.set_session_config(
<add> enable_eager=flags_obj.enable_eager,
<add> enable_xla=flags_obj.enable_xla,
<add> enable_grappler_layout_optimizer=
<add> flags_obj.enable_grappler_layout_optimizer)
<add>
<add> # Execute flag override logic for better model performance
<add> if flags_obj.tf_gpu_thread_mode:
<add> keras_common.set_gpu_thread_mode_and_count(flags_obj)
<add> keras_common.set_cudnn_batchnorm_mode()
<ide>
<ide> dtype = flags_core.get_tf_dtype(flags_obj)
<ide> if dtype == 'fp16':
<ide> def run(flags_obj):
<ide> all_reduce_alg=flags_obj.all_reduce_alg,
<ide> num_packs=flags_obj.num_packs)
<ide>
<add> if strategy:
<add> # flags_obj.enable_get_next_as_optional controls whether enabling
<add> # get_next_as_optional behavior in DistributedIterator. If true, last
<add> # partial batch can be supported.
<add> strategy.extended.experimental_enable_get_next_as_optional = (
<add> flags_obj.enable_get_next_as_optional
<add> )
<add>
<ide> strategy_scope = distribution_utils.get_strategy_scope(strategy)
<ide>
<ide> if flags_obj.use_synthetic_data:
<ide> def run(flags_obj):
<ide> width=cifar_main.WIDTH,
<ide> num_channels=cifar_main.NUM_CHANNELS,
<ide> num_classes=cifar_main.NUM_CLASSES,
<del> dtype=flags_core.get_tf_dtype(flags_obj))
<add> dtype=flags_core.get_tf_dtype(flags_obj),
<add> drop_remainder=True)
<ide> else:
<ide> distribution_utils.undo_set_up_synthetic_data()
<ide> input_fn = cifar_main.input_fn
<ide> def run(flags_obj):
<ide> num_epochs=flags_obj.train_epochs,
<ide> parse_record_fn=parse_record_keras,
<ide> datasets_num_private_threads=flags_obj.datasets_num_private_threads,
<del> dtype=dtype)
<add> dtype=dtype,
<add> # Setting drop_remainder to avoid the partial batch logic in normalization
<add> # layer, which triggers tf.where and leads to extra memory copy of input
<add> # sizes between host and GPU.
<add> drop_remainder=(not flags_obj.enable_get_next_as_optional))
<ide>
<ide> eval_input_dataset = None
<ide> if not flags_obj.skip_eval:
| 2
|
Go
|
Go
|
fix todo for printing error messages
|
883ab41ce8f5163ba8ce0450ffff1e63c266f23b
|
<ide><path>builder/remotecontext/git.go
<ide> import (
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/builder/remotecontext/git"
<ide> "github.com/docker/docker/pkg/archive"
<add> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> // MakeGitContext returns a Context from gitURL that is cloned in a temporary directory.
<ide> func MakeGitContext(gitURL string) (builder.Source, error) {
<ide> }
<ide>
<ide> defer func() {
<del> // TODO: print errors?
<del> c.Close()
<del> os.RemoveAll(root)
<add> err := c.Close()
<add> if err != nil {
<add> logrus.WithField("action", "MakeGitContext").WithField("module", "builder").WithField("url", gitURL).WithError(err).Error("error while closing git context")
<add> }
<add> err = os.RemoveAll(root)
<add> if err != nil {
<add> logrus.WithField("action", "MakeGitContext").WithField("module", "builder").WithField("url", gitURL).WithError(err).Error("error while removing path and children of root")
<add> }
<ide> }()
<ide> return FromArchive(c)
<ide> }
| 1
|
PHP
|
PHP
|
remove strtolower(), already done in snake_case()
|
4a7f96a02e44f464ca20198a81988e1c5a889544
|
<ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateAfter($attribute, $value, $parameters)
<ide> */
<ide> protected function getMessage($attribute, $rule)
<ide> {
<del> $lowerRule = strtolower(snake_case($rule));
<add> $lowerRule = snake_case($rule);
<ide>
<ide> $inlineMessage = $this->getInlineMessage($attribute, $lowerRule);
<ide>
<ide> protected function getInlineMessage($attribute, $lowerRule, $source = null)
<ide> */
<ide> protected function getSizeMessage($attribute, $rule)
<ide> {
<del> $lowerRule = strtolower(snake_case($rule));
<add> $lowerRule = snake_case($rule);
<ide>
<ide> // There are three different types of size validations. The attribute may be
<ide> // either a number, file, or string so we will check a few things to know
| 1
|
Javascript
|
Javascript
|
allow writes after readable 'end' to finish
|
0e89b64d6606d9c7948259e9090a46d185c5281f
|
<ide><path>lib/zlib.js
<ide> function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) {
<ide> this._defaultFlushFlag = flush;
<ide> this._finishFlushFlag = finishFlush;
<ide> this._defaultFullFlushFlag = fullFlush;
<del> this.once('end', this.close);
<add> this.once('end', _close.bind(null, this));
<ide> this._info = opts && opts.info;
<ide> }
<ide> ObjectSetPrototypeOf(ZlibBase.prototype, Transform.prototype);
<ide> function processChunkSync(self, chunk, flushFlag) {
<ide>
<ide> function processChunk(self, chunk, flushFlag, cb) {
<ide> const handle = self._handle;
<del> assert(handle, 'zlib binding closed');
<add> if (!handle) return process.nextTick(cb);
<ide>
<ide> handle.buffer = chunk;
<ide> handle.cb = cb;
<ide> function processCallback() {
<ide> const self = this[owner_symbol];
<ide> const state = self._writeState;
<ide>
<del> if (self._hadError) {
<del> this.buffer = null;
<del> return;
<del> }
<del>
<del> if (self.destroyed) {
<add> if (self._hadError || self.destroyed) {
<ide> this.buffer = null;
<add> this.cb();
<ide> return;
<ide> }
<ide>
<ide> function processCallback() {
<ide> }
<ide>
<ide> if (self.destroyed) {
<add> this.cb();
<ide> return;
<ide> }
<ide>
<ide><path>test/parallel/test-zlib-write-after-end.js
<add>'use strict';
<add>const common = require('../common');
<add>const zlib = require('zlib');
<add>
<add>// Regression test for https://github.com/nodejs/node/issues/30976
<add>// Writes to a stream should finish even after the readable side has been ended.
<add>
<add>const data = zlib.deflateRawSync('Welcome');
<add>
<add>const inflate = zlib.createInflateRaw();
<add>
<add>inflate.resume();
<add>inflate.write(data, common.mustCall());
<add>inflate.write(Buffer.from([0x00]), common.mustCall());
<add>inflate.write(Buffer.from([0x00]), common.mustCall());
<add>inflate.flush(common.mustCall());
| 2
|
Text
|
Text
|
add case conversion functions to the article
|
78949d9f61c86c63de86bf5ccca1add8f1262e3c
|
<ide><path>guide/english/java/strings/index.md
<ide> The result will be:
<ide> Free
<ide> ```
<ide>
<add>
<add>#### String Case Conversion
<add>
<add>1. `.toLowerCase()` - This method will convert the string into lower case characters.
<add> Example:
<add> ```java
<add> String text1 = "Welcome99";
<add> String text2 = "WELCOME";
<add> String text3 = "well";
<add> System.out.println(text1.toLowerCase());
<add> System.out.println(text2.toLowerCase());
<add> System.out.println(text3.toLowerCase());
<add> ```
<add> The output will be:-
<add> ```
<add> welcome99
<add> welcome
<add> well
<add> ```
<add>2. `.toUpperCase()` - This method will convert the string into upper case characters.
<add> Example:
<add>
<add> ```java
<add> String text1 = "Welcome99";
<add> String text2 = "WELCOME";
<add> String text3 = "well";
<add> System.out.println(text1.toUpperCase());
<add> System.out.println(text2.toUpperCase());
<add> System.out.println(text3.toUpperCase());
<add> ```
<add> The output will be:-
<add> ```
<add> WELCOME99
<add> WELCOME
<add> WELL
<add> ```
<add>
<ide> **More Information:**
<ide> - [String Documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html)
| 1
|
PHP
|
PHP
|
add date and cast check for dirty
|
a0402824bf479dc5135b40a7f40095d4e2bbb265
|
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
<ide> public function getDirty()
<ide> {
<ide> $dirty = [];
<ide>
<del> foreach ($this->attributes as $key => $value) {
<del> if (! array_key_exists($key, $this->original)) {
<del> $dirty[$key] = $value;
<del> } elseif ($value !== $this->original[$key] &&
<del> ! $this->originalIsNumericallyEquivalent($key)) {
<add> foreach ($this->getAttributes() as $key => $value) {
<add> if (! $this->originalIsEquivalent($key, $value)) {
<ide> $dirty[$key] = $value;
<ide> }
<ide> }
<ide> public function getDirty()
<ide> }
<ide>
<ide> /**
<del> * Determine if the new and old values for a given key are numerically equivalent.
<add> * Determine if the new and old values for a given key are equivalent.
<ide> *
<del> * @param string $key
<add> * @param string $key
<add> * @param mixed $current
<ide> * @return bool
<ide> */
<del> protected function originalIsNumericallyEquivalent($key)
<add> protected function originalIsEquivalent($key, $current)
<ide> {
<del> $current = $this->attributes[$key];
<add> if (! array_key_exists($key, $this->original)) {
<add> return false;
<add> }
<add>
<add> $original = $this->getOriginal($key);
<ide>
<del> $original = $this->original[$key];
<add> if ($this->isDateAttribute($key)) {
<add> return $this->fromDateTime($current) === $this->fromDateTime($original);
<add> }
<add>
<add> if ($this->hasCast($key)) {
<add> return $this->castAttribute($key, $current) === $this->castAttribute($key, $original);
<add> }
<ide>
<ide> // This method checks if the two values are numerically equivalent even if they
<ide> // are different types. This is in case the two values are not the same type
| 1
|
Javascript
|
Javascript
|
implement proper error handling
|
fc3b3a4101338b5713fb900acb80bbabe597039c
|
<ide><path>client/index.js
<ide> const {
<ide> __NEXT_DATA__: {
<ide> props,
<ide> err,
<add> page,
<ide> pathname,
<ide> query,
<ide> buildId,
<ide> export default async ({ ErrorDebugComponent: passedDebugComponent, stripAnsi: pa
<ide> ErrorComponent = await pageLoader.loadPage('/_error')
<ide>
<ide> try {
<del> Component = await pageLoader.loadPage(pathname)
<add> Component = await pageLoader.loadPage(page)
<ide> } catch (err) {
<ide> console.error(stripAnsi(`${err.message}\n${err.stack}`))
<ide> Component = ErrorComponent
<ide><path>server/document.js
<ide> export class Head extends Component {
<ide>
<ide> return <head {...this.props}>
<ide> {(head || []).map((h, i) => React.cloneElement(h, { key: h.key || i }))}
<del> {page !== '_error' && <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page${pagePathname}`} as='script' />}
<add> {page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page${pagePathname}`} as='script' />}
<ide> <link rel='preload' href={`${assetPrefix}/_next/${buildId}/page/_error.js`} as='script' />
<ide> {this.getPreloadDynamicChunks()}
<ide> {this.getPreloadMainLinks()}
<ide> export class NextScript extends Component {
<ide> __NEXT_REGISTER_PAGE(${htmlescape(pathname)}, function() {
<ide> var error = new Error('Page does not exist: ${htmlescape(pathname)}')
<ide> error.statusCode = 404
<del>
<add>
<ide> return { error: error }
<ide> })
<ide> `}
<ide> `
<ide> }} />}
<del> {page !== '_error' && <script async id={`__NEXT_PAGE__${pathname}`} type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page${pagePathname}`} />}
<add> {page !== '/_error' && <script async id={`__NEXT_PAGE__${pathname}`} type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page${pagePathname}`} />}
<ide> <script async id={`__NEXT_PAGE__/_error`} type='text/javascript' src={`${assetPrefix}/_next/${buildId}/page/_error.js`} />
<ide> {staticMarkup ? null : this.getDynamicChunks()}
<ide> {staticMarkup ? null : this.getScripts()}
<ide><path>server/render.js
<ide> export async function renderError (err, req, res, pathname, query, opts) {
<ide> }
<ide>
<ide> export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
<del> return doRender(req, res, pathname, query, { ...opts, err, page: '_error' })
<add> return doRender(req, res, pathname, query, { ...opts, err, page: '/_error' })
<ide> }
<ide>
<ide> async function doRender (req, res, pathname, query, {
<ide> export function serveStatic (req, res, path) {
<ide> }
<ide>
<ide> async function ensurePage (page, { dir, hotReloader }) {
<del> if (page === '_error' || page === '_document') return
<add> if (page === '/_error') return
<ide>
<ide> await hotReloader.ensurePage(page)
<ide> }
<ide><path>server/require.js
<ide> export default function requirePage (page, {dir, dist}) {
<ide> try {
<ide> return require(pagePath)
<ide> } catch (err) {
<del> console.error(err)
<ide> throw pageNotFoundError(page)
<ide> }
<ide> }
<ide><path>test/integration/basic/test/client-navigation.js
<ide> export default (context, render) => {
<ide> browser.close()
<ide> })
<ide>
<del> it('should work with dir/index page ', async () => {
<del> const browser = await webdriver(context.appPort, '/nested-cdm/index')
<del> const text = await browser.elementByCss('p').text()
<del>
<del> expect(text).toBe('ComponentDidMount executed on client.')
<del> browser.close()
<del> })
<del>
<ide> it('should work with dir/ page ', async () => {
<del> const browser = await webdriver(context.appPort, '/nested-cdm/')
<add> const browser = await webdriver(context.appPort, '/nested-cdm')
<ide> const text = await browser.elementByCss('p').text()
<ide>
<ide> expect(text).toBe('ComponentDidMount executed on client.')
<ide> export default (context, render) => {
<ide> describe('with asPath', () => {
<ide> describe('inside getInitialProps', () => {
<ide> it('should show the correct asPath with a Link with as prop', async () => {
<del> const browser = await webdriver(context.appPort, '/nav/')
<add> const browser = await webdriver(context.appPort, '/nav')
<ide> const asPath = await browser
<ide> .elementByCss('#as-path-link').click()
<ide> .waitForElementByCss('.as-path-content')
<ide> export default (context, render) => {
<ide> })
<ide>
<ide> it('should show the correct asPath with a Link without the as prop', async () => {
<del> const browser = await webdriver(context.appPort, '/nav/')
<add> const browser = await webdriver(context.appPort, '/nav')
<ide> const asPath = await browser
<ide> .elementByCss('#as-path-link-no-as').click()
<ide> .waitForElementByCss('.as-path-content')
<ide> export default (context, render) => {
<ide>
<ide> describe('with next/router', () => {
<ide> it('should show the correct asPath', async () => {
<del> const browser = await webdriver(context.appPort, '/nav/')
<add> const browser = await webdriver(context.appPort, '/nav')
<ide> const asPath = await browser
<ide> .elementByCss('#as-path-using-router-link').click()
<ide> .waitForElementByCss('.as-path-content')
<ide> export default (context, render) => {
<ide> })
<ide> })
<ide> })
<add>
<add> describe('with 404 pages', () => {
<add> it('should 404 on not existent page', async () => {
<add> const browser = await webdriver(context.appPort, '/non-existent')
<add> expect(await browser.elementByCss('h1').text()).toBe('404')
<add> expect(await browser.elementByCss('h2').text()).toBe('This page could not be found.')
<add> browser.close()
<add> })
<add>
<add> it('should 404 for <page>/', async () => {
<add> const browser = await webdriver(context.appPort, '/nav/about/')
<add> expect(await browser.elementByCss('h1').text()).toBe('404')
<add> expect(await browser.elementByCss('h2').text()).toBe('This page could not be found.')
<add> browser.close()
<add> })
<add>
<add> it('should should not contain a page script in a 404 page', async () => {
<add> const browser = await webdriver(context.appPort, '/non-existent')
<add> const scripts = await browser.elementsByCss('script[src]')
<add> for (const script of scripts) {
<add> const src = await script.getAttribute('src')
<add> expect(src.includes('/non-existent')).toBeFalsy()
<add> }
<add> browser.close()
<add> })
<add> })
<ide> })
<ide> }
<ide><path>test/integration/basic/test/rendering.js
<ide> export default function ({ app }, suiteName, render, fetch) {
<ide> expect($('.as-path-content').text()).toBe('/nav/as-path?aa=10')
<ide> })
<ide>
<del> test('error 404', async () => {
<del> const $ = await get$('/non-existent')
<del> expect($('h1').text()).toBe('404')
<del> expect($('h2').text()).toBe('This page could not be found.')
<del> })
<del>
<del> test('error 404 should not have page script', async () => {
<del> const $ = await get$('/non-existent')
<del> $('script[src]').each((index, element) => {
<del> const src = $(element).attr('src')
<del> if (src.includes('/non-existent')) {
<del> throw new Error('Page includes page script')
<del> }
<add> describe('404', () => {
<add> it('should 404 on not existent page', async () => {
<add> const $ = await get$('/non-existent')
<add> expect($('h1').text()).toBe('404')
<add> expect($('h2').text()).toBe('This page could not be found.')
<add> })
<add>
<add> it('should 404 for <page>/', async () => {
<add> const $ = await get$('/nav/about/')
<add> expect($('h1').text()).toBe('404')
<add> expect($('h2').text()).toBe('This page could not be found.')
<add> })
<add>
<add> it('should should not contain a page script in a 404 page', async () => {
<add> const $ = await get$('/non-existent')
<add> $('script[src]').each((index, element) => {
<add> const src = $(element).attr('src')
<add> if (src.includes('/non-existent')) {
<add> throw new Error('Page includes page script')
<add> }
<add> })
<ide> })
<ide> })
<ide>
| 6
|
Ruby
|
Ruby
|
handle tap migration in `tap#initialize`
|
b109e6da5d24baad2fbb76b9b502e817c1f2b902
|
<ide><path>Library/Homebrew/compat/tap.rb
<del>module CaskTapMigrationExtension
<del> def parse_user_repo(*args)
<del> user, repo = super
<add>module CaskTapMigration
<add> def initialize(user, repo)
<add> super
<ide>
<del> if user == "caskroom"
<del> user = "Homebrew"
<del> repo = "cask-#{repo}" unless repo == "cask"
<del> end
<add> return unless user == "caskroom"
<ide>
<del> [user, repo]
<add> # TODO: Remove this check after migration.
<add> return unless repo == "tap-migration-test"
<add>
<add> new_user = "Homebrew"
<add> new_repo = (repo == "cask") ? repo : "cask-#{repo}"
<add>
<add> old_name = name
<add> old_path = path
<add> old_remote = path.git_origin
<add>
<add> super(new_user, new_repo)
<add>
<add> return unless old_path.git?
<add>
<add> new_name = name
<add> new_path = path
<add> new_remote = default_remote
<add>
<add> ohai "Migrating Tap #{old_name} to #{new_name} …"
<add>
<add> puts "Moving #{old_path} to #{new_path} …"
<add> path.dirname.mkpath
<add> FileUtils.mv old_path, new_path
<add>
<add> puts "Changing remote from #{old_remote} to #{new_remote} …"
<add> new_path.git_origin = new_remote
<ide> end
<ide> end
<ide>
<ide> class Tap
<del> class << self
<del> prepend CaskTapMigrationExtension
<del> end
<add> prepend CaskTapMigration
<ide> end
<ide><path>Library/Homebrew/extend/git_repository.rb
<ide> def git_origin
<ide> end
<ide> end
<ide>
<add> def git_origin=(origin)
<add> return unless git? && Utils.git_available?
<add> cd do
<add> Utils.popen_read("git", "remote", "set-url", "origin", origin).chuzzle
<add> end
<add> end
<add>
<ide> def git_head
<ide> return unless git? && Utils.git_available?
<ide> cd do
<ide><path>Library/Homebrew/tap.rb
<ide> class Tap
<ide>
<ide> TAP_DIRECTORY = HOMEBREW_LIBRARY/"Taps"
<ide>
<del> def self.parse_user_repo(*args)
<add> def self.fetch(*args)
<ide> case args.length
<ide> when 1
<ide> user, repo = args.first.split("/", 2)
<ide> def self.parse_user_repo(*args)
<ide> user = user.capitalize if ["homebrew", "linuxbrew"].include? user
<ide> repo = repo.strip_prefix "homebrew-"
<ide>
<del> [user, repo]
<del> end
<del> private_class_method :parse_user_repo
<del>
<del> def self.fetch(*args)
<del> user, repo = parse_user_repo(*args)
<del>
<ide> if ["Homebrew", "Linuxbrew"].include?(user) && ["core", "homebrew"].include?(repo)
<ide> return CoreTap.instance
<ide> end
| 3
|
Javascript
|
Javascript
|
use session kupdatetimer from kupdatetimer
|
fc61ee32fedd5d0bd9bc1dee2b87a41dd7ffa4dd
|
<ide><path>lib/internal/http2/core.js
<ide> class Http2Stream extends Duplex {
<ide> return;
<ide> if (this[kTimeout])
<ide> _unrefActive([kTimeout]);
<del> if (this[kSession] && this[kSession][kTimeout])
<del> _unrefActive(this[kSession][kTimeout]);
<add> if (this[kSession])
<add> this[kSession][kUpdateTimer]();
<ide> }
<ide>
<ide> [kInit](id, handle) {
| 1
|
PHP
|
PHP
|
update commandlistshell to give better help
|
bad819773eac1dd47ac5d3708dc64f185270b15b
|
<ide><path>lib/Cake/Console/Command/CommandListShell.php
<ide> protected function _asText($shellList) {
<ide> $this->out(" " . $row);
<ide> }
<ide> $this->out();
<del> $this->out(__d('cake_console', "To run a command, type <info>cake shell_name [args]</info>"));
<add> $this->out(__d('cake_console', "To run an app or core command, type <info>cake shell_name [args]</info>"));
<add> $this->out(__d('cake_console', "To run a plugin command, type <info>cake Plugin.shell_name [args]</info>"));
<ide> $this->out(__d('cake_console', "To get help on a specific command, type <info>cake shell_name --help</info>"), 2);
<ide> }
<ide>
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.