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 |
|---|---|---|---|---|---|
Java | Java | remove ise in resourceurlprovider | 0bfa124a1ed241501e8a14fd9d92d360139d7c5c | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlProvider.java
<ide> public final String getForLookupPath(String lookupPath) {
<ide> ResourceResolverChain chain = new DefaultResourceResolverChain(handler.getResourceResolvers());
<ide> String resolved = chain.resolveUrlPath(pathWithinMapping, handler.getLocations());
<ide> if (resolved == null) {
<del> throw new IllegalStateException("Failed to get public resource URL path for " + pathWithinMapping);
<add> continue;
<ide> }
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Resolved public resource URL path=\"" + resolved + "\""); | 1 |
Javascript | Javascript | normalize path for binding {{#with as}}. ref #980 | 79d6cbb214b98ac3faf39a373873dc40d6468806 | <ide><path>packages/ember-handlebars/lib/helpers/binding.js
<ide> EmberHandlebars.registerHelper('boundIf', function(property, fn) {
<ide> */
<ide> EmberHandlebars.registerHelper('with', function(context, options) {
<ide> if (arguments.length === 4) {
<del> var keywordName, path;
<add> var keywordName, path, rootPath, normalized;
<ide>
<ide> Ember.assert("If you pass more than one argument to the with helper, it must be in the form #with foo as bar", arguments[1] === "as");
<ide> options = arguments[3];
<ide> EmberHandlebars.registerHelper('with', function(context, options) {
<ide> if (Ember.isGlobal(path)) {
<ide> Ember.bind(options.data.keywords, keywordName, path);
<ide> } else {
<add> normalized = normalizePath(this, path, options.data);
<add> path = normalized.path;
<add> rootPath = normalized.root;
<add>
<ide> // This is a workaround for the fact that you cannot bind separate objects
<ide> // together. When we implement that functionality, we should use it here.
<del> var contextKey = Ember.$.expando + Ember.guidFor(this);
<del> options.data.keywords[contextKey] = this;
<add> var contextKey = Ember.$.expando + Ember.guidFor(rootPath);
<add> options.data.keywords[contextKey] = rootPath;
<ide>
<ide> // if the path is '' ("this"), just bind directly to the current context
<ide> var contextPath = path ? contextKey + '.' + path : contextKey; | 1 |
Java | Java | restore correct order of terminated flag check | 68cc57549a56480b723b6112e1bee0de114eeda1 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java
<ide> public void run() {
<ide> this.elementRef.lazySet(null);
<ide> return;
<ide> }
<del>
<add>
<add> // Check terminal signal before processing element..
<add> boolean isTerminated = this.terminated;
<add>
<ide> Object element = this.elementRef.get();
<ide> if (element != null) {
<ide> this.elementRef.lazySet(null);
<ide> public void run() {
<ide> }
<ide> }
<ide>
<del> if (this.terminated) {
<add> if (isTerminated) {
<ide> this.done = true;
<ide> Throwable ex = this.error;
<ide> this.error = null; | 1 |
PHP | PHP | fix cs error | 57772544227f65683b46eae3139c9b9d0903dffe | <ide><path>tests/TestCase/Error/ExceptionRendererTest.php
<ide> use Cake\Controller\Error\PrivateActionException;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<del>use Cake\Core\Plugin;
<ide> use Cake\Core\Error\MissingPluginException;
<add>use Cake\Core\Plugin;
<ide> use Cake\Error;
<ide> use Cake\Error\ExceptionRenderer;
<ide> use Cake\Event\Event; | 1 |
Text | Text | fix changelog wording as suggested | e45226dd899ebb39d4ae0fae1dda4a2a507eaddd | <ide><path>activerecord/CHANGELOG.md
<del>* Prevent AbstractAdapter from converting exceptions from ActiveSupport::Notification
<del> callbacks into ActiveRecord::StatementInvalids.
<add>* Prevent errors raised by sql.active_record notification subscribers from being converted into
<add> ActiveRecord::StatementInvalid exceptions.
<ide>
<ide> *Dennis Taylor*
<ide> | 1 |
Javascript | Javascript | enable cyrillic punycode test case | dae53238dc1aa38cbdb2dcff6c73373be1d6d071 | <ide><path>test/parallel/test-punycode.js
<ide> var tests = {
<ide> '\uC744\uAE4C',
<ide>
<ide> // (I) Russian (Cyrillic)
<del> /* XXX disabled, fails - possibly a bug in the RFC
<del> 'b1abfaaepdrnnbgefbaDotcwatmq2g4l':
<add> 'b1abfaaepdrnnbgefbadotcwatmq2g4l':
<ide> '\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438' +
<ide> '\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E' +
<ide> '\u0440\u0443\u0441\u0441\u043A\u0438',
<del> */
<ide>
<ide> // (J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol
<ide> 'PorqunopuedensimplementehablarenEspaol-fmd56a': | 1 |
Python | Python | remove extraneous 'import json' from linode driver | 8de7ab58d9e856f23571156d4fce0b0d9ba6241b | <ide><path>libcloud/drivers/linode.py
<ide> from libcloud.base import NodeAuthPassword, NodeAuthSSHKey
<ide> from libcloud.base import NodeImage
<ide> from copy import copy
<del>import json
<ide> import itertools
<ide> import os
<ide> | 1 |
Text | Text | fix typo in a href example | 561087fa0490afd024f8807c764fe5c4551f60a3 | <ide><path>README.md
<ide> import Link from 'next/link'
<ide> export default () => (
<ide> <nav>
<ide> <ul>
<del> <li><Link prefetch ref='/'><a>Home</a></Link></li>
<add> <li><Link prefetch href='/'><a>Home</a></Link></li>
<ide> <li><Link prefetch href='/about'><a>About</a></Link></li>
<ide> <li><Link prefetch href='/contact'><a>Contact</a></Link></li>
<ide> </ul> | 1 |
Ruby | Ruby | remove rails_root from webrick_server docs | ee04aea3ec1461368a72db525b325846e29b0045 | <ide><path>railties/lib/rails/webrick_server.rb
<ide> def self.dispatch(options = {})
<ide> def initialize(server, options) #:nodoc:
<ide> @server_options = options
<ide> @file_handler = WEBrick::HTTPServlet::FileHandler.new(server, options[:server_root])
<del> # Change to the RAILS_ROOT, since Webrick::Daemon.start does a Dir::cwd("/")
<del> # OPTIONS['working_directory'] is an absolute path of the RAILS_ROOT, set in railties/lib/commands/servers/webrick.rb
<add> # Change to the Rails.root, since Webrick::Daemon.start does a Dir::cwd("/")
<add> # OPTIONS['working_directory'] is an absolute path of the Rails.root, set in railties/lib/commands/servers/webrick.rb
<ide> Dir.chdir(OPTIONS['working_directory']) if defined?(OPTIONS) && File.directory?(OPTIONS['working_directory'])
<ide> super
<ide> end | 1 |
PHP | PHP | allow enums as entity_type in morphs | 8a728465360f402f6d4b6c1004cd35f5f7d97ab7 | <ide><path>src/Illuminate/Contracts/Database/Eloquent/StringableAttribute.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Database\Eloquent;
<add>
<add>interface StringableAttribute
<add>{
<add> /**
<add> * Allows enums to be used as morthed entity type
<add> * @return string
<add> */
<add> public function toString(): string;
<add>}
<ide><path>src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithDictionary.php
<ide> namespace Illuminate\Database\Eloquent\Relations\Concerns;
<ide>
<ide> use Doctrine\Instantiator\Exception\InvalidArgumentException;
<add>use Illuminate\Contracts\Database\Eloquent\StringableAttribute;
<ide>
<ide> trait InteractsWithDictionary
<ide> {
<ide> protected function getDictionaryKey($attribute)
<ide> return $attribute->__toString();
<ide> }
<ide>
<del> throw new InvalidArgumentException('Model attribute value is an object but does not have a __toString method.');
<add> if ($attribute instanceof StringableAttribute) {
<add> return $attribute->toString();
<add> }
<add>
<add> $msg = 'Model attribute value is an object but does not have a __toString method '.
<add> 'and does not implement \Illuminate\Contracts\Database\Eloquent\StringableAttribute interface.';
<add> throw new InvalidArgumentException($msg);
<ide> }
<ide>
<ide> return $attribute;
<ide><path>tests/Database/DatabaseEloquentMorphToTest.php
<ide>
<ide> namespace Illuminate\Tests\Database;
<ide>
<add>use Doctrine\Instantiator\Exception\InvalidArgumentException;
<add>use Illuminate\Contracts\Database\Eloquent\StringableAttribute;
<ide> use Illuminate\Database\Eloquent\Builder;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Eloquent\Relations\MorphTo;
<ide> protected function tearDown(): void
<ide> {
<ide> m::close();
<ide> }
<add> public function testLookupDictionaryIsProperlyConstructedForStringableEnums()
<add> {
<add> if (PHP_VERSION < "8.1") {
<add> $this->markTestSkipped('PHP 8.1 is required');
<add> }
<add> $relation = $this->getRelation();
<add> $relation->addEagerConstraints([
<add> $one = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => TestEnumStringAllowed::test2]
<add> ]);
<add> $dictionary = $relation->getDictionary();
<add> $value = $dictionary['morph_type_2'][TestEnumStringAllowed::test2->toString()][0]->foreign_key;
<add> $this->assertEquals(TestEnumStringAllowed::test2, $value);
<add> }
<add>
<add> public function testLookupDictionaryIsNotProperlyConstructedForEnums()
<add> {
<add> if (PHP_VERSION < "8.1") {
<add> $this->markTestSkipped('PHP 8.1 is required');
<add> }
<add> $this->expectException(InvalidArgumentException::class);
<add> $relation = $this->getRelation();
<add> $relation->addEagerConstraints([
<add> $one = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => TestEnum::test]
<add> ]);
<add> $dictionary = $relation->getDictionary();
<add> }
<ide>
<ide> public function testLookupDictionaryIsProperlyConstructed()
<ide> {
<ide> class EloquentMorphToRelatedStub extends Model
<ide> {
<ide> public $table = 'eloquent_morph_to_related_stubs';
<ide> }
<add>
<add>if (PHP_VERSION >= '8.1')
<add>{
<add> enum TestEnum: string
<add> {
<add> case test = 'Test';
<add> }
<add>
<add> enum TestEnumStringAllowed: string implements StringableAttribute
<add> {
<add> case test2 = "Test2";
<add>
<add> /**
<add> * Allows enums to be used as morthed entity type
<add> * @return string
<add> */
<add> public function toString(): string
<add> {
<add> return $this->value;
<add> }
<add> }
<add>} | 3 |
Mixed | Text | provide the whole response | b5c6f33f0d301d8766acb5e516defe4e4eae3119 | <ide><path>actionpack/CHANGELOG.md
<ide> * `process_action.action_controller` notifications now include the following in their payloads:
<ide>
<ide> * `:request` - the `ActionDispatch::Request`
<del> * `:location` - the `Location` response header
<add> * `:response` - the `ActionDispatch::Response`
<ide>
<ide> *George Claghorn*
<ide>
<ide><path>actionpack/lib/action_controller/metal/instrumentation.rb
<ide> def process_action(*)
<ide> raw_payload = {
<ide> controller: self.class.name,
<ide> action: action_name,
<add> request: request,
<ide> params: request.filtered_parameters,
<ide> headers: request.headers,
<ide> format: request.format.ref,
<ide> method: request.request_method,
<del> path: request.fullpath,
<del> request: request
<add> path: request.fullpath
<ide> }
<ide>
<ide> ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload)
<ide>
<ide> ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
<ide> result = super
<add> payload[:response] = response
<ide> payload[:status] = response.status
<del> payload[:location] = response.filtered_location
<ide> result
<ide> ensure
<ide> append_info_to_payload(payload) | 2 |
Ruby | Ruby | use regext#match? where matchdata is not needed | 4a9ef5e1202cdab1882989eb561b0dc854c9891b | <ide><path>actionpack/lib/action_dispatch/journey/formatter.rb
<ide> def missing_keys(route, parts)
<ide> missing_keys << key
<ide> end
<ide> when RegexCaseComparator
<del> unless RegexCaseComparator::DEFAULT_REGEX === parts[key]
<add> unless RegexCaseComparator::DEFAULT_REGEX.match?(parts[key])
<ide> missing_keys ||= []
<ide> missing_keys << key
<ide> end
<ide> else
<del> unless /\A#{tests[key]}\Z/ === parts[key]
<add> unless /\A#{tests[key]}\Z/.match?(parts[key])
<ide> missing_keys ||= []
<ide> missing_keys << key
<ide> end
<ide><path>actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
<ide> def move(t, a)
<ide>
<ide> t.map { |s|
<ide> if states = @regexp_states[s]
<del> regexps.concat states.map { |re, v| re === a ? v : nil }
<add> regexps.concat states.map { |re, v| re.match?(a) ? v : nil }
<ide> end
<ide>
<ide> if states = @string_states[s]
<ide><path>activerecord/lib/arel/visitors/oracle.rb
<ide> def order_hacks(o)
<ide> return o if o.orders.empty?
<ide> return o unless o.cores.any? do |core|
<ide> core.projections.any? do |projection|
<del> /FIRST_VALUE/ === projection
<add> /FIRST_VALUE/.match?(projection)
<ide> end
<ide> end
<ide> # Previous version with join and split broke ORDER BY clause
<ide><path>activerecord/test/cases/test_case.rb
<ide> def assert_sql(*patterns_to_match)
<ide> ensure
<ide> failed_patterns = []
<ide> patterns_to_match.each do |pattern|
<del> failed_patterns << pattern unless SQLCounter.log_all.any? { |sql| pattern === sql }
<add> failed_patterns << pattern unless SQLCounter.log_all.any? { |sql| pattern.match?(sql) }
<ide> end
<ide> assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
<ide> end | 4 |
Javascript | Javascript | fix gltfloader ddsextension | c00575eb8fa92fd4041a4cf3b0afcc4785597859 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
<ide>
<del> switch ( mapName ) {
<del>
<del> case 'aoMap':
<del> case 'emissiveMap':
<del> case 'metalnessMap':
<del> case 'normalMap':
<del> case 'roughnessMap':
<del> texture.format = THREE.RGBFormat;
<del> break;
<add> if ( ! texture.isCompressedTexture ) {
<add>
<add> switch ( mapName ) {
<add>
<add> case 'aoMap':
<add> case 'emissiveMap':
<add> case 'metalnessMap':
<add> case 'normalMap':
<add> case 'roughnessMap':
<add> texture.format = THREE.RGBFormat;
<add> break;
<add>
<add> }
<ide>
<ide> }
<ide> | 1 |
PHP | PHP | add getmorphtype method in morphto | 08bc627c6772b210263236c28be589af25e1f364 | <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphTo.php
<ide> public function createModelByType($type)
<ide> return new $type;
<ide> }
<ide>
<add> /**
<add> * Get the foreign key "type" name.
<add> *
<add> * @return string
<add> */
<add> public function getMorphType()
<add> {
<add> return $this->morphType;
<add> }
<add>
<ide> /**
<ide> * Get the dictionary used by the relationship.
<ide> * | 1 |
Text | Text | add info to the article | ea983e5c136af85c1ce2e6f88da807529c23b142 | <ide><path>client/src/pages/guide/english/c/for/index.md
<ide> title: For Loop
<ide> # For Loop
<ide>
<ide> The `for` loop executes a block of code until a specified condition is false. Use `while` loops when the number of iterations are variable, otherwise use `for` loops. A common use of `for` loops are array iterations.
<add>It is also known as an 'entry-controlled loop' since the condition is checked before the next iteration. Another example of an 'entry-controlled loop' is a while loop.
<ide>
<ide> ## Syntax of For Loop
<ide> | 1 |
Javascript | Javascript | remove unused suppressions | 91c4b0357a1e83419095ed5ae9c9f50602f86ce6 | <ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = createReactClass({
<ide> * - `false`, deprecated, use 'never' instead
<ide> * - `true`, deprecated, use 'always' instead
<ide> */
<del> // $FlowFixMe
<ide> keyboardShouldPersistTaps: PropTypes.oneOf([
<ide> 'always',
<ide> 'never',
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableListView.js
<ide> class SwipeableListView extends React.Component<Props, State> {
<ide>
<ide> render(): React.Node {
<ide> return (
<del> // $FlowFixMe Invalid prop usage
<ide> <ListView
<ide> {...this.props}
<ide> ref={ref => {
<del> // $FlowFixMe Invalid prop usage
<ide> this._listViewRef = ref;
<ide> }}
<ide> dataSource={this.state.dataSource.getDataSource()}
<ide><path>Libraries/Lists/FlatList.js
<ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> {
<ide> _virtualizedListPairs: Array<ViewabilityConfigCallbackPair> = [];
<ide>
<ide> _captureRef = ref => {
<del> // $FlowFixMe Invalid prop usage
<ide> this._listRef = ref;
<ide> };
<ide>
<ide><path>Libraries/Lists/ListView/ListView.js
<ide> const ListView = createReactClass({
<ide> if (props.removeClippedSubviews === undefined) {
<ide> props.removeClippedSubviews = true;
<ide> }
<del> // $FlowFixMe Invalid prop usage
<ide> Object.assign(props, {
<ide> onScroll: this._onScroll,
<del> // $FlowFixMe Invalid prop usage
<ide> stickyHeaderIndices: this.props.stickyHeaderIndices.concat(
<ide> stickySectionHeaderIndices,
<ide> ),
<ide><path>Libraries/Lists/MetroListView.js
<ide> class MetroListView extends React.Component<Props, $FlowFixMeState> {
<ide> }
<ide> setNativeProps(props: Object) {
<ide> if (this._listRef) {
<del> // $FlowFixMe Invalid prop usage
<ide> this._listRef.setNativeProps(props);
<ide> }
<ide> }
<ide> class MetroListView extends React.Component<Props, $FlowFixMeState> {
<ide> }
<ide> render() {
<ide> return (
<del> // $FlowFixMe Invalid prop usage
<ide> <ListView
<ide> {...this.props}
<ide> dataSource={this.state.ds}
<ide> ref={this._captureRef}
<ide> renderRow={this._renderRow}
<ide> renderFooter={this.props.FooterComponent && this._renderFooter}
<ide> renderSectionHeader={this.props.sections && this._renderSectionHeader}
<del> // $FlowFixMe Invalid prop usage
<ide> renderSeparator={this.props.SeparatorComponent && this._renderSeparator}
<ide> />
<ide> );
<ide> class MetroListView extends React.Component<Props, $FlowFixMeState> {
<ide> } else {
<ide> invariant(!props.sections, 'Cannot have both sections and items props.');
<ide> return {
<del> // $FlowFixMe Invalid prop usage
<ide> ds: state.ds.cloneWithRows(props.items),
<ide> sectionHeaderData,
<ide> };
<ide><path>Libraries/Lists/SectionList.js
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> */
<ide> recordInteraction() {
<ide> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
<del> // $FlowFixMe Invalid prop usage
<ide> listRef && listRef.recordInteraction();
<ide> }
<ide>
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> */
<ide> flashScrollIndicators() {
<ide> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
<del> // $FlowFixMe Invalid prop usage
<ide> listRef && listRef.flashScrollIndicators();
<ide> }
<ide>
<ide> class SectionList<SectionT: SectionBase<any>> extends React.PureComponent<
<ide> getScrollResponder(): ?ScrollView {
<ide> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
<ide> if (listRef) {
<del> // $FlowFixMe Invalid prop usage
<ide> return listRef.getScrollResponder();
<ide> }
<ide> }
<ide>
<ide> getScrollableNode() {
<ide> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
<ide> if (listRef) {
<del> // $FlowFixMe Invalid prop usage
<ide> return listRef.getScrollableNode();
<ide> }
<ide> }
<ide>
<ide> setNativeProps(props: Object) {
<ide> const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
<ide> if (listRef) {
<del> // $FlowFixMe Invalid prop usage
<ide> listRef.setNativeProps(props);
<ide> }
<ide> } | 6 |
PHP | PHP | fix php cs | 5836395757e7e5f595be072876920e6ad8449b3a | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function paginate($perPage = null, $columns = ['*'], $pageName = 'page',
<ide> */
<ide> public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page')
<ide> {
<del>
<del>
<ide> $page = Paginator::resolveCurrentPage($pageName);
<ide>
<ide> $perPage = $perPage ?: $this->model->getPerPage(); | 1 |
Ruby | Ruby | avoid direct use of arel constants | b9eec677c4ca28203124a9b5b160a57ca13b95f1 | <ide><path>activerecord/lib/active_record/relation/spawn_methods.rb
<ide> def merge(r)
<ide> merged_wheres = @where_values
<ide>
<ide> r.where_values.each do |w|
<del> if w.is_a?(Arel::Predicates::Equality)
<del> merged_wheres = merged_wheres.reject {|p| p.is_a?(Arel::Predicates::Equality) && p.operand1.name == w.operand1.name }
<add> if w.respond_to?(:operator) && w.operator == :==
<add> merged_wheres = merged_wheres.reject { |p|
<add> p.respond_to?(:operator) && p.operator == :== && p.operand1.name == w.operand1.name
<add> }
<ide> end
<ide>
<ide> merged_wheres += [w] | 1 |
Javascript | Javascript | reduce duplication in pointelement | b31352c665ee41aeae538219dabb39ed18aa8ecc | <ide><path>src/elements/element.point.js
<ide> import Element from '../core/core.element';
<ide> import {drawPoint} from '../helpers/helpers.canvas';
<ide>
<add>function inRange(el, pos, axis, useFinalPosition) {
<add> const options = el.options;
<add> const {[axis]: value} = el.getProps([axis], useFinalPosition);
<add>
<add> return (Math.abs(pos - value) < options.radius + options.hitRadius);
<add>}
<add>
<ide> export default class PointElement extends Element {
<ide>
<ide> constructor(cfg) {
<ide> export default class PointElement extends Element {
<ide> }
<ide>
<ide> inXRange(mouseX, useFinalPosition) {
<del> const options = this.options;
<del> const {x} = this.getProps(['x'], useFinalPosition);
<del>
<del> return (Math.abs(mouseX - x) < options.radius + options.hitRadius);
<add> return inRange(this, mouseX, 'x', useFinalPosition);
<ide> }
<ide>
<ide> inYRange(mouseY, useFinalPosition) {
<del> const options = this.options;
<del> const {y} = this.getProps(['x'], useFinalPosition);
<del> return (Math.abs(mouseY - y) < options.radius + options.hitRadius);
<add> return inRange(this, mouseY, 'y', useFinalPosition);
<ide> }
<ide>
<ide> getCenterPoint(useFinalPosition) { | 1 |
Python | Python | make max_length and static_batch configurable | ab1c1dfc79ea97918250bcf8cbfbe94fde6bea7f | <ide><path>official/transformer/v2/data_pipeline.py
<ide> def batching_fn(bucket_id, grouped_dataset):
<ide>
<ide> def _read_and_batch_from_files(
<ide> file_pattern, batch_size, max_length, num_parallel_calls, shuffle, repeat,
<del> static_batch=False):
<add> static_batch=False, num_replicas=1):
<ide> """Create dataset where each item is a dict of "inputs" and "targets".
<ide>
<ide> Args:
<ide> file_pattern: String used to match the input TFRecord files.
<del> batch_size: Maximum number of tokens per batch of examples
<add> batch_size: Maximum number of tokens per global batch of examples.
<ide> max_length: Maximum number of tokens per example
<ide> num_parallel_calls: Number of cpu cores for parallel input processing.
<ide> shuffle: If true, randomizes order of elements.
<ide> def _read_and_batch_from_files(
<ide> to be grouped so that the number of padding tokens is minimized, and helps
<ide> model training. In cases where the input shape must be static
<ide> (e.g. running on TPU), this setting should be set to True.
<add> num_replicas: Number of GPUs or other workers. We will generate global
<add> batches, and each global batch is equally divisible by number of replicas.
<add> Currently it is only effective when static_batch==True. TODO: make it
<add> effective when static_batch=False.
<ide>
<ide> Returns:
<ide> tf.data.Dataset object containing examples loaded from the files.
<ide> def _read_and_batch_from_files(
<ide>
<ide> # Read files and interleave results. When training, the order of the examples
<ide> # will be non-deterministic.
<add> options = tf.data.Options()
<add> options.experimental_deterministic = False
<ide> dataset = dataset.interleave(
<ide> _load_records,
<ide> cycle_length=num_parallel_calls,
<del> num_parallel_calls=num_parallel_calls)
<add> num_parallel_calls=tf.data.experimental.AUTOTUNE).with_options(options)
<ide>
<ide> # Parse each tf.Example into a dictionary
<ide> # TODO: Look into prefetch_input_elements for performance optimization.
<ide> def _read_and_batch_from_files(
<ide>
<ide> if static_batch:
<ide> dataset = dataset.padded_batch(
<del> batch_size // max_length, ([max_length], [max_length]),
<del> drop_remainder=True)
<add> # First calculate batch size (token number) per worker, then divide it
<add> # into sentences, and finally expand to a global batch. It could prove
<add> # the global batch divisble for distribution strategy.
<add> ((batch_size // num_replicas) // max_length) * num_replicas,
<add> ([max_length], [max_length]), drop_remainder=True)
<ide> else:
<ide> # Group and batch such that each batch has examples of similar length.
<add> # TODO: _batch_examples might need to do something special for num_replicas.
<ide> dataset = _batch_examples(dataset, batch_size, max_length)
<ide>
<ide> dataset = dataset.repeat(repeat)
<ide> def train_input_fn(params):
<ide> return _read_and_batch_from_files(
<ide> file_pattern, params["batch_size"], params["max_length"],
<ide> params["num_parallel_calls"], shuffle=True,
<del> repeat=params["repeat_dataset"], static_batch=params["static_batch"])
<add> repeat=params["repeat_dataset"], static_batch=params["static_batch"],
<add> num_replicas=params["num_gpus"])
<ide>
<ide>
<ide> def eval_input_fn(params):
<ide> def eval_input_fn(params):
<ide> return _read_and_batch_from_files(
<ide> file_pattern, params["batch_size"], params["max_length"],
<ide> params["num_parallel_calls"], shuffle=False, repeat=1,
<del> static_batch=params["static_batch"])
<add> static_batch=params["static_batch"], num_replicas=params["num_gpus"])
<ide>
<ide>
<ide> def map_data_for_transformer_fn(x, y):
<ide><path>official/transformer/v2/misc.py
<ide> def define_transformer_flags():
<ide> help=flags_core.help_wrap(
<ide> 'The Number of training steps to run between evaluations. This is '
<ide> 'used if --train_steps is defined.'))
<add> flags.DEFINE_boolean(
<add> name='enable_time_history', default=True,
<add> help='Whether to enable TimeHistory callback.')
<ide> flags.DEFINE_boolean(
<ide> name='enable_tensorboard', default=False,
<ide> help='Whether to enable Tensorboard callback.')
<ide> def define_transformer_flags():
<ide> 'complete list of parameters, please see model/model_params.py.'))
<ide>
<ide> flags.DEFINE_bool(
<del> name='static_batch', default=False,
<add> name='static_batch', short_name='sb', default=False,
<ide> help=flags_core.help_wrap(
<ide> 'Whether the batches in the dataset should have static shapes. In '
<ide> 'general, this setting should be False. Dynamic shapes allow the '
<ide> 'inputs to be grouped so that the number of padding tokens is '
<ide> 'minimized, and helps model training. In cases where the input shape '
<ide> 'must be static (e.g. running on TPU), this setting will be ignored '
<ide> 'and static batching will always be used.'))
<add> flags.DEFINE_integer(
<add> name='max_length', short_name='ml', default=256,
<add> help=flags_core.help_wrap(
<add> 'Max sentence length for Transformer. Default is 256. Note: Usually '
<add> 'it is more effective to use a smaller max length if static_batch is '
<add> 'enabled, e.g. 64.'))
<ide>
<ide> # Flags for training with steps (may be used for debugging)
<ide> flags.DEFINE_integer(
<ide> def _check_export_vocab_file(flags_dict):
<ide> def get_callbacks():
<ide> """Returns common callbacks."""
<ide> callbacks = []
<del> time_callback = keras_utils.TimeHistory(FLAGS.batch_size, FLAGS.log_steps)
<del> callbacks.append(time_callback)
<add> if FLAGS.enable_time_history:
<add> time_callback = keras_utils.TimeHistory(FLAGS.batch_size, FLAGS.log_steps)
<add> callbacks.append(time_callback)
<ide>
<ide> if FLAGS.enable_tensorboard:
<ide> tensorboard_callback = tf.keras.callbacks.TensorBoard(
<ide><path>official/transformer/v2/transformer_main.py
<ide> def __init__(self, flags_obj):
<ide>
<ide> self.params = params = misc.get_model_params(flags_obj.param_set, num_gpus)
<ide>
<add> params["num_gpus"] = num_gpus
<ide> params["data_dir"] = flags_obj.data_dir
<ide> params["model_dir"] = flags_obj.model_dir
<ide> params["static_batch"] = flags_obj.static_batch
<add> params["max_length"] = flags_obj.max_length
<ide> params["num_parallel_calls"] = (
<ide> flags_obj.num_parallel_calls or tf.data.experimental.AUTOTUNE)
<ide>
<ide> def train(self):
<ide> epochs=i,
<ide> steps_per_epoch=flags_obj.steps_between_evals,
<ide> callbacks=callbacks,
<del> verbose=2)
<add> # If TimeHistory is enabled, progress bar would be messy. Increase the
<add> # verbose level to get rid of it.
<add> verbose=(2 if flags_obj.enable_time_history else 1))
<ide> print("End train iteration:{}/{} global step:{}".format(
<ide> i,
<ide> iterations,
<ide> def train(self):
<ide> if (flags_obj.bleu_source and flags_obj.bleu_ref):
<ide> uncased_score, cased_score = self.eval()
<ide>
<add> print("BLEU: uncased={}, cased={}".format(uncased_score, cased_score))
<add>
<ide> stats = misc.build_stats(history, callbacks)
<ide> if uncased_score and cased_score:
<ide> stats["bleu_uncased"] = uncased_score | 3 |
Text | Text | add seishun as a collaborator | 804ab7ebaaf5d87499e3cbce03184f064264dd2a | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Evan Lucas** ([@evanlucas](https://github.com/evanlucas)) <evanlucas@me.com>
<ide> * **Brendan Ashworth** ([@brendanashworth](https://github.com/brendanashworth)) <brendan.ashworth@me.com>
<ide> * **Vladimir Kurchatkin** ([@vkurchatkin](https://github.com/vkurchatkin)) <vladimir.kurchatkin@gmail.com>
<add>* **Nikolai Vavilov** ([@seishun](https://github.com/seishun)) <vvnicholas@gmail.com>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Python | Python | add sagemakertrainer for model paralellism | 31245775e5772fbded1ac07ed89fbba3b5af0cb9 | <ide><path>src/transformers/sagemaker/__init__.py
<add># flake8: noqa
<add># There's no way to ignore "F401 '...' imported but unused" warnings in this
<add># module, but to preserve other warnings. So, don't check this module at all.
<add>
<add># Copyright 2021 The HuggingFace Team. All rights reserved.
<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>from .trainer_sm import SageMakerTrainer
<add>from .training_args_sm import SageMakerTrainingArguments, is_sagemaker_distributed_available
<ide><path>src/transformers/sagemaker/trainer_sm.py
<add># Copyright 2021 The HuggingFace Team. All rights reserved.
<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>from typing import Any, Dict, List, Optional, Tuple, Union
<add>
<add>import torch
<add>from torch import nn
<add>from torch.utils.data.dataset import Dataset
<add>from torch.utils.data.distributed import DistributedSampler
<add>
<add>from ..trainer import Trainer
<add>from ..trainer_pt_utils import (
<add> DistributedLengthGroupedSampler,
<add> SequentialDistributedSampler,
<add> nested_detach,
<add> nested_numpify,
<add>)
<add>from ..utils import logging
<add>from .training_args_sm import is_smdistributed_available
<add>
<add>
<add>logger = logging.get_logger(__name__)
<add>
<add>
<add>if is_smdistributed_available():
<add> import smdistributed.modelparallel.torch as smp
<add>
<add> @smp.step()
<add> def forward_backward(model, inputs):
<add> outputs = model(**inputs)
<add> loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
<add> model.backward(loss)
<add> return loss
<add>
<add> @smp.step()
<add> def forward_only(model, inputs):
<add> return model(**inputs)
<add>
<add> def smp_gather(tensor):
<add> if isinstance(tensor, (list, tuple)):
<add> return type(tensor)(smp_gather(t) for t in tensor)
<add> elif isinstance(tensor, dict):
<add> return type(tensor)({k: smp_gather(v) for k, v in tensor.items()})
<add> elif not isinstance(tensor, torch.Tensor):
<add> raise TypeError(
<add> f"Can't gather the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors."
<add> )
<add> all_tensors = smp.allgather(tensor, smp.CommGroup.DP_GROUP)
<add> return torch.cat([t.cpu() for t in all_tensors], dim=0)
<add>
<add> def nested_smp_concat(tensor):
<add> if isinstance(tensor, (list, tuple)):
<add> return type(tensor)(nested_smp_concat(t) for t in tensor)
<add> elif isinstance(tensor, dict):
<add> return type(tensor)({k: nested_smp_concat(v) for k, v in tensor.items()})
<add> # It doesn't seem possible to check here if `tensor` is a StepOutput because StepOutput lives in `smp.step`
<add> # which is also the name of the decorator so Python is confused.
<add> return tensor.concat().detach().cpu()
<add>
<add>
<add>class SageMakerTrainer(Trainer):
<add> def __init__(self, args=None, **kwargs):
<add> super().__init__(args=args, **kwargs)
<add> self.is_model_parallel_enabled = is_smdistributed_available() and self.args.mp_parameters != ""
<add> if self.is_model_parallel_enabled and self.args.gradient_accumulation_steps != 1:
<add> raise ValueError("Gradient accumulation is not supported when model parallel is enabled.")
<add>
<add> def _get_train_sampler(self):
<add> if self.is_model_parallel_enabled:
<add> if self.args.group_by_length:
<add> return DistributedLengthGroupedSampler(
<add> self.train_dataset, self.args.train_batch_size, num_replicas=smp.dp_size(), rank=smp.dp_rank()
<add> )
<add> else:
<add> return DistributedSampler(self.train_dataset, num_replicas=smp.dp_size(), rank=smp.dp_rank())
<add> else:
<add> return super()._get_train_sampler()
<add>
<add> def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]:
<add> if self.is_model_parallel_enabled:
<add> return SequentialDistributedSampler(eval_dataset, num_replicas=smp.dp_size(), rank=smp.dp_rank())
<add> else:
<add> return super()._get_eval_sampler(eval_dataset)
<add>
<add> def _wrap_model(self, model, training=True):
<add> if self.is_model_parallel_enabled:
<add> # Wrapping the base model twice in a DistributedModel will raise an error.
<add> if isinstance(self.model_wrapped, smp.model.DistributedModel):
<add> return self.model_wrapped
<add> return smp.DistributedModel(model)
<add> else:
<add> return super()._wrap_model(model)
<add>
<add> def create_optimizer_and_scheduler(self, num_training_steps: int):
<add> super().create_optimizer_and_scheduler(num_training_steps)
<add> if self.is_model_parallel_enabled:
<add> self.optimizer = smp.DistributedOptimizer(self.optimizer)
<add>
<add> def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
<add> if self.is_model_parallel_enabled:
<add> model.train()
<add> inputs = self._prepare_inputs(inputs)
<add> loss_mb = forward_backward(model, inputs)
<add> return loss_mb.reduce_mean().detach().to(self.args.device)
<add> else:
<add> return super().training_step(model, inputs)
<add>
<add> def _gather_and_numpify(self, tensors, name):
<add> if self.is_model_parallel_enabled:
<add> tensors = smp_gather(tensors)
<add> return nested_numpify(tensors)
<add> else:
<add> return super()._gather_and_numpify(tensors, name)
<add>
<add> def prediction_step(
<add> self,
<add> model: nn.Module,
<add> inputs: Dict[str, Union[torch.Tensor, Any]],
<add> prediction_loss_only: bool,
<add> ignore_keys: Optional[List[str]] = None,
<add> ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
<add> if self.is_model_parallel_enabled:
<add> has_labels = all(inputs.get(k) is not None for k in self.label_names)
<add> inputs = self._prepare_inputs(inputs)
<add>
<add> if ignore_keys is None:
<add> if hasattr(self.model, "config"):
<add> ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
<add> else:
<add> ignore_keys = []
<add>
<add> with torch.no_grad():
<add> raw_outputs = forward_only(model, inputs)
<add> if has_labels:
<add> if isinstance(raw_outputs, dict):
<add> loss_mb = raw_outputs["loss"]
<add> logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + ["loss"])
<add> else:
<add> loss_mb = raw_outputs[0]
<add> logits_mb = raw_outputs[1:]
<add>
<add> loss = loss_mb.reduce_mean().detach().cpu()
<add> logits = nested_smp_concat(logits_mb)
<add> else:
<add> loss = None
<add> if isinstance(raw_outputs, dict):
<add> logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys)
<add> else:
<add> logits_mb = raw_outputs
<add> logits = nested_smp_concat(logits_mb)
<add>
<add> if prediction_loss_only:
<add> return (loss, None, None)
<add>
<add> if len(logits) == 1:
<add> logits = logits[0]
<add>
<add> if has_labels:
<add> labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
<add> if len(labels) == 1:
<add> labels = labels[0]
<add> else:
<add> labels = None
<add>
<add> return (loss, logits, labels)
<add> else:
<add> return super().prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
<ide><path>src/transformers/sagemaker/training_args_sm.py
<add># Copyright 2021 The HuggingFace Team. All rights reserved.
<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>import importlib.util
<add>from dataclasses import dataclass, field
<add>
<add>import torch
<add>
<add>from transformers.file_utils import cached_property, is_sagemaker_distributed_available
<add>from transformers.training_args import TrainingArguments
<add>from transformers.utils import logging
<add>
<add>
<add>logger = logging.get_logger(__name__)
<add>
<add>
<add>def is_smdistributed_available():
<add> return importlib.util.find_spec("smdistributed") is not None
<add>
<add>
<add>if is_smdistributed_available():
<add> import smdistributed.modelparallel.torch as smp
<add>
<add>
<add>@dataclass
<add>class SageMakerTrainingArguments(TrainingArguments):
<add> mp_parameters: str = field(
<add> default="", metadata={"help": "Used by the SageMaker launcher to send mp-specific args."}
<add> )
<add>
<add> def __post_init__(self):
<add> super().__post_init__()
<add> if is_smdistributed_available() and self.mp_parameters != "":
<add> smp.init()
<add>
<add> @cached_property
<add> def _setup_devices(self) -> "torch.device":
<add> logger.info("PyTorch: setting up devices")
<add> if self.no_cuda:
<add> device = torch.device("cpu")
<add> self._n_gpu = 0
<add> elif is_smdistributed_available() and self.mp_parameters != "":
<add> local_rank = smp.local_rank()
<add> device = torch.device("cuda", local_rank)
<add> self._n_gpu = 1
<add> elif is_sagemaker_distributed_available():
<add> import smdistributed.dataparallel.torch.distributed as dist
<add>
<add> dist.init_process_group()
<add> self.local_rank = dist.get_local_rank()
<add> device = torch.device("cuda", self.local_rank)
<add> self._n_gpu = 1
<add> elif self.local_rank == -1:
<add> # if n_gpu is > 1 we'll use nn.DataParallel.
<add> # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
<add> # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
<add> # trigger an error that a device index is missing. Index 0 takes into account the
<add> # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
<add> # will use the first GPU in that env, i.e. GPU#1
<add> device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
<add> # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
<add> # the default value.
<add> self._n_gpu = torch.cuda.device_count()
<add> else:
<add> # Here, we'll use torch.distributed.
<add> # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
<add> torch.distributed.init_process_group(backend="nccl")
<add> device = torch.device("cuda", self.local_rank)
<add> self._n_gpu = 1
<add>
<add> if device.type == "cuda":
<add> torch.cuda.set_device(device)
<add>
<add> return device
<add>
<add> @property
<add> def place_model_on_device(self):
<add> return not (is_smdistributed_available() and self.mp_parameters != "")
<ide><path>src/transformers/trainer.py
<ide> def __init__(
<ide> # 1. MP - since we are trying to fit a much bigger than 1 gpu model
<ide> # 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,
<ide> # and we only use deepspeed for training at the moment
<del> if not self.is_model_parallel and not (args.deepspeed and args.do_train):
<add> if not (self.is_model_parallel or (args.deepspeed and args.do_train)) and self.args.place_model_on_device:
<ide> model = model.to(args.device)
<ide>
<ide> # Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs
<ide> def __init__(
<ide> if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
<ide> raise ValueError("eval_dataset must implement __len__")
<ide>
<add> self._signature_columns = None
<ide> if is_datasets_available():
<ide> if isinstance(train_dataset, datasets.Dataset):
<ide> self._remove_unused_columns(self.train_dataset, description="training")
<ide> def remove_callback(self, callback):
<ide> def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None):
<ide> if not self.args.remove_unused_columns:
<ide> return
<del> # Inspect model forward signature to keep only the arguments it accepts.
<del> signature = inspect.signature(self.model.forward)
<del> signature_columns = list(signature.parameters.keys())
<del> # Labels may be named label or label_ids, the default data collator handles that.
<del> signature_columns += ["label", "label_ids"]
<del> columns = [k for k in signature_columns if k in dataset.column_names]
<del> ignored_columns = list(set(dataset.column_names) - set(signature_columns))
<add> if self._signature_columns is None:
<add> # Inspect model forward signature to keep only the arguments it accepts.
<add> signature = inspect.signature(self.model.forward)
<add> self._signature_columns = list(signature.parameters.keys())
<add> # Labels may be named label or label_ids, the default data collator handles that.
<add> self._signature_columns += ["label", "label_ids"]
<add> columns = [k for k in self._signature_columns if k in dataset.column_names]
<add> ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))
<ide> dset_description = "" if description is None else f"in the {description} set "
<ide> logger.info(
<del> f"The following columns {dset_description}don't have a corresponding argument in `{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}."
<add> f"The following columns {dset_description}don't have a corresponding argument in "
<add> f"`{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}."
<ide> )
<ide> dataset.set_format(type=dataset.format["type"], columns=columns)
<ide>
<ide> def call_model_init(self, trial=None):
<ide>
<ide> return model
<ide>
<add> def _wrap_model(self, model, training=True):
<add> # Mixed precision training with apex (torch < 1.6)
<add> if self.use_apex and training:
<add> model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)
<add>
<add> # Multi-gpu training (should be after apex fp16 initialization)
<add> if self.args.n_gpu > 1:
<add> model = torch.nn.DataParallel(model)
<add>
<add> # Note: in torch.distributed mode, there's no point in wrapping the model
<add> # inside a DistributedDataParallel as we'll be under `no_grad` anyways.
<add> if not training:
<add> return model
<add>
<add> # Distributed training (should be after apex fp16 initialization)
<add> if self.sharded_dpp:
<add> model = ShardedDDP(model, self.optimizer)
<add> elif is_sagemaker_distributed_available():
<add> model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)
<add> elif self.deepspeed:
<add> pass # already initialized its own DDP earlier
<add> elif self.args.local_rank != -1:
<add> if self.args.ddp_find_unused_parameters is not None:
<add> find_unused_parameters = self.args.ddp_find_unused_parameters
<add> elif isinstance(model, PreTrainedModel):
<add> # find_unused_parameters breaks checkpointing as per
<add> # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
<add> find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False)
<add> else:
<add> find_unused_parameters = True
<add> model = torch.nn.parallel.DistributedDataParallel(
<add> model,
<add> device_ids=[self.args.local_rank],
<add> output_device=self.args.local_rank,
<add> find_unused_parameters=find_unused_parameters,
<add> )
<add>
<add> return model
<add>
<ide> def train(
<ide> self,
<ide> resume_from_checkpoint: Optional[str] = None,
<ide> def train(
<ide>
<ide> # If model was re-initialized, put it on the right device and update self.model_wrapped
<ide> if model_reloaded:
<del> if not self.is_model_parallel:
<add> if not self.is_model_parallel and self.args.place_model_on_device:
<ide> self.model = self.model.to(self.args.device)
<ide> self.model_wrapped = self.model
<ide>
<ide> def train(
<ide> # Check if saved optimizer or scheduler states exist
<ide> self._load_optimizer_and_scheduler(resume_from_checkpoint)
<ide>
<del> model = self.model_wrapped
<del>
<del> # Mixed precision training with apex (torch < 1.6)
<del> if self.use_apex:
<del> model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)
<del>
<del> # Multi-gpu training (should be after apex fp16 initialization)
<del> if self.args.n_gpu > 1:
<del> model = torch.nn.DataParallel(model)
<del>
<del> # Distributed training (should be after apex fp16 initialization)
<del> if self.sharded_dpp:
<del> model = ShardedDDP(model, self.optimizer)
<del> elif is_sagemaker_distributed_available():
<del> model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)
<del> elif self.deepspeed:
<del> pass # already initialized its own DDP earlier
<del> elif self.args.local_rank != -1:
<del> if self.args.ddp_find_unused_parameters is not None:
<del> find_unused_parameters = self.args.ddp_find_unused_parameters
<del> elif isinstance(model, PreTrainedModel):
<del> # find_unused_parameters breaks checkpointing as per
<del> # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
<del> find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False)
<del> else:
<del> find_unused_parameters = True
<del> model = torch.nn.parallel.DistributedDataParallel(
<del> model,
<del> device_ids=[self.args.local_rank],
<del> output_device=self.args.local_rank,
<del> find_unused_parameters=find_unused_parameters,
<del> )
<add> model = self._wrap_model(self.model_wrapped)
<ide>
<ide> # for the rest of this function `model` is the outside model, whether it was wrapped or not
<ide> if model is not self.model:
<ide> def train(
<ide> )
<ide> if isinstance(self.model, PreTrainedModel):
<ide> self.model = self.model.from_pretrained(self.state.best_model_checkpoint)
<del> if not self.is_model_parallel:
<add> if not self.is_model_parallel and self.args.place_model_on_device:
<ide> self.model = self.model.to(self.args.device)
<ide> else:
<ide> state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME))
<ide> def prediction_loop(
<ide> # flagging only for when --do_train wasn't passed as only then it's redundant
<ide> logger.info("Detected the deepspeed argument but it will not be used for evaluation")
<ide>
<del> model = self.model
<del>
<del> # multi-gpu eval
<del> if self.args.n_gpu > 1:
<del> model = torch.nn.DataParallel(model)
<del> # Note: in torch.distributed mode, there's no point in wrapping the model
<del> # inside a DistributedDataParallel as we'll be under `no_grad` anyways.
<add> model = self._wrap_model(self.model, training=False)
<ide>
<ide> batch_size = dataloader.batch_size
<ide> num_examples = self.num_examples(dataloader)
<ide><path>src/transformers/training_args.py
<ide> def parallel_mode(self):
<ide> else:
<ide> return ParallelMode.NOT_PARALLEL
<ide>
<add> @property
<add> def place_model_on_device(self):
<add> """
<add> Can be subclassed and overridden for some specific integrations.
<add> """
<add> return True
<add>
<ide> def to_dict(self):
<ide> """
<ide> Serializes this instance while replace `Enum` by their values (for JSON serialization support). | 5 |
Ruby | Ruby | add assertion for get? method into test cases | 01d4e060e27c47cb28eea2d0e2a386ac335bbf93 | <ide><path>actionpack/test/dispatch/request_test.rb
<ide> class RequestMethod < BaseRequestTest
<ide>
<ide> assert_equal 'GET', request.request_method
<ide> assert_equal 'GET', request.env["REQUEST_METHOD"]
<add> assert request.get?
<ide> end
<ide>
<ide> test "invalid http method raises exception" do | 1 |
Javascript | Javascript | fix regression with clearimmediate() | 42158a03132568ce28cf94e73ba6b8039b208d5d | <ide><path>lib/timers.js
<ide> function processImmediate() {
<ide> domain.enter();
<ide>
<ide> immediate._callback = immediate._onImmediate;
<add>
<add> // Save next in case `clearImmediate(immediate)` is called from callback
<add> var next = immediate._idleNext;
<add>
<ide> tryOnImmediate(immediate, tail);
<ide>
<ide> if (domain)
<ide> domain.exit();
<ide>
<del> immediate = immediate._idleNext;
<add> // If `clearImmediate(immediate)` wasn't called from the callback, use the
<add> // `immediate`'s next item
<add> if (immediate._idleNext)
<add> immediate = immediate._idleNext;
<add> else
<add> immediate = next;
<ide> }
<ide>
<ide> // Only round-trip to C++ land if we have to. Calling clearImmediate() on an
<ide><path>test/parallel/test-timers-clearImmediate.js
<add>'use strict';
<add>require('../common');
<add>const assert = require('assert');
<add>
<add>const N = 3;
<add>var count = 0;
<add>function next() {
<add> const immediate = setImmediate(function() {
<add> clearImmediate(immediate);
<add> ++count;
<add> });
<add>}
<add>for (var i = 0; i < N; ++i)
<add> next();
<add>
<add>process.on('exit', () => {
<add> assert.strictEqual(count, N, `Expected ${N} immediate callback executions`);
<add>}); | 2 |
Java | Java | update resource handler java config | 0b02551e2f8f8ae7107b2303c10432542a201fbe | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<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>package org.springframework.web.servlet.config.annotation;
<add>
<add>import org.springframework.cache.Cache;
<add>import org.springframework.cache.concurrent.ConcurrentMapCache;
<add>import org.springframework.util.Assert;
<add>import org.springframework.web.servlet.resource.CachingResourceResolver;
<add>import org.springframework.web.servlet.resource.CachingResourceTransformer;
<add>import org.springframework.web.servlet.resource.CssLinkResourceTransformer;
<add>import org.springframework.web.servlet.resource.PathResourceResolver;
<add>import org.springframework.web.servlet.resource.ResourceResolver;
<add>import org.springframework.web.servlet.resource.ResourceTransformer;
<add>import org.springframework.web.servlet.resource.VersionResourceResolver;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Assists with the registration of resource resolvers and transformers.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 4.1
<add> */
<add>public class ResourceChainRegistration {
<add>
<add> private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache";
<add>
<add> private final List<ResourceResolver> resolvers = new ArrayList<ResourceResolver>(4);
<add>
<add> private final List<ResourceTransformer> transformers = new ArrayList<ResourceTransformer>(4);
<add>
<add> private boolean hasVersionResolver;
<add>
<add> private boolean hasPathResolver;
<add>
<add> private boolean hasCssLinkTransformer;
<add>
<add>
<add> public ResourceChainRegistration(boolean cacheResources) {
<add> this(cacheResources, cacheResources ? new ConcurrentMapCache(DEFAULT_CACHE_NAME) : null);
<add> }
<add>
<add> public ResourceChainRegistration(boolean cacheResources, Cache cache) {
<add> Assert.isTrue(!cacheResources || cache != null, "'cache' is required when cacheResources=true");
<add> if (cacheResources) {
<add> this.resolvers.add(new CachingResourceResolver(cache));
<add> this.transformers.add(new CachingResourceTransformer(cache));
<add> }
<add> }
<add>
<add>
<add> /**
<add> * Add a resource resolver to the chain.
<add> * @param resolver the resolver to add
<add> * @return the current instance for chained method invocation
<add> */
<add> public ResourceChainRegistration addResolver(ResourceResolver resolver) {
<add> Assert.notNull(resolver, "The provided ResourceResolver should not be null");
<add> this.resolvers.add(resolver);
<add> if (resolver instanceof VersionResourceResolver) {
<add> this.hasVersionResolver = true;
<add> }
<add> else if (resolver instanceof PathResourceResolver) {
<add> this.hasPathResolver = true;
<add> }
<add> return this;
<add> }
<add>
<add> /**
<add> * Add a resource transformer to the chain.
<add> * @param transformer the transformer to add
<add> * @return the current instance for chained method invocation
<add> */
<add> public ResourceChainRegistration addTransformer(ResourceTransformer transformer) {
<add> Assert.notNull(transformer, "The provided ResourceTransformer should not be null");
<add> this.transformers.add(transformer);
<add> if (transformer instanceof CssLinkResourceTransformer) {
<add> this.hasCssLinkTransformer = true;
<add> }
<add> return this;
<add> }
<add>
<add> protected List<ResourceResolver> getResourceResolvers() {
<add> if (!this.hasPathResolver) {
<add> List<ResourceResolver> result = new ArrayList<ResourceResolver>(this.resolvers);
<add> result.add(new PathResourceResolver());
<add> return result;
<add> }
<add> return this.resolvers;
<add> }
<add>
<add> protected List<ResourceTransformer> getResourceTransformers() {
<add> if (this.hasVersionResolver && !this.hasCssLinkTransformer) {
<add> List<ResourceTransformer> result = new ArrayList<ResourceTransformer>(this.transformers);
<add> boolean hasTransformers = !this.transformers.isEmpty();
<add> boolean hasCaching = hasTransformers && this.transformers.get(0) instanceof CachingResourceTransformer;
<add> result.add(hasCaching ? 1 : 0, new CssLinkResourceTransformer());
<add> return result;
<add> }
<add> return this.transformers;
<add> }
<add>
<add>}
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistration.java
<ide>
<ide> package org.springframework.web.servlet.config.annotation;
<ide>
<del>import java.util.ArrayList;
<del>import java.util.List;
<del>
<ide> import org.springframework.cache.Cache;
<del>import org.springframework.cache.concurrent.ConcurrentMapCache;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.ResourceLoader;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.CollectionUtils;
<del>import org.springframework.web.servlet.resource.CachingResourceResolver;
<del>import org.springframework.web.servlet.resource.CachingResourceTransformer;
<del>import org.springframework.web.servlet.resource.ContentVersionStrategy;
<del>import org.springframework.web.servlet.resource.CssLinkResourceTransformer;
<del>import org.springframework.web.servlet.resource.FixedVersionStrategy;
<ide> import org.springframework.web.servlet.resource.PathResourceResolver;
<ide> import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
<del>import org.springframework.web.servlet.resource.ResourceResolver;
<del>import org.springframework.web.servlet.resource.ResourceTransformer;
<del>import org.springframework.web.servlet.resource.VersionResourceResolver;
<del>import org.springframework.web.servlet.resource.VersionStrategy;
<add>
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * Encapsulates information required to create a resource handlers.
<ide> */
<ide> public class ResourceHandlerRegistration {
<ide>
<del> private static final String RESOURCE_CACHE_NAME = "spring-resourcehandler-cache";
<del>
<ide> private final ResourceLoader resourceLoader;
<ide>
<ide> private final String[] pathPatterns;
<ide> public class ResourceHandlerRegistration {
<ide>
<ide> private Integer cachePeriod;
<ide>
<del> private List<ResourceResolver> customResolvers = new ArrayList<ResourceResolver>();
<del>
<del> private List<ResourceTransformer> customTransformers = new ArrayList<ResourceTransformer>();
<del>
<del> private boolean hasVersionResolver;
<del>
<del> private boolean hasCssLinkTransformer;
<del>
<del> private boolean isDevMode = false;
<del>
<del> private Cache resourceCache;
<add> private ResourceChainRegistration resourceChainRegistration;
<ide>
<ide>
<ide> /**
<ide> public ResourceHandlerRegistration addResourceLocations(String...resourceLocatio
<ide> }
<ide>
<ide> /**
<del> * Add a {@code ResourceResolver} to the chain, allowing to resolve server-side resources from
<del> * HTTP requests.
<del> *
<del> * <p>{@link ResourceResolver}s are registered, in the following order:
<del> * <ol>
<del> * <li>a {@link org.springframework.web.servlet.resource.CachingResourceResolver}
<del> * for caching the results of the next Resolvers; this resolver is only registered if you
<del> * did not provide your own instance of {@link CachingResourceResolver} at the beginning of the chain</li>
<del> * <li>all {@code ResourceResolver}s registered using this method, in the order of methods calls</li>
<del> * <li>a {@link VersionResourceResolver} if a versioning configuration has been applied with
<del> * {@code addVersionStrategy}, {@code addVersion}, etc.</li>
<del> * <li>a {@link PathResourceResolver} for resolving resources on the file system</li>
<del> * </ol>
<del> *
<del> * @param resolver a {@link ResourceResolver} to add to the chain of resolvers
<add> * Specify the cache period for the resources served by the resource handler, in seconds. The default is to not
<add> * send any cache headers but to rely on last-modified timestamps only. Set to 0 in order to send cache headers
<add> * that prevent caching, or to a positive number of seconds to send cache headers with the given max-age value.
<add> * @param cachePeriod the time to cache resources in seconds
<ide> * @return the same {@link ResourceHandlerRegistration} instance for chained method invocation
<del> * @see ResourceResolver
<del> * @since 4.1
<ide> */
<del> public ResourceHandlerRegistration addResolver(ResourceResolver resolver) {
<del> Assert.notNull(resolver, "The provided ResourceResolver should not be null");
<del> this.customResolvers.add(resolver);
<del> if (resolver instanceof VersionResourceResolver) {
<del> this.hasVersionResolver = true;
<del> }
<add> public ResourceHandlerRegistration setCachePeriod(Integer cachePeriod) {
<add> this.cachePeriod = cachePeriod;
<ide> return this;
<ide> }
<ide>
<ide> /**
<del> * Add a {@code ResourceTransformer} to the chain, allowing to transform the content
<del> * of server-side resources when serving them to HTTP clients.
<add> * Configure a chain of resource resolvers and transformers to use. This
<add> * can be useful for example to apply a version strategy to resource URLs.
<ide> *
<del> * <p>{@link ResourceTransformer}s are registered, in the following order:
<del> * <ol>
<del> * <li>a {@link org.springframework.web.servlet.resource.CachingResourceTransformer}
<del> * for caching the results of the next Transformers; this transformer is only registered if you
<del> * did not provide your own instance of {@link CachingResourceTransformer} at the beginning of the chain</li>
<del> * <li>a {@link CssLinkResourceTransformer} for updating links within CSS files; this transformer
<del> * is only registered if a versioning configuration has been applied with {@code addVersionStrategy},
<del> * {@code addVersion}, etc</li>
<del> * <li>all {@code ResourceTransformer}s registered using this method, in the order of methods calls</li>
<del> * </ol>
<add> * <p>If this method is not invoked, by default only a simple
<add> * {@link PathResourceResolver} is used in order to match URL paths to
<add> * resources under the configured locations.
<ide> *
<del> * @param transformer a {@link ResourceTransformer} to add to the chain of transformers
<add> * @param cacheResources whether to cache the result of resource resolution;
<add> * setting this to "true" is recommended for production (and "false" for
<add> * development, especially when applying a version strategy.
<ide> * @return the same {@link ResourceHandlerRegistration} instance for chained method invocation
<del> * @see ResourceResolver
<ide> * @since 4.1
<ide> */
<del> public ResourceHandlerRegistration addTransformer(ResourceTransformer transformer) {
<del> Assert.notNull(transformer, "The provided ResourceTransformer should not be null");
<del> this.customTransformers.add(transformer);
<del> if (transformer instanceof CssLinkResourceTransformer) {
<del> this.hasCssLinkTransformer = true;
<del> }
<del> return this;
<add> public ResourceChainRegistration resourceChain(boolean cacheResources) {
<add> this.resourceChainRegistration = new ResourceChainRegistration(cacheResources);
<add> return this.resourceChainRegistration;
<ide> }
<ide>
<ide> /**
<del> * Disable automatic registration of caching Resolver/Transformer, thus disabling {@code Resource} caching
<del> * if no caching Resolver/Transformer was manually registered.
<del> * <p>Useful when updating static resources at runtime, i.e. during the development phase.</p>
<add> * Configure a chain of resource resolvers and transformers to use. This
<add> * can be useful for example to apply a version strategy to resource URLs.
<add> *
<add> * <p>If this method is not invoked, by default only a simple
<add> * {@link PathResourceResolver} is used in order to match URL paths to
<add> * resources under the configured locations.
<add> *
<add> * @param cacheResources whether to cache the result of resource resolution;
<add> * setting this to "true" is recommended for production (and "false" for
<add> * development, especially when applying a version strategy.
<add> * @param cache the cache to use for storing resolved and transformed resources;
<add> * by default a {@link org.springframework.cache.concurrent.ConcurrentMapCache}
<add> * is used.
<ide> * @return the same {@link ResourceHandlerRegistration} instance for chained method invocation
<del> * @see ResourceResolver
<del> * @see ResourceTransformer
<ide> * @since 4.1
<ide> */
<del> public ResourceHandlerRegistration enableDevMode() {
<del> this.isDevMode = true;
<del> return this;
<del> }
<del>
<del> /**
<del> * Specify the cache period for the resources served by the resource handler, in seconds. The default is to not
<del> * send any cache headers but to rely on last-modified timestamps only. Set to 0 in order to send cache headers
<del> * that prevent caching, or to a positive number of seconds to send cache headers with the given max-age value.
<del> * @param cachePeriod the time to cache resources in seconds
<del> * @return the same {@link ResourceHandlerRegistration} instance for chained method invocation
<del> */
<del> public ResourceHandlerRegistration setCachePeriod(Integer cachePeriod) {
<del> this.cachePeriod = cachePeriod;
<del> return this;
<add> public ResourceChainRegistration resourceChain(boolean cacheResources, Cache cache) {
<add> this.resourceChainRegistration = new ResourceChainRegistration(cacheResources, cache);
<add> return this.resourceChainRegistration;
<ide> }
<ide>
<ide> /**
<ide> protected String[] getPathPatterns() {
<ide> return this.pathPatterns;
<ide> }
<ide>
<del> protected List<ResourceResolver> getResourceResolvers() {
<del> if (this.customResolvers.isEmpty()) {
<del> return null;
<del> }
<del> List<ResourceResolver> resolvers = new ArrayList<ResourceResolver>();
<del> ResourceResolver first = this.customResolvers.get(0);
<del> if (!ClassUtils.isAssignable(CachingResourceResolver.class, first.getClass()) && !this.isDevMode) {
<del> resolvers.add(new CachingResourceResolver(getDefaultResourceCache()));
<del> }
<del> resolvers.addAll(this.customResolvers);
<del> ResourceResolver last = this.customResolvers.get(this.customResolvers.size() - 1);
<del> if (!ClassUtils.isAssignable(PathResourceResolver.class, last.getClass())) {
<del> resolvers.add(new PathResourceResolver());
<del> }
<del> return resolvers;
<del> }
<del>
<del> protected List<ResourceTransformer> getResourceTransformers() {
<del> if (this.customTransformers.isEmpty()) {
<del> return null;
<del> }
<del> List<ResourceTransformer> transformers = new ArrayList<ResourceTransformer>();
<del> ResourceTransformer first = this.customTransformers.get(0);
<del> ResourceTransformer cachingTransformer = null;
<del> if (!this.isDevMode) {
<del> if (ClassUtils.isAssignable(CachingResourceTransformer.class, first.getClass())) {
<del> cachingTransformer = first;
<del> }
<del> else {
<del> cachingTransformer = new CachingResourceTransformer(getDefaultResourceCache());
<del> transformers.add(cachingTransformer);
<del> }
<del> }
<del> transformers.addAll(this.customTransformers);
<del> if (this.hasVersionResolver && !this.hasCssLinkTransformer) {
<del> transformers.add(cachingTransformer != null ? 1 : 0, new CssLinkResourceTransformer());
<del> }
<del> return transformers;
<del> }
<del>
<ide> /**
<ide> * Returns a {@link ResourceHttpRequestHandler} instance.
<ide> */
<ide> protected ResourceHttpRequestHandler getRequestHandler() {
<ide> Assert.isTrue(!CollectionUtils.isEmpty(locations), "At least one location is required for resource handling.");
<del> ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
<del> List<ResourceResolver> resourceResolvers = getResourceResolvers();
<del> if (!CollectionUtils.isEmpty(resourceResolvers)) {
<del> requestHandler.setResourceResolvers(resourceResolvers);
<add> ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
<add> if (this.resourceChainRegistration != null) {
<add> handler.setResourceResolvers(this.resourceChainRegistration.getResourceResolvers());
<add> handler.setResourceTransformers(this.resourceChainRegistration.getResourceTransformers());
<ide> }
<del> List<ResourceTransformer> resourceTransformers = getResourceTransformers();
<del> if (!CollectionUtils.isEmpty(resourceTransformers)) {
<del> requestHandler.setResourceTransformers(resourceTransformers);
<del> }
<del> requestHandler.setLocations(this.locations);
<add> handler.setLocations(this.locations);
<ide> if (this.cachePeriod != null) {
<del> requestHandler.setCacheSeconds(this.cachePeriod);
<del> }
<del> return requestHandler;
<del> }
<del>
<del> /**
<del> * Return a default instance of a {@code ConcurrentCacheMap} for
<del> * caching resolved/transformed resources.
<del> */
<del> private Cache getDefaultResourceCache() {
<del> if(this.resourceCache == null) {
<del> this.resourceCache = new ConcurrentMapCache(RESOURCE_CACHE_NAME);
<add> handler.setCacheSeconds(this.cachePeriod);
<ide> }
<del> return this.resourceCache;
<add> return handler;
<ide> }
<ide>
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java
<ide> package org.springframework.web.servlet.config.annotation;
<ide>
<ide> import java.util.List;
<del>import java.util.Map;
<ide>
<ide> import org.hamcrest.Matchers;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.mockito.Mockito;
<ide>
<del>import org.springframework.beans.DirectFieldAccessor;
<ide> import org.springframework.cache.concurrent.ConcurrentMapCache;
<ide> import org.springframework.mock.web.test.MockHttpServletRequest;
<ide> import org.springframework.mock.web.test.MockHttpServletResponse;
<ide> import org.springframework.web.servlet.resource.ResourceResolver;
<ide> import org.springframework.web.servlet.resource.ResourceTransformer;
<ide> import org.springframework.web.servlet.resource.VersionResourceResolver;
<del>import org.springframework.web.servlet.resource.VersionStrategy;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> public void hasMappingForPattern() {
<ide> }
<ide>
<ide> @Test
<del> public void simpleResourceChain() throws Exception {
<add> public void resourceChain() throws Exception {
<ide> ResourceResolver mockResolver = Mockito.mock(ResourceResolver.class);
<ide> ResourceTransformer mockTransformer = Mockito.mock(ResourceTransformer.class);
<del> this.registration.addResolver(mockResolver).addTransformer(mockTransformer);
<add> this.registration.resourceChain(true).addResolver(mockResolver).addTransformer(mockTransformer);
<ide>
<ide> ResourceHttpRequestHandler handler = getHandler("/resources/**");
<ide> List<ResourceResolver> resolvers = handler.getResourceResolvers();
<ide> public void simpleResourceChain() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void noCacheResourceChain() throws Exception {
<del> this.registration.enableDevMode();
<add> public void resourceChainWithoutCaching() throws Exception {
<add> this.registration.resourceChain(false);
<ide>
<ide> ResourceHttpRequestHandler handler = getHandler("/resources/**");
<ide> List<ResourceResolver> resolvers = handler.getResourceResolvers();
<ide> public void noCacheResourceChain() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void versionResourceChain() throws Exception {
<add> public void resourceChainWithVersionResolver() throws Exception {
<ide> VersionResourceResolver versionResolver = new VersionResourceResolver()
<ide> .addFixedVersionStrategy("fixed", "/**/*.js")
<ide> .addContentVersionStrategy("/**");
<ide>
<del> this.registration.addResolver(versionResolver).addTransformer(new AppCacheManifestTransfomer());
<add> this.registration.resourceChain(true).addResolver(versionResolver)
<add> .addTransformer(new AppCacheManifestTransfomer());
<ide>
<ide> ResourceHttpRequestHandler handler = getHandler("/resources/**");
<ide> List<ResourceResolver> resolvers = handler.getResourceResolvers();
<ide> assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3));
<ide> assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class));
<del> assertThat(resolvers.get(1), Matchers.instanceOf(VersionResourceResolver.class));
<del> DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(resolvers.get(1));
<del> @SuppressWarnings("unchecked")
<del> Map<String, VersionStrategy> strategies =
<del> (Map<String, VersionStrategy>) fieldAccessor.getPropertyValue("versionStrategyMap");
<del> assertNotNull(strategies.get("/**/*.js"));
<del> assertNotNull(strategies.get("/**"));
<add> assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver));
<ide> assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class));
<ide>
<ide> List<ResourceTransformer> transformers = handler.getResourceTransformers();
<ide> public void versionResourceChain() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void customResourceChain() throws Exception {
<del> VersionResourceResolver versionResolver = new VersionResourceResolver()
<del> .addFixedVersionStrategy("fixed", "/**/*.js")
<del> .addContentVersionStrategy("/**");
<del>
<add> public void resourceChainWithOverrides() throws Exception {
<ide> CachingResourceResolver cachingResolver = Mockito.mock(CachingResourceResolver.class);
<add> VersionResourceResolver versionResolver = Mockito.mock(VersionResourceResolver.class);
<add> PathResourceResolver pathResourceResolver = new PathResourceResolver();
<ide> CachingResourceTransformer cachingTransformer = Mockito.mock(CachingResourceTransformer.class);
<del> this.registration
<del> .addResolver(cachingResolver)
<del> .addResolver(versionResolver)
<del> .addResolver(new CustomPathResourceResolver())
<del> .addTransformer(cachingTransformer)
<del> .addTransformer(new AppCacheManifestTransfomer())
<del> .setCachePeriod(3600);
<add> AppCacheManifestTransfomer appCacheTransformer = Mockito.mock(AppCacheManifestTransfomer.class);
<add> CssLinkResourceTransformer cssLinkTransformer = new CssLinkResourceTransformer();
<add>
<add> this.registration.setCachePeriod(3600)
<add> .resourceChain(false)
<add> .addResolver(cachingResolver)
<add> .addResolver(versionResolver)
<add> .addResolver(pathResourceResolver)
<add> .addTransformer(cachingTransformer)
<add> .addTransformer(appCacheTransformer)
<add> .addTransformer(cssLinkTransformer);
<ide>
<ide> ResourceHttpRequestHandler handler = getHandler("/resources/**");
<ide> List<ResourceResolver> resolvers = handler.getResourceResolvers();
<ide> assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3));
<del> assertThat(resolvers.get(0), Matchers.equalTo(cachingResolver));
<del> assertThat(resolvers.get(1), Matchers.instanceOf(VersionResourceResolver.class));
<del> assertThat(resolvers.get(2), Matchers.instanceOf(CustomPathResourceResolver.class));
<add> assertThat(resolvers.get(0), Matchers.sameInstance(cachingResolver));
<add> assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver));
<add> assertThat(resolvers.get(2), Matchers.sameInstance(pathResourceResolver));
<ide>
<ide> List<ResourceTransformer> transformers = handler.getResourceTransformers();
<ide> assertThat(transformers, Matchers.hasSize(3));
<del> assertThat(transformers.get(0), Matchers.equalTo(cachingTransformer));
<del> assertThat(transformers.get(1), Matchers.instanceOf(CssLinkResourceTransformer.class));
<del> assertThat(transformers.get(2), Matchers.instanceOf(AppCacheManifestTransfomer.class));
<add> assertThat(transformers.get(0), Matchers.sameInstance(cachingTransformer));
<add> assertThat(transformers.get(1), Matchers.sameInstance(appCacheTransformer));
<add> assertThat(transformers.get(2), Matchers.sameInstance(cssLinkTransformer));
<ide> }
<ide>
<ide> private ResourceHttpRequestHandler getHandler(String pathPattern) {
<ide> SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) this.registry.getHandlerMapping();
<ide> return (ResourceHttpRequestHandler) handlerMapping.getUrlMap().get(pathPattern);
<ide> }
<ide>
<del>
<del> private static class CustomPathResourceResolver extends PathResourceResolver {
<del>
<del> }
<del>
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderJavaConfigTests.java
<ide> static class WebConfig extends WebMvcConfigurationSupport {
<ide> public void addResourceHandlers(ResourceHandlerRegistry registry) {
<ide> registry.addResourceHandler("/resources/**")
<ide> .addResourceLocations("classpath:org/springframework/web/servlet/resource/test/")
<del> .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
<add> .resourceChain(true).addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
<ide> }
<ide> }
<ide> | 4 |
PHP | PHP | use line here | 8de2d9d6f71bec53c6bf67e944f7382b3bade1ce | <ide><path>src/Illuminate/Foundation/Console/FreshCommand.php
<ide> public function fire()
<ide> {
<ide> $this->files->delete($file);
<ide>
<del> $this->info('<info>Removed File:</info> '.$file);
<add> $this->line('<info>Removed File:</info> '.$file);
<ide> }
<ide>
<ide> foreach ($this->getDirectories() as $directory)
<ide> {
<ide> $this->files->deleteDirectory($directory);
<ide>
<del> $this->info('<comment>Removed Directory:</comment> '.$directory);
<add> $this->line('<comment>Removed Directory:</comment> '.$directory);
<ide> }
<ide>
<ide> $this->info('Scaffolding Removed!'); | 1 |
Text | Text | edit gs guide § say "hello", rails [ci-skip] | 3e182a2d4d37f8b521af39246b1057a64fe9b4ff | <ide><path>guides/source/getting_started.md
<ide> enough to serve a page.
<ide>
<ide> ### Say "Hello", Rails
<ide>
<del>To get Rails saying "Hello", you need to create at minimum a _route_, a _controller_ and a _view_.
<add>To get Rails saying "Hello", you need to create at minimum a *route*, a
<add>*controller* with an *action*, and a *view*. A route maps a request to a
<add>controller action. A controller action performs the necessary work to handle the
<add>request, and prepares any data for the view. A view displays data in a desired
<add>format.
<ide>
<del>A controller's purpose is to receive specific requests for the application.
<del>_Routing_ decides which controller receives which requests. Often, there is more
<del>than one route to each controller, and different routes can be served by
<del>different _actions_. Each action's purpose is to collect information to provide
<del>it to a view.
<add>In terms of implementation: Routes are rules written in a Ruby [DSL
<add>(Domain-Specific Language)](https://en.wikipedia.org/wiki/Domain-specific_language).
<add>Controllers are Ruby classes, and their public methods are actions. And views
<add>are templates, usually written in a mixture of HTML and Ruby.
<ide>
<del>A view's purpose is to display this information in a human readable format. An
<del>important distinction to make is that the _controller_, not the view,
<del>is where information is collected. The view should just display that information.
<del>By default, view templates are written in a language called eRuby (Embedded
<del>Ruby) which is processed by the request cycle in Rails before being sent to the
<del>user.
<del>
<del>When we make a request to our Rails application, we do so by making a request
<del>to a particular _route_. To start off, let's create a route in
<del>`config/routes.rb`:
<add>Let's start by adding a route to our routes file, `config/routes.rb`, at the
<add>top of the `Rails.application.routes.draw` block:
<ide>
<ide> ```ruby
<ide> Rails.application.routes.draw do
<ide> Rails.application.routes.draw do
<ide> end
<ide> ```
<ide>
<del>This is your application's _routing file_ which holds entries in a special [DSL
<del>(domain-specific
<del>language)](https://en.wikipedia.org/wiki/Domain-specific_language) that tells
<del>Rails how to connect incoming requests to controllers and actions.
<del>
<del>The line that we have just added says that we are going to match a `GET
<del>/articles` request to `articles#index`. This string passed as the `to` option
<del>represents the _controller_ and _action_ that will be responsible for handling
<del>this request.
<del>
<del>Controllers are classes that group together common methods for handling a
<del>particular _resource_. The methods inside controllers are given the name
<del>"actions", as they _act upon_ requests as they come in.
<add>The route above declares that `GET /articles` requests are mapped to the `index`
<add>action of `ArticlesController`.
<ide>
<del>To create a new controller, you will need to run the "controller" generator and
<del>tell it you want a controller called "articles" with an action called "index",
<del>just like this:
<add>To create `ArticlesController` and its `index` action, we'll run the controller
<add>generator (with the `--skip-routes` option because we already have an
<add>appropriate route):
<ide>
<ide> ```bash
<del>$ bin/rails generate controller articles index
<add>$ bin/rails generate controller Articles index --skip-routes
<ide> ```
<ide>
<del>Rails will create several files and a route for you.
<add>Rails will create several files for you:
<ide>
<ide> ```
<ide> create app/controllers/articles_controller.rb
<del> route get 'articles/index'
<ide> invoke erb
<ide> create app/views/articles
<ide> create app/views/articles/index.html.erb
<ide> invoke scss
<ide> create app/assets/stylesheets/articles.scss
<ide> ```
<ide>
<del>Most important of these is the controller, located at
<del>`app/controllers/articles_controller.rb`.
<del>
<del>Let's look at that controller now:
<add>The most important of these is the controller file,
<add>`app/controllers/articles_controller.rb`. Let's take a look at it:
<ide>
<ide> ```ruby
<ide> class ArticlesController < ApplicationController
<ide> class ArticlesController < ApplicationController
<ide> end
<ide> ```
<ide>
<del>This controller defines a single action, or "method" in common Ruby terms,
<del>called `index`. This action is where we would define any logic that we would
<del>want to happen when a request comes in to this action. Right at this moment, we
<del>don't want this action to do anything, and so we'll keep it blank for now.
<del>
<del>When an action is left blank like this, Rails will default to rendering a view
<del>that matches the name of the controller and the name of the action. Views in a
<del>Rails application live in `app/views`, and so the default view for this action
<del>is going to be `app/views/articles/index.html.erb`.
<add>The `index` action is empty. When an action does not explicitly render a view
<add>(or otherwise trigger an HTTP response), Rails will automatically render a view
<add>that matches the name of the controller and action. Convention Over
<add>Configuration! Views are located in the `app/views` directory. So the `index`
<add>action will render `app/views/articles/index.html.erb` by default.
<ide>
<del>Open the `app/views/articles/index.html.erb` file in your text editor. Delete all
<del>of the existing code in the file, and replace it with the following single line
<del>of code:
<add>Let's open `app/views/articles/index.html.erb`, and replace its contents with:
<ide>
<ide> ```html
<ide> <h1>Hello, Rails!</h1>
<ide> ```
<ide>
<del>If we go back to our browser and make a request to
<del><http://localhost:3000/articles>, we'll see our text appear on the page.
<add>If you previously stopped the web server to run the controller generator,
<add>restart it with `bin/rails server`. Now visit <http://localhost:3000/articles>,
<add>and see our text displayed!
<ide>
<ide> ### Setting the Application Home Page
<ide> | 1 |
Text | Text | improve doc for http.serverresponse inheritance | e61b62b9d4a7a648496cc5d1539e1111bd2737e9 | <ide><path>doc/api/http.md
<ide> affects new connections to the server, not any existing connections.
<ide> added: v0.1.17
<ide> -->
<ide>
<del>* Extends: {Stream}
<add>* Extends: {http.OutgoingMessage}
<ide>
<ide> This object is created internally by an HTTP server, not by the user. It is
<ide> passed as the second parameter to the [`'request'`][] event. | 1 |
Ruby | Ruby | reduce code duplication in tests | 13e0188187056c5f0523fdd13a5c26a085f8c61d | <ide><path>Library/Homebrew/test/dev-cmd/bottle_spec.rb
<ide> def stub_hash(parameters)
<ide> end
<ide>
<ide> describe "brew bottle --merge", :integration_test, :needs_linux do
<add> let(:core_tap) { CoreTap.new }
<ide> let(:tarball) do
<ide> if OS.linux?
<ide> TEST_FIXTURE_DIR/"tarballs/testball-0.1-linux.tbz"
<ide> def stub_hash(parameters)
<ide> end
<ide> end
<ide>
<add> before do
<add> Pathname("testball-1.0.big_sur.bottle.json").write stub_hash(
<add> "name": "testball",
<add> "version": "1.0",
<add> "path": "#{core_tap.path}/Formula/testball.rb",
<add> "cellar": "any_skip_relocation",
<add> "os": "big_sur",
<add> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<add> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<add> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<add> )
<add>
<add> Pathname("testball-1.0.catalina.bottle.json").write stub_hash(
<add> "name": "testball",
<add> "version": "1.0",
<add> "path": "#{core_tap.path}/Formula/testball.rb",
<add> "cellar": "any_skip_relocation",
<add> "os": "catalina",
<add> "filename": "testball-1.0.catalina.bottle.tar.gz",
<add> "local_filename": "testball--1.0.catalina.bottle.tar.gz",
<add> "sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<add> )
<add> end
<add>
<add> after do
<add> FileUtils.rm_f "testball-1.0.catalina.bottle.json"
<add> FileUtils.rm_f "testball-1.0.big_sur.bottle.json"
<add> end
<add>
<ide> it "adds the bottle block to a formula that has none" do
<del> core_tap = CoreTap.new
<ide> core_tap.path.cd do
<ide> system "git", "init"
<ide> setup_test_formula "testball"
<ide> system "git", "add", "--all"
<ide> system "git", "commit", "-m", "testball 0.1"
<ide> end
<ide>
<del> begin
<del> Pathname("testball-1.0.big_sur.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "big_sur",
<del> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<del> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<del> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<del> },
<del> ),
<del> )
<del>
<del> Pathname("testball-1.0.catalina.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "catalina",
<del> "filename": "testball-1.0.catalina.bottle.tar.gz",
<del> "local_filename": "testball--1.0.catalina.bottle.tar.gz",
<del> "sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<del> },
<del> ),
<del> )
<del>
<del> expect {
<del> brew "bottle",
<del> "--merge",
<del> "--write",
<del> "testball-1.0.big_sur.bottle.json",
<del> "testball-1.0.catalina.bottle.json"
<del> }.to output(
<del> <<~EOS,
<del> ==> testball
<del> bottle do
<del> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
<del> cellar :any_skip_relocation
<del> sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
<del> sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
<del> end
<del> EOS
<del> ).to_stdout
<del> ensure
<del> FileUtils.rm_f "testball-1.0.catalina.bottle.json"
<del> FileUtils.rm_f "testball-1.0.big_sur.bottle.json"
<del> end
<add> expect {
<add> brew "bottle",
<add> "--merge",
<add> "--write",
<add> "testball-1.0.big_sur.bottle.json",
<add> "testball-1.0.catalina.bottle.json"
<add> }.to output(
<add> <<~EOS,
<add> ==> testball
<add> bottle do
<add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
<add> cellar :any_skip_relocation
<add> sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
<add> sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
<add> end
<add> EOS
<add> ).to_stdout
<ide>
<ide> expect((core_tap.path/"Formula/testball.rb").read).to eq(
<ide> <<~EOS,
<ide> def install
<ide> end
<ide>
<ide> it "replaces the bottle block in a formula that already has a bottle block" do
<del> core_tap = CoreTap.new
<ide> core_tap.path.cd do
<ide> system "git", "init"
<ide> bottle_block = <<~EOS
<ide> def install
<ide> system "git", "commit", "-m", "testball 0.1"
<ide> end
<ide>
<del> begin
<del> Pathname("testball-1.0.big_sur.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "big_sur",
<del> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<del> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<del> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<del> },
<del> ),
<del> )
<del>
<del> Pathname("testball-1.0.catalina.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "catalina",
<del> "filename": "testball-1.0.catalina.bottle.tar.gz",
<del> "local_filename": "testball--1.0.catalina.bottle.tar.gz",
<del> "sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<del> },
<del> ),
<del> )
<del>
<del> expect {
<del> brew "bottle",
<del> "--merge",
<del> "--write",
<del> "testball-1.0.big_sur.bottle.json",
<del> "testball-1.0.catalina.bottle.json"
<del> }.to output(
<del> <<~EOS,
<del> ==> testball
<del> bottle do
<del> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
<del> cellar :any_skip_relocation
<del> sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
<del> sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
<del> end
<del> EOS
<del> ).to_stdout
<del> ensure
<del> FileUtils.rm_f "testball-1.0.catalina.bottle.json"
<del> FileUtils.rm_f "testball-1.0.big_sur.bottle.json"
<del> end
<add> expect {
<add> brew "bottle",
<add> "--merge",
<add> "--write",
<add> "testball-1.0.big_sur.bottle.json",
<add> "testball-1.0.catalina.bottle.json"
<add> }.to output(
<add> <<~EOS,
<add> ==> testball
<add> bottle do
<add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
<add> cellar :any_skip_relocation
<add> sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
<add> sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
<add> end
<add> EOS
<add> ).to_stdout
<ide>
<ide> expect((core_tap.path/"Formula/testball.rb").read).to eq(
<ide> <<~EOS,
<ide> def install
<ide> end
<ide>
<ide> it "fails to add the bottle block to a formula that has no bottle block when using --keep-old" do
<del> core_tap = CoreTap.new
<ide> core_tap.path.cd do
<ide> system "git", "init"
<ide> setup_test_formula("testball")
<ide> system "git", "add", "--all"
<ide> system "git", "commit", "-m", "testball 0.1"
<ide> end
<ide>
<del> begin
<del> Pathname("testball-1.0.big_sur.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "big_sur",
<del> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<del> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<del> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<del> },
<del> ),
<del> )
<del>
<del> Pathname("testball-1.0.catalina.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "catalina",
<del> "filename": "testball-1.0.catalina.bottle.tar.gz",
<del> "local_filename": "testball--1.0.catalina.bottle.tar.gz",
<del> "sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<del> },
<del> ),
<del> )
<del>
<del> expect {
<del> brew "bottle",
<del> "--merge",
<del> "--write",
<del> "--keep-old",
<del> "testball-1.0.big_sur.bottle.json",
<del> "testball-1.0.catalina.bottle.json"
<del> }.to output("Error: --keep-old was passed but there was no existing bottle block!\n").to_stderr
<del> ensure
<del> FileUtils.rm_f "testball-1.0.catalina.bottle.json"
<del> FileUtils.rm_f "testball-1.0.big_sur.bottle.json"
<del> end
<add> expect {
<add> brew "bottle",
<add> "--merge",
<add> "--write",
<add> "--keep-old",
<add> "testball-1.0.big_sur.bottle.json",
<add> "testball-1.0.catalina.bottle.json"
<add> }.to output("Error: --keep-old was passed but there was no existing bottle block!\n").to_stderr
<ide> end
<ide>
<ide> it "updates the bottle block in a formula that already has a bottle block when using --keep-old" do
<del> core_tap = CoreTap.new
<ide> core_tap.path.cd do
<ide> system "git", "init"
<ide> bottle_block = <<~EOS
<ide> def install
<ide> system "git", "commit", "-m", "testball 0.1"
<ide> end
<ide>
<del> begin
<del> Pathname("testball-1.0.big_sur.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "big_sur",
<del> "filename": "hello-1.0.big_sur.bottle.tar.gz",
<del> "local_filename": "hello--1.0.big_sur.bottle.tar.gz",
<del> "sha256": "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f",
<del> },
<del> ),
<del> )
<del>
<del> Pathname("testball-1.0.catalina.bottle.json").write(
<del> stub_hash(
<del> {
<del> "name": "testball",
<del> "version": "1.0",
<del> "path": "#{core_tap.path}/Formula/testball.rb",
<del> "cellar": "any_skip_relocation",
<del> "os": "catalina",
<del> "filename": "testball-1.0.catalina.bottle.tar.gz",
<del> "local_filename": "testball--1.0.catalina.bottle.tar.gz",
<del> "sha256": "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac",
<del> },
<del> ),
<del> )
<del>
<del> expect {
<del> brew "bottle",
<del> "--merge",
<del> "--write",
<del> "--keep-old",
<del> "testball-1.0.big_sur.bottle.json",
<del> "testball-1.0.catalina.bottle.json"
<del> }.to output(
<del> <<~EOS,
<del> ==> testball
<del> bottle do
<del> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
<del> cellar :any_skip_relocation
<del> sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
<del> sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
<del> sha256 "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" => :high_sierra
<del> end
<del> EOS
<del> ).to_stdout
<del> ensure
<del> FileUtils.rm_f "testball-1.0.catalina.bottle.json"
<del> FileUtils.rm_f "testball-1.0.big_sur.bottle.json"
<del> end
<add> expect {
<add> brew "bottle",
<add> "--merge",
<add> "--write",
<add> "--keep-old",
<add> "testball-1.0.big_sur.bottle.json",
<add> "testball-1.0.catalina.bottle.json"
<add> }.to output(
<add> <<~EOS,
<add> ==> testball
<add> bottle do
<add> root_url "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}"
<add> cellar :any_skip_relocation
<add> sha256 "a0af7dcbb5c83f6f3f7ecd507c2d352c1a018f894d51ad241ce8492fa598010f" => :big_sur
<add> sha256 "5334dd344986e46b2aa4f0471cac7b0914bd7de7cb890a34415771788d03f2ac" => :catalina
<add> sha256 "6971b6eebf4c00eaaed72a1104a49be63861eabc95d679a0c84040398e320059" => :high_sierra
<add> end
<add> EOS
<add> ).to_stdout
<ide>
<ide> expect((core_tap.path/"Formula/testball.rb").read).to eq(
<ide> <<~EOS, | 1 |
Ruby | Ruby | throw error exception when formula not found | 8db11ea2d9d948c2434d4a3fa75887e8e274af91 | <ide><path>Library/Homebrew/dev-cmd/bump.rb
<ide> def bump
<ide> requested_formula&.downcase!
<ide>
<ide> if requested_formula && !get_formula_details(requested_formula)
<del> ohai "Requested formula #{requested_formula} is not valid Homebrew formula."
<add> raise FormulaUnavailableError, requested_formula
<ide> return
<ide> end
<ide> | 1 |
Javascript | Javascript | add synchronous retries to rimraf | 26991d0831e356c9ab86fa6cd0823afeaa0ec950 | <ide><path>lib/internal/fs/rimraf.js
<ide> const {
<ide> } = require('fs');
<ide> const { join } = require('path');
<ide> const { setTimeout } = require('timers');
<add>const { sleep } = require('internal/util');
<ide> const notEmptyErrorCodes = new Set(['ENOTEMPTY', 'EEXIST', 'EPERM']);
<ide> const retryErrorCodes = new Set(
<ide> ['EBUSY', 'EMFILE', 'ENFILE', 'ENOTEMPTY', 'EPERM']);
<ide> function _rmdirSync(path, options, originalErr) {
<ide> rimrafSync(join(path, child), options);
<ide> });
<ide>
<del> for (let i = 0; i < options.maxRetries + 1; i++) {
<add> for (let i = 1; i <= options.maxRetries + 1; i++) {
<ide> try {
<ide> return rmdirSync(path, options);
<del> } catch {} // Ignore errors.
<add> } catch {
<add> if (options.retryDelay > 0)
<add> sleep(i * options.retryDelay);
<add> }
<ide> }
<ide> }
<ide> } | 1 |
Python | Python | fix typo in hermite_e.py | 2243feef3ca8fb8c511b71b26d6bf6114e44c069 | <ide><path>numpy/polynomial/hermite_e.py
<ide> from ._polybase import ABCPolyBase
<ide>
<ide> __all__ = ['hermezero', 'hermeone', 'hermex', 'hermedomain', 'hermeline',
<del> 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv', 'hermpow',
<add> 'hermeadd', 'hermesub', 'hermemulx', 'hermemul', 'hermediv', 'hermepow',
<ide> 'hermeval',
<ide> 'hermeder', 'hermeint', 'herme2poly', 'poly2herme', 'hermefromroots',
<ide> 'hermevander', 'hermefit', 'hermetrim', 'hermeroots', 'HermiteE', | 1 |
Javascript | Javascript | add perf optimizations to injector | b70739a0f18f3b4d197cf20a75e8a1f5f42bbd17 | <ide><path>src/Injector.js
<ide> import { Component, PropTypes } from 'react';
<ide> import mapValues from 'lodash/object/mapValues';
<add>import shallowEqual from './utils/shallowEqual';
<ide>
<ide> export default class Injector extends Component {
<ide> static contextTypes = {
<ide> export default class Injector extends Component {
<ide> actions: {}
<ide> };
<ide>
<add> shouldComponentUpdate(nextProps, nextState) {
<add> return this.hasChanged(this.state.atom, nextState.atom) ||
<add> !shallowEqual(this.props.actions, nextProps.actions);
<add> }
<add>
<add> hasChanged(atom, prevAtom) {
<add> return atom !== prevAtom;
<add> }
<add>
<ide> constructor(props, context) {
<ide> super(props, context);
<ide>
<ide><path>src/addons/inject.js
<ide> import React from 'react';
<ide> import Injector from '../Injector';
<ide> import getDisplayName from '../utils/getDisplayName';
<add>import shallowEqualScalar from '../utils/shallowEqualScalar';
<ide>
<ide> function mergeAll({ props, state, actions }) {
<ide> return { ...props, ...state, ...actions };
<ide> export default function inject(
<ide> return DecoratedComponent => class InjectorDecorator {
<ide> static displayName = `Injector(${getDisplayName(DecoratedComponent)})`;
<ide>
<add> shouldComponentUpdate(nextProps) {
<add> return !shallowEqualScalar(this.props, nextProps);
<add> }
<add>
<ide> constructor() {
<ide> this.renderChild = this.renderChild.bind(this);
<ide> } | 2 |
Ruby | Ruby | fix symlink creation | 5fc4cabdeb37d47b59bddfa41f28dc3ff92d17ad | <ide><path>Library/Homebrew/dev-cmd/tap-new.rb
<ide> def tap_new
<ide> - git -C "$HOMEBREW_REPOSITORY" reset --hard origin/master
<ide> - brew update || brew update
<ide> - HOMEBREW_TAP_DIR="$(brew --repo "$TRAVIS_REPO_SLUG")"
<add> - mkdir -p "$HOMEBREW_TAP_DIR"
<ide> - rm -rf "$HOMEBREW_TAP_DIR"
<ide> - ln -s "$PWD" "$HOMEBREW_TAP_DIR"
<ide> - export HOMEBREW_DEVELOPER="1" | 1 |
Javascript | Javascript | fix react tests | 70a0746e9f9877c69edc6a2ef7716c928b71841b | <ide><path>src/core/__tests__/ReactRenderDocument-test.js
<ide> describe('rendering React components at document', function() {
<ide> });
<ide>
<ide> React.renderComponentToString(<Root />, function(markup) {
<del> testDocument.innerHTML = markup;
<add> testDocument = getTestDocument(markup);
<ide> var component = React.renderComponent(<Root />, testDocument);
<ide> expect(testDocument.body.innerHTML).toBe(' Hello world ');
<ide>
<ide> describe('rendering React components at document', function() {
<ide> });
<ide>
<ide> React.renderComponentToString(<Root />, function(markup) {
<del> testDocument.innerHTML = markup;
<add> testDocument = getTestDocument(markup);
<ide> React.renderComponent(<Root />, testDocument);
<ide> expect(testDocument.body.innerHTML).toBe(' Hello world ');
<ide>
<ide> describe('rendering React components at document', function() {
<ide> });
<ide>
<ide> React.renderComponentToString(<Component />, function(markup) {
<del> testDocument.innerHTML = markup;
<add> testDocument = getTestDocument(markup);
<ide>
<ide> React.renderComponent(<Component />, testDocument);
<ide>
<ide> describe('rendering React components at document', function() {
<ide> React.renderComponentToString(
<ide> <Component text="Hello world" />,
<ide> function(markup) {
<del> testDocument.innerHTML = markup;
<add> testDocument = getTestDocument(markup);
<ide>
<ide> React.renderComponent(<Component text="Hello world" />, testDocument);
<ide>
<ide> describe('rendering React components at document', function() {
<ide> React.renderComponentToString(
<ide> <Component text="Goodbye world" />,
<ide> function(markup) {
<del> testDocument.innerHTML = markup;
<add> testDocument = getTestDocument(markup);
<ide>
<ide> expect(function() {
<ide> // Notice the text is different!
<ide><path>src/test/getTestDocument.js
<ide> * @providesModule getTestDocument
<ide> */
<ide>
<del>function getTestDocument() {
<add>function getTestDocument(markup) {
<ide> var iframe = document.createElement('iframe');
<ide> iframe.style.display = 'none';
<ide> document.body.appendChild(iframe);
<ide>
<ide> var testDocument = iframe.contentDocument || iframe.contentWindow.document;
<ide> testDocument.open();
<del> testDocument.write('<!doctype html><html><meta charset=utf-8><title>test doc</title>');
<add> testDocument.write(
<add> markup || '<!doctype html><html><meta charset=utf-8><title>test doc</title>'
<add> );
<ide> testDocument.close();
<ide>
<ide> iframe.parentNode.removeChild(iframe); | 2 |
PHP | PHP | remove detector for flash | 20ca5a033c2d3992696d42b649945ab5da18ce97 | <ide><path>src/Http/ServerRequest.php
<ide> class ServerRequest implements ServerRequestInterface
<ide> 'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
<ide> 'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
<ide> 'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
<del> 'flash' => ['env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'],
<ide> 'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
<ide> 'xml' => ['accept' => ['application/xml', 'text/xml'], 'param' => '_ext', 'value' => 'xml'],
<ide> ];
<ide><path>tests/TestCase/Http/ServerRequestTest.php
<ide> public function testSubdomain()
<ide> *
<ide> * @return void
<ide> */
<del> public function testisAjaxFlashAndFriends()
<add> public function testisAjax()
<ide> {
<ide> $request = new ServerRequest();
<ide>
<del> $request = $request->withEnv('HTTP_USER_AGENT', 'Shockwave Flash');
<del> $this->assertTrue($request->is('flash'));
<del>
<del> $request = $request->withEnv('HTTP_USER_AGENT', 'Adobe Flash');
<del> $this->assertTrue($request->is('flash'));
<del>
<ide> $request = $request->withEnv('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
<ide> $this->assertTrue($request->is('ajax'));
<ide> | 2 |
Go | Go | move "images" to graph/list.go | 51dd68d65949b4b542d65e4de2f1b18550c9cff1 | <ide><path>graph/list.go
<add>package graph
<add>
<add>import (
<add> "fmt"
<add> "log"
<add> "path"
<add> "strings"
<add>
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/pkg/parsers/filters"
<add>)
<add>
<add>func (s *TagStore) CmdImages(job *engine.Job) engine.Status {
<add> var (
<add> allImages map[string]*image.Image
<add> err error
<add> filt_tagged = true
<add> )
<add>
<add> imageFilters, err := filters.FromParam(job.Getenv("filters"))
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> if i, ok := imageFilters["dangling"]; ok {
<add> for _, value := range i {
<add> if strings.ToLower(value) == "true" {
<add> filt_tagged = false
<add> }
<add> }
<add> }
<add>
<add> if job.GetenvBool("all") && filt_tagged {
<add> allImages, err = s.graph.Map()
<add> } else {
<add> allImages, err = s.graph.Heads()
<add> }
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> lookup := make(map[string]*engine.Env)
<add> s.Lock()
<add> for name, repository := range s.Repositories {
<add> if job.Getenv("filter") != "" {
<add> if match, _ := path.Match(job.Getenv("filter"), name); !match {
<add> continue
<add> }
<add> }
<add> for tag, id := range repository {
<add> image, err := s.graph.Get(id)
<add> if err != nil {
<add> log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
<add> continue
<add> }
<add>
<add> if out, exists := lookup[id]; exists {
<add> if filt_tagged {
<add> out.SetList("RepoTags", append(out.GetList("RepoTags"), fmt.Sprintf("%s:%s", name, tag)))
<add> }
<add> } else {
<add> // get the boolean list for if only the untagged images are requested
<add> delete(allImages, id)
<add> if filt_tagged {
<add> out := &engine.Env{}
<add> out.Set("ParentId", image.Parent)
<add> out.SetList("RepoTags", []string{fmt.Sprintf("%s:%s", name, tag)})
<add> out.Set("Id", image.ID)
<add> out.SetInt64("Created", image.Created.Unix())
<add> out.SetInt64("Size", image.Size)
<add> out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
<add> lookup[id] = out
<add> }
<add> }
<add>
<add> }
<add> }
<add> s.Unlock()
<add>
<add> outs := engine.NewTable("Created", len(lookup))
<add> for _, value := range lookup {
<add> outs.Add(value)
<add> }
<add>
<add> // Display images which aren't part of a repository/tag
<add> if job.Getenv("filter") == "" {
<add> for _, image := range allImages {
<add> out := &engine.Env{}
<add> out.Set("ParentId", image.Parent)
<add> out.SetList("RepoTags", []string{"<none>:<none>"})
<add> out.Set("Id", image.ID)
<add> out.SetInt64("Created", image.Created.Unix())
<add> out.SetInt64("Size", image.Size)
<add> out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
<add> outs.Add(out)
<add> }
<add> }
<add>
<add> outs.ReverseSort()
<add> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<add> return job.Error(err)
<add> }
<add> return engine.StatusOK
<add>}
<ide><path>graph/service.go
<ide> func (s *TagStore) Install(eng *engine.Engine) error {
<ide> eng.Register("image_tarlayer", s.CmdTarLayer)
<ide> eng.Register("image_export", s.CmdImageExport)
<ide> eng.Register("history", s.CmdHistory)
<add> eng.Register("images", s.CmdImages)
<ide> return nil
<ide> }
<ide>
<ide><path>server/image.go
<ide> import (
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<del> "log"
<ide> "net"
<ide> "net/http"
<ide> "net/url"
<ide> import (
<ide> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/parsers/filters"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide> func (srv *Server) ImagesViz(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del>func (srv *Server) Images(job *engine.Job) engine.Status {
<del> var (
<del> allImages map[string]*image.Image
<del> err error
<del> filt_tagged = true
<del> )
<del>
<del> imageFilters, err := filters.FromParam(job.Getenv("filters"))
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> if i, ok := imageFilters["dangling"]; ok {
<del> for _, value := range i {
<del> if strings.ToLower(value) == "true" {
<del> filt_tagged = false
<del> }
<del> }
<del> }
<del>
<del> if job.GetenvBool("all") && filt_tagged {
<del> allImages, err = srv.daemon.Graph().Map()
<del> } else {
<del> allImages, err = srv.daemon.Graph().Heads()
<del> }
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> lookup := make(map[string]*engine.Env)
<del> srv.daemon.Repositories().Lock()
<del> for name, repository := range srv.daemon.Repositories().Repositories {
<del> if job.Getenv("filter") != "" {
<del> if match, _ := path.Match(job.Getenv("filter"), name); !match {
<del> continue
<del> }
<del> }
<del> for tag, id := range repository {
<del> image, err := srv.daemon.Graph().Get(id)
<del> if err != nil {
<del> log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
<del> continue
<del> }
<del>
<del> if out, exists := lookup[id]; exists {
<del> if filt_tagged {
<del> out.SetList("RepoTags", append(out.GetList("RepoTags"), fmt.Sprintf("%s:%s", name, tag)))
<del> }
<del> } else {
<del> // get the boolean list for if only the untagged images are requested
<del> delete(allImages, id)
<del> if filt_tagged {
<del> out := &engine.Env{}
<del> out.Set("ParentId", image.Parent)
<del> out.SetList("RepoTags", []string{fmt.Sprintf("%s:%s", name, tag)})
<del> out.Set("Id", image.ID)
<del> out.SetInt64("Created", image.Created.Unix())
<del> out.SetInt64("Size", image.Size)
<del> out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
<del> lookup[id] = out
<del> }
<del> }
<del>
<del> }
<del> }
<del> srv.daemon.Repositories().Unlock()
<del>
<del> outs := engine.NewTable("Created", len(lookup))
<del> for _, value := range lookup {
<del> outs.Add(value)
<del> }
<del>
<del> // Display images which aren't part of a repository/tag
<del> if job.Getenv("filter") == "" {
<del> for _, image := range allImages {
<del> out := &engine.Env{}
<del> out.Set("ParentId", image.Parent)
<del> out.SetList("RepoTags", []string{"<none>:<none>"})
<del> out.Set("Id", image.ID)
<del> out.SetInt64("Created", image.Created.Unix())
<del> out.SetInt64("Size", image.Size)
<del> out.SetInt64("VirtualSize", image.GetParentsSize(0)+image.Size)
<del> outs.Add(out)
<del> }
<del> }
<del>
<del> outs.ReverseSort()
<del> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<del> return job.Error(err)
<del> }
<del> return engine.StatusOK
<del>}
<del>
<ide> func (srv *Server) ImageTag(job *engine.Job) engine.Status {
<ide> if len(job.Args) != 2 && len(job.Args) != 3 {
<ide> return job.Errorf("Usage: %s IMAGE REPOSITORY [TAG]\n", job.Name)
<ide><path>server/init.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> for name, handler := range map[string]engine.Handler{
<ide> "tag": srv.ImageTag, // FIXME merge with "image_tag"
<ide> "info": srv.DockerInfo,
<del> "images": srv.Images,
<ide> "viz": srv.ImagesViz,
<ide> "log": srv.Log,
<ide> "load": srv.ImageLoad, | 4 |
PHP | PHP | add backwards compatibility shim for attributes | 9072f113e901322869bc9c3c0e3a0da28cc1f248 | <ide><path>src/Http/Uri.php
<ide> */
<ide> namespace Cake\Http;
<ide>
<add>use Error;
<ide> use Psr\Http\Message\UriInterface;
<ide>
<ide> /**
<ide> public function __construct(UriInterface $uri, string $base, string $webroot)
<ide> $this->webroot = $webroot;
<ide> }
<ide>
<add> /**
<add> * Backwards compatibility shim for previously dynamic properties.
<add> *
<add> * @param string $name The attribute to read.
<add> * @return mixed
<add> */
<add> public function __get(string $name): mixed
<add> {
<add> if ($name === 'base' || $name === 'webroot') {
<add> return $this->{$name};
<add> }
<add>
<add> throw new Error("Cannot access attribute `{$name}`");
<add> }
<add>
<ide> /**
<ide> * Get the decorated URI
<ide> *
<ide><path>tests/TestCase/Http/UriTest.php
<ide>
<ide> use Cake\Http\Uri;
<ide> use Cake\TestSuite\TestCase;
<add>use Error;
<ide> use Laminas\Diactoros\Uri as LaminasUri;
<ide>
<ide> /**
<ide> public function testExtraMethods()
<ide> $this->assertSame('/base/', $uri->getWebroot());
<ide> }
<ide>
<add> public function testMagicAttributes()
<add> {
<add> $inner = new LaminasUri('/articles/view/1');
<add> $uri = new Uri($inner, '/base', '/base/');
<add>
<add> $this->assertSame('/base', $uri->base);
<add> $this->assertSame('/base/', $uri->webroot);
<add>
<add> $this->expectException(Error::class);
<add> $uri->uri;
<add> }
<add>
<ide> public function testWrappedGetMethods()
<ide> {
<ide> $inner = (new LaminasUri('/articles/view/1')) | 2 |
Javascript | Javascript | fix issue with inputs getting re-rendered | 4e585da9dc2882e6babd11499acad6e450805eb9 | <ide><path>packages/ember-htmlbars/lib/keywords/input.js
<ide> import Ember from "ember-metal/core";
<add>import { assign } from "ember-metal/merge";
<ide>
<ide> export default {
<ide> setupState(lastState, env, scope, params, hash) {
<ide> export default {
<ide> Ember.assert("{{input type='checkbox'}} does not support setting `value=someBooleanValue`;" +
<ide> " you must use `checked=someBooleanValue` instead.", !(type === 'checkbox' && hash.hasOwnProperty('value')));
<ide>
<del> return { componentName };
<add> return assign({}, lastState, { componentName });
<ide> },
<ide>
<ide> render(morph, env, scope, params, hash, template, inverse, visitor) {
<ide><path>packages/ember-htmlbars/tests/helpers/input_test.js
<ide> QUnit.test("should become disabled if the disabled attribute is true", function(
<ide>
<ide> QUnit.test("input value is updated when setting value property of view", function() {
<ide> equal(view.$('input').val(), "hello", "renders text field with value");
<add>
<add> let id = view.$('input').prop('id');
<add>
<ide> run(null, set, controller, 'val', 'bye!');
<ide> equal(view.$('input').val(), "bye!", "updates text field after value changes");
<add>
<add> equal(view.$('input').prop('id'), id, "the component hasn't changed");
<ide> });
<ide>
<ide> QUnit.test("input placeholder is updated when setting placeholder property of view", function() {
<ide><path>packages/ember-metal/lib/merge.js
<ide> export default function merge(original, updates) {
<ide>
<ide> return original;
<ide> }
<add>
<add>export function assign(original, ...args) {
<add> for (let i=0, l=args.length; i<l; i++) {
<add> let arg = args[i];
<add> if (!arg) { continue; }
<add>
<add> for (let prop in arg) {
<add> if (arg.hasOwnProperty(prop)) { original[prop] = arg[prop]; }
<add> }
<add> }
<add>
<add> return original;
<add>} | 3 |
Text | Text | fix typos in multiple-entry-points example readme | bfcd2694340fc3dae5acf77ebd962e4c97fdf453 | <ide><path>examples/multiple-entry-points/README.md
<del>This example show how to use multiple entry points with a commons chunk.
<add>This example shows how to use multiple entry points with a commons chunk.
<ide>
<del>In this example you have two (HTML) pages `pageA` and `pageB`. You want to create individual bundles for each page. In addition to this you want to create a shared bundle that contains all modules that used in both pages (assuming there are many/big modules in common). The pages also use Code Splitting to load a less used part of the features on demand.
<add>In this example you have two (HTML) pages `pageA` and `pageB`. You want to create individual bundles for each page. In addition to this you want to create a shared bundle that contains all modules used in both pages (assuming there are many/big modules in common). The pages also use Code Splitting to load a less used part of the features on demand.
<ide>
<ide> You can see how to define multiple entry points via the `entry` option and the required changes (`[name]`) in the `output` option. You can also see how to use the CommonsChunkPlugin.
<ide>
<ide> You can see the output files:
<ide> * `pageA.bundle.js` contains: (`pageB.bundle.js` is similar)
<ide> * the entry point `pageA.js`
<ide> * it would contain any other module that is only used by `pageA`
<del>* `0.chunk.js` is an additional chunk which if used by both pages. It contains:
<add>* `0.chunk.js` is an additional chunk which is used by both pages. It contains:
<ide> * module `shared.js`
<ide>
<ide> You can also see the info that is printed to console. It shows among others:
<ide>
<ide> * the generated files
<ide> * the chunks with file, name and id
<ide> * see lines starting with `chunk`
<del>* the modules that are in this chunks
<add>* the modules that are in the chunks
<ide> * the reasons why the modules are included
<ide> * the reasons why a chunk is created
<ide> * see lines starting with `>`
<ide> module.exports = {
<ide> plugins: [
<ide> new CommonsChunkPlugin("commons.js")
<ide> ]
<del>}
<add>};
<ide> ```
<ide>
<ide> # pageA.html | 1 |
Python | Python | use original loaded keys to find mismatched keys | 2d91e3c30410e0e17e3247323e46c443586eb508 | <ide><path>src/transformers/modeling_utils.py
<ide> def _fix_key(key):
<ide> return key.replace("gamma", "weight")
<ide> return key
<ide>
<add> original_loaded_keys = loaded_keys
<ide> loaded_keys = [_fix_key(key) for key in loaded_keys]
<ide>
<ide> if len(prefix) > 0:
<ide> def _find_mismatched_keys(
<ide> mismatched_keys = _find_mismatched_keys(
<ide> state_dict,
<ide> model_state_dict,
<del> loaded_keys,
<add> original_loaded_keys,
<ide> add_prefix_to_model,
<ide> remove_prefix_from_model,
<ide> ignore_mismatched_sizes,
<ide> def _find_mismatched_keys(
<ide> mismatched_keys += _find_mismatched_keys(
<ide> state_dict,
<ide> model_state_dict,
<del> loaded_keys,
<add> original_loaded_keys,
<ide> add_prefix_to_model,
<ide> remove_prefix_from_model,
<ide> ignore_mismatched_sizes, | 1 |
Javascript | Javascript | remove github oauth2 field - scope | e64a16ed6477215fd646f42870467e8853c24ed9 | <ide><path>server/passport-providers.js
<ide> export default {
<ide> failureRedirect: failureRedirect,
<ide> clientID: process.env.GITHUB_ID,
<ide> clientSecret: process.env.GITHUB_SECRET,
<del> scope: ['email'],
<ide> failureFlash: true
<ide> },
<ide> 'github-link': {
<ide> export default {
<ide> failureRedirect: linkFailureRedirect,
<ide> clientID: process.env.GITHUB_ID,
<ide> clientSecret: process.env.GITHUB_SECRET,
<del> scope: ['email'],
<ide> link: true,
<ide> failureFlash: true,
<ide> successFlash: [ 'We\'ve updated your profile based ', | 1 |
Text | Text | fix typo and add to description. | 06e46f188dcaef2b1968ed060f304c40fdc22557 | <ide><path>guide/english/javascript/template-literals/index.md
<ide> title: Template Literals
<ide> ---
<ide>
<del>Template Literals are an ES6 feature utilizing the backtick charater to define a string value
<add>Template Literals are an ES6 feature utilizing the backtick character to define a string value. They give the programmer the ability to combine variables and strings without concatenation, thus making the code cleaner.
<ide>
<ide> ### The basic syntax
<ide> | 1 |
Text | Text | add wasm examples to toc | 7b1253c705124bba71b6ca1c0de9c14fc498a021 | <ide><path>examples/README.md
<ide> 19. [Scope Hoisting](#scope-hoisting)
<ide> 20. [Side Effects](#side-effects)
<ide> 21. [Source Map](#source-map)
<del>22. [Web Worker](#web-worker)
<del>23. [Requests](#requests)
<del>24. [Building an Example](#building-an-example)
<add>22. [WebAssembly](#webassembly)
<add>23. [Web Worker](#web-worker)
<add>24. [Requests](#requests)
<add>25. [Building an Example](#building-an-example)
<ide>
<ide>
<ide> ## Aggressive Merging
<ide> ## Source Map
<ide> [source-map](source-map)
<ide>
<add>## WebAssembly
<add>[wasm-simple](wasm-simple) example demonstrating simple import from a WebAssembly module
<add>[wasm-complex](wasm-complex) example demonstrating top-level await and import of WebAssembly text format with wast-loader
<add>
<ide> ## Web Worker
<ide> [web-worker](worker) example demonstrating creating WebWorkers with webpack.
<ide> | 1 |
Python | Python | request info logs optimized away too soon | 03046f1b7f81cece5a6f744218da533bfedcea4e | <ide><path>celery/apps/worker.py
<ide> def run(self):
<ide> self.init_queues()
<ide> self.app.loader.init_worker()
<ide>
<del> # apply task execution optimizations
<del> trace.setup_worker_optimizations(self.app)
<del>
<ide> # this signal can be used to e.g. change queues after
<ide> # the -Q option has been applied.
<ide> signals.celeryd_after_setup.send(sender=self.hostname, instance=self,
<ide> def run(self):
<ide> self.set_process_status('-active-')
<ide>
<ide> self.setup_logging()
<add>
<add> # apply task execution optimizations
<add> trace.setup_worker_optimizations(self.app)
<add>
<ide> try:
<ide> self.run_worker()
<ide> except IGNORE_ERRORS:
<ide><path>celery/task/trace.py
<ide> def setup_worker_optimizations(app):
<ide>
<ide> trace_task_ret = _fast_trace_task
<ide> try:
<del> sys.modules['celery.worker.job'].trace_task_ret = _fast_trace_task
<add> job = sys.modules['celery.worker.job']
<ide> except KeyError:
<ide> pass
<add> else:
<add> job.trace_task_ret = _fast_trace_task
<add> job.__optimize__()
<ide>
<ide>
<ide> def reset_worker_optimizations():
<ide><path>celery/worker/job.py
<ide> logger = get_logger(__name__)
<ide> debug, info, warn, error = (logger.debug, logger.info,
<ide> logger.warn, logger.error)
<del>_does_debug = logger.isEnabledFor(logging.DEBUG)
<del>_does_info = logger.isEnabledFor(logging.INFO)
<add>_does_info = False
<add>_does_debug = False
<add>
<add>
<add>def __optimize__():
<add> global _does_debug
<add> global _does_info
<add> _does_debug = logger.isEnabledFor(logging.DEBUG)
<add> _does_info = logger.isEnabledFor(logging.INFO)
<add>__optimize__()
<ide>
<ide> # Localize
<ide> tz_utc = timezone.utc | 3 |
Text | Text | fix typos in cameras article | 8b458550e9dd2befe74f5893a389b77a5b8abfc0 | <ide><path>threejs/lessons/threejs-cameras.md
<ide> This article is one in a series of articles about three.js.
<ide> The first article was [about fundamentals](threejs-fundamentals.html).
<ide> If you haven't read that yet you might want to start there.
<ide>
<del>Let's talk about Cameras in three.js. We covered some of this in the [first article](threejs-fundamentals.html) but we'll cover it in more detail here.
<add>Let's talk about cameras in three.js. We covered some of this in the [first article](threejs-fundamentals.html) but we'll cover it in more detail here.
<ide>
<ide> The most common camera in three.js and the one we've been using up to this point is
<del>the `PerspectiveCamera`. It gives a 3d view where things in the distance appear
<add>the `PerspectiveCamera`. It gives a 3d view where things in the distance appear
<ide> smaller than things up close.
<ide>
<ide> The `PerspectiveCamera` defines a *frustum*. [A *frustum* is a solid pyramid shape with
<del>the tip cut off](https://en.wikipedia.org/wiki/Frustum).
<add>the tip cut off](https://en.wikipedia.org/wiki/Frustum).
<ide> By name of a solid I mean for example a cube, a cone, a sphere, a cylinder,
<ide> and a frustum are all names of different kinds of solids.
<ide>
<ide> I only point that out because I didn't know if for years. Some book or page woul
<ide> shape made those descriptions suddenly make more sense 😅
<ide>
<ide> A `PerspectiveCamera` defines its frustum based on 4 properties. `near` defines where the
<del>front of the frustum starts. `far` defines where it ends. `fov`, the field of view, defines
<del>how tall the front and back of the frustum are by computing the correct height to get
<del>the specified field of view at `near` units from the camera. The `aspect` defines how
<del>wide the front and back of the frustum are. The width of the frustum is just the height
<add>front of the frustum starts. `far` defines where it ends. `fov`, the field of view, defines
<add>how tall the front and back of the frustum are by computing the correct height to get
<add>the specified field of view at `near` units from the camera. The `aspect` defines how
<add>wide the front and back of the frustum are. The width of the frustum is just the height
<ide> multiplied by the aspect.
<ide>
<ide> <img src="resources/frustum-3d.svg" width="500" class="threejs_center"/>
<ide>
<ide> Let's use the scene from [the previous article](threejs-lights.html) that has a ground
<del>plane, a sphere, and a cube and make it so we can adjust the camera's settings
<add>plane, a sphere, and a cube and make it so we can adjust the camera's settings.
<ide>
<del>To do that we'll make a `MinMaxGUIHelper` for the `near` and `far` settings so `far`
<del>is always greater than `near`. It will have `min` and `max` properties that dat.GUI
<add>To do that we'll make a `MinMaxGUIHelper` for the `near` and `far` settings so `far`
<add>is always greater than `near`. It will have `min` and `max` properties that dat.GUI
<ide> will adjust. When adjusted they'll set the 2 properties we specify.
<ide>
<ide> ```js
<ide> gui.add(minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near').onChange(updateCamera
<ide> gui.add(minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far').onChange(updateCamera);
<ide> ```
<ide>
<del>Anytime the camera's settings change we need to call the camera's
<add>Anytime the camera's settings change we need to call the camera's
<ide> [`updateProjectionMatrix`](PerspectiveCamera.updateProjectionMatrix) function
<ide> so we made a function called `updateCamera` add passed it to dat.GUI to call it when things change.
<ide>
<ide> {{{example url="../threejs-cameras-perspective.html" }}}
<ide>
<del>You can just the values and see how they work. Note we didn't make `aspect` setable since
<add>You can adjust the values and see how they work. Note we didn't make `aspect` settable since
<ide> it's taken from the size of the window so if you want to adjust the aspect open the example
<ide> in a new window and then size the window.
<ide>
<ide> scene.add(cameraHelper);
<ide> Now let's look up the 2 view elements.
<ide>
<ide> ```js
<del>const view1Elem = document.querySelector('#view1');
<add>const view1Elem = document.querySelector('#view1');
<ide> const view2Elem = document.querySelector('#view2');
<ide> ```
<ide>
<ide> the frustum.
<ide>
<ide> This brings up the question, why not just set `near` to 0.0000000001 and `far`
<ide> to 10000000000000 or something like that so you can just see everything?
<del>The reason is your GPU only has so much precision to decide if something
<add>The reason is your GPU only has so much precision to decide if something
<ide> is in front or behind something else. That precision is spread out between
<ide> `near` and `far`. Worse, by default the precision close the camera is detailed
<del>and the precision far from the camera is course. The units use start with `near`
<add>and the precision far from the camera is coarse. The units start with `near`
<ide> and slowly expand as they approach `far`.
<ide>
<ide> Starting with the top example, let's change the code to insert 20 spheres in a
<ide> Just in case the issue doesn't show on your machine here's what I see on mine
<ide> <div class="threejs_center"><img src="resources/images/z-fighting.png" style="width: 570px;"></div>
<ide>
<ide> One solution is to tell three.js use to a different method to compute which
<del>pixels are in front and which are behind. We can do that by enabling
<add>pixels are in front and which are behind. We can do that by enabling
<ide> `logarithmicDepthBuffer` when we create the `WebGLRenderer`
<ide>
<ide> ```js
<ide> and with that it might work
<ide> {{{example url="../threejs-cameras-logarithmic-depth-buffer.html" }}}
<ide>
<ide> If this didn't fix the issue for you then you've run into one reason why
<del>you can't always use this solution. That reason is because only certain GPUs
<add>you can't always use this solution. That reason is because only certain GPUs
<ide> support it. As of September 2018 almost no mobile devices support this
<del>solution where as most desktops do.
<add>solution whereas most desktops do.
<ide>
<ide> Another reason not to choose this solution is it can be significantly slower
<ide> than the standard solution.
<ide> camera.far = 1;
<ide> camera.zoom = 1;
<ide> ```
<ide>
<del>Or if we wanted the origin to be in the top left just like a
<add>Or if we wanted the origin to be in the top left just like a
<ide> 2D canvas we could use this
<ide>
<ide> ```js
<ide> In the screenshot above you can see 1 view is a perspective view and 3 views are
<ide> orthographic views.
<ide>
<ide> That's the fundamentals of cameras. We'll cover a few common ways to move cameras
<del>in other articles. For now lets move on to [shadows](threejs-shadows.html).
<add>in other articles. For now let's move on to [shadows](threejs-shadows.html).
<ide>
<ide> <canvas id="c"></canvas>
<ide> <script src="../resources/threejs/r105/three.min.js"></script> | 1 |
Javascript | Javascript | use clearer wording | 8a8d973d3cc5623676a84f87af66ef9259c3937c | <ide><path>packages/react-dom/src/client/ReactDOMComponent.js
<ide> function setInitialDOMProperties(
<ide> // Noop
<ide> } else if (propKey === AUTOFOCUS) {
<ide> // We polyfill it separately on the client during commit.
<del> // We blacklist it here rather than in the property list because we emit it in SSR.
<add> // We could have excluded it in the property list instead of
<add> // adding a special case here, but then it wouldn't be emitted
<add> // on server rendering (but we *do* want to emit it in SSR).
<ide> } else if (registrationNameModules.hasOwnProperty(propKey)) {
<ide> if (nextProp != null) {
<ide> if (__DEV__ && typeof nextProp !== 'function') {
<ide><path>packages/react-dom/src/events/BeforeInputEventPlugin.js
<ide> function getNativeBeforeInputChars(topLevelType: TopLevelType, nativeEvent) {
<ide>
<ide> // If it's a spacebar character, assume that we have already handled
<ide> // it at the keypress level and bail immediately. Android Chrome
<del> // doesn't give us keycodes, so we need to blacklist it.
<add> // doesn't give us keycodes, so we need to ignore it.
<ide> if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
<ide> return null;
<ide> }
<ide><path>scripts/jest/config.build.js
<ide> packages.forEach(name => {
<ide> module.exports = Object.assign({}, baseConfig, {
<ide> // Redirect imports to the compiled bundles
<ide> moduleNameMapper,
<del> // Don't run bundle tests on blacklisted -test.internal.* files
<add> // Don't run bundle tests on -test.internal.* files
<ide> testPathIgnorePatterns: ['/node_modules/', '-test.internal.js$'],
<ide> // Exclude the build output from transforms
<ide> transformIgnorePatterns: ['/node_modules/', '<rootDir>/build/'],
<ide><path>scripts/rollup/build.js
<ide> function isProfilingBundleType(bundleType) {
<ide> }
<ide> }
<ide>
<del>function blacklistFBJS() {
<add>function forbidFBJSImports() {
<ide> return {
<del> name: 'blacklistFBJS',
<add> name: 'forbidFBJSImports',
<ide> resolveId(importee, importer) {
<ide> if (/^fbjs\//.test(importee)) {
<ide> throw new Error(
<ide> function getPlugins(
<ide> // Shim any modules that need forking in this environment.
<ide> useForks(forks),
<ide> // Ensure we don't try to bundle any fbjs modules.
<del> blacklistFBJS(),
<add> forbidFBJSImports(),
<ide> // Use Node resolution mechanism.
<ide> resolve({
<ide> skip: externals,
<ide><path>scripts/rollup/forks.js
<ide> const forks = Object.freeze({
<ide> }
<ide> },
<ide>
<del> // This logic is forked on www to blacklist warnings.
<add> // This logic is forked on www to ignore some warnings.
<ide> 'shared/lowPriorityWarning': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> const forks = Object.freeze({
<ide> }
<ide> },
<ide>
<del> // This logic is forked on www to blacklist warnings.
<add> // This logic is forked on www to ignore some warnings.
<ide> 'shared/warningWithoutStack': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV: | 5 |
Java | Java | add lifecycle to sockjsclient and transport types | 2ebc92154571a496520b53a84442aac9388d8392 | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/JettyXhrTransport.java
<ide> import org.eclipse.jetty.client.util.StringContentProvider;
<ide> import org.eclipse.jetty.http.HttpFields;
<ide> import org.eclipse.jetty.http.HttpMethod;
<add>import org.springframework.context.Lifecycle;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseEntity;
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.1
<ide> */
<del>public class JettyXhrTransport extends AbstractXhrTransport implements XhrTransport {
<add>public class JettyXhrTransport extends AbstractXhrTransport implements XhrTransport, Lifecycle {
<ide>
<ide> private final HttpClient httpClient;
<ide>
<ide> public HttpClient getHttpClient() {
<ide> return this.httpClient;
<ide> }
<ide>
<add> @Override
<add> public void start() {
<add> try {
<add> if (!this.httpClient.isRunning()) {
<add> this.httpClient.start();
<add> }
<add> }
<add> catch (Exception e) {
<add> throw new SockJsException("Failed to start " + this, e);
<add> }
<add> }
<add>
<add> @Override
<add> public void stop() {
<add> try {
<add> if (this.httpClient.isRunning()) {
<add> this.httpClient.stop();
<add> }
<add> }
<add> catch (Exception e) {
<add> throw new SockJsException("Failed to stop " + this, e);
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isRunning() {
<add> return this.httpClient.isRunning();
<add> }
<add>
<ide> @Override
<ide> protected ResponseEntity<String> executeInfoRequestInternal(URI infoUrl) {
<ide> return executeRequest(infoUrl, HttpMethod.GET, getRequestHeaders(), null);
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<add>import org.springframework.context.Lifecycle;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.scheduling.TaskScheduler;
<ide> import org.springframework.util.Assert;
<ide> * @see <a href="http://sockjs.org">http://sockjs.org</a>
<ide> * @see org.springframework.web.socket.sockjs.client.Transport
<ide> */
<del>public class SockJsClient extends AbstractWebSocketClient {
<add>public class SockJsClient extends AbstractWebSocketClient implements Lifecycle {
<ide>
<ide> private static final boolean jackson2Present = ClassUtils.isPresent(
<ide> "com.fasterxml.jackson.databind.ObjectMapper", SockJsClient.class.getClassLoader());
<ide> public class SockJsClient extends AbstractWebSocketClient {
<ide>
<ide> private final Map<URI, ServerInfo> infoCache = new ConcurrentHashMap<URI, ServerInfo>();
<ide>
<add> private volatile boolean running = false;
<add>
<ide>
<ide> /**
<ide> * Create a {@code SockJsClient} with the given transports.
<ide> public void setTaskScheduler(TaskScheduler taskScheduler) {
<ide> this.taskScheduler = taskScheduler;
<ide> }
<ide>
<add> @Override
<add> public void start() {
<add> if (!isRunning()) {
<add> for (Transport transport : this.transports) {
<add> if (transport instanceof Lifecycle) {
<add> if (!((Lifecycle) transport).isRunning()) {
<add> ((Lifecycle) transport).start();
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void stop() {
<add> if (!isRunning()) {
<add> for (Transport transport : this.transports) {
<add> if (transport instanceof Lifecycle) {
<add> if (((Lifecycle) transport).isRunning()) {
<add> ((Lifecycle) transport).stop();
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isRunning() {
<add> return this.running;
<add> }
<add>
<ide> public void clearServerInfoCache() {
<ide> this.infoCache.clear();
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/WebSocketTransport.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<add>import org.springframework.context.Lifecycle;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.concurrent.ListenableFuture;
<ide> import org.springframework.util.concurrent.ListenableFutureCallback;
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.1
<ide> */
<del>public class WebSocketTransport implements Transport {
<add>public class WebSocketTransport implements Transport, Lifecycle {
<ide>
<ide> private static Log logger = LogFactory.getLog(WebSocketTransport.class);
<ide>
<ide> private final WebSocketClient webSocketClient;
<ide>
<add> private volatile boolean running = false;
<add>
<ide>
<ide> public WebSocketTransport(WebSocketClient webSocketClient) {
<ide> Assert.notNull(webSocketClient, "'webSocketClient' is required");
<ide> public WebSocketClient getWebSocketClient() {
<ide> return this.webSocketClient;
<ide> }
<ide>
<add> @Override
<add> public void start() {
<add> if (!isRunning()) {
<add> if (this.webSocketClient instanceof Lifecycle) {
<add> ((Lifecycle) this.webSocketClient).start();
<add> }
<add> else {
<add> this.running = true;
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void stop() {
<add> if (isRunning()) {
<add> if (this.webSocketClient instanceof Lifecycle) {
<add> ((Lifecycle) this.webSocketClient).stop();
<add> }
<add> else {
<add> this.running = false;
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isRunning() {
<add> if (this.webSocketClient instanceof Lifecycle) {
<add> return ((Lifecycle) this.webSocketClient).isRunning();
<add> }
<add> else {
<add> return this.running;
<add> }
<add> }
<add>
<add>
<ide> @Override
<ide> public ListenableFuture<WebSocketSession> connect(TransportRequest request, WebSocketHandler handler) {
<ide> final SettableListenableFuture<WebSocketSession> future = new SettableListenableFuture<WebSocketSession>();
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/AbstractSockJsIntegrationTests.java
<ide> public abstract class AbstractSockJsIntegrationTests {
<ide>
<ide> protected Log logger = LogFactory.getLog(getClass());
<ide>
<add>
<add> private SockJsClient sockJsClient;
<add>
<ide> private WebSocketTestServer server;
<ide>
<ide> private AnnotationConfigWebApplicationContext wac;
<ide> public void setup() throws Exception {
<ide>
<ide> @After
<ide> public void teardown() throws Exception {
<add> try {
<add> this.sockJsClient.stop();
<add> }
<add> catch (Throwable ex) {
<add> logger.error("Failed to stop SockJsClient", ex);
<add> }
<ide> try {
<ide> this.server.undeployConfig();
<ide> }
<ide> public void teardown() throws Exception {
<ide> }
<ide> }
<ide>
<del> protected abstract WebSocketTestServer createWebSocketTestServer();
<del>
<ide> protected abstract Class<?> upgradeStrategyConfigClass();
<ide>
<del> protected abstract Transport getWebSocketTransport();
<add> protected abstract WebSocketTestServer createWebSocketTestServer();
<ide>
<del> protected abstract AbstractXhrTransport getXhrTransport();
<add> protected abstract Transport createWebSocketTransport();
<ide>
<del> protected SockJsClient createSockJsClient(Transport... transports) {
<del> return new SockJsClient(Arrays.<Transport>asList(transports));
<add> protected abstract AbstractXhrTransport createXhrTransport();
<add>
<add> protected void initSockJsClient(Transport... transports) {
<add> this.sockJsClient = new SockJsClient(Arrays.asList(transports));
<add> this.sockJsClient.start();
<ide> }
<ide>
<add>
<ide> @Test
<ide> public void echoWebSocket() throws Exception {
<del> testEcho(100, getWebSocketTransport());
<add> testEcho(100, createWebSocketTransport());
<ide> }
<ide>
<ide> @Test
<ide> public void echoXhrStreaming() throws Exception {
<del> testEcho(100, getXhrTransport());
<add> testEcho(100, createXhrTransport());
<ide> }
<ide>
<ide> @Test
<ide> public void echoXhr() throws Exception {
<del> AbstractXhrTransport xhrTransport = getXhrTransport();
<add> AbstractXhrTransport xhrTransport = createXhrTransport();
<ide> xhrTransport.setXhrStreamingDisabled(true);
<ide> testEcho(100, xhrTransport);
<ide> }
<ide>
<ide> @Test
<ide> public void closeAfterOneMessageWebSocket() throws Exception {
<del> testCloseAfterOneMessage(getWebSocketTransport());
<add> testCloseAfterOneMessage(createWebSocketTransport());
<ide> }
<ide>
<ide> @Test
<ide> public void closeAfterOneMessageXhrStreaming() throws Exception {
<del> testCloseAfterOneMessage(getXhrTransport());
<add> testCloseAfterOneMessage(createXhrTransport());
<ide> }
<ide>
<ide> @Test
<ide> public void closeAfterOneMessageXhr() throws Exception {
<del> AbstractXhrTransport xhrTransport = getXhrTransport();
<add> AbstractXhrTransport xhrTransport = createXhrTransport();
<ide> xhrTransport.setXhrStreamingDisabled(true);
<ide> testCloseAfterOneMessage(xhrTransport);
<ide> }
<ide> public void infoRequestFailure() throws Exception {
<ide> TestClientHandler handler = new TestClientHandler();
<ide> this.errorFilter.responseStatusMap.put("/info", 500);
<ide> CountDownLatch latch = new CountDownLatch(1);
<del> createSockJsClient(getWebSocketTransport()).doHandshake(handler, this.baseUrl + "/echo").addCallback(
<add> initSockJsClient(createWebSocketTransport());
<add> this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").addCallback(
<ide> new ListenableFutureCallback<WebSocketSession>() {
<ide> @Override
<ide> public void onSuccess(WebSocketSession result) {
<ide> public void fallbackAfterTransportFailure() throws Exception {
<ide> this.errorFilter.responseStatusMap.put("/websocket", 200);
<ide> this.errorFilter.responseStatusMap.put("/xhr_streaming", 500);
<ide> TestClientHandler handler = new TestClientHandler();
<del> Transport[] transports = { getWebSocketTransport(), getXhrTransport() };
<del> WebSocketSession session = createSockJsClient(transports).doHandshake(handler, this.baseUrl + "/echo").get();
<add> initSockJsClient(createWebSocketTransport(), createXhrTransport());
<add> WebSocketSession session = this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").get();
<ide> assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, session.getClass());
<ide> TextMessage message = new TextMessage("message1");
<ide> session.sendMessage(message);
<ide> public void fallbackAfterConnectTimeout() throws Exception {
<ide> TestClientHandler clientHandler = new TestClientHandler();
<ide> this.errorFilter.sleepDelayMap.put("/xhr_streaming", 10000L);
<ide> this.errorFilter.responseStatusMap.put("/xhr_streaming", 503);
<del> SockJsClient sockJsClient = createSockJsClient(getXhrTransport());
<del> sockJsClient.setTaskScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class));
<add> initSockJsClient(createXhrTransport());
<add> this.sockJsClient.setTaskScheduler(this.wac.getBean(ThreadPoolTaskScheduler.class));
<ide> WebSocketSession clientSession = sockJsClient.doHandshake(clientHandler, this.baseUrl + "/echo").get();
<ide> assertEquals("Fallback didn't occur", XhrClientSockJsSession.class, clientSession.getClass());
<ide> TextMessage message = new TextMessage("message1");
<ide> private void testEcho(int messageCount, Transport transport) throws Exception {
<ide> messages.add(new TextMessage("m" + i));
<ide> }
<ide> TestClientHandler handler = new TestClientHandler();
<del> WebSocketSession session = createSockJsClient(transport).doHandshake(handler, this.baseUrl + "/echo").get();
<add> initSockJsClient(transport);
<add> WebSocketSession session = this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").get();
<ide> for (TextMessage message : messages) {
<ide> session.sendMessage(message);
<ide> }
<ide> private void testEcho(int messageCount, Transport transport) throws Exception {
<ide>
<ide> private void testCloseAfterOneMessage(Transport transport) throws Exception {
<ide> TestClientHandler clientHandler = new TestClientHandler();
<del> createSockJsClient(transport).doHandshake(clientHandler, this.baseUrl + "/test").get();
<add> initSockJsClient(transport);
<add> this.sockJsClient.doHandshake(clientHandler, this.baseUrl + "/test").get();
<ide> TestServerHandler serverHandler = this.wac.getBean(TestServerHandler.class);
<ide>
<ide> assertNotNull("afterConnectionEstablished should have been called", clientHandler.session);
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/JettySockJsIntegrationTests.java
<ide> */
<ide> public class JettySockJsIntegrationTests extends AbstractSockJsIntegrationTests {
<ide>
<del> private WebSocketClient webSocketClient;
<ide>
<del> private HttpClient httpClient;
<del>
<del>
<del> @Before
<del> public void setup() throws Exception {
<del> super.setup();
<del> this.webSocketClient = new WebSocketClient();
<del> this.webSocketClient.start();
<del> this.httpClient = new HttpClient();
<del> this.httpClient.start();
<del> }
<del>
<del> @After
<del> public void teardown() throws Exception {
<del> super.teardown();
<del> try {
<del> this.webSocketClient.stop();
<del> }
<del> catch (Throwable ex) {
<del> logger.error("Failed to stop Jetty WebSocketClient", ex);
<del> }
<del> try {
<del> this.httpClient.stop();
<del> }
<del> catch (Throwable ex) {
<del> logger.error("Failed to stop Jetty HttpClient", ex);
<del> }
<add> @Override
<add> protected Class<?> upgradeStrategyConfigClass() {
<add> return JettyTestConfig.class;
<ide> }
<ide>
<ide> @Override
<ide> protected JettyWebSocketTestServer createWebSocketTestServer() {
<ide> }
<ide>
<ide> @Override
<del> protected Class<?> upgradeStrategyConfigClass() {
<del> return JettyTestConfig.class;
<del> }
<del>
<del> @Override
<del> protected Transport getWebSocketTransport() {
<del> return new WebSocketTransport(new JettyWebSocketClient(this.webSocketClient));
<add> protected Transport createWebSocketTransport() {
<add> return new WebSocketTransport(new JettyWebSocketClient());
<ide> }
<ide>
<ide> @Override
<del> protected AbstractXhrTransport getXhrTransport() {
<del> return new JettyXhrTransport(this.httpClient);
<add> protected AbstractXhrTransport createXhrTransport() {
<add> return new JettyXhrTransport(new HttpClient());
<ide> }
<ide>
<ide>
<ide> @Configuration
<ide> static class JettyTestConfig {
<del>
<ide> @Bean
<ide> public RequestUpgradeStrategy upgradeStrategy() {
<ide> return new JettyRequestUpgradeStrategy(); | 5 |
Go | Go | collect warnings in sysinfo struct | 1fb62f455c95815667d9d46eecf0cb2dbe5e4999 | <ide><path>pkg/sysinfo/cgroup2_linux.go
<ide> import (
<ide> )
<ide>
<ide> func newV2(quiet bool, options ...Opt) *SysInfo {
<del> var warnings []string
<ide> sysInfo := &SysInfo{
<ide> CgroupUnified: true,
<ide> cg2GroupPath: "/",
<ide> func newV2(quiet bool, options ...Opt) *SysInfo {
<ide> }
<ide>
<ide> for _, o := range ops {
<del> w := o(sysInfo)
<del> warnings = append(warnings, w...)
<add> o(sysInfo)
<ide> }
<ide> if !quiet {
<del> for _, w := range warnings {
<add> for _, w := range sysInfo.Warnings {
<ide> logrus.Warn(w)
<ide> }
<ide> }
<ide> func getSwapLimitV2() bool {
<ide> return true
<ide> }
<ide>
<del>func applyMemoryCgroupInfoV2(info *SysInfo) []string {
<del> var warnings []string
<add>func applyMemoryCgroupInfoV2(info *SysInfo) {
<ide> if _, ok := info.cg2Controllers["memory"]; !ok {
<del> warnings = append(warnings, "Unable to find memory controller")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find memory controller")
<add> return
<ide> }
<ide>
<ide> info.MemoryLimit = true
<ide> func applyMemoryCgroupInfoV2(info *SysInfo) []string {
<ide> info.MemorySwappiness = false
<ide> info.KernelMemory = false
<ide> info.KernelMemoryTCP = false
<del> return warnings
<ide> }
<ide>
<del>func applyCPUCgroupInfoV2(info *SysInfo) []string {
<del> var warnings []string
<add>func applyCPUCgroupInfoV2(info *SysInfo) {
<ide> if _, ok := info.cg2Controllers["cpu"]; !ok {
<del> warnings = append(warnings, "Unable to find cpu controller")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find cpu controller")
<add> return
<ide> }
<ide> info.CPUShares = true
<ide> info.CPUCfs = true
<ide> info.CPURealtime = false
<del> return warnings
<ide> }
<ide>
<del>func applyIOCgroupInfoV2(info *SysInfo) []string {
<del> var warnings []string
<add>func applyIOCgroupInfoV2(info *SysInfo) {
<ide> if _, ok := info.cg2Controllers["io"]; !ok {
<del> warnings = append(warnings, "Unable to find io controller")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find io controller")
<add> return
<ide> }
<ide>
<ide> info.BlkioWeight = true
<ide> func applyIOCgroupInfoV2(info *SysInfo) []string {
<ide> info.BlkioWriteBpsDevice = true
<ide> info.BlkioReadIOpsDevice = true
<ide> info.BlkioWriteIOpsDevice = true
<del> return warnings
<ide> }
<ide>
<del>func applyCPUSetCgroupInfoV2(info *SysInfo) []string {
<del> var warnings []string
<add>func applyCPUSetCgroupInfoV2(info *SysInfo) {
<ide> if _, ok := info.cg2Controllers["cpuset"]; !ok {
<del> warnings = append(warnings, "Unable to find cpuset controller")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find cpuset controller")
<add> return
<ide> }
<ide> info.Cpuset = true
<ide>
<ide> cpus, err := ioutil.ReadFile(path.Join("/sys/fs/cgroup", info.cg2GroupPath, "cpuset.cpus.effective"))
<ide> if err != nil {
<del> return warnings
<add> return
<ide> }
<ide> info.Cpus = strings.TrimSpace(string(cpus))
<ide>
<ide> mems, err := ioutil.ReadFile(path.Join("/sys/fs/cgroup", info.cg2GroupPath, "cpuset.mems.effective"))
<ide> if err != nil {
<del> return warnings
<add> return
<ide> }
<ide> info.Mems = strings.TrimSpace(string(mems))
<del> return warnings
<ide> }
<ide>
<del>func applyPIDSCgroupInfoV2(info *SysInfo) []string {
<del> var warnings []string
<add>func applyPIDSCgroupInfoV2(info *SysInfo) {
<ide> if _, ok := info.cg2Controllers["pids"]; !ok {
<del> warnings = append(warnings, "Unable to find pids controller")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find pids controller")
<add> return
<ide> }
<ide> info.PidsLimit = true
<del> return warnings
<ide> }
<ide>
<del>func applyDevicesCgroupInfoV2(info *SysInfo) []string {
<add>func applyDevicesCgroupInfoV2(info *SysInfo) {
<ide> info.CgroupDevicesEnabled = !userns.RunningInUserNS()
<del> return nil
<ide> }
<ide><path>pkg/sysinfo/sysinfo.go
<ide> type SysInfo struct {
<ide> // Whether the cgroup is in unified mode (v2).
<ide> CgroupUnified bool
<ide>
<add> // Warnings contains a slice of warnings that occurred while collecting
<add> // system information. These warnings are intended to be informational
<add> // messages for the user, and can either be logged or returned to the
<add> // client; they are not intended to be parsed / used for other purposes,
<add> // and do not have a fixed format.
<add> Warnings []string
<add>
<ide> // cgMounts is the list of cgroup v1 mount paths, indexed by subsystem, to
<ide> // inspect availability of subsystems.
<ide> cgMounts map[string]string
<ide><path>pkg/sysinfo/sysinfo_linux.go
<ide> func findCgroupMountpoints() (map[string]string, error) {
<ide> return mps, nil
<ide> }
<ide>
<del>type infoCollector func(info *SysInfo) (warnings []string)
<add>type infoCollector func(info *SysInfo)
<ide>
<ide> // WithCgroup2GroupPath specifies the cgroup v2 group path to inspect availability
<ide> // of the controllers.
<ide> func WithCgroup2GroupPath(g string) Opt {
<ide> }
<ide>
<ide> // New returns a new SysInfo, using the filesystem to detect which features
<del>// the kernel supports. If `quiet` is `false` warnings are printed in logs
<add>// the kernel supports. If `quiet` is `false` info.Warnings are printed in logs
<ide> // whenever an error occurs or misconfigurations are present.
<ide> func New(quiet bool, options ...Opt) *SysInfo {
<ide> if cdcgroups.Mode() == cdcgroups.Unified {
<ide> func New(quiet bool, options ...Opt) *SysInfo {
<ide>
<ide> func newV1(quiet bool) *SysInfo {
<ide> var (
<del> err error
<del> warnings []string
<del> sysInfo = &SysInfo{}
<add> err error
<add> sysInfo = &SysInfo{}
<ide> )
<ide>
<ide> ops := []infoCollector{
<ide> func newV1(quiet bool) *SysInfo {
<ide> }
<ide>
<ide> for _, o := range ops {
<del> w := o(sysInfo)
<del> warnings = append(warnings, w...)
<add> o(sysInfo)
<ide> }
<ide> if !quiet {
<del> for _, w := range warnings {
<add> for _, w := range sysInfo.Warnings {
<ide> logrus.Warn(w)
<ide> }
<ide> }
<ide> return sysInfo
<ide> }
<ide>
<ide> // applyMemoryCgroupInfo adds the memory cgroup controller information to the info.
<del>func applyMemoryCgroupInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyMemoryCgroupInfo(info *SysInfo) {
<ide> mountPoint, ok := info.cgMounts["memory"]
<ide> if !ok {
<del> warnings = append(warnings, "Your kernel does not support cgroup memory limit")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup memory limit")
<add> return
<ide> }
<ide> info.MemoryLimit = ok
<ide>
<ide> info.SwapLimit = cgroupEnabled(mountPoint, "memory.memsw.limit_in_bytes")
<ide> if !info.SwapLimit {
<del> warnings = append(warnings, "Your kernel does not support swap memory limit")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support swap memory limit")
<ide> }
<ide> info.MemoryReservation = cgroupEnabled(mountPoint, "memory.soft_limit_in_bytes")
<ide> if !info.MemoryReservation {
<del> warnings = append(warnings, "Your kernel does not support memory reservation")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support memory reservation")
<ide> }
<ide> info.OomKillDisable = cgroupEnabled(mountPoint, "memory.oom_control")
<ide> if !info.OomKillDisable {
<del> warnings = append(warnings, "Your kernel does not support oom control")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support oom control")
<ide> }
<ide> info.MemorySwappiness = cgroupEnabled(mountPoint, "memory.swappiness")
<ide> if !info.MemorySwappiness {
<del> warnings = append(warnings, "Your kernel does not support memory swappiness")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support memory swappiness")
<ide> }
<ide> info.KernelMemory = cgroupEnabled(mountPoint, "memory.kmem.limit_in_bytes")
<ide> if !info.KernelMemory {
<del> warnings = append(warnings, "Your kernel does not support kernel memory limit")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support kernel memory limit")
<ide> }
<ide> info.KernelMemoryTCP = cgroupEnabled(mountPoint, "memory.kmem.tcp.limit_in_bytes")
<ide> if !info.KernelMemoryTCP {
<del> warnings = append(warnings, "Your kernel does not support kernel memory TCP limit")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support kernel memory TCP limit")
<ide> }
<del>
<del> return warnings
<ide> }
<ide>
<ide> // applyCPUCgroupInfo adds the cpu cgroup controller information to the info.
<del>func applyCPUCgroupInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyCPUCgroupInfo(info *SysInfo) {
<ide> mountPoint, ok := info.cgMounts["cpu"]
<ide> if !ok {
<del> warnings = append(warnings, "Unable to find cpu cgroup in mounts")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find cpu cgroup in mounts")
<add> return
<ide> }
<ide>
<ide> info.CPUShares = cgroupEnabled(mountPoint, "cpu.shares")
<ide> if !info.CPUShares {
<del> warnings = append(warnings, "Your kernel does not support CPU shares")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support CPU shares")
<ide> }
<ide>
<ide> info.CPUCfs = cgroupEnabled(mountPoint, "cpu.cfs_quota_us")
<ide> if !info.CPUCfs {
<del> warnings = append(warnings, "Your kernel does not support CPU CFS scheduler")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support CPU CFS scheduler")
<ide> }
<ide>
<ide> info.CPURealtime = cgroupEnabled(mountPoint, "cpu.rt_period_us")
<ide> if !info.CPURealtime {
<del> warnings = append(warnings, "Your kernel does not support CPU realtime scheduler")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support CPU realtime scheduler")
<ide> }
<del>
<del> return warnings
<ide> }
<ide>
<ide> // applyBlkioCgroupInfo adds the blkio cgroup controller information to the info.
<del>func applyBlkioCgroupInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyBlkioCgroupInfo(info *SysInfo) {
<ide> mountPoint, ok := info.cgMounts["blkio"]
<ide> if !ok {
<del> warnings = append(warnings, "Unable to find blkio cgroup in mounts")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find blkio cgroup in mounts")
<add> return
<ide> }
<ide>
<ide> info.BlkioWeight = cgroupEnabled(mountPoint, "blkio.weight")
<ide> if !info.BlkioWeight {
<del> warnings = append(warnings, "Your kernel does not support cgroup blkio weight")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup blkio weight")
<ide> }
<ide>
<ide> info.BlkioWeightDevice = cgroupEnabled(mountPoint, "blkio.weight_device")
<ide> if !info.BlkioWeightDevice {
<del> warnings = append(warnings, "Your kernel does not support cgroup blkio weight_device")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup blkio weight_device")
<ide> }
<ide>
<ide> info.BlkioReadBpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.read_bps_device")
<ide> if !info.BlkioReadBpsDevice {
<del> warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.read_bps_device")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup blkio throttle.read_bps_device")
<ide> }
<ide>
<ide> info.BlkioWriteBpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.write_bps_device")
<ide> if !info.BlkioWriteBpsDevice {
<del> warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.write_bps_device")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup blkio throttle.write_bps_device")
<ide> }
<ide> info.BlkioReadIOpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.read_iops_device")
<ide> if !info.BlkioReadIOpsDevice {
<del> warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.read_iops_device")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup blkio throttle.read_iops_device")
<ide> }
<ide>
<ide> info.BlkioWriteIOpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.write_iops_device")
<ide> if !info.BlkioWriteIOpsDevice {
<del> warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.write_iops_device")
<add> info.Warnings = append(info.Warnings, "Your kernel does not support cgroup blkio throttle.write_iops_device")
<ide> }
<del>
<del> return warnings
<ide> }
<ide>
<ide> // applyCPUSetCgroupInfo adds the cpuset cgroup controller information to the info.
<del>func applyCPUSetCgroupInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyCPUSetCgroupInfo(info *SysInfo) {
<ide> mountPoint, ok := info.cgMounts["cpuset"]
<ide> if !ok {
<del> warnings = append(warnings, "Unable to find cpuset cgroup in mounts")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find cpuset cgroup in mounts")
<add> return
<ide> }
<ide> info.Cpuset = ok
<ide>
<ide> var err error
<ide>
<ide> cpus, err := ioutil.ReadFile(path.Join(mountPoint, "cpuset.cpus"))
<ide> if err != nil {
<del> return warnings
<add> return
<ide> }
<ide> info.Cpus = strings.TrimSpace(string(cpus))
<ide>
<ide> mems, err := ioutil.ReadFile(path.Join(mountPoint, "cpuset.mems"))
<ide> if err != nil {
<del> return warnings
<add> return
<ide> }
<ide> info.Mems = strings.TrimSpace(string(mems))
<del>
<del> return warnings
<ide> }
<ide>
<ide> // applyPIDSCgroupInfo adds whether the pids cgroup controller is available to the info.
<del>func applyPIDSCgroupInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyPIDSCgroupInfo(info *SysInfo) {
<ide> _, ok := info.cgMounts["pids"]
<ide> if !ok {
<del> warnings = append(warnings, "Unable to find pids cgroup in mounts")
<del> return warnings
<add> info.Warnings = append(info.Warnings, "Unable to find pids cgroup in mounts")
<add> return
<ide> }
<ide> info.PidsLimit = true
<del> return warnings
<ide> }
<ide>
<ide> // applyDevicesCgroupInfo adds whether the devices cgroup controller is available to the info.
<del>func applyDevicesCgroupInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyDevicesCgroupInfo(info *SysInfo) {
<ide> _, ok := info.cgMounts["devices"]
<ide> info.CgroupDevicesEnabled = ok
<del> return warnings
<ide> }
<ide>
<ide> // applyNetworkingInfo adds networking information to the info.
<del>func applyNetworkingInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyNetworkingInfo(info *SysInfo) {
<ide> info.IPv4ForwardingDisabled = !readProcBool("/proc/sys/net/ipv4/ip_forward")
<ide> info.BridgeNFCallIPTablesDisabled = !readProcBool("/proc/sys/net/bridge/bridge-nf-call-iptables")
<ide> info.BridgeNFCallIP6TablesDisabled = !readProcBool("/proc/sys/net/bridge/bridge-nf-call-ip6tables")
<del> return warnings
<ide> }
<ide>
<ide> // applyAppArmorInfo adds whether AppArmor is enabled to the info.
<del>func applyAppArmorInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyAppArmorInfo(info *SysInfo) {
<ide> if _, err := os.Stat("/sys/kernel/security/apparmor"); !os.IsNotExist(err) {
<ide> if _, err := ioutil.ReadFile("/sys/kernel/security/apparmor/profiles"); err == nil {
<ide> info.AppArmor = true
<ide> }
<ide> }
<del> return warnings
<ide> }
<ide>
<ide> // applyCgroupNsInfo adds whether cgroupns is enabled to the info.
<del>func applyCgroupNsInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applyCgroupNsInfo(info *SysInfo) {
<ide> if _, err := os.Stat("/proc/self/ns/cgroup"); !os.IsNotExist(err) {
<ide> info.CgroupNamespaces = true
<ide> }
<del> return warnings
<ide> }
<ide>
<ide> var (
<ide> var (
<ide> )
<ide>
<ide> // applySeccompInfo checks if Seccomp is supported, via CONFIG_SECCOMP.
<del>func applySeccompInfo(info *SysInfo) []string {
<del> var warnings []string
<add>func applySeccompInfo(info *SysInfo) {
<ide> seccompOnce.Do(func() {
<ide> // Check if Seccomp is supported, via CONFIG_SECCOMP.
<ide> if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL {
<ide> func applySeccompInfo(info *SysInfo) []string {
<ide> }
<ide> })
<ide> info.Seccomp = seccompEnabled
<del> return warnings
<ide> }
<ide>
<ide> func cgroupEnabled(mountPoint, name string) bool { | 3 |
Text | Text | remove the @github handle as it generates emails | 6fe3da9924fc22bd02eba0803abb42b10fc28baf | <ide><path>CONTRIBUTING.md
<ide> e. I hereby grant to the Project, Docker, Inc and its successors; and recipient
<ide>
<ide> then you just add a line saying
<ide>
<del> Docker-DCO-1.0-Signed-off-by: Joe Smith <joe.smith@email.com> @github_handle
<add> Docker-DCO-1.0-Signed-off-by: Joe Smith <joe.smith@email.com> (github: github_handle)
<ide>
<ide> using your real name (sorry, no pseudonyms or anonymous contributions.)
<ide> | 1 |
Java | Java | improve check for actual return value type | 03eb6f76db2208e4283027fba338fe8da9dd755a | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageWriterResultHandler.java
<ide> protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParame
<ide> }
<ide> else {
<ide> publisher = Mono.justOrEmpty(body);
<del> elementType = (bodyClass == null && body != null ? ResolvableType.forInstance(body) : bodyType);
<add> elementType = ((bodyClass == null || bodyClass.equals(Object.class)) && body != null ?
<add> ResolvableType.forInstance(body) : bodyType);
<ide> }
<ide>
<ide> if (void.class == elementType.getRawClass() || Void.class == elementType.getRawClass()) { | 1 |
PHP | PHP | fix default null not being reflected by sqlserver | 729ef8fe58b98a0b0ab96ae25b7aa55b061f2516 | <ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php
<ide> public function describe($model) {
<ide> $fields[$field] = array(
<ide> 'type' => $this->column($column),
<ide> 'null' => ($column->Null === 'YES' ? true : false),
<del> 'default' => preg_replace("/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/", "$1", $column->Default),
<add> 'default' => $column->Default,
<ide> 'length' => $this->length($column),
<ide> 'key' => ($column->Key == '1') ? 'primary' : false
<ide> );
<ide>
<ide> if ($fields[$field]['default'] === 'null') {
<ide> $fields[$field]['default'] = null;
<del> } else {
<add> }
<add> if ($fields[$field]['default'] !== null) {
<add> $fields[$field]['default'] = preg_replace(
<add> "/^[(]{1,2}'?([^')]*)?'?[)]{1,2}$/",
<add> "$1",
<add> $fields[$field]['default']
<add> );
<ide> $this->value($fields[$field]['default'], $fields[$field]['type']);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php
<ide> public function testDescribe() {
<ide> 'Length' => 72,
<ide> 'Null' => 'NO',
<ide> 'Size' => ''
<del> )
<add> ),
<add> (object)array(
<add> 'Default' => null,
<add> 'Field' => 'parent_id',
<add> 'Key' => '0',
<add> 'Type' => 'bigint',
<add> 'Length' => 8,
<add> 'Null' => 'YES',
<add> 'Size' => '0',
<add> ),
<ide> ));
<ide> $this->db->executeResultsStack = array($SqlserverTableDescription);
<ide> $dummyModel = $this->model;
<ide> public function testDescribe() {
<ide> 'default' => '',
<ide> 'length' => 36,
<ide> 'key' => 'primary'
<del> )
<add> ),
<add> 'parent_id' => array(
<add> 'type' => 'biginteger',
<add> 'null' => true,
<add> 'default' => null,
<add> 'length' => 8,
<add> ),
<ide> );
<ide> $this->assertEquals($expected, $result);
<add> $this->assertSame($expected['parent_id'], $result['parent_id']);
<ide> }
<ide>
<ide> /** | 2 |
Python | Python | point users of np.outer to np.multiply.outer | e66453568b685dee47d6e6e634b3a47edffcaeed | <ide><path>numpy/core/_add_newdocs.py
<ide> """))
<ide>
<ide> add_newdoc('numpy.core', 'ufunc', ('outer',
<del> """
<add> r"""
<ide> outer(A, B, **kwargs)
<ide>
<ide> Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.
<ide>
<ide> See Also
<ide> --------
<del> numpy.outer
<add> numpy.outer : A less powerful version of ``np.multiply.outer``
<add> that `ravel`\ s all inputs to 1D. This exists
<add> primarily for compatibility with old code.
<add>
<add> tensordot : ``np.tensordot(a, b, axes=((), ()))`` and
<add> ``np.multiply.outer(a, b)`` behave same for all
<add> dimensions of a and b.
<ide>
<ide> Examples
<ide> --------
<ide><path>numpy/core/numeric.py
<ide> def outer(a, b, out=None):
<ide> --------
<ide> inner
<ide> einsum : ``einsum('i,j->ij', a.ravel(), b.ravel())`` is the equivalent.
<del> ufunc.outer : A generalization to N dimensions and other operations.
<del> ``np.multiply.outer(a.ravel(), b.ravel())`` is the equivalent.
<add> ufunc.outer : A generalization to dimensions other than 1D and other
<add> operations. ``np.multiply.outer(a.ravel(), b.ravel())``
<add> is the equivalent.
<add> tensordot : ``np.tensordot(a.ravel(), b.ravel(), axes=((), ()))``
<add> is the equivalent.
<ide>
<ide> References
<ide> ---------- | 2 |
Ruby | Ruby | ignore psqlrc files when executing psql commands | 69e0e0acf9a286a41f1adaae8e3e04b3a34101a1 | <ide><path>activejob/test/support/integration/adapters/que.rb
<ide> def start_workers
<ide> user = uri.user || ENV["USER"]
<ide> pass = uri.password
<ide> db = uri.path[1..-1]
<del> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'drop database if exists "#{db}"' -U #{user} -t template1}
<del> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
<add> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -X -c 'drop database if exists "#{db}"' -U #{user} -t template1}
<add> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -X -c 'create database "#{db}"' -U #{user} -t template1}
<ide> Que.connection = Sequel.connect(que_url)
<ide> Que.migrate!
<ide>
<ide><path>activejob/test/support/integration/adapters/queue_classic.rb
<ide> def start_workers
<ide> user = uri.user || ENV["USER"]
<ide> pass = uri.password
<ide> db = uri.path[1..-1]
<del> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'drop database if exists "#{db}"' -U #{user} -t template1}
<del> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
<add> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -X -c 'drop database if exists "#{db}"' -U #{user} -t template1}
<add> %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -X -c 'create database "#{db}"' -U #{user} -t template1}
<ide> QC::Setup.create
<ide>
<ide> QC.default_conn_adapter.disconnect
<ide><path>activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
<ide> def structure_dump(filename, extra_flags)
<ide> ActiveRecord::Base.dump_schemas
<ide> end
<ide>
<del> args = ["-s", "-x", "-O", "-f", filename]
<add> args = ["-s", "-X", "-x", "-O", "-f", filename]
<ide> args.concat(Array(extra_flags)) if extra_flags
<ide> unless search_path.blank?
<ide> args += search_path.split(",").map do |part|
<ide><path>activerecord/test/cases/tasks/postgresql_rake_test.rb
<ide> def test_structure_dump
<ide> assert_called_with(
<ide> Kernel,
<ide> :system,
<del> ["pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db"],
<add> ["pg_dump", "-s", "-X", "-x", "-O", "-f", @filename, "my-app-db"],
<ide> returns: true
<ide> ) do
<ide> ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename)
<ide> def test_structure_dump_header_comments_removed
<ide> end
<ide>
<ide> def test_structure_dump_with_extra_flags
<del> expected_command = ["pg_dump", "-s", "-x", "-O", "-f", @filename, "--noop", "my-app-db"]
<add> expected_command = ["pg_dump", "-s", "-X", "-x", "-O", "-f", @filename, "--noop", "my-app-db"]
<ide>
<ide> assert_called_with(Kernel, :system, expected_command, returns: true) do
<ide> with_structure_dump_flags(["--noop"]) do
<ide> def test_structure_dump_with_ignore_tables
<ide> assert_called_with(
<ide> Kernel,
<ide> :system,
<del> ["pg_dump", "-s", "-x", "-O", "-f", @filename, "-T", "foo", "-T", "bar", "my-app-db"],
<add> ["pg_dump", "-s", "-X", "-x", "-O", "-f", @filename, "-T", "foo", "-T", "bar", "my-app-db"],
<ide> returns: true
<ide> ) do
<ide> ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename)
<ide> def test_structure_dump_with_schema_search_path
<ide> assert_called_with(
<ide> Kernel,
<ide> :system,
<del> ["pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db"],
<add> ["pg_dump", "-s", "-X", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db"],
<ide> returns: true
<ide> ) do
<ide> ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename)
<ide> def test_structure_dump_with_schema_search_path_and_dump_schemas_all
<ide> assert_called_with(
<ide> Kernel,
<ide> :system,
<del> ["pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db"],
<add> ["pg_dump", "-s", "-X", "-x", "-O", "-f", @filename, "my-app-db"],
<ide> returns: true
<ide> ) do
<ide> with_dump_schemas(:all) do
<ide> def test_structure_dump_with_dump_schemas_string
<ide> assert_called_with(
<ide> Kernel,
<ide> :system,
<del> ["pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db"],
<add> ["pg_dump", "-s", "-X", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db"],
<ide> returns: true
<ide> ) do
<ide> with_dump_schemas("foo,bar") do
<ide> def test_structure_dump_execution_fails
<ide> assert_called_with(
<ide> Kernel,
<ide> :system,
<del> ["pg_dump", "-s", "-x", "-O", "-f", filename, "my-app-db"],
<add> ["pg_dump", "-s", "-X", "-x", "-O", "-f", filename, "my-app-db"],
<ide> returns: nil
<ide> ) do
<ide> e = assert_raise(RuntimeError) do | 4 |
PHP | PHP | check parameter count | d1275cb6c95cec22e7d9009bba26eb8eb845a75f | <ide><path>src/Illuminate/Routing/Route.php
<ide> public function bindParameters(Request $request)
<ide> */
<ide> protected function combineMatchesWithKeys(array $matches)
<ide> {
<add> if (count($this->parameterNames()) == 0) return array();
<add>
<ide> return array_combine($this->parameterNames(), $this->padMatches($matches));
<ide> }
<ide> | 1 |
Javascript | Javascript | add support for aborting via timeout promises | 9f4f5937112655a9881d3281da8e72035bc8b180 | <ide><path>src/ng/http.js
<ide> function $HttpProvider() {
<ide> * GET request, otherwise if a cache instance built with
<ide> * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
<ide> * caching.
<del> * - **timeout** – `{number}` – timeout in milliseconds.
<add> * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
<add> * that should abort the request when resolved.
<ide> * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
<ide> * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
<ide> * requests with credentials} for more information.
<ide> function $HttpProvider() {
<ide> }
<ide>
<ide> resolvePromise(response, status, headersString);
<del> $rootScope.$apply();
<add> if (!$rootScope.$$phase) $rootScope.$apply();
<ide> }
<ide>
<ide>
<ide><path>src/ng/httpBackend.js
<ide> function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument,
<ide> }
<ide>
<ide> if (timeout > 0) {
<del> var timeoutId = $browserDefer(function() {
<del> status = -1;
<del> jsonpDone && jsonpDone();
<del> xhr && xhr.abort();
<del> }, timeout);
<add> var timeoutId = $browserDefer(timeoutRequest, timeout);
<add> } else if (timeout && timeout.then) {
<add> timeout.then(timeoutRequest);
<ide> }
<ide>
<ide>
<add> function timeoutRequest() {
<add> status = -1;
<add> jsonpDone && jsonpDone();
<add> xhr && xhr.abort();
<add> }
<add>
<ide> function completeRequest(callback, status, response, headersString) {
<ide> // URL_MATCH is defined in src/service/location.js
<ide> var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1];
<ide>
<del> // cancel timeout
<add> // cancel timeout and subsequent timeout promise resolution
<ide> timeoutId && $browserDefer.cancel(timeoutId);
<add> jsonpDone = xhr = null;
<ide>
<ide> // fix status code for file protocol (it's always 0)
<ide> status = (protocol == 'file') ? (response ? 200 : 404) : status;
<ide><path>src/ngMock/angular-mocks.js
<ide> function createHttpBackendMock($rootScope, $delegate, $browser) {
<ide> }
<ide>
<ide> // TODO(vojta): change params to: method, url, data, headers, callback
<del> function $httpBackend(method, url, data, callback, headers) {
<add> function $httpBackend(method, url, data, callback, headers, timeout) {
<ide> var xhr = new MockXhr(),
<ide> expectation = expectations[0],
<ide> wasExpected = false;
<ide> function createHttpBackendMock($rootScope, $delegate, $browser) {
<ide> : angular.toJson(data);
<ide> }
<ide>
<add> function wrapResponse(wrapped) {
<add> if (!$browser && timeout && timeout.then) timeout.then(handleTimeout);
<add>
<add> return handleResponse;
<add>
<add> function handleResponse() {
<add> var response = wrapped.response(method, url, data, headers);
<add> xhr.$$respHeaders = response[2];
<add> callback(response[0], response[1], xhr.getAllResponseHeaders());
<add> }
<add>
<add> function handleTimeout() {
<add> for (var i = 0, ii = responses.length; i < ii; i++) {
<add> if (responses[i] === handleResponse) {
<add> responses.splice(i, 1);
<add> callback(-1, undefined, '');
<add> break;
<add> }
<add> }
<add> }
<add> }
<add>
<ide> if (expectation && expectation.match(method, url)) {
<ide> if (!expectation.matchData(data))
<ide> throw Error('Expected ' + expectation + ' with different data\n' +
<ide> function createHttpBackendMock($rootScope, $delegate, $browser) {
<ide> expectations.shift();
<ide>
<ide> if (expectation.response) {
<del> responses.push(function() {
<del> var response = expectation.response(method, url, data, headers);
<del> xhr.$$respHeaders = response[2];
<del> callback(response[0], response[1], xhr.getAllResponseHeaders());
<del> });
<add> responses.push(wrapResponse(expectation));
<ide> return;
<ide> }
<ide> wasExpected = true;
<ide> function createHttpBackendMock($rootScope, $delegate, $browser) {
<ide> if (definition.match(method, url, data, headers || {})) {
<ide> if (definition.response) {
<ide> // if $browser specified, we do auto flush all requests
<del> ($browser ? $browser.defer : responsesPush)(function() {
<del> var response = definition.response(method, url, data, headers);
<del> xhr.$$respHeaders = response[2];
<del> callback(response[0], response[1], xhr.getAllResponseHeaders());
<del> });
<add> ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));
<ide> } else if (definition.passThrough) {
<del> $delegate(method, url, data, callback, headers);
<add> $delegate(method, url, data, callback, headers, timeout);
<ide> } else throw Error('No response defined !');
<ide> return;
<ide> }
<ide><path>src/ngResource/resource.js
<ide> * GET request, otherwise if a cache instance built with
<ide> * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
<ide> * caching.
<del> * - **`timeout`** – `{number}` – timeout in milliseconds.
<add> * - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that
<add> * should abort the request when resolved.
<ide> * - **`withCredentials`** - `{boolean}` - whether to to set the `withCredentials` flag on the
<ide> * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
<ide> * requests with credentials} for more information.
<ide><path>test/ng/httpBackendSpec.js
<ide> describe('$httpBackend', function() {
<ide> });
<ide>
<ide>
<add> it('should abort request on timeout promise resolution', inject(function($timeout) {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(-1);
<add> });
<add>
<add> $backend('GET', '/url', null, callback, {}, $timeout(noop, 2000));
<add> xhr = MockXhr.$$lastInstance;
<add> spyOn(xhr, 'abort');
<add>
<add> $timeout.flush();
<add> expect(xhr.abort).toHaveBeenCalledOnce();
<add>
<add> xhr.status = 0;
<add> xhr.readyState = 4;
<add> xhr.onreadystatechange();
<add> expect(callback).toHaveBeenCalledOnce();
<add> }));
<add>
<add>
<add> it('should not abort resolved request on timeout promise resolution', inject(function($timeout) {
<add> callback.andCallFake(function(status, response) {
<add> expect(status).toBe(200);
<add> });
<add>
<add> $backend('GET', '/url', null, callback, {}, $timeout(noop, 2000));
<add> xhr = MockXhr.$$lastInstance;
<add> spyOn(xhr, 'abort');
<add>
<add> xhr.status = 200;
<add> xhr.readyState = 4;
<add> xhr.onreadystatechange();
<add> expect(callback).toHaveBeenCalledOnce();
<add>
<add> $timeout.flush();
<add> expect(xhr.abort).not.toHaveBeenCalled();
<add> }));
<add>
<add>
<ide> it('should cancel timeout on completion', function() {
<ide> callback.andCallFake(function(status, response) {
<ide> expect(status).toBe(200);
<ide><path>test/ng/httpSpec.js
<ide> describe('$http', function() {
<ide> });
<ide>
<ide>
<add> describe('timeout', function() {
<add>
<add> it('should abort requests when timeout promise resolves', inject(function($q) {
<add> var canceler = $q.defer();
<add>
<add> $httpBackend.expect('GET', '/some').respond(200);
<add>
<add> $http({method: 'GET', url: '/some', timeout: canceler.promise}).error(
<add> function(data, status, headers, config) {
<add> expect(data).toBeUndefined();
<add> expect(status).toBe(0);
<add> expect(headers()).toEqual({});
<add> expect(config.url).toBe('/some');
<add> callback();
<add> });
<add>
<add> $rootScope.$apply(function() {
<add> canceler.resolve();
<add> });
<add>
<add> expect(callback).toHaveBeenCalled();
<add> $httpBackend.verifyNoOutstandingExpectation();
<add> $httpBackend.verifyNoOutstandingRequest();
<add> }));
<add> });
<add>
<add>
<ide> describe('pendingRequests', function() {
<ide>
<ide> it('should be an array of pending requests', function() {
<ide><path>test/ngMock/angular-mocksSpec.js
<ide> describe('ngMock', function() {
<ide> });
<ide>
<ide>
<add> it('should abort requests when timeout promise resolves', function() {
<add> hb.expect('GET', '/url1').respond(200);
<add>
<add> var canceler, then = jasmine.createSpy('then').andCallFake(function(fn) {
<add> canceler = fn;
<add> });
<add>
<add> hb('GET', '/url1', null, callback, null, {then: then});
<add> expect(typeof canceler).toBe('function');
<add>
<add> canceler(); // simulate promise resolution
<add>
<add> expect(callback).toHaveBeenCalledWith(-1, undefined, '');
<add> hb.verifyNoOutstandingExpectation();
<add> hb.verifyNoOutstandingRequest();
<add> });
<add>
<add>
<ide> it('should throw an exception if no response defined', function() {
<ide> hb.when('GET', '/test');
<ide> expect(function() {
<ide> describe('ngMockE2E', function() {
<ide> hb.when('GET', /\/passThrough\/.*/).passThrough();
<ide> hb('GET', '/passThrough/23', null, callback);
<ide>
<del> expect(realHttpBackend).
<del> toHaveBeenCalledOnceWith('GET', '/passThrough/23', null, callback, undefined);
<add> expect(realHttpBackend).toHaveBeenCalledOnceWith(
<add> 'GET', '/passThrough/23', null, callback, undefined, undefined);
<ide> });
<ide> });
<ide> | 7 |
PHP | PHP | remove @access and unnecessary $name | a643295e4c48681d26d775d6f50a395e194eaf04 | <ide><path>lib/Cake/Console/Command/TestShell.php
<ide> public function available() {
<ide> * @param string $file
<ide> * @param string $category
<ide> * @param boolean $throwOnMissingFile
<del> * @access protected
<ide> * @return array array(type, case)
<ide> * @throws Exception
<ide> */
<ide> protected function _mapFileToCase($file, $category, $throwOnMissingFile = true)
<ide> * For the given file, what category of test is it? returns app, core or the name of the plugin
<ide> *
<ide> * @param string $file
<del> * @access protected
<ide> * @return string
<ide> */
<ide> protected function _mapFileToCategory($file) {
<ide><path>lib/Cake/Model/Datasource/DataSource.php
<ide> public function resolveKey(Model $model, $key) {
<ide> * Returns the schema name. Override this in subclasses.
<ide> *
<ide> * @return string schema name
<del> * @access public
<ide> */
<ide> public function getSchemaName() {
<ide> return null;
<ide> public function getSchemaName() {
<ide> * Closes a connection. Override in subclasses
<ide> *
<ide> * @return boolean
<del> * @access public
<ide> */
<ide> public function close() {
<ide> return $this->connected = false;
<ide><path>lib/Cake/Model/Model.php
<ide> class Model extends Object implements CakeEventListener {
<ide> * Holds physical schema/database name for this model. Automatically set during Model creation.
<ide> *
<ide> * @var string
<del> * @access public
<ide> */
<ide> public $schemaName = null;
<ide>
<ide><path>lib/Cake/Test/Case/Core/ObjectTest.php
<ide> class RequestActionController extends Controller {
<ide> * uses property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $uses = array('RequestActionPost');
<ide>
<ide> /**
<ide> * test_request_action method
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function test_request_action() {
<ide> public function test_request_action() {
<ide> *
<ide> * @param mixed $id
<ide> * @param mixed $other
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function another_ra_test($id, $other) {
<ide><path>lib/Cake/Test/Case/Model/CakeSchemaTest.php
<ide> public function testSchemaRead() {
<ide> /**
<ide> * testSchemaReadWithAppModel method
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testSchemaReadWithAppModel() {
<ide><path>lib/Cake/Test/Case/Model/ModelIntegrationTest.php
<ide> public function testDynamicBehaviorAttachment() {
<ide> /**
<ide> * testFindWithJoinsOption method
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testFindWithJoinsOption() {
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testInsertNoData() {
<ide> /**
<ide> * testInsertAnotherHabtmRecordWithSameForeignKey method
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testInsertAnotherHabtmRecordWithSameForeignKey() {
<ide> public function testSaveWithCounterCacheScope() {
<ide> /**
<ide> * Tests having multiple counter caches for an associated model
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testCounterCacheMultipleCaches() {
<ide><path>lib/Cake/Test/Case/TestSuite/ControllerTestCaseTest.php
<ide> class AppController extends Controller {
<ide> * helpers property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $helpers = array('Html');
<ide>
<ide> /**
<ide> * uses property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $uses = array('ControllerPost');
<ide>
<ide> /**
<ide> * components property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $components = array('Cookie');
<ide>
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testTextFieldGenerationForFloats() {
<ide> /**
<ide> * Tests correct generation of number fields for integer fields
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testTextFieldTypeNumberGenerationForIntegers() {
<ide> public function testPasswordValidation() {
<ide> /**
<ide> * Test validation errors, when validation message is an empty string.
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testEmptyErrorValidation() {
<ide> public function testEmptyErrorValidation() {
<ide> /**
<ide> * Test validation errors, when calling input() overriding validation message by an empty string.
<ide> *
<del> * @access public
<ide> * @return void
<ide> */
<ide> public function testEmptyInputErrorValidation() {
<ide><path>lib/Cake/Test/Fixture/AccountFixture.php
<ide> */
<ide> class AccountFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Aco'
<del> */
<del> public $name = 'Account';
<del>
<ide> public $table = 'Accounts';
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Fixture/AcoActionFixture.php
<ide> */
<ide> class AcoActionFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AcoAction'
<del> */
<del> public $name = 'AcoAction';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AcoFixture.php
<ide> */
<ide> class AcoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Aco'
<del> */
<del> public $name = 'Aco';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AcoTwoFixture.php
<ide> */
<ide> class AcoTwoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AcoTwo'
<del> */
<del> public $name = 'AcoTwo';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AdFixture.php
<ide> */
<ide> class AdFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Ad'
<del> */
<del> public $name = 'Ad';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AdvertisementFixture.php
<ide> */
<ide> class AdvertisementFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Advertisement'
<del> */
<del> public $name = 'Advertisement';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AfterTreeFixture.php
<ide> */
<ide> class AfterTreeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AfterTree'
<del> */
<del> public $name = 'AfterTree';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AnotherArticleFixture.php
<ide> */
<ide> class AnotherArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AnotherArticle'
<del> */
<del> public $name = 'AnotherArticle';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AppleFixture.php
<ide> */
<ide> class AppleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Apple'
<del> */
<del> public $name = 'Apple';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArmorFixture.php
<ide> */
<ide> class ArmorFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Armor'
<del> */
<del> public $name = 'Armor';
<del>
<ide> /**
<ide> * Datasource
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArmorsPlayerFixture.php
<ide> */
<ide> class ArmorsPlayerFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArmorsPlayer'
<del> */
<del> public $name = 'ArmorsPlayer';
<del>
<ide> /**
<ide> * Datasource
<ide> *
<ide><path>lib/Cake/Test/Fixture/AroFixture.php
<ide> */
<ide> class AroFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Aro'
<del> */
<del> public $name = 'Aro';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AroTwoFixture.php
<ide> */
<ide> class AroTwoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AroTwo'
<del> */
<del> public $name = 'AroTwo';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArosAcoFixture.php
<ide> */
<ide> class ArosAcoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArosAco'
<del> */
<del> public $name = 'ArosAco';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArosAcoTwoFixture.php
<ide> */
<ide> class ArosAcoTwoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArosAcoTwo'
<del> */
<del> public $name = 'ArosAcoTwo';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArticleFeaturedFixture.php
<ide> */
<ide> class ArticleFeaturedFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArticleFeatured'
<del> */
<del> public $name = 'ArticleFeatured';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArticleFeaturedsTagsFixture.php
<ide> */
<ide> class ArticleFeaturedsTagsFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArticleFeaturedsTags'
<del> */
<del> public $name = 'ArticleFeaturedsTags';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArticleFixture.php
<ide> */
<ide> class ArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Article'
<del> */
<del> public $name = 'Article';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ArticlesTagFixture.php
<ide> */
<ide> class ArticlesTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArticlesTag'
<del> */
<del> public $name = 'ArticlesTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AttachmentFixture.php
<ide> */
<ide> class AttachmentFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Attachment'
<del> */
<del> public $name = 'Attachment';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AuthUserCustomFieldFixture.php
<ide> */
<ide> class AuthUserCustomFieldFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AuthUser'
<del> */
<del> public $name = 'AuthUserCustomField';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AuthUserFixture.php
<ide> */
<ide> class AuthUserFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'AuthUser'
<del> */
<del> public $name = 'AuthUser';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/AuthorFixture.php
<ide> */
<ide> class AuthorFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Author'
<del> */
<del> public $name = 'Author';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BakeArticleFixture.php
<ide> */
<ide> class BakeArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string
<del> */
<del> public $name = 'BakeArticle';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BakeArticlesBakeTagFixture.php
<ide> */
<ide> class BakeArticlesBakeTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ArticlesTag'
<del> */
<del> public $name = 'BakeArticlesBakeTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BakeCommentFixture.php
<ide> */
<ide> class BakeCommentFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Comment'
<del> */
<del> public $name = 'BakeComment';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BakeTagFixture.php
<ide> */
<ide> class BakeTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Tag'
<del> */
<del> public $name = 'BakeTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BasketFixture.php
<ide> */
<ide> class BasketFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Basket'
<del> */
<del> public $name = 'Basket';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BidFixture.php
<ide> */
<ide> class BidFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Bid'
<del> */
<del> public $name = 'Bid';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BiddingFixture.php
<ide> */
<ide> class BiddingFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Bidding'
<del> */
<del> public $name = 'Bidding';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BiddingMessageFixture.php
<ide> */
<ide> class BiddingMessageFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'BiddingMessage'
<del> */
<del> public $name = 'BiddingMessage';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BinaryTestFixture.php
<ide> */
<ide> class BinaryTestFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'BinaryTest'
<del> */
<del> public $name = 'BinaryTest';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/BookFixture.php
<ide> */
<ide> class BookFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Book'
<del> */
<del> public $name = 'Book';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CacheTestModelFixture.php
<ide> */
<ide> class CacheTestModelFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'CacheTestModel'
<del> */
<del> public $name = 'CacheTestModel';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CakeSessionFixture.php
<ide> */
<ide> class CakeSessionFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string
<del> */
<del> public $name = 'CakeSession';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CallbackFixture.php
<ide> */
<ide> class CallbackFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Callback'
<del> */
<del> public $name = 'Callback';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CampaignFixture.php
<ide> */
<ide> class CampaignFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Campaign'
<del> */
<del> public $name = 'Campaign';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CategoryFixture.php
<ide> */
<ide> class CategoryFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Category'
<del> */
<del> public $name = 'Category';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CategoryThreadFixture.php
<ide> */
<ide> class CategoryThreadFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'CategoryThread'
<del> */
<del> public $name = 'CategoryThread';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CdFixture.php
<ide> */
<ide> class CdFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Cd'
<del> */
<del> public $name = 'Cd';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/CommentFixture.php
<ide> */
<ide> class CommentFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Comment'
<del> */
<del> public $name = 'Comment';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ContentAccountFixture.php
<ide> */
<ide> class ContentAccountFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Aco'
<del> */
<del> public $name = 'ContentAccount';
<del>
<ide> public $table = 'ContentAccounts';
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Fixture/ContentFixture.php
<ide> */
<ide> class ContentFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Aco'
<del> */
<del> public $name = 'Content';
<del>
<ide> public $table = 'Content';
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Fixture/CounterCachePostFixture.php
<ide> */
<ide> class CounterCachePostFixture extends CakeTestFixture {
<ide>
<del> public $name = 'CounterCachePost';
<del>
<ide> public $fields = array(
<ide> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> 'title' => array('type' => 'string', 'length' => 255),
<ide><path>lib/Cake/Test/Fixture/CounterCachePostNonstandardPrimaryKeyFixture.php
<ide> */
<ide> class CounterCachePostNonstandardPrimaryKeyFixture extends CakeTestFixture {
<ide>
<del> public $name = 'CounterCachePostNonstandardPrimaryKey';
<del>
<ide> public $fields = array(
<ide> 'pid' => array('type' => 'integer', 'key' => 'primary'),
<ide> 'title' => array('type' => 'string', 'length' => 255, 'null' => false),
<ide><path>lib/Cake/Test/Fixture/CounterCacheUserFixture.php
<ide> */
<ide> class CounterCacheUserFixture extends CakeTestFixture {
<ide>
<del> public $name = 'CounterCacheUser';
<del>
<ide> public $fields = array(
<ide> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> 'name' => array('type' => 'string', 'length' => 255, 'null' => false),
<ide><path>lib/Cake/Test/Fixture/CounterCacheUserNonstandardPrimaryKeyFixture.php
<ide> */
<ide> class CounterCacheUserNonstandardPrimaryKeyFixture extends CakeTestFixture {
<ide>
<del> public $name = 'CounterCacheUserNonstandardPrimaryKey';
<del>
<ide> public $fields = array(
<ide> 'uid' => array('type' => 'integer', 'key' => 'primary'),
<ide> 'name' => array('type' => 'string', 'length' => 255, 'null' => false),
<ide><path>lib/Cake/Test/Fixture/DataTestFixture.php
<ide> */
<ide> class DataTestFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * Name property
<del> *
<del> * @var string 'DataTest'
<del> */
<del> public $name = 'DataTest';
<del>
<ide> /**
<ide> * Fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DatatypeFixture.php
<ide> */
<ide> class DatatypeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * Name property
<del> *
<del> * @var string 'Datatype'
<del> */
<del> public $name = 'Datatype';
<del>
<ide> /**
<ide> * Fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DependencyFixture.php
<ide> */
<ide> class DependencyFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Dependency'
<del> */
<del> public $name = 'Dependency';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DeviceFixture.php
<ide> */
<ide> class DeviceFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Device'
<del> */
<del> public $name = 'Device';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DeviceTypeCategoryFixture.php
<ide> */
<ide> class DeviceTypeCategoryFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'DeviceTypeCategory'
<del> */
<del> public $name = 'DeviceTypeCategory';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DeviceTypeFixture.php
<ide> */
<ide> class DeviceTypeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'DeviceType'
<del> */
<del> public $name = 'DeviceType';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DocumentDirectoryFixture.php
<ide> */
<ide> class DocumentDirectoryFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'DocumentDirectory'
<del> */
<del> public $name = 'DocumentDirectory';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DocumentFixture.php
<ide> */
<ide> class DocumentFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Document'
<del> */
<del> public $name = 'Document';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/DomainFixture.php
<ide> */
<ide> class DomainFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Domain'
<del> * @access public
<del> */
<del> public $name = 'Domain';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $fields = array(
<ide> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> class DomainFixture extends CakeTestFixture {
<ide> * records property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $records = array(
<ide> array('domain' => 'cakephp.org', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'),
<ide><path>lib/Cake/Test/Fixture/DomainsSiteFixture.php
<ide> */
<ide> class DomainsSiteFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Domain'
<del> * @access public
<del> */
<del> public $name = 'DomainsSite';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $fields = array(
<ide> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> class DomainsSiteFixture extends CakeTestFixture {
<ide> * records property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $records = array(
<ide> array('site_id' => 1, 'domain_id' => 1, 'active' => true, 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'),
<ide><path>lib/Cake/Test/Fixture/ExteriorTypeCategoryFixture.php
<ide> */
<ide> class ExteriorTypeCategoryFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ExteriorTypeCategory'
<del> */
<del> public $name = 'ExteriorTypeCategory';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/FeatureSetFixture.php
<ide> */
<ide> class FeatureSetFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'FeatureSet'
<del> */
<del> public $name = 'FeatureSet';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/FeaturedFixture.php
<ide> */
<ide> class FeaturedFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Featured'
<del> */
<del> public $name = 'Featured';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/FilmFileFixture.php
<ide> */
<ide> class FilmFileFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'FilmFile'
<del> */
<del> public $name = 'FilmFile';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/FlagTreeFixture.php
<ide> */
<ide> class FlagTreeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'FlagTree'
<del> */
<del> public $name = 'FlagTree';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/FruitFixture.php
<ide> */
<ide> class FruitFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Fruit'
<del> */
<del> public $name = 'Fruit';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/FruitsUuidTagFixture.php
<ide> */
<ide> class FruitsUuidTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'FruitsUuidTag'
<del> */
<del> public $name = 'FruitsUuidTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/GroupUpdateAllFixture.php
<ide> */
<ide> class GroupUpdateAllFixture extends CakeTestFixture {
<ide>
<del> public $name = 'GroupUpdateAll';
<del>
<ide> public $table = 'group_update_all';
<ide>
<ide> public $fields = array(
<ide><path>lib/Cake/Test/Fixture/GuildFixture.php
<ide> */
<ide> class GuildFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Guild'
<del> */
<del> public $name = 'Guild';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/GuildsPlayerFixture.php
<ide> */
<ide> class GuildsPlayerFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'GuildsPlayer'
<del> */
<del> public $name = 'GuildsPlayer';
<del>
<ide> public $useDbConfig = 'test2';
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Fixture/HomeFixture.php
<ide> */
<ide> class HomeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Home'
<del> */
<del> public $name = 'Home';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ImageFixture.php
<ide> */
<ide> class ImageFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Image'
<del> */
<del> public $name = 'Image';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/InnoFixture.php
<ide> */
<ide> class InnoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Article'
<del> */
<del> public $name = 'Inno';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ItemFixture.php
<ide> */
<ide> class ItemFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Item'
<del> */
<del> public $name = 'Item';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ItemsPortfolioFixture.php
<ide> */
<ide> class ItemsPortfolioFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ItemsPortfolio'
<del> */
<del> public $name = 'ItemsPortfolio';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/JoinAFixture.php
<ide> */
<ide> class JoinAFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'JoinA'
<del> */
<del> public $name = 'JoinA';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/JoinBFixture.php
<ide> */
<ide> class JoinBFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'JoinB'
<del> */
<del> public $name = 'JoinB';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/JoinCFixture.php
<ide> */
<ide> class JoinCFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'JoinC'
<del> */
<del> public $name = 'JoinC';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/JoinThingFixture.php
<ide> */
<ide> class JoinThingFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'JoinThing'
<del> */
<del> public $name = 'JoinThing';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/MessageFixture.php
<ide> */
<ide> class MessageFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Message'
<del> */
<del> public $name = 'Message';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/MyCategoriesMyProductsFixture.php
<ide> */
<ide> class MyCategoriesMyProductsFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'MyCategoriesMyProducts'
<del> */
<del> public $name = 'MyCategoriesMyProducts';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/MyCategoriesMyUsersFixture.php
<ide> */
<ide> class MyCategoriesMyUsersFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'MyCategoriesMyUsers'
<del> */
<del> public $name = 'MyCategoriesMyUsers';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/MyCategoryFixture.php
<ide> */
<ide> class MyCategoryFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'MyCategory'
<del> */
<del> public $name = 'MyCategory';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/MyProductFixture.php
<ide> */
<ide> class MyProductFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'MyProduct'
<del> */
<del> public $name = 'MyProduct';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/MyUserFixture.php
<ide> */
<ide> class MyUserFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'MyUser'
<del> */
<del> public $name = 'MyUser';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/NodeFixture.php
<ide> */
<ide> class NodeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Node'
<del> */
<del> public $name = 'Node';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/NumberTreeFixture.php
<ide> */
<ide> class NumberTreeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'NumberTree'
<del> */
<del> public $name = 'NumberTree';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/NumberTreeTwoFixture.php
<ide> */
<ide> class NumberTreeTwoFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'NumberTree'
<del> */
<del> public $name = 'NumberTreeTwo';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/NumericArticleFixture.php
<ide> */
<ide> class NumericArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'NumericArticle'
<del> */
<del> public $name = 'NumericArticle';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/OverallFavoriteFixture.php
<ide> */
<ide> class OverallFavoriteFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'OverallFavorite'
<del> */
<del> public $name = 'OverallFavorite';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/PersonFixture.php
<ide> */
<ide> class PersonFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Person'
<del> */
<del> public $name = 'Person';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/PlayerFixture.php
<ide> */
<ide> class PlayerFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Player'
<del> */
<del> public $name = 'Player';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/PortfolioFixture.php
<ide> */
<ide> class PortfolioFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Portfolio'
<del> */
<del> public $name = 'Portfolio';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/PostFixture.php
<ide> */
<ide> class PostFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Post'
<del> */
<del> public $name = 'Post';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/PostsTagFixture.php
<ide> */
<ide> class PostsTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'PostsTag'
<del> */
<del> public $name = 'PostsTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/PrefixTestFixture.php
<ide> */
<ide> class PrefixTestFixture extends CakeTestFixture {
<ide>
<del> public $name = 'PrefixTest';
<del>
<ide> public $table = 'prefix_prefix_tests';
<ide>
<ide> public $fields = array(
<ide><path>lib/Cake/Test/Fixture/PrimaryModelFixture.php
<ide> */
<ide> class PrimaryModelFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'PrimaryModel'
<del> */
<del> public $name = 'PrimaryModel';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ProductFixture.php
<ide> */
<ide> class ProductFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Product'
<del> */
<del> public $name = 'Product';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ProductUpdateAllFixture.php
<ide> */
<ide> class ProductUpdateAllFixture extends CakeTestFixture {
<ide>
<del> public $name = 'ProductUpdateAll';
<del>
<ide> public $table = 'product_update_all';
<ide>
<ide> public $fields = array(
<ide><path>lib/Cake/Test/Fixture/ProjectFixture.php
<ide> */
<ide> class ProjectFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Project'
<del> */
<del> public $name = 'Project';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/SampleFixture.php
<ide> */
<ide> class SampleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Sample'
<del> */
<del> public $name = 'Sample';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/SecondaryModelFixture.php
<ide> */
<ide> class SecondaryModelFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'SecondaryModel'
<del> */
<del> public $name = 'SecondaryModel';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/SessionFixture.php
<ide> */
<ide> class SessionFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Session'
<del> */
<del> public $name = 'Session';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/SiteFixture.php
<ide> */
<ide> class SiteFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Site'
<del> * @access public
<del> */
<del> public $name = 'Site';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $fields = array(
<ide> 'id' => array('type' => 'integer', 'key' => 'primary'),
<ide> class SiteFixture extends CakeTestFixture {
<ide> * records property
<ide> *
<ide> * @var array
<del> * @access public
<ide> */
<ide> public $records = array(
<ide> array('name' => 'cakephp', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31'),
<ide><path>lib/Cake/Test/Fixture/SomethingElseFixture.php
<ide> */
<ide> class SomethingElseFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'SomethingElse'
<del> */
<del> public $name = 'SomethingElse';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/SomethingFixture.php
<ide> */
<ide> class SomethingFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Something'
<del> */
<del> public $name = 'Something';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/StoriesTagFixture.php
<ide> */
<ide> class StoriesTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'StoriesTag'
<del> */
<del> public $name = 'StoriesTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/StoryFixture.php
<ide> */
<ide> class StoryFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Story'
<del> */
<del> public $name = 'Story';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/SyfileFixture.php
<ide> */
<ide> class SyfileFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Syfile'
<del> */
<del> public $name = 'Syfile';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TagFixture.php
<ide> */
<ide> class TagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Tag'
<del> */
<del> public $name = 'Tag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TestPluginArticleFixture.php
<ide> */
<ide> class TestPluginArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Article'
<del> */
<del> public $name = 'TestPluginArticle';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TestPluginCommentFixture.php
<ide> */
<ide> class TestPluginCommentFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Comment'
<del> */
<del> public $name = 'TestPluginComment';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ThePaperMonkiesFixture.php
<ide> */
<ide> class ThePaperMonkiesFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'ThePaperMonkies'
<del> */
<del> public $name = 'ThePaperMonkies';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/ThreadFixture.php
<ide> */
<ide> class ThreadFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Thread'
<del> */
<del> public $name = 'Thread';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TranslateArticleFixture.php
<ide> */
<ide> class TranslateArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Translate'
<del> */
<del> public $name = 'TranslateArticle';
<del>
<ide> /**
<ide> * table property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TranslateFixture.php
<ide> */
<ide> class TranslateFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Translate'
<del> */
<del> public $name = 'Translate';
<del>
<ide> /**
<ide> * table property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TranslateTableFixture.php
<ide> */
<ide> class TranslateTableFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'TranslateTable'
<del> */
<del> public $name = 'TranslateTable';
<del>
<ide> /**
<ide> * table property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TranslateWithPrefixFixture.php
<ide> */
<ide> class TranslateWithPrefixFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Translate'
<del> */
<del> public $name = 'TranslateWithPrefix';
<del>
<ide> /**
<ide> * table property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TranslatedArticleFixture.php
<ide> */
<ide> class TranslatedArticleFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'TranslatedItem'
<del> */
<del> public $name = 'TranslatedArticle';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/TranslatedItemFixture.php
<ide> */
<ide> class TranslatedItemFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'TranslatedItem'
<del> */
<del> public $name = 'TranslatedItem';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UnconventionalTreeFixture.php
<ide> */
<ide> class UnconventionalTreeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'FlagTree'
<del> */
<del> public $name = 'UnconventionalTree';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UnderscoreFieldFixture.php
<ide> */
<ide> class UnderscoreFieldFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'UnderscoreField'
<del> */
<del> public $name = 'UnderscoreField';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UserFixture.php
<ide> */
<ide> class UserFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'User'
<del> */
<del> public $name = 'User';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuidFixture.php
<ide> */
<ide> class UuidFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Uuid'
<del> */
<del> public $name = 'Uuid';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuidTagFixture.php
<ide> */
<ide> class UuidTagFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'UuidTag'
<del> */
<del> public $name = 'UuidTag';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuidTreeFixture.php
<ide> */
<ide> class UuidTreeFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'UuidTree'
<del> */
<del> public $name = 'UuidTree';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuiditemFixture.php
<ide> */
<ide> class UuiditemFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Uuiditem'
<del> */
<del> public $name = 'Uuiditem';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuiditemsUuidportfolioFixture.php
<ide> */
<ide> class UuiditemsUuidportfolioFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'UuiditemsUuidportfolio'
<del> */
<del> public $name = 'UuiditemsUuidportfolio';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuiditemsUuidportfolioNumericidFixture.php
<ide> */
<ide> class UuiditemsUuidportfolioNumericidFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'UuiditemsUuidportfolioNumericid'
<del> */
<del> public $name = 'UuiditemsUuidportfolioNumericid';
<del>
<ide> /**
<ide> * fields property
<ide> *
<ide><path>lib/Cake/Test/Fixture/UuidportfolioFixture.php
<ide> */
<ide> class UuidportfolioFixture extends CakeTestFixture {
<ide>
<del>/**
<del> * name property
<del> *
<del> * @var string 'Uuidportfolio'
<del> */
<del> public $name = 'Uuidportfolio';
<del>
<ide> /**
<ide> * fields property
<ide> * | 136 |
PHP | PHP | fix coding standards in core/ | 63c992a85b9d834e69be847852d9946b73827ea7 | <ide><path>lib/Cake/Core/App.php
<ide> public static function path($type, $plugin = null) {
<ide> if (!empty($plugin)) {
<ide> $path = array();
<ide> $pluginPath = self::pluginPath($plugin);
<del> $packageFormat= self::_packageFormat();
<add> $packageFormat = self::_packageFormat();
<ide> if (!empty($packageFormat[$type])) {
<ide> foreach ($packageFormat[$type] as $f) {
<ide> $path[] = sprintf($f, $pluginPath);
<ide> public static function themePath($theme) {
<ide> $themeDir = 'Themed' . DS . Inflector::camelize($theme);
<ide> foreach (self::$_packages['View'] as $path) {
<ide> if (is_dir($path . $themeDir)) {
<del> return $path . $themeDir . DS ;
<add> return $path . $themeDir . DS;
<ide> }
<ide> }
<ide> return self::$_packages['View'][0] . $themeDir . DS;
<ide> public static function objects($type, $path = null, $cache = true) {
<ide> foreach ($files as $file) {
<ide> $fileName = basename($file);
<ide> if (!$file->isDot() && $fileName[0] !== '.') {
<del> $isDir = $file->isDir() ;
<add> $isDir = $file->isDir();
<ide> if ($isDir && $includeDirectories) {
<ide> $objects[] = $fileName;
<ide> } elseif (!$includeDirectories && !$isDir) {
<ide> public static function load($className) {
<ide>
<ide> if (empty($plugin)) {
<ide> $appLibs = empty(self::$_packages['Lib']) ? APPLIBS : current(self::$_packages['Lib']);
<del> $paths[] = $appLibs . $package . DS;
<add> $paths[] = $appLibs . $package . DS;
<ide> $paths[] = APP . $package . DS;
<ide> $paths[] = CAKE . $package . DS;
<ide> } else {
<ide> protected static function _loadFile($name, $plugin, $search, $file, $return) {
<ide> if ($return) {
<ide> return $returnValue;
<ide> }
<del> return (bool) $returnValue;
<add> return (bool)$returnValue;
<ide> }
<ide> return false;
<ide> }
<ide> protected static function _loadFile($name, $plugin, $search, $file, $return) {
<ide> */
<ide> protected static function _loadVendor($name, $plugin, $file, $ext) {
<ide> if ($mapped = self::_mapped($name, $plugin)) {
<del> return (bool) include_once($mapped);
<add> return (bool)include_once $mapped;
<ide> }
<ide> $fileTries = array();
<ide> $paths = ($plugin) ? App::path('vendors', $plugin) : App::path('vendors');
<ide> protected static function _loadVendor($name, $plugin, $file, $ext) {
<ide> foreach ($paths as $path) {
<ide> if (file_exists($path . $file)) {
<ide> self::_map($path . $file, $name, $plugin);
<del> return (bool) include($path . $file);
<add> return (bool)include $path . $file;
<ide> }
<ide> }
<ide> }
<ide> public static function shutdown() {
<ide> Cache::write('object_map', self::$_objects, '_cake_core_');
<ide> }
<ide> }
<add>
<ide> }
<ide><path>lib/Cake/Core/CakePlugin.php
<ide> public static function loadAll($options = array()) {
<ide> if ($opts === null && isset($options[0])) {
<ide> $opts = $options[0];
<ide> }
<del> self::load($p, (array) $opts);
<add> self::load($p, (array)$opts);
<ide> }
<ide> }
<ide>
<ide> public static function bootstrap($plugin) {
<ide>
<ide> $path = self::path($plugin);
<ide> if ($config['bootstrap'] === true) {
<del> return include($path . 'Config' . DS . 'bootstrap.php');
<add> return include $path . 'Config' . DS . 'bootstrap.php';
<ide> }
<ide>
<ide> $bootstrap = (array)$config['bootstrap'];
<ide> public static function routes($plugin = null) {
<ide> if ($config['routes'] === false) {
<ide> return false;
<ide> }
<del> return (bool) include self::path($plugin) . 'Config' . DS . 'routes.php';
<add> return (bool)include self::path($plugin) . 'Config' . DS . 'routes.php';
<ide> }
<ide>
<ide> /**
<ide> public static function unload($plugin = null) {
<ide> unset(self::$_plugins[$plugin]);
<ide> }
<ide> }
<add>
<ide> }
<ide><path>lib/Cake/Core/Configure.php
<ide> public static function bootstrap($boot = true) {
<ide> 'www_root' => WWW_ROOT
<ide> ));
<ide>
<del> if (!include(APP . 'Config' . DS . 'core.php')) {
<add> if (!include APP . 'Config' . DS . 'core.php') {
<ide> trigger_error(__d('cake_dev', "Can't find application core file. Please create %score.php, and make sure it is readable by PHP.", APP . 'Config' . DS), E_USER_ERROR);
<ide> }
<ide> App::$bootstrapping = false;
<ide> App::init();
<ide> App::build();
<del> if (!include(APP . 'Config' . DS . 'bootstrap.php')) {
<add> if (!include APP . 'Config' . DS . 'bootstrap.php') {
<ide> trigger_error(__d('cake_dev', "Can't find application bootstrap file. Please create %sbootstrap.php, and make sure it is readable by PHP.", APP . 'Config' . DS), E_USER_ERROR);
<ide> }
<ide> $level = -1;
<ide> public static function restore($name, $cacheConfig = 'default') {
<ide> }
<ide> return false;
<ide> }
<del>}
<ide>
<add>}
<ide><path>lib/Cake/Core/Object.php
<ide> <?php
<ide> /**
<del> * Object class, allowing __construct and __destruct in PHP4.
<del> *
<del> * Also includes methods for logging and the special method RequestAction,
<del> * to call other Controllers' Actions from anywhere.
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> protected function _mergeVars($properties, $class, $normalize = true) {
<ide> }
<ide> }
<ide> }
<add>
<ide> } | 4 |
Javascript | Javascript | replace touchable with usepressability hook | c4aa411ee374f2320343b900f1f8b24a47b633c9 | <ide><path>Libraries/Components/TextInput/TextInput.js
<ide> const StyleSheet = require('../../StyleSheet/StyleSheet');
<ide> const Text = require('../../Text/Text');
<ide> const TextAncestor = require('../../Text/TextAncestor');
<ide> const TextInputState = require('./TextInputState');
<del>const TouchableWithoutFeedback = require('../Touchable/TouchableWithoutFeedback');
<ide>
<ide> const invariant = require('invariant');
<ide> const nullthrows = require('nullthrows');
<ide> const setAndForwardRef = require('../../Utilities/setAndForwardRef');
<ide>
<add>import usePressability from '../../Pressability/usePressability';
<add>
<ide> import type {TextStyleProp, ViewStyleProp} from '../../StyleSheet/StyleSheet';
<ide> import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide> import type {ViewProps} from '../View/ViewPropTypes';
<ide> function InternalTextInput(props: Props): React.Node {
<ide> },
<ide> });
<ide>
<del> const _onPress = (event: PressEvent) => {
<del> if (props.editable || props.editable === undefined) {
<del> nullthrows(inputRef.current).focus();
<del> }
<del> };
<del>
<ide> const _onChange = (event: ChangeEvent) => {
<ide> const text = event.nativeEvent.text;
<ide> props.onChange && props.onChange(event);
<ide> function InternalTextInput(props: Props): React.Node {
<ide> };
<ide>
<ide> let textInput = null;
<del> let additionalTouchableProps: {|
<del> rejectResponderTermination?: $PropertyType<
<del> Props,
<del> 'rejectResponderTermination',
<del> >,
<del> // This is a hack to let Flow know we want an exact object
<del> |} = {...null};
<ide>
<ide> // The default value for `blurOnSubmit` is true for single-line fields and
<ide> // false for multi-line fields.
<ide> const blurOnSubmit = props.blurOnSubmit ?? !props.multiline;
<ide>
<add> const accessible = props.accessible !== false;
<add> const focusable = props.focusable !== false;
<add>
<add> const config = React.useMemo(
<add> () => ({
<add> onPress: (event: PressEvent) => {
<add> if (props.editable !== false) {
<add> nullthrows(inputRef.current).focus();
<add> }
<add> },
<add> onPressIn: props.onPressIn,
<add> onPressOut: props.onPressOut,
<add> cancelable:
<add> Platform.OS === 'ios' ? !props.rejectResponderTermination : null,
<add> }),
<add> [
<add> props.editable,
<add> props.onPressIn,
<add> props.onPressOut,
<add> props.rejectResponderTermination,
<add> ],
<add> );
<add>
<add> // TextInput handles onBlur and onFocus events
<add> // so omitting onBlur and onFocus pressability handlers here.
<add> const {onBlur, onFocus, ...eventHandlers} = usePressability(config) || {};
<add>
<ide> if (Platform.OS === 'ios') {
<ide> const RCTTextInputView = props.multiline
<ide> ? RCTMultilineTextInputView
<ide> function InternalTextInput(props: Props): React.Node {
<ide> ? [styles.multilineInput, props.style]
<ide> : props.style;
<ide>
<del> additionalTouchableProps.rejectResponderTermination =
<del> props.rejectResponderTermination;
<del>
<ide> textInput = (
<ide> <RCTTextInputView
<ide> ref={_setNativeRef}
<ide> {...props}
<add> {...eventHandlers}
<add> accessible={accessible}
<ide> blurOnSubmit={blurOnSubmit}
<ide> dataDetectorTypes={props.dataDetectorTypes}
<add> focusable={focusable}
<ide> mostRecentEventCount={mostRecentEventCount}
<ide> onBlur={_onBlur}
<ide> onChange={_onChange}
<ide> function InternalTextInput(props: Props): React.Node {
<ide> <AndroidTextInput
<ide> ref={_setNativeRef}
<ide> {...props}
<add> {...eventHandlers}
<add> accessible={accessible}
<ide> autoCapitalize={autoCapitalize}
<ide> blurOnSubmit={blurOnSubmit}
<ide> children={children}
<ide> disableFullscreenUI={props.disableFullscreenUI}
<add> focusable={focusable}
<ide> mostRecentEventCount={mostRecentEventCount}
<ide> onBlur={_onBlur}
<ide> onChange={_onChange}
<ide> function InternalTextInput(props: Props): React.Node {
<ide> );
<ide> }
<ide> return (
<del> <TextAncestor.Provider value={true}>
<del> <TouchableWithoutFeedback
<del> onLayout={props.onLayout}
<del> onPress={_onPress}
<del> onPressIn={props.onPressIn}
<del> onPressOut={props.onPressOut}
<del> accessible={props.accessible}
<del> accessibilityLabel={props.accessibilityLabel}
<del> accessibilityRole={props.accessibilityRole}
<del> accessibilityState={props.accessibilityState}
<del> nativeID={props.nativeID}
<del> testID={props.testID}
<del> {...additionalTouchableProps}>
<del> {textInput}
<del> </TouchableWithoutFeedback>
<del> </TextAncestor.Provider>
<add> <TextAncestor.Provider value={true}>{textInput}</TextAncestor.Provider>
<ide> );
<ide> }
<ide> | 1 |
Python | Python | introduce relu exception for old theano versions | 36892dba8f5dd2847a565cf9b1f0ebfd74c29a5d | <ide><path>keras/backend/theano_backend.py
<ide> def switch(condition, then_expression, else_expression):
<ide> # NN OPERATIONS
<ide>
<ide> def relu(x, alpha=0., max_value=None):
<add> assert hasattr(T.nnet, 'relu'), ('It looks like like your version of '
<add> 'Theano is out of date. '
<add> 'Install the latest version with:\n'
<add> 'pip install git+git://github.com/Theano/Theano.git --upgrade')
<ide> x = T.nnet.relu(x, alpha)
<ide> if max_value is not None:
<ide> x = T.minimum(x, max_value) | 1 |
Javascript | Javascript | remove unneeded . escape | 4463d2b36003fd58a8e4c9a231f073e92e7d477e | <ide><path>benchmark/_http-benchmarkers.js
<ide> AutocannonBenchmarker.prototype.processResults = function(output) {
<ide>
<ide> function WrkBenchmarker() {
<ide> this.name = 'wrk';
<del> this.regexp = /Requests\/sec:[ \t]+([0-9\.]+)/;
<add> this.regexp = /Requests\/sec:[ \t]+([0-9.]+)/;
<ide> const result = child_process.spawnSync('wrk', ['-h']);
<ide> this.present = !(result.error && result.error.code === 'ENOENT');
<ide> }
<ide><path>lib/_tls_wrap.js
<ide> Server.prototype.addContext = function(servername, context) {
<ide> }
<ide>
<ide> var re = new RegExp('^' +
<del> servername.replace(/([\.^$+?\-\\[\]{}])/g, '\\$1')
<add> servername.replace(/([.^$+?\-\\[\]{}])/g, '\\$1')
<ide> .replace(/\*/g, '[^.]*') +
<ide> '$');
<ide> this._contexts.push([re, tls.createSecureContext(context).context]);
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> if (read_buffer !== client_unix.expect) {
<ide> var expect = client_unix.expect;
<ide> if (expect === prompt_multiline)
<del> expect = /[\.]{3} /;
<add> expect = /[.]{3} /;
<ide> assert.ok(read_buffer.match(expect));
<ide> console.error('match');
<ide> }
<ide><path>tools/doc/json.js
<ide> function deepCopy_(src) {
<ide> // these parse out the contents of an H# tag
<ide> var eventExpr = /^Event(?::|\s)+['"]?([^"']+).*$/i;
<ide> var classExpr = /^Class:\s*([^ ]+).*?$/i;
<del>var propExpr = /^(?:property:?\s*)?[^\.]+\.([^ \.\(\)]+)\s*?$/i;
<del>var braceExpr = /^(?:property:?\s*)?[^\.\[]+(\[[^\]]+\])\s*?$/i;
<add>var propExpr = /^(?:property:?\s*)?[^.]+\.([^ .()]+)\s*?$/i;
<add>var braceExpr = /^(?:property:?\s*)?[^.\[]+(\[[^\]]+\])\s*?$/i;
<ide> var classMethExpr =
<del> /^class\s*method\s*:?[^\.]+\.([^ \.\(\)]+)\([^\)]*\)\s*?$/i;
<add> /^class\s*method\s*:?[^.]+\.([^ .()]+)\([^)]*\)\s*?$/i;
<ide> var methExpr =
<del> /^(?:method:?\s*)?(?:[^\.]+\.)?([^ \.\(\)]+)\([^\)]*\)\s*?$/i;
<add> /^(?:method:?\s*)?(?:[^.]+\.)?([^ .()]+)\([^)]*\)\s*?$/i;
<ide> var newExpr = /^new ([A-Z][a-zA-Z]+)\([^\)]*\)\s*?$/;
<ide> var paramExpr = /\((.*)\);?$/;
<ide> | 4 |
Javascript | Javascript | upgrade libmanifestplugin to tapable v1 | 99bbbebfe2ceb762eda365d300d99d0050a50ffe | <ide><path>lib/LibManifestPlugin.js
<ide> class LibManifestPlugin {
<ide> }
<ide>
<ide> apply(compiler) {
<del> compiler.plugin("emit", (compilation, callback) => {
<add> compiler.hooks.emit.tapAsync("LibManifestPlugin", (compilation, callback) => {
<ide> asyncLib.forEach(compilation.chunks, (chunk, callback) => {
<ide> if(!chunk.isInitial()) {
<ide> callback();
<ide> class LibManifestPlugin {
<ide> return obj;
<ide> }, Object.create(null))
<ide> };
<del> const content = new Buffer(JSON.stringify(manifest), "utf8"); //eslint-disable-line
<add> const content = new Buffer.from(JSON.stringify(manifest), "utf8");
<ide> compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => {
<ide> if(err) return callback(err);
<ide> compiler.outputFileSystem.writeFile(targetPath, content, callback); | 1 |
Python | Python | change handling of the expired financial functions | adccacf32ea8c159b2397a6053f4b97543ec08a7 | <ide><path>numpy/__init__.py
<ide> del Arrayterator
<ide>
<ide> # These names were removed in NumPy 1.20. For at least one release,
<del> # attempts to access these names in the numpy namespace will have an
<del> # error message that refers to NEP 32 and points to the numpy_financial
<del> # library.
<add> # attempts to access these names in the numpy namespace will trigger
<add> # a warning, and calling the function will raise an exception.
<ide> _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
<ide> 'ppmt', 'pv', 'rate']
<ide> __expired_attrs__ = {
<ide> # module level getattr is only supported in 3.7 onwards
<ide> # https://www.python.org/dev/peps/pep-0562/
<ide> def __getattr__(attr):
<del> # Raise AttributeError for expired attributes
<add> # Warn for expired attributes, and return a dummy function
<add> # that always raises an exception.
<ide> try:
<ide> msg = __expired_attrs__[attr]
<ide> except KeyError:
<ide> pass
<ide> else:
<del> raise AttributeError(msg)
<add> warnings.warn(msg, RuntimeWarning)
<add>
<add> def _expired(*args, **kwds):
<add> raise RuntimeError(msg)
<add>
<add> return _expired
<ide>
<ide> # Emit warnings for deprecated attributes
<ide> try:
<ide><path>numpy/lib/tests/test_financial_expired.py
<ide> import numpy as np
<ide>
<ide>
<add>@pytest.mark.skipif(sys.version_info[:2] < (3, 7),
<add> reason="requires python 3.7 or higher")
<ide> def test_financial_expired():
<del> if sys.version_info[:2] >= (3, 7):
<del> match = 'NEP 32'
<del> else:
<del> match = None
<del> with pytest.raises(AttributeError, match=match):
<del> np.fv
<add> match = 'NEP 32'
<add> with pytest.warns(RuntimeWarning, match=match):
<add> func = np.fv
<add> with pytest.raises(RuntimeError, match=match):
<add> func(1, 2, 3) | 2 |
Python | Python | remove subclass for sortish sampler | 115d97dd2f752880715cd01aa915286e3d9a5442 | <ide><path>examples/seq2seq/finetune_trainer.py
<ide> from typing import Optional
<ide>
<ide> import transformers
<add>from seq2seq_trainer import Seq2SeqTrainer
<add>from seq2seq_training_args import Seq2SeqTrainingArguments
<ide> from transformers import (
<ide> AutoConfig,
<ide> AutoModelForSeq2SeqLM,
<ide> AutoTokenizer,
<ide> HfArgumentParser,
<ide> MBartTokenizer,
<ide> MBartTokenizerFast,
<del> Seq2SeqTrainer,
<del> Seq2SeqTrainingArguments,
<ide> set_seed,
<ide> )
<ide> from transformers.trainer_utils import EvaluationStrategy, is_main_process
<ide> def main():
<ide> trainer = Seq2SeqTrainer(
<ide> model=model,
<ide> args=training_args,
<add> data_args=data_args,
<ide> train_dataset=train_dataset,
<ide> eval_dataset=eval_dataset,
<ide> data_collator=Seq2SeqDataCollator(
<ide> def main():
<ide> if training_args.do_eval:
<ide> logger.info("*** Evaluate ***")
<ide>
<del> metrics = trainer.evaluate(
<del> metric_key_prefix="val", max_length=data_args.val_max_target_length, num_beams=data_args.eval_beams
<del> )
<add> metrics = trainer.evaluate(metric_key_prefix="val")
<ide> metrics["val_n_objs"] = data_args.n_val
<ide> metrics["val_loss"] = round(metrics["val_loss"], 4)
<ide>
<ide> def main():
<ide> if training_args.do_predict:
<ide> logger.info("*** Predict ***")
<ide>
<del> test_output = trainer.predict(
<del> test_dataset=test_dataset,
<del> metric_key_prefix="test",
<del> max_length=data_args.val_max_target_length,
<del> num_beams=data_args.eval_beams,
<del> )
<add> test_output = trainer.predict(test_dataset=test_dataset, metric_key_prefix="test")
<ide> metrics = test_output.metrics
<ide> metrics["test_n_objs"] = data_args.n_test
<ide>
<ide><path>src/transformers/trainer_seq2seq.py
<ide> import torch
<ide> from packaging import version
<ide> from torch import nn
<del>from torch.utils.data import DistributedSampler, RandomSampler
<ide> from torch.utils.data.dataset import Dataset
<ide>
<del>from .file_utils import is_torch_tpu_available
<ide> from .trainer import Trainer
<del>from .trainer_pt_utils import get_tpu_sampler
<ide> from .trainer_utils import PredictionOutput
<del>from .training_args import ParallelMode
<ide> from .utils import logging
<ide>
<ide>
<ide>
<ide>
<ide> class Seq2SeqTrainer(Trainer):
<del> def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]:
<del> if isinstance(self.train_dataset, torch.utils.data.IterableDataset):
<del> return None
<del> elif is_torch_tpu_available():
<del> return get_tpu_sampler(self.train_dataset)
<del> else:
<del> if self.args.sortish_sampler:
<del> self.train_dataset.make_sortish_sampler(
<del> self.args.per_device_train_batch_size,
<del> distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED),
<del> )
<del>
<del> return (
<del> RandomSampler(self.train_dataset)
<del> if self.args.local_rank == -1
<del> else DistributedSampler(self.train_dataset)
<del> )
<del>
<ide> def evaluate(
<ide> self,
<ide> eval_dataset: Optional[Dataset] = None, | 2 |
Javascript | Javascript | convert `pdfpageviewbuffer` to a standard class | 0eba15b43ae7394a2807c17cac3fccaa47292d7d | <ide><path>web/base_viewer.js
<ide> const DEFAULT_CACHE_SIZE = 10;
<ide> * @property {IL10n} l10n - Localization service.
<ide> */
<ide>
<del>function PDFPageViewBuffer(size) {
<del> const data = [];
<del> this.push = function (view) {
<del> const i = data.indexOf(view);
<add>class PDFPageViewBuffer {
<add> #data = [];
<add>
<add> #size = 0;
<add>
<add> constructor(size) {
<add> this.#size = size;
<add>
<add> if (
<add> typeof PDFJSDev === "undefined" ||
<add> PDFJSDev.test("!PRODUCTION || TESTING")
<add> ) {
<add> Object.defineProperty(this, "_buffer", {
<add> get() {
<add> return this.#data.slice();
<add> },
<add> });
<add> }
<add> }
<add>
<add> push(view) {
<add> const data = this.#data,
<add> i = data.indexOf(view);
<ide> if (i >= 0) {
<ide> data.splice(i, 1);
<ide> }
<ide> data.push(view);
<del> if (data.length > size) {
<add> if (data.length > this.#size) {
<ide> data.shift().destroy();
<ide> }
<del> };
<add> }
<ide>
<ide> /**
<ide> * After calling resize, the size of the buffer will be `newSize`.
<ide> function PDFPageViewBuffer(size) {
<ide> * `idsToKeep` has no impact on the final size of the buffer; if `idsToKeep`
<ide> * is larger than `newSize`, some of those pages will be destroyed anyway.
<ide> */
<del> this.resize = function (newSize, idsToKeep = null) {
<del> size = newSize;
<add> resize(newSize, idsToKeep = null) {
<add> this.#size = newSize;
<add>
<add> const data = this.#data;
<ide> if (idsToKeep) {
<ide> moveToEndOfArray(data, function (page) {
<ide> return idsToKeep.has(page.id);
<ide> });
<ide> }
<del> while (data.length > size) {
<add> while (data.length > this.#size) {
<ide> data.shift().destroy();
<ide> }
<del> };
<del>
<del> this.has = function (view) {
<del> return data.includes(view);
<del> };
<add> }
<ide>
<del> if (
<del> typeof PDFJSDev === "undefined" ||
<del> PDFJSDev.test("!PRODUCTION || TESTING")
<del> ) {
<del> Object.defineProperty(this, "_buffer", {
<del> get() {
<del> return data.slice();
<del> },
<del> });
<add> has(view) {
<add> return this.#data.includes(view);
<ide> }
<ide> }
<ide>
<ide> function isSameScale(oldScale, newScale) {
<ide> * Simple viewer control to display PDF content/pages.
<ide> */
<ide> class BaseViewer {
<add> #buffer = null;
<add>
<ide> #scrollModePageState = null;
<ide>
<ide> /**
<ide> class BaseViewer {
<ide> }
<ide> // Add the page to the buffer at the start of drawing. That way it can be
<ide> // evicted from the buffer and destroyed even if we pause its rendering.
<del> this._buffer.push(pageView);
<add> this.#buffer.push(pageView);
<ide> };
<ide> this.eventBus._on("pagerender", this._onBeforeDraw);
<ide>
<ide> class BaseViewer {
<ide> this._currentScale = UNKNOWN_SCALE;
<ide> this._currentScaleValue = null;
<ide> this._pageLabels = null;
<del> this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
<add> this.#buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
<ide> this._location = null;
<ide> this._pagesRotation = 0;
<ide> this._optionalContentConfigPromise = null;
<ide> class BaseViewer {
<ide> return;
<ide> }
<ide> const newCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * numVisiblePages + 1);
<del> this._buffer.resize(newCacheSize, visible.ids);
<add> this.#buffer.resize(newCacheSize, visible.ids);
<ide>
<ide> this.renderingQueue.renderHighestPriority(visible);
<ide>
<ide> class BaseViewer {
<ide> return false;
<ide> }
<ide> const pageView = this._pages[pageNumber - 1];
<del> return this._buffer.has(pageView);
<add> return this.#buffer.has(pageView);
<ide> }
<ide>
<ide> cleanup() { | 1 |
PHP | PHP | improve test of filter in collection | b15dc2ac7e4c7b382ec5cf09e2983ab94cccc83c | <ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testFilter($collection)
<ide> $this->assertEquals(['first' => 'Hello', 'second' => 'World'], $c->filter(function ($item, $key) {
<ide> return $key !== 'id';
<ide> })->all());
<add>
<add> $c = new $collection([1, 2, 3, null, false, '', 0, []]);
<add> $this->assertEquals([1, 2, 3], $c->filter()->all());
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add kickstarter link | 0a3c1bb5751fb774b9b595a88830c56ff9531bbc | <ide><path>README.md
<ide> Homebrew
<ide> ========
<ide> Features, usage and installation instructions are [summarized on the homepage][home].
<ide>
<add>Kickstarter
<add>-----------
<add>
<add>Please [back our Kickstarter](http://www.kickstarter.com/projects/homebrew/brew-test-bot) before March 6th:
<add>[](http://www.kickstarter.com/projects/homebrew/brew-test-bot)
<add>
<ide> What Packages Are Available?
<ide> ----------------------------
<ide> 1. You can [browse the Formula directory on GitHub][formula]. | 1 |
Javascript | Javascript | correct a typo in the regex matching safari 8 | c17543fd3c14ff86c448dbb90f9fe1223661a73b | <ide><path>test/unit/support.js
<ide> testIframeWithCallback( "Check CSP (https://developer.mozilla.org/en-US/docs/Sec
<ide> "radioValue": false,
<ide> "reliableMarginRight": true
<ide> };
<del> } else if ( /8.0(\.\d+|) safari/i.test( userAgent ) ) {
<add> } else if ( /8\.0(\.\d+|) safari/i.test( userAgent ) ) {
<ide> expected = {
<ide> "ajax": true,
<ide> "boxSizingReliable": true, | 1 |
PHP | PHP | add three convenience methods to load plugins | eb0374f97eca2813ff1cf62f5dcc362db6cebd73 | <ide><path>src/Http/BaseApplication.php
<ide> * @since 3.3.0
<ide> * @license https://opensource.org/licenses/mit-license.php MIT License
<ide> */
<add>
<ide> namespace Cake\Http;
<ide>
<ide> use Cake\Console\CommandCollection;
<ide> use Cake\Controller\ControllerFactory;
<ide> use Cake\Core\ConsoleApplicationInterface;
<add>use Cake\Core\Exception\MissingPluginException;
<ide> use Cake\Core\HttpApplicationInterface;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Core\PluginApplicationInterface;
<ide> public function addPlugin($name, array $config = [])
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Add an optional plugin
<add> *
<add> * If it isn't available, ignore it.
<add> *
<add> * @param string|\Cake\Core\PluginInterface $name The plugin name or plugin object.
<add> * @param array $config The configuration data for the plugin if using a string for $name
<add> * @return $this
<add> */
<add> public function addOptionalPlugin($name, array $config = [])
<add> {
<add> try {
<add> $this->addPlugin($name, $config);
<add> } catch (MissingPluginException $e) {
<add> // Do not halt if the plugin is missing
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Add a plugin, when in CLI
<add> *
<add> * @param string|\Cake\Core\PluginInterface $name The plugin name or plugin object.
<add> * @param array $config The configuration data for the plugin if using a string for $name
<add> * @return $this
<add> */
<add> public function addCliPlugin($name, array $config = [])
<add> {
<add> if (PHP_SAPI === 'cli') {
<add> $this->addPlugin($name, $config);
<add> }
<add>
<add> return $this;
<add> }
<add>
<add> /**
<add> * Add an optional plugin, when in CLI
<add> *
<add> * If it isn't available, ignore it.
<add> *
<add> * @param string|\Cake\Core\PluginInterface $name The plugin name or plugin object.
<add> * @param array $config The configuration data for the plugin if using a string for $name
<add> * @return $this
<add> */
<add> public function addOptionalCliPlugin($name, array $config = [])
<add> {
<add> if (PHP_SAPI === 'cli') {
<add> $this->addOptionalCliPlugin($name, $config);
<add> }
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Get the plugin collection in use.
<ide> * | 1 |
Ruby | Ruby | allow all available locales for template lookups | 12c12899df560d65c03eb10f0ddd46d6ce418bc6 | <ide><path>actionview/lib/action_view/template/resolver.rb
<ide> class PathParser # :nodoc:
<ide> ParsedPath = Struct.new(:path, :details)
<ide>
<ide> def build_path_regex
<del> handlers = Template::Handlers.extensions.map { |x| Regexp.escape(x) }.join("|")
<del> formats = Template::Types.symbols.map { |x| Regexp.escape(x) }.join("|")
<del> locales = "[a-z]{2}(?:[-_][A-Z]{2})?"
<add> handlers = Regexp.union(Template::Handlers.extensions.map(&:to_s))
<add> formats = Regexp.union(Template::Types.symbols.map(&:to_s))
<add> available_locales = I18n.available_locales.map(&:to_s)
<add> regular_locales = [/[a-z]{2}(?:[-_][A-Z]{2})?/]
<add> locales = Regexp.union(available_locales + regular_locales)
<ide> variants = "[^.]*"
<ide>
<ide> %r{
<ide><path>actionview/test/template/resolver_shared_tests.rb
<ide> def test_finds_template_with_lowdash_format
<ide>
<ide> assert_equal "Texto simple!", es_ar[0].source
<ide> end
<add>
<add> def test_finds_template_with_arbitrarily_formatted_locale
<add> I18n.backend.store_translations(:en_customer1, { hello: "hello" })
<add> with_file "test/hello_world.en_customer1.text.erb", "Good day, world."
<add>
<add> templates = context.find_all("hello_world", "test", false, [], locale: [:en_customer1])
<add>
<add> assert_equal 1, templates.size
<add> assert_equal "Good day, world.", templates[0].source
<add> ensure
<add> I18n.reload!
<add> end
<ide> end | 2 |
Javascript | Javascript | render empty section headers | e07fe0cc6063d48a5c0fc2245f54b58dd4f48c49 | <ide><path>Libraries/CustomComponents/ListView/ListView.js
<ide> var ListView = React.createClass({
<ide> * @platform ios
<ide> */
<ide> stickyHeaderIndices: PropTypes.arrayOf(PropTypes.number),
<add> /**
<add> * Flag indicating whether empty section headers should be rendered. In the future release
<add> * empty section headers will be rendered by default, and the flag will be deprecated.
<add> * If empty sections are not desired to be rendered their indices should be excluded from sectionID object.
<add> */
<add> enableEmptySections: PropTypes.bool,
<ide> },
<ide>
<ide> /**
<ide> var ListView = React.createClass({
<ide> getMetrics: function() {
<ide> return {
<ide> contentLength: this.scrollProperties.contentLength,
<del> totalRows: this.props.dataSource.getRowCount(),
<add> totalRows: (this.props.enableEmptySections ? this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount()),
<ide> renderedRows: this.state.curRenderedRowsCount,
<ide> visibleRows: Object.keys(this._visibleRows).length,
<ide> };
<ide> var ListView = React.createClass({
<ide> state.curRenderedRowsCount,
<ide> props.initialListSize
<ide> ),
<del> props.dataSource.getRowCount()
<add> props.enableEmptySections ? props.dataSource.getRowAndSectionCount() : props.dataSource.getRowCount()
<ide> ),
<ide> };
<ide> }, () => this._renderMoreRowsIfNeeded());
<ide> var ListView = React.createClass({
<ide> var sectionID = dataSource.sectionIdentities[sectionIdx];
<ide> var rowIDs = allRowIDs[sectionIdx];
<ide> if (rowIDs.length === 0) {
<del> continue;
<add> if (this.props.enableEmptySections === undefined) {
<add> var warning = require('fbjs/lib/warning');
<add> warning(false, 'In next release empty section headers will be rendered.'
<add> + ' In this release you can use \'enableEmptySections\' flag to render empty section headers.');
<add> continue;
<add> } else {
<add> var invariant = require('fbjs/lib/invariant');
<add> invariant(
<add> this.props.enableEmptySections,
<add> 'In next release \'enableEmptySections\' flag will be deprecated, empty section headers will always be rendered.'
<add> + ' If empty section headers are not desirable their indices should be excluded from sectionIDs object.'
<add> + ' In this release \'enableEmptySections\' may only have value \'true\' to allow empty section headers rendering.');
<add> }
<ide> }
<ide>
<ide> if (this.props.renderSectionHeader) {
<ide> var ListView = React.createClass({
<ide> if (this.props.onEndReached &&
<ide> this.scrollProperties.contentLength !== this._sentEndForContentLength &&
<ide> this._getDistanceFromEnd(this.scrollProperties) < this.props.onEndReachedThreshold &&
<del> this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) {
<add> this.state.curRenderedRowsCount === (this.props.enableEmptySections ? this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount())) {
<ide> this._sentEndForContentLength = this.scrollProperties.contentLength;
<ide> this.props.onEndReached(event);
<ide> return true;
<ide> var ListView = React.createClass({
<ide> _renderMoreRowsIfNeeded: function() {
<ide> if (this.scrollProperties.contentLength === null ||
<ide> this.scrollProperties.visibleLength === null ||
<del> this.state.curRenderedRowsCount === this.props.dataSource.getRowCount()) {
<add> this.state.curRenderedRowsCount === (this.props.enableEmptySections ? this.props.dataSource.getRowAndSectionCount() : this.props.dataSource.getRowCount())) {
<ide> this._maybeCallOnEndReached();
<ide> return;
<ide> }
<ide> var ListView = React.createClass({
<ide> this.setState((state, props) => {
<ide> var rowsToRender = Math.min(
<ide> state.curRenderedRowsCount + props.pageSize,
<del> props.dataSource.getRowCount()
<add> props.dataSource.getRowAndSectionCount()
<ide> );
<ide> this._prevRenderedRowsCount = state.curRenderedRowsCount;
<ide> return {
<ide><path>Libraries/CustomComponents/ListView/ListViewDataSource.js
<ide> class ListViewDataSource {
<ide> typeof this._sectionHeaderHasChanged === 'function',
<ide> 'Must provide a sectionHeaderHasChanged function with section data.'
<ide> );
<add> invariant(
<add> !sectionIdentities || !rowIdentities || sectionIdentities.length === rowIdentities.length,
<add> 'row and section ids lengths must be the same'
<add> );
<add>
<ide> var newSource = new ListViewDataSource({
<ide> getRowData: this._getRowData,
<ide> getSectionHeaderData: this._getSectionHeaderData,
<ide> class ListViewDataSource {
<ide> return this._cachedRowCount;
<ide> }
<ide>
<add> getRowAndSectionCount(): number {
<add> return (this._cachedRowCount + this.sectionIdentities.length);
<add> }
<add>
<ide> /**
<ide> * Returns if the row is dirtied and needs to be rerendered
<ide> */ | 2 |
Javascript | Javascript | remove unused var | fef6282d5532ddb211e3d72bc9f49c7d0c17ae0b | <ide><path>test/unit/media.html5.js
<ide> module('HTML5');
<ide>
<del>var oldAndroidVersion;
<del>
<ide> test('should detect whether the volume can be changed', function(){
<ide> var testVid, ConstVolumeVideo;
<ide> if (!{}['__defineSetter__']) { | 1 |
Javascript | Javascript | add a second argument to assert.throws() | 943d0853076437896963975d039e7786e5f74192 | <ide><path>test/addons/make-callback-recurse/test.js
<ide> assert.throws(function() {
<ide> makeCallback({}, function() {
<ide> throw new Error('hi from domain error');
<ide> });
<del>});
<add>}, /^Error: hi from domain error$/);
<ide>
<ide>
<ide> // Check the execution order of the nextTickQueue and MicrotaskQueue in | 1 |
Java | Java | update copyright year of changed file | 7adac25e7e87f66c1291c5543501c31171bb47ec | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/CorsRegistration.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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. | 1 |
Java | Java | add delaysubscription() methods to completable | f78bd953e6d09792d2ba2aa1c3fce0f7c9110810 | <ide><path>src/main/java/io/reactivex/Completable.java
<ide> public final Completable delay(final long delay, final TimeUnit unit, final Sche
<ide> return RxJavaPlugins.onAssembly(new CompletableDelay(this, delay, unit, scheduler, delayError));
<ide> }
<ide>
<add> /**
<add> * Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time.
<add> * <p>
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>This version of {@code delaySubscription} operates by default on the {@code computation} {@link Scheduler}.</dd>
<add> * </dl>
<add> *
<add> * @param delay the time to delay the subscription
<add> * @param unit the time unit of {@code delay}
<add> * @return a Completable that delays the subscription to the source CompletableSource by the given amount
<add> * @since 2.2.3 - experimental
<add> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<add> */
<add> @CheckReturnValue
<add> @Experimental
<add> @SchedulerSupport(SchedulerSupport.COMPUTATION)
<add> public final Completable delaySubscription(long delay, TimeUnit unit) {
<add> return delaySubscription(delay, unit, Schedulers.computation());
<add> }
<add>
<add> /**
<add> * Returns a Completable that delays the subscription to the source CompletableSource by a given amount of time,
<add> * both waiting and subscribing on a given Scheduler.
<add> * <p>
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>You specify which {@link Scheduler} this operator will use.</dd>
<add> * </dl>
<add> *
<add> * @param delay the time to delay the subscription
<add> * @param unit the time unit of {@code delay}
<add> * @param scheduler the Scheduler on which the waiting and subscription will happen
<add> * @return a Completable that delays the subscription to the source CompletableSource by a given
<add> * amount, waiting and subscribing on the given Scheduler
<add> * @since 2.2.3 - experimental
<add> * @see <a href="http://reactivex.io/documentation/operators/delay.html">ReactiveX operators documentation: Delay</a>
<add> */
<add> @CheckReturnValue
<add> @Experimental
<add> @SchedulerSupport(SchedulerSupport.CUSTOM)
<add> public final Completable delaySubscription(long delay, TimeUnit unit, Scheduler scheduler) {
<add> return Completable.timer(delay, unit, scheduler).andThen(this);
<add> }
<add>
<ide> /**
<ide> * Returns a Completable which calls the given onComplete callback if this Completable completes.
<ide> * <p>
<ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableDelayTest.java
<ide>
<ide> import org.junit.Test;
<ide>
<del>import io.reactivex.*;
<add>import io.reactivex.CompletableSource;
<add>import io.reactivex.TestHelper;
<add>import io.reactivex.Completable;
<ide> import io.reactivex.exceptions.TestException;
<ide> import io.reactivex.functions.*;
<ide> import io.reactivex.observers.TestObserver;
<del>import io.reactivex.schedulers.*;
<add>import io.reactivex.schedulers.Schedulers;
<add>import io.reactivex.schedulers.TestScheduler;
<ide>
<ide> public class CompletableDelayTest {
<ide>
<ide> public void errorDelayed() {
<ide>
<ide> to.assertFailure(TestException.class);
<ide> }
<add>
<add> @Test
<add> public void errorDelayedSubscription() {
<add> TestScheduler scheduler = new TestScheduler();
<add>
<add> TestObserver<Void> to = Completable.error(new TestException())
<add> .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler)
<add> .test();
<add>
<add> to.assertEmpty();
<add>
<add> scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS);
<add>
<add> to.assertEmpty();
<add>
<add> scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS);
<add>
<add> to.assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void errorDelayedSubscriptionDisposeBeforeTime() {
<add> TestScheduler scheduler = new TestScheduler();
<add>
<add> Completable result = Completable.complete()
<add> .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler);
<add> TestObserver<Void> to = result.test();
<add>
<add> to.assertEmpty();
<add>
<add> scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS);
<add> to.dispose();
<add>
<add> scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS);
<add>
<add> to.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void testDelaySubscriptionDisposeBeforeTime() {
<add> TestScheduler scheduler = new TestScheduler();
<add>
<add> Completable result = Completable.complete()
<add> .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler);
<add> TestObserver<Void> to = result.test();
<add>
<add> to.assertEmpty();
<add> scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS);
<add> to.dispose();
<add> scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS);
<add> to.assertEmpty();
<add> }
<add>
<add> @Test
<add> public void testDelaySubscription() {
<add> TestScheduler scheduler = new TestScheduler();
<add> Completable result = Completable.complete()
<add> .delaySubscription(100, TimeUnit.MILLISECONDS, scheduler);
<add> TestObserver<Void> to = result.test();
<add>
<add> scheduler.advanceTimeBy(90, TimeUnit.MILLISECONDS);
<add> to.assertEmpty();
<add> scheduler.advanceTimeBy(15, TimeUnit.MILLISECONDS);
<add> to.assertResult();
<add> }
<ide> }
<ide><path>src/test/java/io/reactivex/validators/ParamValidationCheckerTest.java
<ide> public void checkParallelFlowable() {
<ide> addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class));
<ide> addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delay", Long.TYPE, TimeUnit.class, Scheduler.class, Boolean.TYPE));
<ide>
<add> // negative time is considered as zero time
<add> addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delaySubscription", Long.TYPE, TimeUnit.class));
<add> addOverride(new ParamOverride(Completable.class, 0, ParamMode.ANY, "delaySubscription", Long.TYPE, TimeUnit.class, Scheduler.class));
<add>
<ide> // zero repeat is allowed
<ide> addOverride(new ParamOverride(Completable.class, 0, ParamMode.NON_NEGATIVE, "repeat", Long.TYPE));
<ide> | 3 |
Ruby | Ruby | add missing parantheses in index_exists? | be37b0c143da6dc682fd53eab744e0c1115063d1 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def table_exists?(table_name)
<ide> # index_exists?(:suppliers, :company_id, unique: true)
<ide> #
<ide> # # Check an index with a custom name exists
<del> # index_exists?(:suppliers, :company_id, name: "idx_company_id"
<add> # index_exists?(:suppliers, :company_id, name: "idx_company_id")
<ide> #
<ide> def index_exists?(table_name, column_name, options = {})
<ide> column_names = Array(column_name) | 1 |
Javascript | Javascript | remove avatar from nav | 9f40714d0a2ed25ef3e654a20b6a301fd9b4dc45 | <ide><path>client/src/components/Header/components/SignedIn.js
<ide> import React from 'react';
<ide> import PropTypes from 'prop-types';
<ide> import { Link } from 'gatsby';
<del>import { connect } from 'react-redux';
<del>import { createSelector } from 'reselect';
<ide>
<del>import { userSelector } from '../../../redux';
<del>
<del>const mapStateToProps = createSelector(
<del> userSelector,
<del> ({ picture }) => ({
<del> picture
<del> })
<del>);
<del>
<del>function SignedIn({ picture }) {
<add>function SignedIn() {
<ide> return (
<del> <Link className='settings-link' to='/settings'>
<del> <img alt='' className='user-avatar' src={picture} />
<add> <Link className='top-right-nav-link' to='/settings'>
<add> Settings
<ide> </Link>
<ide> );
<ide> }
<ide> SignedIn.propTypes = {
<ide> picture: PropTypes.string
<ide> };
<ide>
<del>export default connect(mapStateToProps)(SignedIn);
<add>export default SignedIn; | 1 |
Javascript | Javascript | resume stream on drain | 224b78ff06980407589b81bd8462bbd528d89110 | <ide><path>lib/internal/streams/readable.js
<ide> function pipeOnDrain(src, dest) {
<ide>
<ide> if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) &&
<ide> EE.listenerCount(src, 'data')) {
<del> state.flowing = true;
<del> flow(src);
<add> src.resume();
<ide> }
<ide> };
<ide> }
<ide><path>test/parallel/test-stream-readable-pause-and-resume.js
<ide> function readAndPause() {
<ide> assert(readable.isPaused());
<ide> });
<ide> }
<add>
<add>{
<add> const { PassThrough } = require('stream');
<add>
<add> const source3 = new PassThrough();
<add> const target3 = new PassThrough();
<add>
<add> const chunk = Buffer.allocUnsafe(1000);
<add> while (target3.write(chunk));
<add>
<add> source3.pipe(target3);
<add> target3.on('drain', common.mustCall(() => {
<add> assert(!source3.isPaused());
<add> }));
<add> target3.on('data', () => {});
<add>} | 2 |
PHP | PHP | use getters instead of hardcoded values | 466e0e1cd026fa456b189d45975ae7c7adf3e53f | <ide><path>src/Illuminate/Foundation/Console/KeyGenerateCommand.php
<ide> public function fire()
<ide> return $this->line('<comment>'.$key.'</comment>');
<ide> }
<ide>
<del> $path = base_path('.env');
<add> $path = $app->environmentPath().'/'.$app->environmentFile();
<ide>
<ide> if (file_exists($path)) {
<ide> $content = str_replace('APP_KEY='.$app['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)); | 1 |
Java | Java | infer proxy on `@lazy`-annotated injection points | 455715899d5a93f7eaee7996e5b17ba8db20e476 | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
<ide> import java.lang.reflect.Member;
<ide> import java.lang.reflect.Method;
<ide> import java.lang.reflect.Modifier;
<add>import java.lang.reflect.Proxy;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import org.springframework.beans.factory.config.DependencyDescriptor;
<ide> import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
<ide> import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory;
<add>import org.springframework.beans.factory.support.AutowireCandidateResolver;
<add>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.LookupOverride;
<ide> import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
<ide> import org.springframework.beans.factory.support.RegisteredBean;
<ide> public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registe
<ide> InjectionMetadata metadata = findInjectionMetadata(beanName, beanClass, beanDefinition);
<ide> Collection<AutowiredElement> autowiredElements = getAutowiredElements(metadata);
<ide> if (!ObjectUtils.isEmpty(autowiredElements)) {
<del> return new AotContribution(beanClass, autowiredElements);
<add> return new AotContribution(beanClass, autowiredElements, getAutowireCandidateResolver());
<ide> }
<ide> return null;
<ide> }
<ide> private Collection<AutowiredElement> getAutowiredElements(InjectionMetadata meta
<ide> return (Collection) metadata.getInjectedElements();
<ide> }
<ide>
<add> @Nullable
<add> private AutowireCandidateResolver getAutowireCandidateResolver() {
<add> if (this.beanFactory instanceof DefaultListableBeanFactory lbf) {
<add> return lbf.getAutowireCandidateResolver();
<add> }
<add> return null;
<add> }
<add>
<ide> private InjectionMetadata findInjectionMetadata(String beanName, Class<?> beanType, RootBeanDefinition beanDefinition) {
<ide> InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
<ide> metadata.checkConfigMembers(beanDefinition);
<ide> private static class AotContribution implements BeanRegistrationAotContribution
<ide>
<ide> private final Collection<AutowiredElement> autowiredElements;
<ide>
<add> @Nullable
<add> private final AutowireCandidateResolver candidateResolver;
<add>
<add> AotContribution(Class<?> target, Collection<AutowiredElement> autowiredElements,
<add> @Nullable AutowireCandidateResolver candidateResolver) {
<ide>
<del> AotContribution(Class<?> target, Collection<AutowiredElement> autowiredElements) {
<ide> this.target = target;
<ide> this.autowiredElements = autowiredElements;
<add> this.candidateResolver = candidateResolver;
<ide> }
<ide>
<ide>
<ide> public void applyTo(GenerationContext generationContext,
<ide> });
<ide> beanRegistrationCode.addInstancePostProcessor(
<ide> MethodReference.ofStatic(generatedClass.getName(), generateMethod.getName()));
<add>
<add> if (this.candidateResolver != null) {
<add> registerHints(generationContext.getRuntimeHints());
<add> }
<ide> }
<ide>
<ide> private CodeBlock generateMethodCode(RuntimeHints hints) {
<ide> private CodeBlock generateParameterTypesCode(Class<?>[] parameterTypes) {
<ide> return code.build();
<ide> }
<ide>
<add> private void registerHints(RuntimeHints runtimeHints) {
<add> this.autowiredElements.forEach(autowiredElement -> {
<add> boolean required = autowiredElement.required;
<add> Member member = autowiredElement.getMember();
<add> if (member instanceof Field field) {
<add> DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(
<add> field, required);
<add> registerProxyIfNecessary(runtimeHints, dependencyDescriptor);
<add> }
<add> if (member instanceof Method method) {
<add> Class<?>[] parameterTypes = method.getParameterTypes();
<add> for (int i = 0; i < parameterTypes.length; i++) {
<add> MethodParameter methodParam = new MethodParameter(method, i);
<add> DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(
<add> methodParam, required);
<add> registerProxyIfNecessary(runtimeHints, dependencyDescriptor);
<add> }
<add> }
<add> });
<add> }
<add>
<add> private void registerProxyIfNecessary(RuntimeHints runtimeHints, DependencyDescriptor dependencyDescriptor) {
<add> Class<?> proxyType = this.candidateResolver
<add> .getLazyResolutionProxyClass(dependencyDescriptor, null);
<add> if (proxyType != null && Proxy.isProxyClass(proxyType)) {
<add> runtimeHints.proxies().registerJdkProxy(proxyType.getInterfaces());
<add> }
<add> }
<add>
<ide> }
<ide>
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGenerator.java
<ide>
<ide> package org.springframework.beans.factory.aot;
<ide>
<add>import java.lang.reflect.Constructor;
<ide> import java.lang.reflect.Executable;
<add>import java.lang.reflect.Method;
<add>import java.lang.reflect.Proxy;
<ide> import java.util.List;
<ide>
<ide> import javax.lang.model.element.Modifier;
<ide> import org.springframework.aot.generate.GeneratedMethods;
<ide> import org.springframework.aot.generate.GenerationContext;
<ide> import org.springframework.aot.generate.MethodReference;
<add>import org.springframework.aot.hint.RuntimeHints;
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<add>import org.springframework.beans.factory.config.DependencyDescriptor;
<add>import org.springframework.beans.factory.support.AutowireCandidateResolver;
<add>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.RegisteredBean;
<add>import org.springframework.core.MethodParameter;
<ide> import org.springframework.javapoet.ClassName;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.StringUtils;
<ide> class BeanDefinitionMethodGenerator {
<ide> MethodReference generateBeanDefinitionMethod(GenerationContext generationContext,
<ide> BeanRegistrationsCode beanRegistrationsCode) {
<ide>
<add> registerRuntimeHintsIfNecessary(generationContext.getRuntimeHints());
<ide> BeanRegistrationCodeFragments codeFragments = getCodeFragments(generationContext,
<ide> beanRegistrationsCode);
<ide> Class<?> target = codeFragments.getTarget(this.registeredBean,
<ide> private String getSimpleBeanName(String beanName) {
<ide> return StringUtils.uncapitalize(beanName);
<ide> }
<ide>
<add> private void registerRuntimeHintsIfNecessary(RuntimeHints runtimeHints) {
<add> if (this.registeredBean.getBeanFactory() instanceof DefaultListableBeanFactory dlbf) {
<add> ProxyRuntimeHintsRegistrar registrar = new ProxyRuntimeHintsRegistrar(dlbf.getAutowireCandidateResolver());
<add> if (this.constructorOrFactoryMethod instanceof Method method) {
<add> registrar.registerRuntimeHints(runtimeHints, method);
<add> }
<add> else if (this.constructorOrFactoryMethod instanceof Constructor<?> constructor) {
<add> registrar.registerRuntimeHints(runtimeHints, constructor);
<add> }
<add> }
<add> }
<add>
<add> private static class ProxyRuntimeHintsRegistrar {
<add>
<add> private final AutowireCandidateResolver candidateResolver;
<add>
<add> public ProxyRuntimeHintsRegistrar(AutowireCandidateResolver candidateResolver) {
<add> this.candidateResolver = candidateResolver;
<add> }
<add>
<add> public void registerRuntimeHints(RuntimeHints runtimeHints, Method method) {
<add> Class<?>[] parameterTypes = method.getParameterTypes();
<add> for (int i = 0; i < parameterTypes.length; i++) {
<add> MethodParameter methodParam = new MethodParameter(method, i);
<add> DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(
<add> methodParam, true);
<add> registerProxyIfNecessary(runtimeHints, dependencyDescriptor);
<add> }
<add> }
<add>
<add> public void registerRuntimeHints(RuntimeHints runtimeHints, Constructor<?> constructor) {
<add> Class<?>[] parameterTypes = constructor.getParameterTypes();
<add> for (int i = 0; i < parameterTypes.length; i++) {
<add> MethodParameter methodParam = new MethodParameter(constructor, i);
<add> DependencyDescriptor dependencyDescriptor = new DependencyDescriptor(
<add> methodParam, true);
<add> registerProxyIfNecessary(runtimeHints, dependencyDescriptor);
<add> }
<add> }
<add>
<add> private void registerProxyIfNecessary(RuntimeHints runtimeHints, DependencyDescriptor dependencyDescriptor) {
<add> Class<?> proxyType = this.candidateResolver
<add> .getLazyResolutionProxyClass(dependencyDescriptor, null);
<add> if (proxyType != null && Proxy.isProxyClass(proxyType)) {
<add> runtimeHints.proxies().registerJdkProxy(proxyType.getInterfaces());
<add> }
<add> }
<add>
<add> }
<add>
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/context/aot/ApplicationContextAotGeneratorTests.java
<ide> package org.springframework.context.aot;
<ide>
<ide> import java.io.IOException;
<add>import java.lang.reflect.Proxy;
<ide> import java.util.function.BiConsumer;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.aot.generate.GeneratedFiles.Kind;
<add>import org.springframework.aot.generate.GenerationContext;
<ide> import org.springframework.aot.hint.MemberCategory;
<add>import org.springframework.aot.hint.RuntimeHints;
<ide> import org.springframework.aot.hint.TypeReference;
<ide> import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
<ide> import org.springframework.aot.test.generator.compile.Compiled;
<ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.AnnotationConfigUtils;
<ide> import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
<add>import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
<ide> import org.springframework.context.support.GenericApplicationContext;
<ide> import org.springframework.context.testfixture.context.generator.SimpleComponent;
<ide> import org.springframework.context.testfixture.context.generator.annotation.AutowiredComponent;
<ide> import org.springframework.context.testfixture.context.generator.annotation.CglibConfiguration;
<ide> import org.springframework.context.testfixture.context.generator.annotation.InitDestroyComponent;
<add>import org.springframework.context.testfixture.context.generator.annotation.LazyAutowiredFieldComponent;
<add>import org.springframework.context.testfixture.context.generator.annotation.LazyAutowiredMethodComponent;
<add>import org.springframework.context.testfixture.context.generator.annotation.LazyConstructorArgumentComponent;
<add>import org.springframework.context.testfixture.context.generator.annotation.LazyFactoryMethodArgumentComponent;
<add>import org.springframework.core.env.Environment;
<add>import org.springframework.core.io.ResourceLoader;
<ide> import org.springframework.core.testfixture.aot.generate.TestGenerationContext;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> void processAheadOfTimeWhenHasAutowiring() {
<ide> });
<ide> }
<ide>
<add> @Test
<add> void processAheadOfTimeWhenHasLazyAutowiringOnField() {
<add> testAutowiredComponent(LazyAutowiredFieldComponent.class, (bean, generationContext) -> {
<add> Environment environment = bean.getEnvironment();
<add> assertThat(environment).isInstanceOf(Proxy.class);
<add> ResourceLoader resourceLoader = bean.getResourceLoader();
<add> assertThat(resourceLoader).isNotInstanceOf(Proxy.class);
<add> RuntimeHints runtimeHints = generationContext.getRuntimeHints();
<add> assertThat(runtimeHints.proxies().jdkProxies()).singleElement().satisfies(proxyHint ->
<add> assertThat(proxyHint.getProxiedInterfaces()).isEqualTo(TypeReference.listOf(
<add> environment.getClass().getInterfaces())));
<add>
<add> });
<add> }
<add>
<add> @Test
<add> void processAheadOfTimeWhenHasLazyAutowiringOnMethod() {
<add> testAutowiredComponent(LazyAutowiredMethodComponent.class, (bean, generationContext) -> {
<add> Environment environment = bean.getEnvironment();
<add> assertThat(environment).isNotInstanceOf(Proxy.class);
<add> ResourceLoader resourceLoader = bean.getResourceLoader();
<add> assertThat(resourceLoader).isInstanceOf(Proxy.class);
<add> RuntimeHints runtimeHints = generationContext.getRuntimeHints();
<add> assertThat(runtimeHints.proxies().jdkProxies()).singleElement().satisfies(proxyHint ->
<add> assertThat(proxyHint.getProxiedInterfaces()).isEqualTo(TypeReference.listOf(
<add> resourceLoader.getClass().getInterfaces())));
<add> });
<add> }
<add>
<add> @Test
<add> void processAheadOfTimeWhenHasLazyAutowiringOnConstructor() {
<add> testAutowiredComponent(LazyConstructorArgumentComponent.class, (bean, generationContext) -> {
<add> Environment environment = bean.getEnvironment();
<add> assertThat(environment).isInstanceOf(Proxy.class);
<add> ResourceLoader resourceLoader = bean.getResourceLoader();
<add> assertThat(resourceLoader).isNotInstanceOf(Proxy.class);
<add> RuntimeHints runtimeHints = generationContext.getRuntimeHints();
<add> assertThat(runtimeHints.proxies().jdkProxies()).singleElement().satisfies(proxyHint ->
<add> assertThat(proxyHint.getProxiedInterfaces()).isEqualTo(TypeReference.listOf(
<add> environment.getClass().getInterfaces())));
<add> });
<add> }
<add>
<add> @Test
<add> void processAheadOfTimeWhenHasLazyAutowiringOnFactoryMethod() {
<add> RootBeanDefinition bd = new RootBeanDefinition(LazyFactoryMethodArgumentComponent.class);
<add> bd.setFactoryMethodName("of");
<add> testAutowiredComponent(LazyFactoryMethodArgumentComponent.class, bd, (bean, generationContext) -> {
<add> Environment environment = bean.getEnvironment();
<add> assertThat(environment).isInstanceOf(Proxy.class);
<add> ResourceLoader resourceLoader = bean.getResourceLoader();
<add> assertThat(resourceLoader).isNotInstanceOf(Proxy.class);
<add> RuntimeHints runtimeHints = generationContext.getRuntimeHints();
<add> assertThat(runtimeHints.proxies().jdkProxies()).singleElement().satisfies(proxyHint ->
<add> assertThat(proxyHint.getProxiedInterfaces()).isEqualTo(TypeReference.listOf(
<add> environment.getClass().getInterfaces())));
<add> });
<add> }
<add>
<add> private <T> void testAutowiredComponent(Class<T> type, BiConsumer<T, GenerationContext> assertions) {
<add> testAutowiredComponent(type, new RootBeanDefinition(type), assertions);
<add> }
<add>
<add> private <T> void testAutowiredComponent(Class<T> type, RootBeanDefinition beanDefinition,
<add> BiConsumer<T, GenerationContext> assertions) {
<add> GenericApplicationContext applicationContext = new GenericApplicationContext();
<add> applicationContext.getDefaultListableBeanFactory().setAutowireCandidateResolver(
<add> new ContextAnnotationAutowireCandidateResolver());
<add> applicationContext.registerBeanDefinition(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME,
<add> BeanDefinitionBuilder
<add> .rootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class)
<add> .setRole(BeanDefinition.ROLE_INFRASTRUCTURE).getBeanDefinition());
<add> applicationContext.registerBeanDefinition("testComponent", beanDefinition);
<add> TestGenerationContext generationContext = processAheadOfTime(applicationContext);
<add> testCompiledResult(generationContext, (initializer, compiled) -> {
<add> GenericApplicationContext freshApplicationContext = toFreshApplicationContext(initializer);
<add> assertThat(freshApplicationContext.getBeanDefinitionNames()).containsOnly("testComponent");
<add> assertions.accept(freshApplicationContext.getBean("testComponent", type), generationContext);
<add> });
<add> }
<add>
<ide> @Test
<ide> void processAheadOfTimeWhenHasInitDestroyMethods() {
<ide> GenericApplicationContext applicationContext = new GenericApplicationContext();
<ide> private static TestGenerationContext processAheadOfTime(GenericApplicationContex
<ide> return generationContext;
<ide> }
<ide>
<del> @SuppressWarnings({ "rawtypes", "unchecked" })
<ide> private void testCompiledResult(GenericApplicationContext applicationContext,
<ide> BiConsumer<ApplicationContextInitializer<GenericApplicationContext>, Compiled> result) {
<del> TestGenerationContext generationContext = processAheadOfTime(applicationContext);
<add> testCompiledResult(processAheadOfTime(applicationContext), result);
<add> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> private void testCompiledResult(TestGenerationContext generationContext,
<add> BiConsumer<ApplicationContextInitializer<GenericApplicationContext>, Compiled> result) {
<ide> TestCompiler.forSystem().withFiles(generationContext.getGeneratedFiles()).compile(compiled ->
<ide> result.accept(compiled.getInstance(ApplicationContextInitializer.class), compiled));
<ide> }
<ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/generator/annotation/LazyAutowiredFieldComponent.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://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>package org.springframework.context.testfixture.context.generator.annotation;
<add>
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Lazy;
<add>import org.springframework.core.env.Environment;
<add>import org.springframework.core.io.ResourceLoader;
<add>
<add>public class LazyAutowiredFieldComponent {
<add>
<add> @Lazy
<add> @Autowired
<add> private Environment environment;
<add>
<add> @Autowired
<add> private ResourceLoader resourceLoader;
<add>
<add> public Environment getEnvironment() {
<add> return this.environment;
<add> }
<add>
<add>
<add> public ResourceLoader getResourceLoader() {
<add> return this.resourceLoader;
<add> }
<add>}
<ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/generator/annotation/LazyAutowiredMethodComponent.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://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>package org.springframework.context.testfixture.context.generator.annotation;
<add>
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Lazy;
<add>import org.springframework.core.env.Environment;
<add>import org.springframework.core.io.ResourceLoader;
<add>
<add>public class LazyAutowiredMethodComponent {
<add>
<add> private Environment environment;
<add>
<add> private ResourceLoader resourceLoader;
<add>
<add> @Autowired
<add> public void setEnvironment(Environment environment) {
<add> this.environment = environment;
<add> }
<add>
<add> public Environment getEnvironment() {
<add> return this.environment;
<add> }
<add>
<add> @Autowired
<add> public void setResourceLoader(@Lazy ResourceLoader resourceLoader) {
<add> this.resourceLoader = resourceLoader;
<add> }
<add>
<add> public ResourceLoader getResourceLoader() {
<add> return this.resourceLoader;
<add> }
<add>}
<ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/generator/annotation/LazyConstructorArgumentComponent.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://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>package org.springframework.context.testfixture.context.generator.annotation;
<add>
<add>import org.springframework.context.annotation.Lazy;
<add>import org.springframework.core.env.Environment;
<add>import org.springframework.core.io.ResourceLoader;
<add>
<add>/**
<add> *
<add> * @author Stephane Nicoll
<add> */
<add>public class LazyConstructorArgumentComponent {
<add>
<add> private final Environment environment;
<add>
<add> private final ResourceLoader resourceLoader;
<add>
<add> public LazyConstructorArgumentComponent(@Lazy Environment environment, ResourceLoader resourceLoader) {
<add> this.environment = environment;
<add> this.resourceLoader = resourceLoader;
<add> }
<add>
<add> public Environment getEnvironment() {
<add> return this.environment;
<add> }
<add>
<add> public ResourceLoader getResourceLoader() {
<add> return this.resourceLoader;
<add> }
<add>
<add>}
<ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/generator/annotation/LazyFactoryMethodArgumentComponent.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<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> * https://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>package org.springframework.context.testfixture.context.generator.annotation;
<add>
<add>import org.springframework.context.annotation.Lazy;
<add>import org.springframework.core.env.Environment;
<add>import org.springframework.core.io.ResourceLoader;
<add>
<add>public class LazyFactoryMethodArgumentComponent {
<add>
<add> private final Environment environment;
<add>
<add> private final ResourceLoader resourceLoader;
<add>
<add> LazyFactoryMethodArgumentComponent(Environment environment, ResourceLoader resourceLoader) {
<add> this.environment = environment;
<add> this.resourceLoader = resourceLoader;
<add> }
<add>
<add> public static LazyFactoryMethodArgumentComponent of(@Lazy Environment environment, ResourceLoader resourceLoader) {
<add> return new LazyFactoryMethodArgumentComponent(environment, resourceLoader);
<add> }
<add>
<add> public Environment getEnvironment() {
<add> return this.environment;
<add> }
<add>
<add> public ResourceLoader getResourceLoader() {
<add> return this.resourceLoader;
<add> }
<add>
<add>} | 7 |
PHP | PHP | remove obsolete class import in file.php | 6a58e983164d0f4a7bf4bc82bdb890f35fcb8151 | <ide><path>laravel/file.php
<del><?php namespace Laravel; use Closure, FilesystemIterator as fIterator;
<add><?php namespace Laravel; use FilesystemIterator as fIterator;
<ide>
<ide> class File {
<ide> | 1 |
Javascript | Javascript | add jsdoc types to lib/path | f1a21e5c914f9bcbbb2a77b436eae2bc4f4c2a86 | <ide><path>lib/path.js
<ide> function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
<ide> return res;
<ide> }
<ide>
<add>/**
<add> * @param {string} sep
<add> * @param {{
<add> * dir?: string;
<add> * root?: string;
<add> * base?: string;
<add> * name?: string;
<add> * ext?: string;
<add> * }} pathObject
<add> * @returns {string}
<add> */
<ide> function _format(sep, pathObject) {
<ide> validateObject(pathObject, 'pathObject');
<ide> const dir = pathObject.dir || pathObject.root;
<ide> function _format(sep, pathObject) {
<ide> }
<ide>
<ide> const win32 = {
<del> // path.resolve([from ...], to)
<add> /**
<add> * path.resolve([from ...], to)
<add> * @param {...string} args
<add> * @returns {string}
<add> */
<ide> resolve(...args) {
<ide> let resolvedDevice = '';
<ide> let resolvedTail = '';
<ide> const win32 = {
<ide> `${resolvedDevice}${resolvedTail}` || '.';
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {string}
<add> */
<ide> normalize(path) {
<ide> validateString(path, 'path');
<ide> const len = path.length;
<ide> const win32 = {
<ide> return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {boolean}
<add> */
<ide> isAbsolute(path) {
<ide> validateString(path, 'path');
<ide> const len = path.length;
<ide> const win32 = {
<ide> isPathSeparator(StringPrototypeCharCodeAt(path, 2)));
<ide> },
<ide>
<add> /**
<add> * @param {...string} args
<add> * @returns {string}
<add> */
<ide> join(...args) {
<ide> if (args.length === 0)
<ide> return '.';
<ide> const win32 = {
<ide> return win32.normalize(joined);
<ide> },
<ide>
<del> // It will solve the relative path from `from` to `to`, for instance:
<del> // from = 'C:\\orandea\\test\\aaa'
<del> // to = 'C:\\orandea\\impl\\bbb'
<del> // The output of the function should be: '..\\..\\impl\\bbb'
<add> /**
<add> * It will solve the relative path from `from` to `to`, for instancee
<add> * from = 'C:\\orandea\\test\\aaa'
<add> * to = 'C:\\orandea\\impl\\bbb'
<add> * The output of the function should be: '..\\..\\impl\\bbb'
<add> * @param {string} from
<add> * @param {string} to
<add> * @returns {string}
<add> */
<ide> relative(from, to) {
<ide> validateString(from, 'from');
<ide> validateString(to, 'to');
<ide> const win32 = {
<ide> return path;
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {string}
<add> */
<ide> dirname(path) {
<ide> validateString(path, 'path');
<ide> const len = path.length;
<ide> const win32 = {
<ide> return StringPrototypeSlice(path, 0, end);
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @param {string} [ext]
<add> * @returns {string}
<add> */
<ide> basename(path, ext) {
<ide> if (ext !== undefined)
<ide> validateString(ext, 'ext');
<ide> const win32 = {
<ide> return StringPrototypeSlice(path, start, end);
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {string}
<add> */
<ide> extname(path) {
<ide> validateString(path, 'path');
<ide> let start = 0;
<ide> const win32 = {
<ide>
<ide> format: FunctionPrototypeBind(_format, null, '\\'),
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {{
<add> * dir: string;
<add> * root: string;
<add> * base: string;
<add> * name: string;
<add> * ext: string;
<add> * }}
<add> */
<ide> parse(path) {
<ide> validateString(path, 'path');
<ide>
<ide> const posixCwd = (() => {
<ide> })();
<ide>
<ide> const posix = {
<del> // path.resolve([from ...], to)
<add> /**
<add> * path.resolve([from ...], to)
<add> * @param {...string} args
<add> * @returns {string}
<add> */
<ide> resolve(...args) {
<ide> let resolvedPath = '';
<ide> let resolvedAbsolute = false;
<ide> const posix = {
<ide> return resolvedPath.length > 0 ? resolvedPath : '.';
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {string}
<add> */
<ide> normalize(path) {
<ide> validateString(path, 'path');
<ide>
<ide> const posix = {
<ide> return isAbsolute ? `/${path}` : path;
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {boolean}
<add> */
<ide> isAbsolute(path) {
<ide> validateString(path, 'path');
<ide> return path.length > 0 &&
<ide> StringPrototypeCharCodeAt(path, 0) === CHAR_FORWARD_SLASH;
<ide> },
<ide>
<add> /**
<add> * @param {...string} args
<add> * @returns {string}
<add> */
<ide> join(...args) {
<ide> if (args.length === 0)
<ide> return '.';
<ide> const posix = {
<ide> return posix.normalize(joined);
<ide> },
<ide>
<add> /**
<add> * @param {string} from
<add> * @param {string} to
<add> * @returns {string}
<add> */
<ide> relative(from, to) {
<ide> validateString(from, 'from');
<ide> validateString(to, 'to');
<ide> const posix = {
<ide> return path;
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {string}
<add> */
<ide> dirname(path) {
<ide> validateString(path, 'path');
<ide> if (path.length === 0)
<ide> const posix = {
<ide> return StringPrototypeSlice(path, 0, end);
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @param {string} [ext]
<add> * @returns {string}
<add> */
<ide> basename(path, ext) {
<ide> if (ext !== undefined)
<ide> validateString(ext, 'ext');
<ide> const posix = {
<ide> return StringPrototypeSlice(path, start, end);
<ide> },
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {string}
<add> */
<ide> extname(path) {
<ide> validateString(path, 'path');
<ide> let startDot = -1;
<ide> const posix = {
<ide>
<ide> format: FunctionPrototypeBind(_format, null, '/'),
<ide>
<add> /**
<add> * @param {string} path
<add> * @returns {{
<add> * dir: string;
<add> * root: string;
<add> * base: string;
<add> * name: string;
<add> * ext: string;
<add> * }}
<add> */
<ide> parse(path) {
<ide> validateString(path, 'path');
<ide> | 1 |
Javascript | Javascript | move unnecessary work for early return | 128567128352a46c8add41f86c0d04ff6dc81d8b | <ide><path>lib/module.js
<ide> function tryExtensions(p, exts) {
<ide>
<ide> var warned = false;
<ide> Module._findPath = function(request, paths) {
<del> var exts = Object.keys(Module._extensions);
<del>
<ide> if (path.isAbsolute(request)) {
<ide> paths = [''];
<ide> }
<ide>
<del> var trailingSlash = (request.slice(-1) === '/');
<del>
<ide> var cacheKey = JSON.stringify({request: request, paths: paths});
<ide> if (Module._pathCache[cacheKey]) {
<ide> return Module._pathCache[cacheKey];
<ide> }
<ide>
<add> const exts = Object.keys(Module._extensions);
<add> const trailingSlash = request.slice(-1) === '/';
<add>
<ide> // For each path
<ide> for (var i = 0, PL = paths.length; i < PL; i++) {
<ide> // Don't search further if path doesn't exist | 1 |
Ruby | Ruby | make use of helpers in associationreflection | 9db4c07e0bdf60982d08cb26035573995404eb98 | <ide><path>activerecord/lib/active_record/associations/through_association.rb
<ide> def construct_joins
<ide> conditions = []
<ide>
<ide> if @reflection.source_reflection.macro == :belongs_to
<del> reflection_primary_key = @reflection.source_reflection.options[:primary_key] ||
<del> @reflection.klass.primary_key
<add> reflection_primary_key = @reflection.source_reflection.association_primary_key
<ide> source_primary_key = @reflection.source_reflection.foreign_key
<add>
<ide> if @reflection.options[:source_type]
<ide> column = @reflection.source_reflection.foreign_type
<ide> conditions <<
<ide> right[column].eq(@reflection.options[:source_type])
<ide> end
<ide> else
<ide> reflection_primary_key = @reflection.source_reflection.foreign_key
<del> source_primary_key = @reflection.source_reflection.options[:primary_key] ||
<del> @reflection.through_reflection.klass.primary_key
<add> source_primary_key = @reflection.source_reflection.active_record_primary_key
<add>
<ide> if @reflection.source_reflection.options[:as]
<ide> column = "#{@reflection.source_reflection.options[:as]}_type"
<ide> conditions << | 1 |
Text | Text | update example icu url | d8ec5a2e92b431ccea3fb83362628a0696273842 | <ide><path>doc/guides/maintaining-icu.md
<ide> V8 will not compile.
<ide>
<ide> ```c
<ide> // deps/v8/src/objects/intl-objects.h
<del>#define V8_MINIMUM_ICU_VERSION 64
<add>#define V8_MINIMUM_ICU_VERSION 65
<ide> ```
<ide>
<ide> V8 in Node.js depends on the ICU version supplied by Node.js.
<ide> should be sufficient).
<ide> ```bash
<ide> ./configure \
<ide> --with-intl=full-icu \
<del> --with-icu-source=http://download.icu-project.org/files/icu4c/58.1/icu4c-58_1-src.tgz
<add> --with-icu-source=https://github.com/unicode-org/icu/releases/download/release-67-1/icu4c-67_1-src.tgz
<ide> make
<ide> ```
<ide> | 1 |
Javascript | Javascript | add some test cases for cjs tree-shaking | 26f30cebce31579699f9a75d94de9bd78853a6de | <ide><path>test/cases/cjs-tree-shaking/bailouts/accessing-call-context.js
<add>module.exports.func = function f() {
<add> "use strict";
<add> return this;
<add>};
<add>module.exports.abc = "abc";
<ide><path>test/cases/cjs-tree-shaking/bailouts/accessing-module.js
<add>exports.abc = "abc";
<add>
<add>function f(m) {
<add> m.exports = { abc: "abc", def: "def" };
<add>}
<add>
<add>f(module);
<ide><path>test/cases/cjs-tree-shaking/bailouts/assign-exports-assign.js
<add>exports.abc = "abc";
<add>
<add>var newObj = {};
<add>exports = newObj;
<add>
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/bailouts/assign-exports-define.js
<add>Object.defineProperty(exports, "abc", { value: "abc" });
<add>
<add>var newObj = {};
<add>exports = newObj;
<add>
<add>Object.defineProperty(exports, "def", { value: "def" });
<ide><path>test/cases/cjs-tree-shaking/bailouts/define-module-properties.js
<add>exports.abc = "abc";
<add>
<add>Object.defineProperties(module, {
<add> exports: {
<add> value: {
<add> abc: "abc",
<add> def: "def"
<add> }
<add> }
<add>});
<ide><path>test/cases/cjs-tree-shaking/bailouts/define-module-property.js
<add>exports.abc = "abc";
<add>
<add>Object.defineProperty(module, "exports", {
<add> value: {
<add> abc: "abc",
<add> def: "def"
<add> }
<add>});
<ide><path>test/cases/cjs-tree-shaking/bailouts/index.js
<add>it("should bailout when reading whole exports object from this", () => {
<add> var test = require("./reading-this").test;
<add> expect(test().abc).toBe("abc");
<add>});
<add>
<add>it("should bailout when reading whole exports object from exports", () => {
<add> var test = require("./reading-exports").test;
<add> expect(test().abc).toBe("abc");
<add>});
<add>
<add>it("should bailout when reading whole exports object from module.exports", () => {
<add> var test = require("./reading-module-exports").test;
<add> expect(test().abc).toBe("abc");
<add>});
<add>
<add>it("should reassigning exports (assign values)", () => {
<add> expect(require("./assign-exports-assign").abc).toBe("abc");
<add> expect(require("./assign-exports-assign").def).toBe(undefined);
<add>});
<add>
<add>it("should reassigning exports (define values)", () => {
<add> expect(require("./assign-exports-define").abc).toBe("abc");
<add> expect(require("./assign-exports-define").def).toBe(undefined);
<add>});
<add>
<add>it("should not mangle or remove nested properties", () => {
<add> expect(require("./nested-property").abc).toBe("abc");
<add>});
<add>
<add>it("should be able to access the exports via call context", () => {
<add> expect(require("./accessing-call-context?1").func().abc).toBe("abc");
<add> var cc = require("./accessing-call-context?2");
<add> expect(cc.func().abc).toBe("abc");
<add> var func = require("./accessing-call-context?3").func;
<add> expect(func()).toBe(undefined);
<add>});
<add>
<add>it("should be able to define an exports property on module (property)", () => {
<add> expect(require("./define-module-property?2").abc).toBe("abc");
<add> expect(require("./define-module-property?1").def).toBe("def");
<add>});
<add>
<add>it("should be able to define an exports property on module (properties)", () => {
<add> expect(require("./define-module-properties?2").abc).toBe("abc");
<add> expect(require("./define-module-properties?1").def).toBe("def");
<add>});
<add>
<add>it("should be able to do stuff with the module object", () => {
<add> expect(require("./accessing-module?2").abc).toBe("abc");
<add> expect(require("./accessing-module?1").def).toBe("def");
<add>});
<add>
<add>it("should be able to use AMD to define exports", () => {
<add> expect(require("./using-amd?2").abc).toBe("abc");
<add> expect(require("./using-amd?1").def).toBe("def");
<add>});
<ide><path>test/cases/cjs-tree-shaking/bailouts/nested-property.js
<add>var abc = {};
<add>
<add>module.exports = abc;
<add>
<add>module.exports.abc = "abc";
<add>module.exports.def = "def";
<add>
<add>expect(abc).toEqual({ abc: "abc", def: "def" });
<ide><path>test/cases/cjs-tree-shaking/bailouts/reading-exports.js
<add>exports.abc = "abc";
<add>
<add>exports.test = function() {
<add> return exports;
<add>};
<ide><path>test/cases/cjs-tree-shaking/bailouts/reading-module-exports.js
<add>exports.abc = "abc";
<add>
<add>exports.test = function() {
<add> return module.exports;
<add>};
<ide><path>test/cases/cjs-tree-shaking/bailouts/reading-this.js
<add>exports.abc = "abc";
<add>
<add>exports.test = () => {
<add> return this;
<add>};
<ide><path>test/cases/cjs-tree-shaking/bailouts/using-amd.js
<add>exports.abc = "not-abc";
<add>define({
<add> abc: "abc",
<add> def: "def"
<add>});
<ide><path>test/cases/cjs-tree-shaking/cjs-to-esm/index.js
<add>it("should allow to require esm", () => {
<add> expect(require("./module?1").abc).toBe("abc");
<add> expect(typeof require("./module?2").func).toBe("function");
<add> // check if a function called with a namespace object as context
<add> // still yield the same optimization, compared to only accessing
<add> // the export
<add> expect(Object.keys(require("./module?3").func())).toEqual(
<add> Object.keys(require.cache[require.resolve("./module?2")].exports)
<add> );
<add>});
<ide><path>test/cases/cjs-tree-shaking/cjs-to-esm/module.js
<add>export const abc = "abc";
<add>export const def = "def";
<add>export const func = function() {
<add> "use strict";
<add> return this;
<add>};
<ide><path>test/cases/cjs-tree-shaking/esm-to-cjs/index.js
<add>import m1 from "./module?1";
<add>import m2 from "./module?2";
<add>import { abc } from "./module?3";
<add>
<add>it("should allow to import cjs with esm", () => {
<add> expect(m1.abc).toBe("abc");
<add> expect(m2).toEqual({ abc: "abc", def: "def" });
<add> expect(abc).toBe("abc");
<add>});
<ide><path>test/cases/cjs-tree-shaking/esm-to-cjs/module.js
<add>exports.abc = "abc";
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/assign-exports-property.js
<add>exports.abc = "abc";
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/assign-module-exports-property.js
<add>module.exports.abc = "abc";
<add>module.exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/assign-this-property.js
<add>this.abc = "abc";
<add>this.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/attach-to-arrow-function.js
<add>module.exports = () => "abc";
<add>
<add>module.exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/attach-to-function.js
<add>module.exports = function() {
<add> return "abc";
<add>};
<add>
<add>module.exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/attach-to-object.js
<add>module.exports = {
<add> abc: "abc"
<add>};
<add>
<add>module.exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/exports/define-exports-property.js
<add>Object.defineProperty(exports, "abc", { enumerable: true, value: "abc" });
<add>Object.defineProperty(exports, "def", { enumerable: true, value: "def" });
<ide><path>test/cases/cjs-tree-shaking/exports/define-module-exports-property.js
<add>Object.defineProperty(module.exports, "abc", {
<add> enumerable: true,
<add> value: "abc"
<add>});
<add>Object.defineProperty(module.exports, "def", {
<add> enumerable: true,
<add> value: "def"
<add>});
<ide><path>test/cases/cjs-tree-shaking/exports/define-this-property.js
<add>Object.defineProperty(this, "abc", { enumerable: true, value: "abc" });
<add>Object.defineProperty(this, "def", { enumerable: true, value: "def" });
<ide><path>test/cases/cjs-tree-shaking/exports/index.js
<add>it("should allow to export via exports", () => {
<add> expect(require("./assign-exports-property?1").abc).toBe("abc");
<add> expect(require("./assign-exports-property?2")).toEqual({
<add> abc: "abc",
<add> def: "def"
<add> });
<add>});
<add>
<add>it("should allow to export via module.exports", () => {
<add> expect(require("./assign-module-exports-property?1").abc).toBe("abc");
<add> expect(require("./assign-module-exports-property?2")).toEqual({
<add> abc: "abc",
<add> def: "def"
<add> });
<add>});
<add>
<add>it("should allow to export via this", () => {
<add> expect(require("./assign-this-property?1").abc).toBe("abc");
<add> expect(require("./assign-this-property?2")).toEqual({
<add> abc: "abc",
<add> def: "def"
<add> });
<add>});
<add>
<add>it("should allow to export via define property on exports", () => {
<add> expect(require("./define-exports-property?1").abc).toBe("abc");
<add> expect(require("./define-exports-property?2")).toEqual({
<add> abc: "abc",
<add> def: "def"
<add> });
<add>});
<add>
<add>it("should allow to export via define property on module.exports", () => {
<add> expect(require("./define-module-exports-property?1").abc).toBe("abc");
<add> expect(require("./define-module-exports-property?2")).toEqual({
<add> abc: "abc",
<add> def: "def"
<add> });
<add>});
<add>
<add>it("should allow to export via define property on this", () => {
<add> expect(require("./define-this-property?1").abc).toBe("abc");
<add> expect(require("./define-this-property?2")).toEqual({
<add> abc: "abc",
<add> def: "def"
<add> });
<add>});
<add>
<add>it("should allow to read own exports via exports", () => {
<add> var test = require("./reading-self-from-exports").test;
<add> expect(test()).toBe("abc");
<add>});
<add>
<add>it("should allow to read own exports via module.exports", () => {
<add> var test = require("./reading-self-from-module-exports").test;
<add> expect(test()).toBe("abc");
<add>});
<add>
<add>it("should allow to read own exports via this", () => {
<add> var test = require("./reading-self-from-this").test;
<add> expect(test()).toBe("abc");
<add>});
<add>
<add>it("should allow to attach exports to object", () => {
<add> expect(require("./attach-to-object?1").abc).toBe("abc");
<add> expect(require("./attach-to-object?2").def).toBe("def");
<add> expect(require("./attach-to-object?3").abc).toBe("abc");
<add> expect(require("./attach-to-object?3").def).toBe("def");
<add>});
<add>
<add>it("should allow to attach exports to function", () => {
<add> expect(require("./attach-to-function?1")()).toBe("abc");
<add> expect(require("./attach-to-function?2").def).toBe("def");
<add> expect(require("./attach-to-function?3")()).toBe("abc");
<add> expect(require("./attach-to-function?3").def).toBe("def");
<add>});
<add>
<add>it("should allow to attach exports to arrow function", () => {
<add> expect(require("./attach-to-arrow-function?1")()).toBe("abc");
<add> expect(require("./attach-to-arrow-function?2").def).toBe("def");
<add> expect(require("./attach-to-arrow-function?3")()).toBe("abc");
<add> expect(require("./attach-to-arrow-function?3").def).toBe("def");
<add>});
<ide><path>test/cases/cjs-tree-shaking/exports/reading-self-from-exports.js
<add>exports.abc = "abc";
<add>
<add>exports.test = function() {
<add> return exports.abc;
<add>};
<ide><path>test/cases/cjs-tree-shaking/exports/reading-self-from-module-exports.js
<add>exports.abc = "abc";
<add>
<add>exports.test = function() {
<add> return module.exports.abc;
<add>};
<ide><path>test/cases/cjs-tree-shaking/exports/reading-self-from-this.js
<add>exports.abc = "abc";
<add>
<add>exports.test = () => {
<add> return this.abc;
<add>};
<ide><path>test/cases/cjs-tree-shaking/importing/index.js
<add>it("should be able to import a module via require and property", () => {
<add> expect(require("./module").abc).toBe("abc");
<add>});
<add>
<add>it("should be able to import a module via require and destruct", () => {
<add> var { abc } = require("./module");
<add> expect(abc).toBe("abc");
<add>});
<add>
<add>it("should be able to import a module via require and exports object", () => {
<add> var module1 = require("./module?1");
<add> expect(module1.abc).toBe("abc");
<add> var module2 = require("./module?2");
<add> expect(module2).toEqual({ abc: "abc", def: "def" });
<add>});
<ide><path>test/cases/cjs-tree-shaking/importing/module.js
<add>exports.abc = "abc";
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/mutate/index.js
<add>import module1 from "./module?1";
<add>import module2, { a } from "./module?2";
<add>
<add>it("should allow mutating imported modules (changing existing exports)", () => {
<add> expect(module1.abc).toBe("abc");
<add> expect(module1.def).toBe("def");
<add> module1.abc = "new-abc";
<add> expect(module1.abc).toBe("new-abc");
<add> expect(module1.def).toBe("def");
<add>});
<add>
<add>it("should allow mutating imported modules (adding new properties)", () => {
<add> expect(module2.abc).toBe("abc");
<add> expect(module2.def).toBe("def");
<add> expect(module2.ghi).toBe(undefined);
<add> expect(module2.Oi).toBe(undefined);
<add> expect(module2.a).toBe(undefined);
<add> expect(a).toBe(undefined);
<add> expect(module2[""]).toBe(undefined);
<add> module2.ghi = "ghi";
<add> module2.Oi = "Oi";
<add> module2.a = "a";
<add> module2[""] = {};
<add> module2[""].abc = "abc";
<add> expect(module2.abc).toBe("abc");
<add> expect(module2.def).toBe("def");
<add> expect(module2.ghi).toBe("ghi");
<add> expect(module2.Oi).toBe("Oi");
<add> expect(module2.a).toBe("a");
<add> expect(a).toBe("a");
<add> expect(module2[""]).toEqual({ abc: "abc" });
<add> expect(module2[""].abc).toBe("abc");
<add>});
<ide><path>test/cases/cjs-tree-shaking/mutate/module.js
<add>exports.abc = "abc";
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/namespace/index.js
<add>it("should allow to create namespace exports via __esModule on exports", async () => {
<add> expect(await import("./namespace-via-exports")).toBe(
<add> require("./namespace-via-exports")
<add> );
<add>});
<add>it("should allow to create namespace exports via __esModule on literal", async () => {
<add> expect(await import("./namespace-via-literal")).toBe(
<add> require("./namespace-via-literal")
<add> );
<add>});
<add>it("should allow to create namespace exports via __esModule with Object.defineProperty", async () => {
<add> expect(await import("./namespace-via-define-property")).toBe(
<add> require("./namespace-via-define-property")
<add> );
<add>});
<add>it("should allow to create namespace exports via __esModule with Object.defineProperty minimized true", async () => {
<add> expect(await import("./namespace-via-define-property-minimized")).toBe(
<add> require("./namespace-via-define-property-minimized")
<add> );
<add>});
<add>it("should allow to create namespace exports via __esModule with Object.defineProperties", async () => {
<add> expect(await import("./namespace-via-define-properties")).toBe(
<add> require("./namespace-via-define-properties")
<add> );
<add>});
<ide><path>test/cases/cjs-tree-shaking/namespace/namespace-via-define-properties.js
<add>Object.defineProperties(exports, {
<add> __esModule: { value: true },
<add> abc: { enumerable: true, value: "abc" },
<add> default: { enumerable: true, value: "default" }
<add>});
<ide><path>test/cases/cjs-tree-shaking/namespace/namespace-via-define-property-minimized.js
<add>Object.defineProperty(exports, "__esModule", { value: !0 });
<add>exports.abc = "abc";
<add>exports.default = "default";
<ide><path>test/cases/cjs-tree-shaking/namespace/namespace-via-define-property.js
<add>Object.defineProperty(exports, "__esModule", { value: true });
<add>exports.abc = "abc";
<add>exports.default = "default";
<ide><path>test/cases/cjs-tree-shaking/namespace/namespace-via-exports.js
<add>exports.__esModule = true;
<add>exports.abc = "abc";
<add>exports.default = "default";
<ide>\ No newline at end of file
<ide><path>test/cases/cjs-tree-shaking/namespace/namespace-via-literal.js
<add>module.exports = {
<add> __esModule: true,
<add> abc: "abc",
<add> default: "default"
<add>};
<ide><path>test/cases/cjs-tree-shaking/objects/direct-object.js
<add>module.exports = {
<add> abc: "abc",
<add> def: "def"
<add>};
<ide><path>test/cases/cjs-tree-shaking/objects/index.js
<add>it("should be able to export an object literal", () => {
<add> expect(require("./direct-object?1").abc).toBe("abc");
<add> expect(require("./direct-object?2")).toEqual({ abc: "abc", def: "def" });
<add>});
<add>
<add>it("should be able to export an object literal indirect", () => {
<add> expect(require("./indirect-object?1").abc).toBe("abc");
<add> expect(require("./indirect-object?2")).toEqual({ abc: "abc", def: "def" });
<add>});
<ide><path>test/cases/cjs-tree-shaking/objects/indirect-object.js
<add>var value = {
<add> abc: "abc",
<add> def: "def"
<add>};
<add>
<add>module.exports = value;
<ide><path>test/cases/cjs-tree-shaking/reexports/index.js
<add>it("should allow to reexport a exports object (this, exports)", () => {
<add> expect(require("./reexport-whole-exports?1").m1.abc).toBe("abc");
<add> expect(require("./reexport-whole-exports?2").m2.abc).toBe("abc");
<add> expect(require("./reexport-whole-exports?3").m3.abc).toBe("abc");
<add> expect(require("./reexport-whole-exports?4").m4.abc).toBe("abc");
<add>});
<add>
<add>it("should allow to reexport a exports object (module.exports, object literal)", () => {
<add> expect(require("./reexport-whole-module-exports?1").m1.abc).toBe("abc");
<add> expect(require("./reexport-whole-module-exports?2").m2.abc).toBe("abc");
<add> expect(require("./reexport-whole-module-exports?3").m3.abc).toBe("abc");
<add> expect(require("./reexport-whole-module-exports?4").m4.abc).toBe("abc");
<add>});
<add>
<add>it("should allow to reexport a imported property (this, exports)", () => {
<add> expect(require("./reexport-property-exports?1").p1).toBe("abc");
<add> expect(require("./reexport-property-exports?2").p2).toBe("abc");
<add> expect(require("./reexport-property-exports?3").p3).toBe("abc");
<add> expect(require("./reexport-property-exports?4").p4).toBe("abc");
<add>});
<add>
<add>it("should allow to reexport a imported property (module.exports, object literal)", () => {
<add> expect(require("./reexport-property-module-exports?1").p1).toBe("abc");
<add> expect(require("./reexport-property-module-exports?2").p2).toBe("abc");
<add> expect(require("./reexport-property-module-exports?3").p3).toBe("abc");
<add> expect(require("./reexport-property-module-exports?4").p4).toBe("abc");
<add>});
<add>
<add>it("should allow to reexport a reexported exports object (this, exports)", () => {
<add> expect(require("./reexport-reexport-exports?1").x1.abc).toBe("abc");
<add> expect(require("./reexport-reexport-exports?2").x2.abc).toBe("abc");
<add> expect(require("./reexport-reexport-exports?3").x3.abc).toBe("abc");
<add> expect(require("./reexport-reexport-exports?4").x4.abc).toBe("abc");
<add>});
<add>
<add>it("should allow to reexport a reexported exports object (module.exports, object literal)", () => {
<add> expect(require("./reexport-reexport-module-exports?1").x1.abc).toBe("abc");
<add> expect(require("./reexport-reexport-module-exports?2").x2.abc).toBe("abc");
<add> expect(require("./reexport-reexport-module-exports?3").x3.abc).toBe("abc");
<add> expect(require("./reexport-reexport-module-exports?4").x4.abc).toBe("abc");
<add>});
<ide><path>test/cases/cjs-tree-shaking/reexports/module.js
<add>exports.abc = "abc";
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/reexports/reexport-property-exports.js
<add>exports.p1 = require("./module?pe1").abc;
<add>var m2 = require("./module?pe2");
<add>exports.p2 = m2.abc;
<add>this.p3 = require("./module?pe3").abc;
<add>var m4 = require("./module?pe4");
<add>this.p4 = m4.abc;
<ide><path>test/cases/cjs-tree-shaking/reexports/reexport-property-module-exports.js
<add>var m2 = require("./module?pme2");
<add>module.exports = {
<add> p1: require("./module?pme1").abc,
<add> p2: m2.abc
<add>};
<add>module.exports.p3 = require("./module?pme3").abc;
<add>var m4 = require("./module?pme4");
<add>module.exports.p4 = m4.abc;
<ide><path>test/cases/cjs-tree-shaking/reexports/reexport-reexport-exports.js
<add>exports.x1 = require("./reexport-whole-exports?x1").m1;
<add>var m2 = require("./reexport-whole-exports?x2");
<add>exports.x2 = m2.m2;
<add>this.x3 = require("./reexport-whole-exports?x3").m3;
<add>var m4 = require("./reexport-whole-exports?x4");
<add>this.x4 = m4.m4;
<ide><path>test/cases/cjs-tree-shaking/reexports/reexport-reexport-module-exports.js
<add>var m2 = require("./reexport-whole-module-exports?x2");
<add>module.exports = {
<add> x1: require("./reexport-whole-module-exports?x1").m1,
<add> x2: m2.m2
<add>};
<add>module.exports.x3 = require("./reexport-whole-module-exports?x3").m3;
<add>var m4 = require("./reexport-whole-module-exports?x4");
<add>module.exports.x4 = m4.m4;
<ide><path>test/cases/cjs-tree-shaking/reexports/reexport-whole-exports.js
<add>exports.m1 = require("./module?we1");
<add>var m2 = require("./module?we2");
<add>exports.m2 = m2;
<add>this.m3 = require("./module?we3");
<add>var m4 = require("./module?we4");
<add>this.m4 = m4;
<ide><path>test/cases/cjs-tree-shaking/reexports/reexport-whole-module-exports.js
<add>var m2 = require("./module?wme2");
<add>module.exports = {
<add> m1: require("./module?wme1"),
<add> m2
<add>};
<add>module.exports.m3 = require("./module?wme3");
<add>var m4 = require("./module?wme4");
<add>module.exports.m4 = m4;
<ide><path>test/cases/cjs-tree-shaking/transpiled/babel-default-interop.js
<add>var xxx = _interopRequireDefault(require("./module?2"));
<add>function _interopRequireDefault(obj) {
<add> return obj && obj.__esModule ? obj : { default: obj };
<add>}
<add>module.exports = xxx.default.abc;
<ide><path>test/cases/cjs-tree-shaking/transpiled/index.js
<add>it("should support typescript export *", () => {
<add> expect(require("./typescript-reexport").abc).toBe("abc");
<add>});
<add>
<add>it("should support babel default interop", () => {
<add> var xxx2 = _interopRequireDefault(require("./module?2"));
<add> var xxx3 = _interopRequireDefault(require("./module?3"));
<add> expect(xxx2.default.abc).toBe("abc");
<add> expect(xxx3.default).toEqual({ abc: "abc", def: "def" });
<add>});
<add>
<add>function _interopRequireDefault(obj) {
<add> return obj && obj.__esModule ? obj : { default: obj };
<add>}
<ide><path>test/cases/cjs-tree-shaking/transpiled/module.js
<add>exports.abc = "abc";
<add>exports.def = "def";
<ide><path>test/cases/cjs-tree-shaking/transpiled/typescript-reexport.js
<add>function __export(m) {
<add> for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
<add>}
<add>__export(require("./module?1"));
<ide><path>test/cases/cjs-tree-shaking/weird-names/index.js
<add>import m from "./module";
<add>
<add>it("should allow any name as exports in CommonJs", () => {
<add> expect(m.abc).toBe("abc");
<add> expect(m[""]).toBe("");
<add> expect(m["default"]).toBe("default");
<add> expect(m["0"]).toBe("0");
<add> expect(m[1]).toBe(1);
<add> expect(m.length).toBe("length");
<add> expect(m["0_0"]).toBe("0_0");
<add> expect(m.if).toBe("if");
<add> expect(m["\0"]).toBe("\0");
<add> expect(m["\n"]).toBe("\n");
<add> expect(m["*/"]).toBe("*/");
<add> expect(m["a.b.c"]).toBe("a.b.c");
<add>});
<ide><path>test/cases/cjs-tree-shaking/weird-names/module.js
<add>exports.abc = "abc";
<add>exports[""] = "";
<add>exports["default"] = "default";
<add>exports["0"] = "0";
<add>exports[1] = 1;
<add>exports.length = "length";
<add>exports["0_0"] = "0_0";
<add>exports.if = "if";
<add>exports["\0"] = "\0";
<add>exports["\n"] = "\n";
<add>exports["*/"] = "*/";
<add>exports["a.b.c"] = "a.b.c"; | 56 |
Javascript | Javascript | add regression test for scry order | feae9ad0a82b3e4f5755a8dc5607005c4cb0441b | <ide><path>src/test/__tests__/ReactTestUtils-test.js
<ide> describe('ReactTestUtils', function() {
<ide> expect(scryResults.length).toBe(0);
<ide>
<ide> });
<add>
<add> it('traverses children in the correct order', function() {
<add> var container = document.createElement('div');
<add>
<add> React.render(
<add> <div>
<add> {null}
<add> <div>purple</div>
<add> </div>,
<add> container
<add> );
<add> var tree = React.render(
<add> <div>
<add> <div>orange</div>
<add> <div>purple</div>
<add> </div>,
<add> container
<add> );
<add>
<add> var log = [];
<add> ReactTestUtils.findAllInRenderedTree(tree, function(child) {
<add> log.push(child.getDOMNode().textContent);
<add> });
<add>
<add> // Should be document order, not mount order (which would be purple, orange)
<add> expect(log).toEqual(['orangepurple', 'orange', 'purple']);
<add> });
<ide> }); | 1 |
PHP | PHP | improve performance in tests | 8979159988278a9cff674f92e9ab66cb6a9461d6 | <ide><path>src/TestSuite/Fixture/FixtureDataManager.php
<ide> class FixtureDataManager extends FixtureLoader
<ide> */
<ide> protected $inserted = [];
<ide>
<add> /**
<add> * A map of test classes and whether or not their fixtures have
<add> * been added to the nameMap.
<add> *
<add> * @var bool[]
<add> */
<add> protected $visitedTests = [];
<add>
<ide> /**
<ide> * Looks for fixture files and instantiates the classes accordingly
<ide> *
<ide> class FixtureDataManager extends FixtureLoader
<ide> protected function loadFixtureClasses(TestCase $test): void
<ide> {
<ide> $fixtures = $test->getFixtures();
<del> if (!$fixtures) {
<add> if (!$fixtures || isset($this->visitedTests[get_class($test)])) {
<ide> return;
<ide> }
<add> $this->visitedTests[get_class($test)] = true;
<add>
<ide> foreach ($fixtures as $fixture) {
<ide> if (isset($this->fixtures[$fixture])) {
<ide> continue;
<ide><path>src/TestSuite/Fixture/TruncationStrategy.php
<ide> public function beforeTest(string $test): void
<ide> }
<ide> $schema = $db->getSchemaCollection();
<ide> $tables = $schema->listTables();
<del> $tables = array_intersect($schema->listTables(), $fixtures->lastInserted());
<add> $tables = array_intersect($tables, $fixtures->lastInserted());
<ide>
<ide> $db->disableConstraints(function (Connection $db) use ($tables): void {
<ide> foreach ($tables as $table) {
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php
<ide> protected function _extractTranslations($data)
<ide> */
<ide> public function testCustomTranslationTable()
<ide> {
<add> ConnectionManager::setConfig('custom_i18n_datasource', ['url' => getenv('DB_URL')]);
<add>
<ide> $table = $this->getTableLocator()->get('Articles');
<ide>
<ide> $table->addBehavior('Translate', [
<ide> public function testCustomTranslationTable()
<ide>
<ide> $this->assertSame('CustomI18n', $i18n->getName());
<ide> $this->assertInstanceOf(CustomI18nTable::class, $i18n->getTarget());
<del> $this->assertSame('test_custom_i18n_datasource', $i18n->getTarget()->getConnection()->configName());
<add> $this->assertSame('custom_i18n_datasource', $i18n->getTarget()->getConnection()->configName());
<ide> $this->assertSame('custom_i18n_table', $i18n->getTarget()->getTable());
<add>
<add> ConnectionManager::drop('custom_i18n_datasource');
<ide> }
<ide>
<ide> /**
<ide><path>tests/bootstrap.php
<ide> }
<ide>
<ide> ConnectionManager::setConfig('test', ['url' => getenv('DB_URL')]);
<del>ConnectionManager::setConfig('test_custom_i18n_datasource', ['url' => getenv('DB_URL')]);
<ide>
<ide> Configure::write('Session', [
<ide> 'defaults' => 'php', | 4 |
Javascript | Javascript | remove special test entries | bb6125bac7f7f5ea28c15b3edf0c98901bcc9ada | <ide><path>benchmark/assert/deepequal-buffer.js
<ide> const bench = common.createBenchmark(main, {
<ide> n: [2e4],
<ide> len: [1e2, 1e3],
<ide> strict: [0, 1],
<del> method: [ 'deepEqual', 'notDeepEqual' ],
<add> method: ['deepEqual', 'notDeepEqual'],
<ide> });
<ide>
<ide> function main({ len, n, method, strict }) {
<del> if (!method)
<del> method = 'deepEqual';
<ide> const data = Buffer.allocUnsafe(len + 1);
<ide> const actual = Buffer.alloc(len);
<ide> const expected = Buffer.alloc(len);
<ide><path>benchmark/assert/deepequal-map.js
<ide> function main({ n, len, method, strict }) {
<ide> const array = Array(len).fill(1);
<ide>
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual_primitiveOnly': {
<ide> const values = array.map((_, i) => [`str_${i}`, 123]);
<ide> benchmark(strict ? deepStrictEqual : deepEqual, n, values);
<ide><path>benchmark/assert/deepequal-object.js
<ide> const bench = common.createBenchmark(main, {
<ide> n: [5e3],
<ide> size: [1e2, 1e3, 5e4],
<ide> strict: [0, 1],
<del> method: [ 'deepEqual', 'notDeepEqual' ],
<add> method: ['deepEqual', 'notDeepEqual'],
<ide> });
<ide>
<ide> function createObj(source, add = '') {
<ide> function main({ size, n, method, strict }) {
<ide> // TODO: Fix this "hack". `n` should not be manipulated.
<ide> n = Math.min(Math.ceil(n / size), 20);
<ide>
<del> if (!method)
<del> method = 'deepEqual';
<del>
<ide> const source = Array.apply(null, Array(size));
<ide> const actual = createObj(source);
<ide> const expected = createObj(source);
<ide><path>benchmark/assert/deepequal-prims-and-objs-big-array-set.js
<ide> function main({ n, len, primitive, method, strict }) {
<ide> const expectedWrongSet = new Set(expectedWrong);
<ide>
<ide> switch (method) {
<del> // Empty string falls through to next line as default, mostly for tests.
<del> case '':
<ide> case 'deepEqual_Array':
<ide> run(strict ? deepStrictEqual : deepEqual, n, actual, expected);
<ide> break;
<ide><path>benchmark/assert/deepequal-prims-and-objs-big-loop.js
<ide> const bench = common.createBenchmark(main, {
<ide> primitive: Object.keys(primValues),
<ide> n: [2e4],
<ide> strict: [0, 1],
<del> method: [ 'deepEqual', 'notDeepEqual' ],
<add> method: ['deepEqual', 'notDeepEqual'],
<ide> });
<ide>
<ide> function main({ n, primitive, method, strict }) {
<del> if (!method)
<del> method = 'deepEqual';
<ide> const prim = primValues[primitive];
<ide> const actual = prim;
<ide> const expected = prim;
<ide><path>benchmark/assert/deepequal-set.js
<ide> function main({ n, len, method, strict }) {
<ide> const array = Array(len).fill(1);
<ide>
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'deepEqual_primitiveOnly': {
<ide> const values = array.map((_, i) => `str_${i}`);
<ide> benchmark(strict ? deepStrictEqual : deepEqual, n, values);
<ide><path>benchmark/assert/deepequal-typedarrays.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ type, n, len, method, strict }) {
<del> if (!method)
<del> method = 'deepEqual';
<ide> const clazz = global[type];
<ide> const actual = new clazz(len);
<ide> const expected = new clazz(len);
<ide><path>benchmark/assert/throws.js
<ide> function main({ n, method }) {
<ide> const message = 'failure';
<ide>
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'doesNotThrow':
<ide> bench.start();
<ide> for (let i = 0; i < n; ++i) {
<ide><path>benchmark/buffers/buffer-bytelength.js
<ide> const chars = [
<ide>
<ide> function main({ n, len, encoding }) {
<ide> let strings = [];
<del> let results = [ len * 16 ];
<add> let results = [len * 16];
<ide> if (encoding === 'buffer') {
<del> strings = [ Buffer.alloc(len * 16, 'a') ];
<add> strings = [Buffer.alloc(len * 16, 'a')];
<ide> } else {
<ide> for (const string of chars) {
<ide> // Strings must be built differently, depending on encoding
<ide><path>benchmark/buffers/buffer-creation.js
<ide> const bench = common.createBenchmark(main, {
<ide> function main({ len, n, type }) {
<ide> let fn, i;
<ide> switch (type) {
<del> case '':
<ide> case 'fast-alloc':
<ide> fn = Buffer.alloc;
<ide> break;
<ide><path>benchmark/buffers/buffer-fill.js
<ide> function main({ n, type, size }) {
<ide> const buffer = Buffer.allocUnsafe(size);
<ide> const testFunction = new Function('b', `
<ide> for (var i = 0; i < ${n}; i++) {
<del> b.${type || 'fill(0)'};
<add> b.${type};
<ide> }
<ide> `);
<ide> bench.start();
<ide><path>benchmark/buffers/buffer-iterate.js
<ide> function main({ size, type, method, n }) {
<ide> Buffer.alloc(size) :
<ide> SlowBuffer(size).fill(0);
<ide>
<del> const fn = methods[method || 'for'];
<add> const fn = methods[method];
<ide>
<ide> bench.start();
<ide> fn(buffer, n);
<ide><path>benchmark/buffers/buffer-read-float.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, type, endian, value }) {
<del> type = type || 'Double';
<ide> const buff = Buffer.alloc(8);
<ide> const fn = `read${type}${endian}`;
<ide> const values = {
<ide><path>benchmark/buffers/buffer-read-with-byteLength.js
<ide> function main({ n, buf, type, byteLength }) {
<ide> const buff = buf === 'fast' ?
<ide> Buffer.alloc(8) :
<ide> require('buffer').SlowBuffer(8);
<del> const fn = `read${type || 'IntBE'}`;
<add> const fn = `read${type}`;
<ide>
<ide> buff.writeDoubleLE(0, 0);
<ide> bench.start();
<ide><path>benchmark/buffers/buffer-read.js
<ide> function main({ n, buf, type }) {
<ide> const buff = buf === 'fast' ?
<ide> Buffer.alloc(8) :
<ide> require('buffer').SlowBuffer(8);
<del> const fn = `read${type || 'UInt8'}`;
<add> const fn = `read${type}`;
<ide>
<ide> buff.writeDoubleLE(0, 0);
<ide> bench.start();
<ide><path>benchmark/buffers/buffer-swap.js
<ide> function genMethod(method) {
<ide>
<ide> function main({ method, len, n, aligned = 'true' }) {
<ide> const buf = createBuffer(len, aligned === 'true');
<del> const bufferSwap = genMethod(method || 'swap16');
<add> const bufferSwap = genMethod(method);
<ide>
<ide> bufferSwap(n, buf);
<ide> bench.start();
<ide><path>benchmark/buffers/buffer-write.js
<ide> function main({ n, buf, type }) {
<ide> const buff = buf === 'fast' ?
<ide> Buffer.alloc(8) :
<ide> require('buffer').SlowBuffer(8);
<del> const fn = `write${type || 'UInt8'}`;
<add> const fn = `write${type}`;
<ide>
<ide> if (!/\d/.test(fn))
<ide> benchSpecialInt(buff, fn, n);
<ide><path>benchmark/buffers/dataview-set.js
<ide> const mod = {
<ide> };
<ide>
<ide> function main({ n, type }) {
<del> type = type || 'Uint8';
<ide> const ab = new ArrayBuffer(8);
<ide> const dv = new DataView(ab, 0, 8);
<ide> const le = /LE$/.test(type);
<ide><path>benchmark/crypto/aes-gcm-throughput.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, len, cipher }) {
<del> // Default cipher for tests.
<del> if (cipher === '')
<del> cipher = 'aes-128-gcm';
<ide> const message = Buffer.alloc(len, 'b');
<ide> const key = crypto.randomBytes(keylen[cipher]);
<ide> const iv = crypto.randomBytes(12);
<ide><path>benchmark/crypto/cipher-stream.js
<ide> const common = require('../common.js');
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide> writes: [500],
<del> cipher: [ 'AES192', 'AES256' ],
<add> cipher: ['AES192', 'AES256'],
<ide> type: ['asc', 'utf', 'buf'],
<ide> len: [2, 1024, 102400, 1024 * 1024],
<ide> api: ['legacy', 'stream']
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ api, cipher, type, len, writes }) {
<del> // Default cipher for tests.
<del> if (cipher === '')
<del> cipher = 'AES192';
<ide> if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) {
<ide> console.error('Crypto streams not available until v0.10');
<ide> // Use the legacy, just so that we can compare them.
<ide> function main({ api, cipher, type, len, writes }) {
<ide> alice.generateKeys();
<ide> bob.generateKeys();
<ide>
<del>
<ide> const pubEnc = /^v0\.[0-8]/.test(process.version) ? 'binary' : null;
<ide> const alice_secret = alice.computeSecret(bob.getPublicKey(), pubEnc, 'hex');
<ide> const bob_secret = bob.computeSecret(alice.getPublicKey(), pubEnc, 'hex');
<ide><path>benchmark/es/defaultparams-bench.js
<ide> function runDefaultParams(n) {
<ide>
<ide> function main({ n, method }) {
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'withoutdefaults':
<ide> runOldStyleDefaults(n);
<ide> break;
<ide><path>benchmark/es/destructuring-bench.js
<ide> function runSwapDestructured(n) {
<ide>
<ide> function main({ n, method }) {
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'swap':
<ide> runSwapManual(n);
<ide> break;
<ide><path>benchmark/es/destructuring-object-bench.js
<ide> function runDestructured(n) {
<ide>
<ide> function main({ n, method }) {
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'normal':
<ide> runNormal(n);
<ide> break;
<ide><path>benchmark/es/foreach-bench.js
<ide> function main({ n, count, method }) {
<ide> items[i] = i;
<ide>
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'for':
<ide> fn = useFor;
<ide> break;
<ide><path>benchmark/es/map-bench.js
<ide> function runMap(n) {
<ide>
<ide> function main({ n, method }) {
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'object':
<ide> runObject(n);
<ide> break;
<ide><path>benchmark/es/restparams-bench.js
<ide> function runUseArguments(n) {
<ide> function main({ n, method }) {
<ide> let fn;
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'copy':
<ide> fn = runCopyArguments;
<ide> break;
<ide><path>benchmark/es/spread-assign.js
<ide> function main({ n, context, count, rest, method }) {
<ide> let obj; // eslint-disable-line no-unused-vars
<ide>
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case '_extend':
<ide> bench.start();
<ide> for (let i = 0; i < n; i++)
<ide><path>benchmark/es/spread-bench.js
<ide> function main({ n, context, count, rest, method }) {
<ide> args[i] = i;
<ide>
<ide> switch (method) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'apply':
<ide> bench.start();
<ide> for (let i = 0; i < n; i++)
<ide><path>benchmark/es/string-concatenations.js
<ide> function main({ n, mode }) {
<ide> let string;
<ide>
<ide> switch (mode) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'multi-concat':
<ide> bench.start();
<ide> for (let i = 0; i < n; i++)
<ide><path>benchmark/es/string-repeat.js
<ide> function main({ n, size, encoding, mode }) {
<ide> let str;
<ide>
<ide> switch (mode) {
<del> case '':
<del> // Empty string falls through to next line as default, mostly for tests.
<ide> case 'Array':
<ide> bench.start();
<ide> for (let i = 0; i < n; i++)
<ide><path>benchmark/misc/arguments.js
<ide> function usingPredefined() {
<ide> function main({ n, method, args }) {
<ide> let fn;
<ide> switch (method) {
<del> // '' is a default case for tests
<del> case '':
<ide> case 'restAndSpread':
<ide> fn = usingRestAndSpread;
<ide> break;
<ide><path>benchmark/misc/getstringwidth.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, type }) {
<del> // Default value for testing purposes.
<del> type = type || 'ascii';
<ide> const { getStringWidth } = require('internal/util/inspect');
<ide>
<ide> const str = ({
<ide><path>benchmark/misc/object-property-bench.js
<ide> function runSymbol(n) {
<ide> function main({ n, method }) {
<ide>
<ide> switch (method) {
<del> // '' is a default case for tests
<del> case '':
<ide> case 'property':
<ide> runProperty(n);
<ide> break;
<ide><path>benchmark/misc/punycode.js
<ide> function runICU(n, val) {
<ide>
<ide> function main({ n, val, method }) {
<ide> switch (method) {
<del> // '' is a default case for tests
<del> case '':
<ide> case 'punycode':
<ide> runPunycode(n, val);
<ide> break;
<ide><path>benchmark/misc/trace.js
<ide> function main({ n, method }) {
<ide> } = common.binding('trace_events');
<ide>
<ide> switch (method) {
<del> case '':
<ide> case 'trace':
<ide> doTrace(n, trace);
<ide> break;
<ide><path>benchmark/misc/util-extend-vs-object-assign.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, type }) {
<del> // Default value for tests.
<del> if (type === '')
<del> type = 'extend';
<del>
<ide> let fn;
<ide> if (type === 'extend') {
<ide> fn = util._extend;
<ide><path>benchmark/url/url-format.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ type, n }) {
<del> const input = inputs[type] || '';
<add> const input = inputs[type];
<ide>
<ide> // Force-optimize url.format() so that the benchmark doesn't get
<ide> // disrupted by the optimizer kicking in halfway through.
<ide><path>benchmark/url/url-parse.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ type, n }) {
<del> const input = inputs[type] || '';
<add> const input = inputs[type];
<ide>
<ide> bench.start();
<ide> for (let i = 0; i < n; i += 1)
<ide><path>benchmark/util/format.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, type }) {
<del> // For testing, if supplied with an empty type, default to string.
<del> const [first, second] = inputs[type || 'string'];
<add> const [first, second] = inputs[type];
<ide>
<ide> bench.start();
<ide> for (let i = 0; i < n; i++) {
<ide><path>benchmark/util/inspect-array.js
<ide> function main({ n, len, type }) {
<ide> opts = { showHidden: true };
<ide> arr = arr.fill('denseArray');
<ide> break;
<del> // For testing, if supplied with an empty type, default to denseArray.
<del> case '':
<ide> case 'denseArray':
<ide> arr = arr.fill('denseArray');
<ide> break;
<ide><path>benchmark/util/type-check.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ type, argument, version, n }) {
<del> // For testing, if supplied with an empty type, default to ArrayBufferView.
<del> type = type || 'ArrayBufferView';
<del>
<ide> const util = common.binding('util');
<ide> const types = require('internal/util/types');
<ide> | 41 |
Python | Python | remove the unneeded migration | fc27eafff0203e4b5ee29cbae32b57c60eb52e94 | <ide><path>airflow/migrations/versions/c7ba8a8c824_add_env_var_to_connection.py
<del>"""add env_var to connection
<del>
<del>Revision ID: c7ba8a8c824
<del>Revises: 338e90f54d61
<del>Create Date: 2015-08-29 12:02:37.905111
<del>
<del>"""
<del>
<del># revision identifiers, used by Alembic.
<del>revision = 'c7ba8a8c824'
<del>down_revision = '338e90f54d61'
<del>branch_labels = None
<del>depends_on = None
<del>
<del>from alembic import op
<del>import sqlalchemy as sa
<del>
<del>
<del>def upgrade():
<del> op.add_column('connection', sa.Column('env_variable', sa.String(255), nullable=True))
<del>
<del>
<del>def downgrade():
<del> op.drop_column('connection', 'env_variable') | 1 |
PHP | PHP | add reset method to migrator | 080f8192b5a9531b1c54e3efa455c526e5f264ee | <ide><path>src/Illuminate/Database/Console/Migrations/ResetCommand.php
<ide> public function fire()
<ide>
<ide> $pretend = $this->input->getOption('pretend');
<ide>
<del> while (true)
<del> {
<del> $count = $this->migrator->rollback($pretend);
<del>
<del> // Once the migrator has run we will grab the note output and send it out to
<del> // the console screen, since the migrator itself functions without having
<del> // any instances of the OutputInterface contract passed into the class.
<del> foreach ($this->migrator->getNotes() as $note)
<del> {
<del> $this->output->writeln($note);
<del> }
<add> $this->migrator->reset($pretend);
<ide>
<del> if ($count == 0) break;
<add> // Once the migrator has run we will grab the note output and send it out to
<add> // the console screen, since the migrator itself functions without having
<add> // any instances of the OutputInterface contract passed into the class.
<add> foreach ($this->migrator->getNotes() as $note)
<add> {
<add> $this->output->writeln($note);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Migrations/Migrator.php
<ide> public function rollback($pretend = false)
<ide> return count($migrations);
<ide> }
<ide>
<add> /**
<add> * Rolls all of the currently applied migrations back.
<add> *
<add> * @param bool $pretend
<add> * @return int
<add> */
<add> public function reset($pretend = false)
<add> {
<add> $this->notes = [];
<add>
<add> $migrations = array_reverse($this->repository->getRan());
<add>
<add> if (count($migrations) == 0)
<add> {
<add> $this->note('<info>Nothing to rollback.</info>');
<add>
<add> return count($migrations);
<add> }
<add>
<add> foreach ($migrations as $migration)
<add> {
<add> $this->runDown((object) ['migration' => $migration], $pretend);
<add> }
<add>
<add> return count($migrations);
<add> }
<add>
<ide> /**
<ide> * Run "down" a migration instance.
<ide> *
<ide><path>tests/Database/DatabaseMigrationResetCommandTest.php
<ide> public function testResetCommandCallsMigratorWithProperArguments()
<ide> $command = new ResetCommand($migrator = m::mock('Illuminate\Database\Migrations\Migrator'));
<ide> $command->setLaravel(new AppDatabaseMigrationStub());
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('rollback')->twice()->with(false)->andReturn(true, false);
<del> $migrator->shouldReceive('getNotes')->andReturn(array());
<add> $migrator->shouldReceive('reset')->once()->with(false);
<add> $migrator->shouldReceive('getNotes')->andReturn([]);
<ide>
<ide> $this->runCommand($command);
<ide> }
<ide> public function testResetCommandCanBePretended()
<ide> $command = new ResetCommand($migrator = m::mock('Illuminate\Database\Migrations\Migrator'));
<ide> $command->setLaravel(new AppDatabaseMigrationStub());
<ide> $migrator->shouldReceive('setConnection')->once()->with('foo');
<del> $migrator->shouldReceive('rollback')->twice()->with(true)->andReturn(true, false);
<del> $migrator->shouldReceive('getNotes')->andReturn(array());
<add> $migrator->shouldReceive('reset')->once()->with(true);
<add> $migrator->shouldReceive('getNotes')->andReturn([]);
<ide>
<ide> $this->runCommand($command, array('--pretend' => true, '--database' => 'foo'));
<ide> }
<ide> protected function runCommand($command, $input = array())
<ide> {
<ide> return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), new Symfony\Component\Console\Output\NullOutput);
<ide> }
<add>
<ide> }
<ide>
<ide> class AppDatabaseMigrationStub extends \Illuminate\Foundation\Application {
<ide><path>tests/Database/DatabaseMigratorTest.php
<ide> public function testNothingIsRolledBackWhenNothingInRepository()
<ide> $migrator->rollback();
<ide> }
<ide>
<add>
<add> public function testResettingMigrationsRollsBackAllMigrations()
<add> {
<add> $migrator = $this->getMock('Illuminate\Database\Migrations\Migrator', ['resolve'], [
<add> m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'),
<add> $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'),
<add> m::mock('Illuminate\Filesystem\Filesystem'),
<add> ]);
<add>
<add> $fooMigration = (object) ['migration' => 'foo'];
<add> $barMigration = (object) ['migration' => 'bar'];
<add> $bazMigration = (object) ['migration' => 'baz'];
<add>
<add> $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([
<add> $fooMigration->migration,
<add> $barMigration->migration,
<add> $bazMigration->migration
<add> ]);
<add>
<add> $barMock = m::mock('stdClass');
<add> $barMock->shouldReceive('down')->once();
<add>
<add> $fooMock = m::mock('stdClass');
<add> $fooMock->shouldReceive('down')->once();
<add>
<add> $bazMock = m::mock('stdClass');
<add> $bazMock->shouldReceive('down')->once();
<add>
<add> $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('baz'))->will($this->returnValue($bazMock));
<add> $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('bar'))->will($this->returnValue($barMock));
<add> $migrator->expects($this->at(2))->method('resolve')->with($this->equalTo('foo'))->will($this->returnValue($fooMock));
<add>
<add> $migrator->getRepository()->shouldReceive('delete')->once()->with(m::mustBe($bazMigration));
<add> $migrator->getRepository()->shouldReceive('delete')->once()->with(m::mustBe($barMigration));
<add> $migrator->getRepository()->shouldReceive('delete')->once()->with(m::mustBe($fooMigration));
<add>
<add> $migrator->reset();
<add> }
<add>
<add>
<add> public function testResetMigrationsCanBePretended()
<add> {
<add> $migrator = $this->getMock('Illuminate\Database\Migrations\Migrator', ['resolve'], [
<add> m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'),
<add> $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'),
<add> m::mock('Illuminate\Filesystem\Filesystem'),
<add> ]);
<add>
<add> $fooMigration = (object) ['migration' => 'foo'];
<add> $barMigration = (object) ['migration' => 'bar'];
<add> $bazMigration = (object) ['migration' => 'baz'];
<add>
<add> $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([
<add> $fooMigration->migration,
<add> $barMigration->migration,
<add> $bazMigration->migration
<add> ]);
<add>
<add> $barMock = m::mock('stdClass');
<add> $barMock->shouldReceive('getConnection')->once()->andReturn(null);
<add> $barMock->shouldReceive('down')->once();
<add>
<add> $fooMock = m::mock('stdClass');
<add> $fooMock->shouldReceive('getConnection')->once()->andReturn(null);
<add> $fooMock->shouldReceive('down')->once();
<add>
<add> $bazMock = m::mock('stdClass');
<add> $bazMock->shouldReceive('getConnection')->once()->andReturn(null);
<add> $bazMock->shouldReceive('down')->once();
<add>
<add> $migrator->expects($this->at(0))->method('resolve')->with($this->equalTo('baz'))->will($this->returnValue($bazMock));
<add> $migrator->expects($this->at(1))->method('resolve')->with($this->equalTo('bar'))->will($this->returnValue($barMock));
<add> $migrator->expects($this->at(2))->method('resolve')->with($this->equalTo('foo'))->will($this->returnValue($fooMock));
<add>
<add> $connection = m::mock('stdClass');
<add> $connection->shouldReceive('pretend')->with(m::type('Closure'))->andReturnUsing(function($closure)
<add> {
<add> $closure();
<add> return [['query' => 'baz']];
<add> },
<add> function($closure)
<add> {
<add> $closure();
<add> return [['query' => 'bar']];
<add> },
<add> function($closure)
<add> {
<add> $closure();
<add> return [['query' => 'foo']];
<add> });
<add> $resolver->shouldReceive('connection')->with(null)->andReturn($connection);
<add>
<add> $migrator->reset(true);
<add> }
<add>
<add>
<add> public function testNothingIsResetBackWhenNothingInRepository()
<add> {
<add> $migrator = $this->getMock('Illuminate\Database\Migrations\Migrator', ['resolve'], [
<add> m::mock('Illuminate\Database\Migrations\MigrationRepositoryInterface'),
<add> $resolver = m::mock('Illuminate\Database\ConnectionResolverInterface'),
<add> m::mock('Illuminate\Filesystem\Filesystem'),
<add> ]);
<add> $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([]);
<add>
<add> $migrator->reset();
<add> }
<add>
<ide> }
<ide>
<ide> | 4 |
Javascript | Javascript | update jsm module | 62fef74709d9e24790927aadbd4d5005a3e2479e | <ide><path>examples/jsm/renderers/SVGRenderer.js
<ide> var SVGRenderer = function () {
<ide>
<ide> }
<ide>
<del> function getSvgColor( color, opacity ) {
<add> function getSvgColor( color, opacity, asStroke ) {
<ide>
<ide> var arg = Math.floor( color.r * 255 ) + ',' + Math.floor( color.g * 255 ) + ',' + Math.floor( color.b * 255 );
<ide>
<ide> if ( opacity === undefined || opacity === 1 ) return 'rgb(' + arg + ')';
<ide>
<del> return 'rgb(' + arg + '); fill-opacity: ' + opacity;
<add> return 'rgb(' + arg + ');' + ( asStroke ? 'stroke-opacity' : 'fill-opacity' ) + ':' + opacity;
<ide>
<ide> }
<ide>
<ide> var SVGRenderer = function () {
<ide>
<ide> if ( material.isLineBasicMaterial ) {
<ide>
<del> var style = 'fill:none;stroke:' + getSvgColor( material.color, material.opacity ) + ';stroke-width:' + material.linewidth + ';stroke-linecap:' + material.linecap;
<add> var style = 'fill:none;stroke:' + getSvgColor( material.color, material.opacity, true ) + ';stroke-width:' + material.linewidth + ';stroke-linecap:' + material.linecap;
<ide>
<ide> if ( material.isLineDashedMaterial ) {
<ide>
<ide> var SVGRenderer = function () {
<ide>
<ide> if ( material.wireframe ) {
<ide>
<del> style = 'fill:none;stroke:' + getSvgColor( _color, material.opacity ) + ';stroke-width:' + material.wireframeLinewidth + ';stroke-linecap:' + material.wireframeLinecap + ';stroke-linejoin:' + material.wireframeLinejoin;
<add> style = 'fill:none;stroke:' + getSvgColor( _color, material.opacity, true ) + ';stroke-width:' + material.wireframeLinewidth + ';stroke-linecap:' + material.wireframeLinecap + ';stroke-linejoin:' + material.wireframeLinejoin;
<ide>
<ide> } else {
<ide> | 1 |
Java | Java | relax check on default data mimetype | be4facef1b663849e9be33fb62a3cb444ae0d918 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilder.java
<ide> private MimeType getDataMimeType(RSocketStrategies strategies) {
<ide> if (this.dataMimeType != null) {
<ide> return this.dataMimeType;
<ide> }
<del> // Look for non-basic Decoder (e.g. CBOR, Protobuf)
<del> MimeType selected = null;
<del> List<Decoder<?>> decoders = strategies.decoders();
<del> for (Decoder<?> candidate : decoders) {
<add> // First non-basic Decoder (e.g. CBOR, Protobuf)
<add> for (Decoder<?> candidate : strategies.decoders()) {
<ide> if (!isCoreCodec(candidate) && !candidate.getDecodableMimeTypes().isEmpty()) {
<del> Assert.state(selected == null,
<del> () -> "Cannot select default data MimeType based on configured decoders: " + decoders);
<del> selected = getMimeType(candidate);
<add> return getMimeType(candidate);
<ide> }
<ide> }
<del> if (selected != null) {
<del> return selected;
<del> }
<del> // Fall back on 1st decoder (e.g. String)
<del> for (Decoder<?> decoder : decoders) {
<add> // First core decoder (e.g. String)
<add> for (Decoder<?> decoder : strategies.decoders()) {
<ide> if (!decoder.getDecodableMimeTypes().isEmpty()) {
<ide> return getMimeType(decoder);
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java
<ide> interface Builder {
<ide> /**
<ide> * Configure the payload data MimeType to specify on the {@code SETUP}
<ide> * frame that applies to the whole connection.
<del> * <p>If this is not set, the builder will try to select the mime type
<del> * based on the presence of a single
<add> * <p>If this is not set, it will be set to the MimeType of the first
<ide> * {@link RSocketStrategies.Builder#decoder(Decoder[]) non-default}
<del> * {@code Decoder}, or the first default decoder otherwise
<del> * (i.e. {@code String}) if no others are configured.
<add> * {@code Decoder}, or otherwise fall back on the MimeType of the first
<add> * (default) decoder.
<ide> */
<ide> RSocketRequester.Builder dataMimeType(@Nullable MimeType mimeType);
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketMessageHandler.java
<ide> protected void handleNoMatch(@Nullable RouteMatcher.Route destination, Message<?
<ide> */
<ide> public SocketAcceptor serverResponder() {
<ide> return (setupPayload, sendingRSocket) -> {
<del> MessagingRSocket responder = createResponder(setupPayload, sendingRSocket);
<add> MessagingRSocket responder;
<add> try {
<add> responder = createResponder(setupPayload, sendingRSocket);
<add> }
<add> catch (Throwable ex) {
<add> return Mono.error(ex);
<add> }
<ide> return responder.handleConnectionSetupPayload(setupPayload).then(Mono.just(responder));
<ide> };
<ide> }
<ide> private MessagingRSocket createResponder(ConnectionSetupPayload setupPayload, RS
<ide> String s = setupPayload.dataMimeType();
<ide> MimeType dataMimeType = StringUtils.hasText(s) ? MimeTypeUtils.parseMimeType(s) : this.defaultDataMimeType;
<ide> Assert.notNull(dataMimeType, "No `dataMimeType` in ConnectionSetupPayload and no default value");
<add> Assert.isTrue(isDataMimeTypeSupported(dataMimeType), "Data MimeType '" + dataMimeType + "' not supported");
<ide>
<ide> s = setupPayload.metadataMimeType();
<del> MimeType metadataMimeType = StringUtils.hasText(s) ? MimeTypeUtils.parseMimeType(s) : this.defaultMetadataMimeType;
<del> Assert.notNull(metadataMimeType, "No `metadataMimeType` in ConnectionSetupPayload and no default value");
<add> MimeType metaMimeType = StringUtils.hasText(s) ? MimeTypeUtils.parseMimeType(s) : this.defaultMetadataMimeType;
<add> Assert.notNull(metaMimeType, "No `metadataMimeType` in ConnectionSetupPayload and no default value");
<ide>
<ide> RSocketStrategies strategies = this.rsocketStrategies;
<ide> Assert.notNull(strategies, "No RSocketStrategies. Was afterPropertiesSet not called?");
<del> RSocketRequester requester = RSocketRequester.wrap(rsocket, dataMimeType, metadataMimeType, strategies);
<add> RSocketRequester requester = RSocketRequester.wrap(rsocket, dataMimeType, metaMimeType, strategies);
<ide>
<ide> Assert.state(this.metadataExtractor != null,
<ide> () -> "No MetadataExtractor. Was afterPropertiesSet not called?");
<ide>
<ide> Assert.state(getRouteMatcher() != null,
<ide> () -> "No RouteMatcher. Was afterPropertiesSet not called?");
<ide>
<del> return new MessagingRSocket(dataMimeType, metadataMimeType, this.metadataExtractor, requester,
<add> return new MessagingRSocket(dataMimeType, metaMimeType, this.metadataExtractor, requester,
<ide> this, getRouteMatcher(), strategies);
<ide> }
<ide>
<add> private boolean isDataMimeTypeSupported(MimeType dataMimeType) {
<add> for (Encoder<?> encoder : getEncoders()) {
<add> for (MimeType encodable : encoder.getEncodableMimeTypes()) {
<add> if (encodable.isCompatibleWith(dataMimeType)) {
<add> return true;
<add> }
<add> }
<add> }
<add> return false;
<add> }
<ide>
<ide> public static ClientRSocketFactoryConfigurer clientResponder(Object... handlers) {
<ide> return new ResponderConfigurer(handlers);
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilderTests.java
<ide> import org.springframework.util.ReflectionUtils;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<del>import static org.assertj.core.api.Assertions.assertThatThrownBy;
<ide> import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.ArgumentMatchers.anyInt;
<ide> import static org.mockito.BDDMockito.given;
<ide> public void defaultDataMimeTypeWithCustomDecoderRegitered() {
<ide> .isEqualTo(MimeTypeUtils.APPLICATION_JSON);
<ide> }
<ide>
<del> @Test
<del> public void defaultDataMimeTypeWithMultipleCustomDecoderRegitered() {
<del> RSocketStrategies strategies = RSocketStrategies.builder()
<del> .decoder(new TestJsonDecoder(MimeTypeUtils.APPLICATION_JSON))
<del> .decoder(new TestJsonDecoder(MimeTypeUtils.APPLICATION_XML))
<del> .build();
<del>
<del> assertThatThrownBy(() ->
<del> RSocketRequester
<del> .builder()
<del> .rsocketStrategies(strategies)
<del> .connect(this.transport)
<del> .block())
<del> .hasMessageContaining("Cannot select default data MimeType");
<del> }
<del>
<ide> @Test
<ide> public void dataMimeTypeSet() {
<ide> RSocketRequester requester = RSocketRequester.builder() | 4 |
Go | Go | add an unsafe memory discovery store for testing | 22a81a2c588a7505fd5f900e2093c44cd51ae142 | <ide><path>pkg/discovery/memory/memory.go
<add>package memory
<add>
<add>import (
<add> "time"
<add>
<add> "github.com/docker/docker/pkg/discovery"
<add>)
<add>
<add>// Discovery implements a descovery backend that keeps
<add>// data in memory.
<add>type Discovery struct {
<add> heartbeat time.Duration
<add> values []string
<add>}
<add>
<add>func init() {
<add> Init()
<add>}
<add>
<add>// Init registers the memory backend on demand.
<add>func Init() {
<add> discovery.Register("memory", &Discovery{})
<add>}
<add>
<add>// Initialize sets the heartbeat for the memory backend.
<add>func (s *Discovery) Initialize(_ string, heartbeat time.Duration, _ time.Duration, _ map[string]string) error {
<add> s.heartbeat = heartbeat
<add> return nil
<add>}
<add>
<add>// Watch sends periodic discovery updates to a channel.
<add>func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) {
<add> ch := make(chan discovery.Entries)
<add> errCh := make(chan error)
<add> ticker := time.NewTicker(s.heartbeat)
<add>
<add> go func() {
<add> defer close(errCh)
<add> defer close(ch)
<add>
<add> // Send the initial entries if available.
<add> var currentEntries discovery.Entries
<add> if len(s.values) > 0 {
<add> var err error
<add> currentEntries, err = discovery.CreateEntries(s.values)
<add> if err != nil {
<add> errCh <- err
<add> } else {
<add> ch <- currentEntries
<add> }
<add> }
<add>
<add> // Periodically send updates.
<add> for {
<add> select {
<add> case <-ticker.C:
<add> newEntries, err := discovery.CreateEntries(s.values)
<add> if err != nil {
<add> errCh <- err
<add> continue
<add> }
<add>
<add> // Check if the file has really changed.
<add> if !newEntries.Equals(currentEntries) {
<add> ch <- newEntries
<add> }
<add> currentEntries = newEntries
<add> case <-stopCh:
<add> ticker.Stop()
<add> return
<add> }
<add> }
<add> }()
<add>
<add> return ch, errCh
<add>}
<add>
<add>// Register adds a new address to the discovery.
<add>func (s *Discovery) Register(addr string) error {
<add> s.values = append(s.values, addr)
<add> return nil
<add>}
<ide><path>pkg/discovery/memory/memory_test.go
<add>package memory
<add>
<add>import (
<add> "testing"
<add>
<add> "github.com/docker/docker/pkg/discovery"
<add> "github.com/go-check/check"
<add>)
<add>
<add>// Hook up gocheck into the "go test" runner.
<add>func Test(t *testing.T) { check.TestingT(t) }
<add>
<add>type discoverySuite struct{}
<add>
<add>var _ = check.Suite(&discoverySuite{})
<add>
<add>func (s *discoverySuite) TestWatch(c *check.C) {
<add> d := &Discovery{}
<add> d.Initialize("foo", 1000, 0, nil)
<add> stopCh := make(chan struct{})
<add> ch, errCh := d.Watch(stopCh)
<add>
<add> // We have to drain the error channel otherwise Watch will get stuck.
<add> go func() {
<add> for range errCh {
<add> }
<add> }()
<add>
<add> expected := discovery.Entries{
<add> &discovery.Entry{Host: "1.1.1.1", Port: "1111"},
<add> }
<add>
<add> c.Assert(d.Register("1.1.1.1:1111"), check.IsNil)
<add> c.Assert(<-ch, check.DeepEquals, expected)
<add>
<add> expected = discovery.Entries{
<add> &discovery.Entry{Host: "1.1.1.1", Port: "1111"},
<add> &discovery.Entry{Host: "2.2.2.2", Port: "2222"},
<add> }
<add>
<add> c.Assert(d.Register("2.2.2.2:2222"), check.IsNil)
<add> c.Assert(<-ch, check.DeepEquals, expected)
<add>
<add> // Stop and make sure it closes all channels.
<add> close(stopCh)
<add> c.Assert(<-ch, check.IsNil)
<add> c.Assert(<-errCh, check.IsNil)
<add>} | 2 |
Text | Text | update example readme | ca99a2d5009c32b4c718e83ed47adacf525261dc | <ide><path>examples/README.md
<ide> Quick benchmarks from the script (no other modifications):
<ide> | Titan V | AMP | 26s | 0.8281/0.8568/0.8411 |
<ide> | V100 | FP32 | 35s | 0.8646/0.8359/0.8464 |
<ide> | V100 | AMP | 22s | 0.8646/0.8385/0.8411 |
<del>| 1080 Ti | FP32 | 55s | - |
<add>| 1080 Ti | FP32 | 55s | - |
<ide>
<ide> Mixed precision (AMP) reduces the training time considerably for the same hardware and hyper-parameters (same batch size was used).
<ide>
<ide> eval_loss = 0.44457291918821606
<ide>
<ide> Based on the script [`run_squad.py`](https://github.com/huggingface/transformers/blob/master/examples/run_squad.py).
<ide>
<del>#### Fine-tuning on SQuAD
<add>#### Fine-tuning BERT on SQuAD1.0
<ide>
<del>This example code fine-tunes BERT on the SQuAD dataset. It runs in 24 min (with BERT-base) or 68 min (with BERT-large)
<add>This example code fine-tunes BERT on the SQuAD1.0 dataset. It runs in 24 min (with BERT-base) or 68 min (with BERT-large)
<ide> on a single tesla V100 16GB. The data for SQuAD can be downloaded with the following links and should be saved in a
<ide> $SQUAD_DIR directory.
<ide>
<ide> * [train-v1.1.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v1.1.json)
<ide> * [dev-v1.1.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json)
<ide> * [evaluate-v1.1.py](https://github.com/allenai/bi-att-flow/blob/master/squad/evaluate-v1.1.py)
<ide>
<add>And for SQuAD2.0, you need to download:
<add>
<add>- [train-v2.0.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v2.0.json)
<add>- [dev-v2.0.json](https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json)
<add>- [evaluate-v2.0.py](https://worksheets.codalab.org/rest/bundles/0x6b567e1cf2e041ec80d7098f031c5c9e/contents/blob/)
<add>
<ide> ```bash
<ide> export SQUAD_DIR=/path/to/SQUAD
<ide>
<ide> exact_match = 81.22
<ide> #### Distributed training
<ide>
<ide>
<del>Here is an example using distributed training on 8 V100 GPUs and Bert Whole Word Masking uncased model to reach a F1 > 93 on SQuAD:
<add>Here is an example using distributed training on 8 V100 GPUs and Bert Whole Word Masking uncased model to reach a F1 > 93 on SQuAD1.0:
<ide>
<ide> ```bash
<ide> python -m torch.distributed.launch --nproc_per_node=8 run_squad.py \
<ide> This fine-tuned model is available as a checkpoint under the reference
<ide>
<ide> #### Fine-tuning XLNet on SQuAD
<ide>
<del>This example code fine-tunes XLNet on the SQuAD dataset. See above to download the data for SQuAD .
<add>This example code fine-tunes XLNet on both SQuAD1.0 and SQuAD2.0 dataset. See above to download the data for SQuAD .
<add>
<add>##### Command for SQuAD1.0:
<ide>
<ide> ```bash
<ide> export SQUAD_DIR=/path/to/SQUAD
<ide> python /data/home/hlu/transformers/examples/run_squad.py \
<ide> --save_steps 5000
<ide> ```
<ide>
<del>Training with the previously defined hyper-parameters yields the following results:
<add>##### Command for SQuAD2.0:
<add>
<add>```bash
<add>export SQUAD_DIR=/path/to/SQUAD
<add>
<add>python run_squad.py \
<add> --model_type xlnet \
<add> --model_name_or_path xlnet-large-cased \
<add> --do_train \
<add> --do_eval \
<add> --version_2_with_negative \
<add> --train_file $SQUAD_DIR/train-v2.0.json \
<add> --predict_file $SQUAD_DIR/dev-v2.0.json \
<add> --learning_rate 3e-5 \
<add> --num_train_epochs 4 \
<add> --max_seq_length 384 \
<add> --doc_stride 128 \
<add> --output_dir ./wwm_cased_finetuned_squad/ \
<add> --per_gpu_eval_batch_size=2 \
<add> --per_gpu_train_batch_size=2 \
<add> --save_steps 5000
<add>```
<add>
<add>Larger batch size may improve the performance while costing more memory.
<add>
<add>##### Results for SQuAD1.0 with the previously defined hyper-parameters:
<ide>
<ide> ```python
<ide> {
<ide> Training with the previously defined hyper-parameters yields the following resul
<ide> }
<ide> ```
<ide>
<add>##### Results for SQuAD2.0 with the previously defined hyper-parameters:
<add>
<add>```python
<add>{
<add>"exact": 80.4177545691906,
<add>"f1": 84.07154997729623,
<add>"total": 11873,
<add>"HasAns_exact": 76.73751686909581,
<add>"HasAns_f1": 84.05558584352873,
<add>"HasAns_total": 5928,
<add>"NoAns_exact": 84.0874684608915,
<add>"NoAns_f1": 84.0874684608915,
<add>"NoAns_total": 5945
<add>}
<add>```
<add>
<add>
<add>
<ide> ## Named Entity Recognition
<ide>
<ide> Based on the script [`run_ner.py`](https://github.com/huggingface/transformers/blob/master/examples/run_ner.py). | 1 |
Javascript | Javascript | remove forced optimization from path | eba2c62bb10fb65785050600212f70d38f1ffba3 | <ide><path>benchmark/path/basename-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> pathext: [
<ide> function main(conf) {
<ide> input = input.slice(0, extIdx);
<ide> }
<ide>
<del> // Force optimization before starting the benchmark
<del> p.basename(input, ext);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.basename)');
<del> p.basename(input, ext);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.basename(input, ext);
<ide><path>benchmark/path/basename-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> pathext: [
<ide> function main(conf) {
<ide> input = input.slice(0, extIdx);
<ide> }
<ide>
<del> // Force optimization before starting the benchmark
<del> p.basename(input, ext);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.basename)');
<del> p.basename(input, ext);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.basename(input, ext);
<ide><path>benchmark/path/dirname-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.dirname(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.dirname)');
<del> p.dirname(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.dirname(input);
<ide><path>benchmark/path/dirname-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.dirname(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.dirname)');
<del> p.dirname(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.dirname(input);
<ide><path>benchmark/path/extname-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.extname(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.extname)');
<del> p.extname(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.extname(input);
<ide><path>benchmark/path/extname-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.extname(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.extname)');
<del> p.extname(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.extname(input);
<ide><path>benchmark/path/format-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> props: [
<ide> function main(conf) {
<ide> name: props[4] || '',
<ide> };
<ide>
<del> // Force optimization before starting the benchmark
<del> p.format(obj);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.format)');
<del> p.format(obj);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.format(obj);
<ide><path>benchmark/path/format-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> props: [
<ide> function main(conf) {
<ide> name: props[4] || '',
<ide> };
<ide>
<del> // Force optimization before starting the benchmark
<del> p.format(obj);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.format)');
<del> p.format(obj);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.format(obj);
<ide><path>benchmark/path/isAbsolute-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.isAbsolute(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.isAbsolute)');
<del> p.isAbsolute(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.isAbsolute(input);
<ide><path>benchmark/path/isAbsolute-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.isAbsolute(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.isAbsolute)');
<del> p.isAbsolute(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.isAbsolute(input);
<ide><path>benchmark/path/join-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> paths: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var args = ('' + conf.paths).split('|');
<ide>
<del> // Force optimization before starting the benchmark
<del> p.join.apply(null, args);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.join)');
<del> p.join.apply(null, args);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.join.apply(null, args);
<ide><path>benchmark/path/join-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> paths: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var args = ('' + conf.paths).split('|');
<ide>
<del> // Force optimization before starting the benchmark
<del> p.join.apply(null, args);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.join)');
<del> p.join.apply(null, args);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.join.apply(null, args);
<ide><path>benchmark/path/makeLong-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p._makeLong(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p._makeLong)');
<del> p._makeLong(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p._makeLong(input);
<ide><path>benchmark/path/normalize-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.normalize(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.normalize)');
<del> p.normalize(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.normalize(input);
<ide><path>benchmark/path/normalize-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.normalize(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.normalize)');
<del> p.normalize(input);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.normalize(input);
<ide><path>benchmark/path/parse-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.parse(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.parse)');
<del> p.parse(input);
<del>
<del> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.parse(input);
<ide> }
<add> bench.start();
<add> for (i = 0; i < n; i++) {
<add> p.parse(input);
<add> }
<ide> bench.end(n);
<ide> }
<ide><path>benchmark/path/parse-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> path: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var input = '' + conf.path;
<ide>
<del> // Force optimization before starting the benchmark
<del> p.parse(input);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.parse)');
<del> p.parse(input);
<del>
<del> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.parse(input);
<ide> }
<add> bench.start();
<add> for (i = 0; i < n; i++) {
<add> p.parse(input);
<add> }
<ide> bench.end(n);
<ide> }
<ide><path>benchmark/path/relative-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> paths: [
<ide> function main(conf) {
<ide> to = from.slice(delimIdx + 1);
<ide> from = from.slice(0, delimIdx);
<ide> }
<del>
<del> // Force optimization before starting the benchmark
<del> p.relative(from, to);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.relative)');
<del> p.relative(from, to);
<add> for (var i = 0; i < n; i++) {
<add> p.relative(from, to);
<add> }
<ide>
<ide> bench.start();
<del> for (var i = 0; i < n; i++) {
<add> for (i = 0; i < n; i++) {
<ide> p.relative(from, to);
<ide> }
<ide> bench.end(n);
<ide><path>benchmark/path/relative-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> paths: [
<ide> function main(conf) {
<ide> from = from.slice(0, delimIdx);
<ide> }
<ide>
<del> // Force optimization before starting the benchmark
<del> p.relative(from, to);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.relative)');
<del> p.relative(from, to);
<add> // Warmup
<add> for (var i = 0; i < n; i++) {
<add> p.relative(from, to);
<add> }
<ide>
<ide> bench.start();
<del> for (var i = 0; i < n; i++) {
<add> for (i = 0; i < n; i++) {
<ide> p.relative(from, to);
<ide> }
<ide> bench.end(n);
<ide><path>benchmark/path/resolve-posix.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> paths: [
<ide> function main(conf) {
<ide> var p = path.posix;
<ide> var args = ('' + conf.paths).split('|');
<ide>
<del> // Force optimization before starting the benchmark
<del> p.resolve.apply(null, args);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.resolve)');
<del> p.resolve.apply(null, args);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.resolve.apply(null, args);
<ide><path>benchmark/path/resolve-win32.js
<ide> 'use strict';
<ide> var common = require('../common.js');
<ide> var path = require('path');
<del>var v8 = require('v8');
<ide>
<ide> var bench = common.createBenchmark(main, {
<ide> paths: [
<ide> function main(conf) {
<ide> var p = path.win32;
<ide> var args = ('' + conf.paths).split('|');
<ide>
<del> // Force optimization before starting the benchmark
<del> p.resolve.apply(null, args);
<del> v8.setFlagsFromString('--allow_natives_syntax');
<del> eval('%OptimizeFunctionOnNextCall(p.resolve)');
<del> p.resolve.apply(null, args);
<del>
<ide> bench.start();
<ide> for (var i = 0; i < n; i++) {
<ide> p.resolve.apply(null, args); | 21 |
Python | Python | test morphological features | 19e6b39786964d5c4c401fe9bf8c03dacda11dd5 | <ide><path>spacy/tests/doc/test_morphanalysis.py
<ide> def test_token_morph_id(i_has):
<ide>
<ide> def test_morph_props(i_has):
<ide> assert i_has[0].morph.pron_type == i_has.vocab.strings["PronType_prs"]
<add> assert i_has[0].morph.pron_type_ == "PronType_prs"
<ide> assert i_has[1].morph.pron_type == 0
<ide>
<ide>
<ide> def test_morph_iter(i_has):
<ide> assert list(i_has[0].morph) == ["PronType_prs"]
<ide> assert list(i_has[1].morph) == ["Number_sing", "Person_three", "VerbForm_fin"]
<add>
<add>
<add>def test_morph_get(i_has):
<add> assert i_has[0].morph.get("pron_type") == "PronType_prs" | 1 |
Text | Text | add lead maintainer guidelines | dced0da7e9577329db39272897aee60b4328307e | <ide><path>docs/Maintainer-Guidelines.md
<ide> Maintainers have a variety of ways to communicate with each other:
<ide> All communication should ideally occur in public on GitHub. Where this is not possible or appropriate (e.g. a security disclosure, interpersonal issue between two maintainers, urgent breakage that needs to be resolved) this can move to maintainers' private group communication and, if necessary, 1:1 communication. Technical decisions should not happen in 1:1 communications but if they do (or did in the past) they must end up back as something linkable on GitHub. For example, if a technical decision was made a year ago on Slack and another maintainer/contributor/user asks about it on GitHub, that's a good chance to explain it to them and have something that can be linked to in the future.
<ide>
<ide> This makes it easier for other maintainers, contributors and users to follow along with what we're doing (and, more importantly, why we're doing it) and means that decisions have a linkable URL.
<add>
<add>## Lead maintainer guidelines
<add>There should be one lead maintainer for Homebrew. This person should (sparingly) be the tiebreaker for decisions where a mutual consensus cannot be reached amongst other maintainers. They should also be seen as the product manager for Homebrew itself and ensuring that changes made to the entire Homebrew ecosystem are consistent and providing an increasingly positive experience for Homebrew's users.
<add>
<add>In the same way that Homebrew maintainers are expected to be spending more of their time reviewing and merging contributions from non-maintainer contributors than making their own contributions, the lead maintainer should be spending most of their time reviewing work from and mentoring other maintainers.
<add>
<add>Individual Homebrew repositories should not have formal lead maintainers (although those who do the most work will have the loudest voices). | 1 |
Text | Text | remove sam roberts from release team | 3b9749e7ce34325dd4de89d16213e9c1cf156260 | <ide><path>README.md
<ide> Releases of Node.js and io.js will be signed with one of the following GPG keys:
<ide> `C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8`
<ide> * **Rod Vagg** <rod@vagg.org>
<ide> `DD8F2338BAE7501E3DD5AC78C273792F7D83545D`
<del>* **Sam Roberts** <octetcloud@keybase.io>
<del>`0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93`
<ide>
<ide> The full set of trusted release keys can be imported by running:
<ide>
<ide> ```shell
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 9554F04D7259F04124DE6B476D5A82AC7E37093B
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5
<del>gpg --keyserver pool.sks-keyservers.net --recv-keys 0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D | 1 |
Java | Java | expose lazyviewmanagers option on reactnativehost | d4b59cd9d02a8c4eda3ac4bf89cfe8161847adf0 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/LazyReactPackage.java
<ide> public final List<NativeModule> createNativeModules(ReactApplicationContext reac
<ide> List<NativeModule> modules = new ArrayList<>();
<ide> for (ModuleSpec holder : getNativeModules(reactContext)) {
<ide> NativeModule nativeModule;
<del> SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createNativeModule")
<del> .arg("module", holder.getType())
<del> .flush();
<add> SystraceMessage.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createNativeModule").flush();
<ide> ReactMarker.logMarker(ReactMarkerConstants.CREATE_MODULE_START, holder.getName());
<ide> try {
<ide> nativeModule = holder.getProvider().get();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java
<ide> protected ReactInstanceManager createReactInstanceManager() {
<ide> .setDevSupportManagerFactory(getDevSupportManagerFactory())
<ide> .setRequireActivity(getShouldRequireActivity())
<ide> .setSurfaceDelegateFactory(getSurfaceDelegateFactory())
<add> .setLazyViewManagersEnabled(getLazyViewManagersEnabled())
<ide> .setRedBoxHandler(getRedBoxHandler())
<ide> .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
<ide> .setUIImplementationProvider(getUIImplementationProvider())
<ide> public boolean getShouldRequireActivity() {
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * Returns whether view managers should be created lazily. See {@link
<add> * ViewManagerOnDemandReactPackage} for details.
<add> *
<add> * @experimental
<add> */
<add> public boolean getLazyViewManagersEnabled() {
<add> return false;
<add> }
<add>
<ide> /**
<ide> * Return the {@link SurfaceDelegateFactory} used by NativeModules to get access to a {@link
<ide> * SurfaceDelegate} to interact with a surface. By default in the mobile platform the {@link
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleSpec.java
<ide> public class ModuleSpec {
<ide>
<ide> private static final String TAG = "ModuleSpec";
<del> private final @Nullable Class<? extends NativeModule> mType;
<ide> private final Provider<? extends NativeModule> mProvider;
<del> private final String mName;
<add> private final @Nullable String mName;
<ide>
<ide> public static ModuleSpec viewManagerSpec(Provider<? extends NativeModule> provider) {
<ide> return new ModuleSpec(provider);
<ide> public static ModuleSpec nativeModuleSpec(
<ide> * @param provider
<ide> */
<ide> private ModuleSpec(Provider<? extends NativeModule> provider) {
<del> mType = null;
<ide> mProvider = provider;
<ide> mName = null;
<ide> }
<ide>
<ide> private ModuleSpec(Provider<? extends NativeModule> provider, String name) {
<del> mType = null;
<ide> mProvider = provider;
<ide> mName = name;
<ide> }
<ide>
<del> public @Nullable Class<? extends NativeModule> getType() {
<del> return mType;
<del> }
<del>
<del> public String getName() {
<add> public @Nullable String getName() {
<ide> return mName;
<ide> }
<ide> | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.