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
|
---|---|---|---|---|---|
Python | Python | fix documentation typo | 18c8aef9d3e5c8247b36b786a20707a17284fa28 | <ide><path>examples/run_classifier.py
<ide> def _create_examples(self, lines, set_type):
<ide>
<ide>
<ide> class QqpProcessor(DataProcessor):
<del> """Processor for the STS-B data set (GLUE version)."""
<add> """Processor for the QQP data set (GLUE version)."""
<ide>
<ide> def get_train_examples(self, data_dir):
<ide> """See base class."""
<ide> def _create_examples(self, lines, set_type):
<ide>
<ide>
<ide> class QnliProcessor(DataProcessor):
<del> """Processor for the STS-B data set (GLUE version)."""
<add> """Processor for the QNLI data set (GLUE version)."""
<ide>
<ide> def get_train_examples(self, data_dir):
<ide> """See base class.""" | 1 |
Python | Python | fix hddtemp not displayed in web ui | fe2383f1073e0ab2ea11b2f6cabd296f445bb57e | <ide><path>glances/webserver.py
<ide> class GlancesWebServer(object):
<ide>
<ide> def __init__(self, config=None, args=None):
<ide> # Init stats
<del> self.stats = GlancesStats(config)
<add> self.stats = GlancesStats(config, args)
<ide>
<ide> if not WINDOWS and args.no_kernel_threads:
<ide> # Ignore kernel threads in process list | 1 |
Python | Python | update another initializer change | 66efe4123224cbabaa65e4c866eee3896015f0a3 | <ide><path>inception/inception/slim/variables.py
<ide>
<ide> biases = variables.variable('biases',
<ide> shape=[100],
<del> initializer=tf.zeros_initializer,
<add> initializer=tf.zeros_initializer(),
<ide> device='/cpu:0')
<ide>
<ide> # More complex example. | 1 |
Ruby | Ruby | remove nilclass whiners feature | d1abf29e796a86cbac315da217f3fe7addb88106 | <ide><path>activerecord/lib/active_record/base.rb
<ide> def populate_with_current_scope_attributes
<ide> include AutosaveAssociation, NestedAttributes
<ide> include Aggregations, Transactions, Reflection, Serialization, Store
<ide>
<del> NilClass.add_whiner(self) if NilClass.respond_to?(:add_whiner)
<del>
<ide> # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
<ide> # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
<ide> # (Alias for the protected read_attribute method).
<ide><path>activesupport/lib/active_support/whiny_nil.rb
<ide> # Extensions to +nil+ which allow for more helpful error messages for people who
<ide> # are new to Rails.
<ide> #
<del># Ruby raises NoMethodError if you invoke a method on an object that does not
<del># respond to it:
<del>#
<del># $ ruby -e nil.destroy
<del># -e:1: undefined method `destroy' for nil:NilClass (NoMethodError)
<del>#
<del># With these extensions, if the method belongs to the public interface of the
<del># classes in NilClass::WHINERS the error message suggests which could be the
<del># actual intended class:
<del>#
<del># $ rails runner nil.destroy
<del># ...
<del># You might have expected an instance of ActiveRecord::Base.
<del># ...
<del>#
<ide> # NilClass#id exists in Ruby 1.8 (though it is deprecated). Since +id+ is a fundamental
<ide> # method of Active Record models NilClass#id is redefined as well to raise a RuntimeError
<ide> # and warn the user. She probably wanted a model database identifier and the 4
<ide> # By default it is on in development and test modes, and it is off in production
<ide> # mode.
<ide> class NilClass
<del> METHOD_CLASS_MAP = Hash.new
<del>
<ide> def self.add_whiner(klass)
<del> methods = klass.public_instance_methods - public_instance_methods
<del> class_name = klass.name
<del> methods.each { |method| METHOD_CLASS_MAP[method.to_sym] = class_name }
<add> ActiveSupport::Deprecation.warn "NilClass.add_whiner is deprecated and this functionality is " \
<add> "removed from Rails versions as it affects Ruby 1.9 performance.", caller
<ide> end
<ide>
<del> add_whiner ::Array
<del>
<ide> # Raises a RuntimeError when you attempt to call +id+ on +nil+.
<ide> def id
<ide> raise RuntimeError, "Called id for nil, which would mistakenly be #{object_id} -- if you really wanted the id of nil, use object_id", caller
<ide> end
<del>
<del> private
<del> def method_missing(method, *args)
<del> if klass = METHOD_CLASS_MAP[method]
<del> raise_nil_warning_for klass, method, caller
<del> else
<del> super
<del> end
<del> end
<del>
<del> # Raises a NoMethodError when you attempt to call a method on +nil+.
<del> def raise_nil_warning_for(class_name = nil, selector = nil, with_caller = nil)
<del> message = "You have a nil object when you didn't expect it!"
<del> message << "\nYou might have expected an instance of #{class_name}." if class_name
<del> message << "\nThe error occurred while evaluating nil.#{selector}" if selector
<del>
<del> raise NoMethodError, message, with_caller || caller
<del> end
<ide> end
<ide><path>activesupport/test/whiny_nil_test.rb
<del># Stub to enable testing without Active Record
<del>module ActiveRecord
<del> class Base
<del> def save!
<del> end
<del> end
<del>end
<del>
<ide> require 'abstract_unit'
<ide> require 'active_support/whiny_nil'
<ide>
<del>NilClass.add_whiner ::ActiveRecord::Base
<del>
<ide> class WhinyNilTest < Test::Unit::TestCase
<del> def test_unchanged
<del> nil.method_thats_not_in_whiners
<del> rescue NoMethodError => nme
<del> assert_match(/nil:NilClass/, nme.message)
<del> end
<del>
<del> def test_active_record
<del> nil.save!
<del> rescue NoMethodError => nme
<del> assert_no_match(/nil:NilClass/, nme.message)
<del> assert_match(/nil\.save!/, nme.message)
<del> end
<del>
<del> def test_array
<del> nil.each
<del> rescue NoMethodError => nme
<del> assert_no_match(/nil:NilClass/, nme.message)
<del> assert_match(/nil\.each/, nme.message)
<del> end
<del>
<ide> def test_id
<ide> nil.id
<ide> rescue RuntimeError => nme
<ide> assert_no_match(/nil:NilClass/, nme.message)
<ide> assert_match(Regexp.new(nil.object_id.to_s), nme.message)
<ide> end
<del>
<del> def test_no_to_ary_coercion
<del> nil.to_ary
<del> rescue NoMethodError => nme
<del> assert_no_match(/nil:NilClass/, nme.message)
<del> assert_match(/nil\.to_ary/, nme.message)
<del> end
<del>
<del> def test_no_to_str_coercion
<del> nil.to_str
<del> rescue NoMethodError => nme
<del> assert_match(/nil:NilClass/, nme.message)
<del> end
<ide> end | 3 |
Python | Python | remove duplicate calls to inputspec | 3dcd9c767ce6875fc8b69c74971ac8a552e23131 | <ide><path>keras/layers/convolutional.py
<ide> def __init__(self, filters,
<ide> kernel_constraint=kernel_constraint,
<ide> bias_constraint=bias_constraint,
<ide> **kwargs)
<del> self.input_spec = InputSpec(ndim=3)
<ide>
<ide> def get_config(self):
<ide> config = super(Conv1D, self).get_config()
<ide> def __init__(self, filters,
<ide> kernel_constraint=kernel_constraint,
<ide> bias_constraint=bias_constraint,
<ide> **kwargs)
<del> self.input_spec = InputSpec(ndim=4)
<ide>
<ide> def get_config(self):
<ide> config = super(Conv2D, self).get_config()
<ide> def __init__(self, filters,
<ide> kernel_constraint=kernel_constraint,
<ide> bias_constraint=bias_constraint,
<ide> **kwargs)
<del> self.input_spec = InputSpec(ndim=5)
<ide>
<ide> def get_config(self):
<ide> config = super(Conv3D, self).get_config()
<ide> def __init__(self, filters,
<ide> kernel_constraint=kernel_constraint,
<ide> bias_constraint=bias_constraint,
<ide> **kwargs)
<del> self.input_spec = InputSpec(ndim=4)
<ide>
<ide> self.output_padding = output_padding
<ide> if self.output_padding is not None:
<ide> def __init__(self, filters,
<ide> kernel_constraint=kernel_constraint,
<ide> bias_constraint=bias_constraint,
<ide> **kwargs)
<del> self.input_spec = InputSpec(ndim=5)
<add>
<ide> self.output_padding = output_padding
<ide> if self.output_padding is not None:
<ide> self.output_padding = conv_utils.normalize_tuple( | 1 |
Ruby | Ruby | add env.cppflags shortcut | 9752fc93fd7aea9731dec80272810ab02e651cde | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def ncurses_define
<ide> def cc; self['CC'] or "gcc"; end
<ide> def cxx; self['CXX'] or "g++"; end
<ide> def cflags; self['CFLAGS']; end
<add> def cppflags;self['CPPLAGS']; end
<ide> def ldflags; self['LDFLAGS']; end
<ide>
<ide> def m64 | 1 |
Javascript | Javascript | publish tarballs to s3 for channel builds | eccb77d292980dd71ee02631d66b00a342c66588 | <ide><path>config/s3ProjectConfig.js
<add>'use strict';
<add>
<add>const semver = require('semver');
<add>
<ide> function fileMap(revision, tag, date) {
<del> return {
<add> let filesToPublish = {
<ide> "ember.debug.js": fileObject("ember.debug", ".js", "text/javascript", revision, tag, date),
<ide> "ember-testing.js": fileObject("ember-testing", ".js", "text/javascript", revision, tag, date),
<ide> "ember-tests.js": fileObject("ember-tests", ".js", "text/javascript", revision, tag, date),
<ide> function fileMap(revision, tag, date) {
<ide> "composer.json": fileObject("composer", ".json", "application/json", revision, tag, date),
<ide> "package.json": fileObject("package", ".json", "application/json", revision, tag, date),
<ide> };
<add>
<add> let version = require('../package').version;
<add> // semver.parse(...).version drops the `+build-info-metadata` stuff
<add> let sanitizedVersion = semver.parse(version).version;
<add> filesToPublish[`../ember-source-${sanitizedVersion}.tgz`] = {
<add> contentType: 'application/x-gzip',
<add> destinations: {
<add> 'alpha': [
<add> `alpha.tgz`,
<add> `alpha/daily/${date}.tgz`,
<add> `alpha/shas/${revision}.tgz`,
<add> ],
<add> 'canary': [
<add> `canary.tgz`,
<add> `canary/daily/${date}.tgz`,
<add> `canary/shas/${revision}.tgz`,
<add> ],
<add> 'beta': [
<add> `beta.tgz`,
<add> `beta/daily/${date}.tgz`,
<add> `beta/shas/${revision}.tgz`,
<add> ],
<add> 'release': [
<add> `release.tgz`,
<add> `release/daily/${date}.tgz`,
<add> `release/shas/${revision}.tgz`,
<add> ],
<add> }
<add> };
<add>
<add> return filesToPublish;
<ide> }
<ide>
<ide> function fileObject(baseName, extension, contentType, currentRevision, tag, date) { | 1 |
Javascript | Javascript | apply the review comment | f5417fac65c89ee5ef52ebbea21e38dbbc782fe0 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide> * @param {THREE.Mesh} mesh
<ide> * @param {GLTF.Mesh} meshDef
<ide> * @param {GLTF.Primitive} primitiveDef
<del> * @param {Array} accessors
<add> * @param {Array<THREE.BufferAttribute>} accessors
<ide> */
<ide> function addMorphTargets( mesh, meshDef, primitiveDef, accessors ) {
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide> GLTFParser.prototype.getMultiDependencies = function ( types ) {
<ide>
<ide> var results = {};
<del> var fns = [];
<add> var pendings = [];
<ide>
<ide> for ( var i = 0, il = types.length; i < il; i ++ ) {
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
<ide>
<del> fns.push( value );
<add> pendings.push( value );
<ide>
<ide> }
<ide>
<del> return Promise.all( fns ).then( function () {
<add> return Promise.all( pendings ).then( function () {
<ide>
<ide> return results;
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide> /**
<ide> * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
<ide> * @param {number} accessorIndex
<del> * @return {Promise<THREE.(Interleaved)BufferAttribute>}
<add> * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
<ide> */
<ide> GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide> /**
<ide> * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
<ide> * @param {number} meshIndex
<del> * @return {Promise<THREE.(Skinned)Material>}
<add> * @return {Promise<THREE.Mesh|THREE.SkinnedMesh>}
<ide> */
<ide> GLTFParser.prototype.loadMesh = function ( meshIndex ) {
<ide> | 1 |
Javascript | Javascript | remove path resolution from internal forks plugin | 274b9fb168eae1b3e5b83db657eb964d365fc45a | <ide><path>scripts/rollup/forks.js
<ide> const __EXPERIMENTAL__ =
<ide>
<ide> // If you need to replace a file with another file for a specific environment,
<ide> // add it to this list with the logic for choosing the right replacement.
<add>
<add>// Fork paths are relative to the project root. They must include the full path,
<add>// including the extension. We intentionally don't use Node's module resolution
<add>// algorithm because 1) require.resolve doesn't work with ESM modules, and 2)
<add>// the behavior is easier to predict.
<ide> const forks = Object.freeze({
<ide> // Optimization: for UMDs, use a version that we can inline into the React bundle.
<ide> // Use that from all other bundles.
<del> 'object-assign': (bundleType, entry, dependencies) => {
<add>
<add> // NOTE: This is hard-coded to the main entry point of the (third-party)
<add> // object-assign package.
<add> './node_modules/object-assign/index.js': (
<add> bundleType,
<add> entry,
<add> dependencies
<add> ) => {
<ide> if (
<ide> bundleType !== UMD_DEV &&
<ide> bundleType !== UMD_PROD &&
<ide> const forks = Object.freeze({
<ide> }
<ide> if (entry === 'react' || entry === 'react/unstable-shared-subset') {
<ide> // Use the forked version that uses ES modules instead of CommonJS.
<del> return 'shared/forks/object-assign.inline-umd.js';
<add> return './packages/shared/forks/object-assign.inline-umd.js';
<ide> }
<ide> if (dependencies.indexOf('react') === -1) {
<ide> // We can only apply the optimizations to bundle that depend on React
<ide> // because we read assign() from an object exposed on React internals.
<ide> return null;
<ide> }
<ide> // We can use the fork that reads the secret export!
<del> return 'shared/forks/object-assign.umd.js';
<add> return './packages/shared/forks/object-assign.umd.js';
<ide> },
<ide>
<del> 'react-shallow-renderer': () => {
<add> // NOTE: This is hard-coded to the main entry point of the (third-party)
<add> // react-shallow-renderer package.
<add> './node_modules/react-shallow-renderer/index.js': () => {
<ide> // Use ESM build of `react-shallow-renderer`.
<del> return 'react-shallow-renderer/esm/index.js';
<add> return './node_modules/react-shallow-renderer/esm/index.js';
<ide> },
<ide>
<ide> // Without this fork, importing `shared/ReactSharedInternals` inside
<ide> // the `react` package itself would not work due to a cyclical dependency.
<del> 'shared/ReactSharedInternals': (bundleType, entry, dependencies) => {
<add> './packages/shared/ReactSharedInternals.js': (
<add> bundleType,
<add> entry,
<add> dependencies
<add> ) => {
<ide> if (entry === 'react' || entry === 'react/unstable-shared-subset') {
<del> return 'react/src/ReactSharedInternals.js';
<add> return './packages/react/src/ReactSharedInternals.js';
<ide> }
<ide> if (!entry.startsWith('react/') && dependencies.indexOf('react') === -1) {
<ide> // React internals are unavailable if we can't reference the package.
<ide> const forks = Object.freeze({
<ide> },
<ide>
<ide> // We have a few forks for different environments.
<del> 'shared/ReactFeatureFlags': (bundleType, entry) => {
<add> './packages/shared/ReactFeatureFlags.js': (bundleType, entry) => {
<ide> switch (entry) {
<ide> case 'react-native-renderer':
<ide> switch (bundleType) {
<ide> case RN_FB_DEV:
<ide> case RN_FB_PROD:
<ide> case RN_FB_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.native-fb.js';
<add> return './packages/shared/forks/ReactFeatureFlags.native-fb.js';
<ide> case RN_OSS_DEV:
<ide> case RN_OSS_PROD:
<ide> case RN_OSS_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.native-oss.js';
<add> return './packages/shared/forks/ReactFeatureFlags.native-oss.js';
<ide> default:
<ide> throw Error(
<ide> `Unexpected entry (${entry}) and bundleType (${bundleType})`
<ide> const forks = Object.freeze({
<ide> case RN_FB_DEV:
<ide> case RN_FB_PROD:
<ide> case RN_FB_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.native-fb.js';
<add> return './packages/shared/forks/ReactFeatureFlags.native-fb.js';
<ide> case RN_OSS_DEV:
<ide> case RN_OSS_PROD:
<ide> case RN_OSS_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.native-oss.js';
<add> return './packages/shared/forks/ReactFeatureFlags.native-oss.js';
<ide> default:
<ide> throw Error(
<ide> `Unexpected entry (${entry}) and bundleType (${bundleType})`
<ide> const forks = Object.freeze({
<ide> case RN_OSS_DEV:
<ide> case RN_OSS_PROD:
<ide> case RN_OSS_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.test-renderer.native.js';
<add> return './packages/shared/forks/ReactFeatureFlags.test-renderer.native.js';
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.test-renderer.www.js';
<add> return './packages/shared/forks/ReactFeatureFlags.test-renderer.www.js';
<ide> }
<del> return 'shared/forks/ReactFeatureFlags.test-renderer.js';
<add> return './packages/shared/forks/ReactFeatureFlags.test-renderer.js';
<ide> case 'react-dom/unstable_testing':
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.testing.www.js';
<add> return './packages/shared/forks/ReactFeatureFlags.testing.www.js';
<ide> }
<del> return 'shared/forks/ReactFeatureFlags.testing.js';
<add> return './packages/shared/forks/ReactFeatureFlags.testing.js';
<ide> default:
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.www.js';
<add> return './packages/shared/forks/ReactFeatureFlags.www.js';
<ide> case RN_FB_DEV:
<ide> case RN_FB_PROD:
<ide> case RN_FB_PROFILING:
<del> return 'shared/forks/ReactFeatureFlags.native-fb.js';
<add> return './packages/shared/forks/ReactFeatureFlags.native-fb.js';
<ide> }
<ide> }
<ide> return null;
<ide> },
<ide>
<del> scheduler: (bundleType, entry, dependencies) => {
<add> './packages/scheduler/index.js': (bundleType, entry, dependencies) => {
<ide> switch (bundleType) {
<ide> case UMD_DEV:
<ide> case UMD_PROD:
<ide> const forks = Object.freeze({
<ide> }
<ide> // Optimization: for UMDs, use the API that is already a part of the React
<ide> // package instead of requiring it to be loaded via a separate <script> tag
<del> return 'shared/forks/Scheduler.umd.js';
<add> return './packages/shared/forks/Scheduler.umd.js';
<ide> default:
<ide> // For other bundles, use the shared NPM package.
<ide> return null;
<ide> }
<ide> },
<ide>
<del> 'scheduler/src/SchedulerFeatureFlags': (bundleType, entry, dependencies) => {
<add> './packages/scheduler/src/SchedulerFeatureFlags.js': (
<add> bundleType,
<add> entry,
<add> dependencies
<add> ) => {
<ide> if (
<ide> bundleType === FB_WWW_DEV ||
<ide> bundleType === FB_WWW_PROD ||
<ide> bundleType === FB_WWW_PROFILING
<ide> ) {
<del> return 'scheduler/src/forks/SchedulerFeatureFlags.www.js';
<add> return './packages/scheduler/src/forks/SchedulerFeatureFlags.www.js';
<ide> }
<del> return 'scheduler/src/SchedulerFeatureFlags';
<add> return './packages/scheduler/src/SchedulerFeatureFlags.js';
<ide> },
<ide>
<del> 'shared/consoleWithStackDev': (bundleType, entry) => {
<add> './packages/shared/consoleWithStackDev.js': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<del> return 'shared/forks/consoleWithStackDev.www.js';
<add> return './packages/shared/forks/consoleWithStackDev.www.js';
<ide> default:
<ide> return null;
<ide> }
<ide> },
<ide>
<ide> // In FB bundles, we preserve an inline require to ReactCurrentOwner.
<ide> // See the explanation in FB version of ReactCurrentOwner in www:
<del> 'react/src/ReactCurrentOwner': (bundleType, entry) => {
<add> './packages/react/src/ReactCurrentOwner.js': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<del> return 'react/src/forks/ReactCurrentOwner.www.js';
<add> return './packages/react/src/forks/ReactCurrentOwner.www.js';
<ide> default:
<ide> return null;
<ide> }
<ide> },
<ide>
<ide> // Similarly, we preserve an inline require to ReactCurrentDispatcher.
<ide> // See the explanation in FB version of ReactCurrentDispatcher in www:
<del> 'react/src/ReactCurrentDispatcher': (bundleType, entry) => {
<add> './packages/react/src/ReactCurrentDispatcher.js': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<del> return 'react/src/forks/ReactCurrentDispatcher.www.js';
<add> return './packages/react/src/forks/ReactCurrentDispatcher.www.js';
<ide> default:
<ide> return null;
<ide> }
<ide> },
<ide>
<del> 'react/src/ReactSharedInternals.js': (bundleType, entry) => {
<add> './packages/react/src/ReactSharedInternals.js': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case UMD_DEV:
<ide> case UMD_PROD:
<ide> case UMD_PROFILING:
<del> return 'react/src/forks/ReactSharedInternals.umd.js';
<add> return './packages/react/src/forks/ReactSharedInternals.umd.js';
<ide> default:
<ide> return null;
<ide> }
<ide> },
<ide>
<ide> // Different wrapping/reporting for caught errors.
<del> 'shared/invokeGuardedCallbackImpl': (bundleType, entry) => {
<add> './packages/shared/invokeGuardedCallbackImpl.js': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<del> return 'shared/forks/invokeGuardedCallbackImpl.www.js';
<add> return './packages/shared/forks/invokeGuardedCallbackImpl.www.js';
<ide> default:
<ide> return null;
<ide> }
<ide> },
<ide>
<del> 'react-reconciler/src/ReactFiberReconciler': (
<add> './packages/react-reconciler/src/ReactFiberReconciler.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<ide> // Use the forked version of the reconciler
<del> return 'react-reconciler/src/ReactFiberReconciler.new.js';
<add> return './packages/react-reconciler/src/ReactFiberReconciler.new.js';
<ide> }
<ide> }
<ide> // Otherwise, use the non-forked version.
<del> return 'react-reconciler/src/ReactFiberReconciler.old.js';
<add> return './packages/react-reconciler/src/ReactFiberReconciler.old.js';
<ide> },
<ide>
<del> 'react-reconciler/src/ReactEventPriorities': (
<add> './packages/react-reconciler/src/ReactEventPriorities.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<ide> // Use the forked version of the reconciler
<del> return 'react-reconciler/src/ReactEventPriorities.new.js';
<add> return './packages/react-reconciler/src/ReactEventPriorities.new.js';
<ide> }
<ide> }
<ide> // Otherwise, use the non-forked version.
<del> return 'react-reconciler/src/ReactEventPriorities.old.js';
<add> return './packages/react-reconciler/src/ReactEventPriorities.old.js';
<ide> },
<ide>
<del> 'react-reconciler/src/ReactFiberHotReloading': (
<add> './packages/react-reconciler/src/ReactFiberHotReloading.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<ide> // Use the forked version of the reconciler
<del> return 'react-reconciler/src/ReactFiberHotReloading.new.js';
<add> return './packages/react-reconciler/src/ReactFiberHotReloading.new.js';
<ide> }
<ide> }
<ide> // Otherwise, use the non-forked version.
<del> return 'react-reconciler/src/ReactFiberHotReloading.old.js';
<add> return './packages/react-reconciler/src/ReactFiberHotReloading.old.js';
<ide> },
<ide>
<ide> // Different dialogs for caught errors.
<del> 'react-reconciler/src/ReactFiberErrorDialog': (bundleType, entry) => {
<add> './packages/react-reconciler/src/ReactFiberErrorDialog.js': (
<add> bundleType,
<add> entry
<add> ) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> case FB_WWW_PROFILING:
<ide> // Use the www fork which shows an error dialog.
<del> return 'react-reconciler/src/forks/ReactFiberErrorDialog.www.js';
<add> return './packages/react-reconciler/src/forks/ReactFiberErrorDialog.www.js';
<ide> case RN_OSS_DEV:
<ide> case RN_OSS_PROD:
<ide> case RN_OSS_PROFILING:
<ide> const forks = Object.freeze({
<ide> case 'react-native-renderer':
<ide> case 'react-native-renderer/fabric':
<ide> // Use the RN fork which plays well with redbox.
<del> return 'react-reconciler/src/forks/ReactFiberErrorDialog.native.js';
<add> return './packages/react-reconciler/src/forks/ReactFiberErrorDialog.native.js';
<ide> default:
<ide> return null;
<ide> }
<ide> const forks = Object.freeze({
<ide> }
<ide> },
<ide>
<del> 'react-reconciler/src/ReactFiberHostConfig': (
<add> './packages/react-reconciler/src/ReactFiberHostConfig.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> // eslint-disable-next-line no-for-of-loops/no-for-of-loops
<ide> for (let rendererInfo of inlinedHostConfigs) {
<ide> if (rendererInfo.entryPoints.indexOf(entry) !== -1) {
<del> return `react-reconciler/src/forks/ReactFiberHostConfig.${rendererInfo.shortName}.js`;
<add> return `./packages/react-reconciler/src/forks/ReactFiberHostConfig.${rendererInfo.shortName}.js`;
<ide> }
<ide> }
<ide> throw new Error(
<ide> const forks = Object.freeze({
<ide> );
<ide> },
<ide>
<del> 'react-server/src/ReactServerStreamConfig': (
<add> './packages/react-server/src/ReactServerStreamConfig.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> if (!rendererInfo.isServerSupported) {
<ide> return null;
<ide> }
<del> return `react-server/src/forks/ReactServerStreamConfig.${rendererInfo.shortName}.js`;
<add> return `./packages/react-server/src/forks/ReactServerStreamConfig.${rendererInfo.shortName}.js`;
<ide> }
<ide> }
<ide> throw new Error(
<ide> const forks = Object.freeze({
<ide> );
<ide> },
<ide>
<del> 'react-server/src/ReactServerFormatConfig': (
<add> './packages/react-server/src/ReactServerFormatConfig.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> if (!rendererInfo.isServerSupported) {
<ide> return null;
<ide> }
<del> return `react-server/src/forks/ReactServerFormatConfig.${rendererInfo.shortName}.js`;
<add> return `./packages/react-server/src/forks/ReactServerFormatConfig.${rendererInfo.shortName}.js`;
<ide> }
<ide> }
<ide> throw new Error(
<ide> const forks = Object.freeze({
<ide> );
<ide> },
<ide>
<del> 'react-server/src/ReactFlightServerConfig': (
<add> './packages/react-server/src/ReactFlightServerConfig.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> if (!rendererInfo.isServerSupported) {
<ide> return null;
<ide> }
<del> return `react-server/src/forks/ReactFlightServerConfig.${rendererInfo.shortName}.js`;
<add> return `./packages/react-server/src/forks/ReactFlightServerConfig.${rendererInfo.shortName}.js`;
<ide> }
<ide> }
<ide> throw new Error(
<ide> const forks = Object.freeze({
<ide> );
<ide> },
<ide>
<del> 'react-client/src/ReactFlightClientHostConfig': (
<add> './packages/react-client/src/ReactFlightClientHostConfig.js': (
<ide> bundleType,
<ide> entry,
<ide> dependencies,
<ide> const forks = Object.freeze({
<ide> if (!rendererInfo.isServerSupported) {
<ide> return null;
<ide> }
<del> return `react-client/src/forks/ReactFlightClientHostConfig.${rendererInfo.shortName}.js`;
<add> return `./packages/react-client/src/forks/ReactFlightClientHostConfig.${rendererInfo.shortName}.js`;
<ide> }
<ide> }
<ide> throw new Error(
<ide> const forks = Object.freeze({
<ide> },
<ide>
<ide> // We wrap top-level listeners into guards on www.
<del> 'react-dom/src/events/EventListener': (bundleType, entry) => {
<add> './packages/react-dom/src/events/EventListener.js': (bundleType, entry) => {
<ide> switch (bundleType) {
<ide> case FB_WWW_DEV:
<ide> case FB_WWW_PROD:
<ide> const forks = Object.freeze({
<ide> return null;
<ide> } else {
<ide> // Use the www fork which is integrated with TimeSlice profiling.
<del> return 'react-dom/src/events/forks/EventListener-www.js';
<add> return './packages/react-dom/src/events/forks/EventListener-www.js';
<ide> }
<ide> default:
<ide> return null;
<ide> }
<ide> },
<ide>
<del> 'use-sync-external-store/src/useSyncExternalStore': (bundleType, entry) => {
<add> './packages/use-sync-external-store/src/useSyncExternalStore.js': (
<add> bundleType,
<add> entry
<add> ) => {
<ide> if (entry.startsWith('use-sync-external-store/shim')) {
<del> return 'use-sync-external-store/src/forks/useSyncExternalStore.forward-to-shim';
<add> return './packages/use-sync-external-store/src/forks/useSyncExternalStore.forward-to-shim.js';
<ide> }
<ide> if (entry !== 'use-sync-external-store') {
<ide> // Internal modules that aren't shims should use the native API from the
<ide> // react package.
<del> return 'use-sync-external-store/src/forks/useSyncExternalStore.forward-to-built-in';
<add> return './packages/use-sync-external-store/src/forks/useSyncExternalStore.forward-to-built-in.js';
<ide> }
<ide> return null;
<ide> },
<ide>
<del> 'use-sync-external-store/src/isServerEnvironment': (bundleType, entry) => {
<add> './packages/use-sync-external-store/src/isServerEnvironment.js': (
<add> bundleType,
<add> entry
<add> ) => {
<ide> if (entry.endsWith('.native')) {
<del> return 'use-sync-external-store/src/forks/isServerEnvironment.native';
<add> return './packages/use-sync-external-store/src/forks/isServerEnvironment.native.js';
<ide> }
<ide> },
<ide> });
<ide><path>scripts/rollup/plugins/use-forks-plugin.js
<ide> let resolveCache = new Map();
<ide> function useForks(forks) {
<ide> let resolvedForks = new Map();
<ide> Object.keys(forks).forEach(srcModule => {
<add> // Fork paths are relative to the project root. They must include the full
<add> // path, including the extension. We intentionally don't use Node's module
<add> // resolution algorithm because 1) require.resolve doesn't work with ESM
<add> // modules, and 2) the behavior is easier to predict.
<ide> const targetModule = forks[srcModule];
<ide> resolvedForks.set(
<del> require.resolve(srcModule),
<add> path.resolve(process.cwd(), srcModule),
<ide> // targetModule could be a string (a file path),
<ide> // or an error (which we'd throw if it gets used).
<ide> // Don't try to "resolve" errors, but cache
<ide> // resolved file paths.
<ide> typeof targetModule === 'string'
<del> ? require.resolve(targetModule)
<add> ? path.resolve(process.cwd(), targetModule)
<ide> : targetModule
<ide> );
<ide> }); | 2 |
Python | Python | fix python2.5 dependency in lookfor | 55f467b6e64949eef5c614501df34a5e9af70b38 | <ide><path>numpy/lib/utils.py
<ide> import os
<ide> import sys
<del>import pkgutil
<ide> import types
<ide> import re
<ide>
<ide> def _lookfor_generate_cache(module, import_modules, regenerate):
<ide> _all = item.__all__
<ide> except AttributeError:
<ide> _all = None
<add>
<ide> # import sub-packages
<ide> if import_modules and hasattr(item, '__path__'):
<del> for m in pkgutil.iter_modules(item.__path__):
<del> if _all is not None and m[1] not in _all:
<del> continue
<del> try:
<del> __import__("%s.%s" % (name, m[1]))
<del> except ImportError:
<del> continue
<add> for pth in item.__path__:
<add> for mod_path in os.listdir(pth):
<add> init_py = os.path.join(pth, mod_path, '__init__.py')
<add> if not os.path.isfile(init_py):
<add> continue
<add> if _all is not None and mod_path not in _all:
<add> continue
<add> try:
<add> __import__("%s.%s" % (name, mod_path))
<add> except ImportError:
<add> continue
<add>
<ide> for n, v in inspect.getmembers(item):
<ide> if _all is not None and n not in _all:
<ide> continue | 1 |
Ruby | Ruby | retry the download on a failure | 2d91613d06ae3f1a8fa84f087d9f6e3a6ff89e31 | <ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def retry_fetch? f
<ide> return false
<ide> end
<ide>
<add> ohai "Retrying download"
<add>
<ide> f.clear_cache
<ide> @fetch_failed[f.name] = true
<ide> true
<ide> def fetch_fetchable f
<ide> f.clear_cache if ARGV.force?
<ide>
<ide> already_fetched = f.cached_download.exist?
<del> download = f.fetch
<add> download = nil
<add>
<add> begin
<add> download = f.fetch
<add> rescue => e
<add> retry if retry_fetch? f
<add> raise e
<add> end
<ide>
<ide> return unless download.file?
<ide> | 1 |
PHP | PHP | fix secure cookie issue | 232bf01ae2f26e560e629b8cc56527efe84ec557 | <ide><path>laravel/cookie.php
<ide> public static function put($name, $value, $expiration = 0, $path = '/', $domain
<ide> $expiration = time() + ($expiration * 60);
<ide> }
<ide>
<add> // If the secure option is set to true, yet the request is not over HTTPS
<add> // we'll throw an exception to let the developer know that they are
<add> // attempting to send a secure cookie over the unsecure HTTP.
<add> if ($secure and ! Request::secure())
<add> {
<add> throw new \Exception("Attempting to set secure cookie over HTTP.");
<add> }
<add>
<ide> static::$jar[$name] = compact('name', 'value', 'expiration', 'path', 'domain', 'secure');
<ide> }
<ide> | 1 |
Javascript | Javascript | fix typo in plugin 'destroy' | 58563fddf9eb719f8a6ffc604048a068b305f8a8 | <ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide> canvas.style.width = this.chart.originalCanvasStyleWidth;
<ide> canvas.style.height = this.chart.originalCanvasStyleHeight;
<ide>
<del> Chart.pluginService.notifyPlugins('destory', [this]);
<add> Chart.pluginService.notifyPlugins('destroy', [this]);
<ide>
<ide> delete Chart.instances[this.id];
<ide> },
<ide><path>src/core/core.plugin.js
<ide> module.exports = function(Chart) {
<ide> afterDraw: helpers.noop,
<ide>
<ide> // Called during destroy
<del> destory: helpers.noop,
<add> destroy: helpers.noop,
<ide> });
<del>};
<ide>\ No newline at end of file
<add>}; | 2 |
PHP | PHP | populate defaultconfig in all cache adapters | fdde2bc9533a372b769893fa81a9011cdf626399 | <ide><path>Cake/Cache/Cache.php
<ide> * This engine is recommended to people deploying on windows with IIS.
<ide> * - `RedisEngine` - Uses redis and php-redis extension to store cache data.
<ide> *
<del> * The following keys are used in core cache engines:
<del> *
<del> * - `duration` Specify how long items in this cache configuration last.
<del> * - `groups` List of groups or 'tags' associated to every key stored in this config.
<del> * handy for deleting a complete group from cache.
<del> * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
<del> * with either another cache config or another application.
<del> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
<del> * cache::gc from ever being called automatically.
<del> * - `servers' Used by memcache. Give the address of the memcached servers to use.
<del> * - `compress` Used by memcache. Enables memcache's compressed format.
<del> * - `serialize` Used by FileCache. Should cache objects be serialized first.
<del> * - `path` Used by FileCache. Path to where cachefiles should be saved.
<del> * - `lock` Used by FileCache. Should files be locked before writing to them?
<del> * - `user` Used by Xcache. Username for XCache
<del> * - `password` Used by Xcache/Redis. Password for XCache/Redis
<add> * See Cache engine documentation for expected configuration keys.
<ide> *
<ide> * @see app/Config/core.php for configuration settings
<ide> * @param string $name Name of the configuration
<ide><path>Cake/Cache/CacheEngine.php
<ide> abstract class CacheEngine {
<ide>
<ide> /**
<del> * Settings of current engine instance
<add> * Runtime config
<add> *
<add> * This is the config of a particular instance
<ide> *
<ide> * @var array
<ide> */
<ide> protected $_config = [];
<ide>
<ide> /**
<del> * Default configuration
<add> * The default cache configuration is overriden in most cache adapters. These are
<add> * the keys that are common to all adapters. If overriden, this property is not used.
<ide> *
<del> * These settings apply to all cache engines, and can be overriden by a specific cache
<del> * engine or runtime config
<add> * - `duration` Specify how long items in this cache configuration last.
<add> * - `groups` List of groups or 'tags' associated to every key stored in this config.
<add> * handy for deleting a complete group from cache.
<add> * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
<add> * with either another cache config or another application.
<add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
<add> * cache::gc from ever being called automatically.
<ide> *
<ide> * @var array
<ide> */
<ide> protected static $_defaultConfig = [
<del> 'prefix' => 'cake_',
<ide> 'duration' => 3600,
<del> 'probability' => 100,
<del> 'groups' => []
<add> 'groups' => [],
<add> 'prefix' => 'cake_',
<add> 'probability' => 100
<ide> ];
<ide>
<ide> /**
<ide> abstract class CacheEngine {
<ide> * @return boolean True if the engine has been successfully initialized, false if not
<ide> */
<ide> public function init($config = []) {
<del> $config += $this->_config + static::$_defaultConfig + self::$_defaultConfig;
<add> $config += $this->_config + static::$_defaultConfig;
<ide> $this->_config = $config;
<ide> if (!empty($this->_config['groups'])) {
<ide> sort($this->_config['groups']);
<ide><path>Cake/Cache/Engine/ApcEngine.php
<ide> class ApcEngine extends CacheEngine {
<ide> *
<ide> * Called automatically by the cache frontend
<ide> *
<del> * @param array $settings array of setting for the engine
<add> * @param array $config array of setting for the engine
<ide> * @return boolean True if the engine has been successfully initialized, false if not
<ide> */
<del> public function init($settings = []) {
<del> if (!isset($settings['prefix'])) {
<del> $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
<add> public function init($config = []) {
<add> if (!isset($config['prefix'])) {
<add> $config['prefix'] = Inflector::slug(APP_DIR) . '_';
<ide> }
<del> parent::init($settings);
<add> parent::init($config);
<ide> return function_exists('apc_dec');
<ide> }
<ide>
<ide> public function write($key, $value, $duration) {
<ide> public function read($key) {
<ide> $time = time();
<ide> $cachetime = intval(apc_fetch($key . '_expires'));
<del> if ($cachetime !== 0 && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
<add> if ($cachetime !== 0 && ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime)) {
<ide> return false;
<ide> }
<ide> return apc_fetch($key);
<ide> public function clear($check) {
<ide> $cacheKeys = $info['cache_list'];
<ide> unset($info);
<ide> foreach ($cacheKeys as $key) {
<del> if (strpos($key['info'], $this->settings['prefix']) === 0) {
<add> if (strpos($key['info'], $this->_config['prefix']) === 0) {
<ide> apc_delete($key['info']);
<ide> }
<ide> }
<ide> public function clear($check) {
<ide> */
<ide> public function groups() {
<ide> if (empty($this->_compiledGroupNames)) {
<del> foreach ($this->settings['groups'] as $group) {
<del> $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
<add> foreach ($this->_config['groups'] as $group) {
<add> $this->_compiledGroupNames[] = $this->_config['prefix'] . $group;
<ide> }
<ide> }
<ide>
<ide> $groups = apc_fetch($this->_compiledGroupNames);
<del> if (count($groups) !== count($this->settings['groups'])) {
<add> if (count($groups) !== count($this->_config['groups'])) {
<ide> foreach ($this->_compiledGroupNames as $group) {
<ide> if (!isset($groups[$group])) {
<ide> apc_store($group, 1);
<ide> public function groups() {
<ide>
<ide> $result = [];
<ide> $groups = array_values($groups);
<del> foreach ($this->settings['groups'] as $i => $group) {
<add> foreach ($this->_config['groups'] as $i => $group) {
<ide> $result[] = $group . $groups[$i];
<ide> }
<ide> return $result;
<ide> public function groups() {
<ide> * @return boolean success
<ide> */
<ide> public function clearGroup($group) {
<del> apc_inc($this->settings['prefix'] . $group, 1, $success);
<add> apc_inc($this->_config['prefix'] . $group, 1, $success);
<ide> return $success;
<ide> }
<ide>
<ide><path>Cake/Cache/Engine/FileEngine.php
<ide> class FileEngine extends CacheEngine {
<ide> protected $_File = null;
<ide>
<ide> /**
<del> * Settings
<add> * The defaults used unless overriden by runtime configuration
<ide> *
<del> * - path = absolute path to cache directory, default => CACHE
<del> * - prefix = string prefix for filename, default => cake_
<del> * - lock = enable file locking on write, default => true
<del> * - serialize = serialize the data, default => true
<add> * - `duration` Specify how long items in this cache configuration last.
<add> * - `groups` List of groups or 'tags' associated to every key stored in this config.
<add> * handy for deleting a complete group from cache.
<add> * - `isWindows` Automatically populated with whether the host is windows or not
<add> * - `lock` Used by FileCache. Should files be locked before writing to them?
<add> * - `mask` The mask used for created files
<add> * - `path` Path to where cachefiles should be saved.
<add> * - `prefix` Prepended to all entries. Good for when you need to share a keyspace
<add> * with either another cache config or another application.
<add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
<add> * cache::gc from ever being called automatically.
<add> * - `serialize` Should cache objects be serialized first.
<ide> *
<ide> * @var array
<del> */
<del> protected $_config = [];
<del>
<del>/**
<del> * _defaultConfig
<del> *
<del> * @var mixed
<ide> */
<ide> protected static $_defaultConfig = [
<add> 'duration' => 3600,
<add> 'groups' => [],
<add> 'isWindows' => false,
<add> 'lock' => true,
<add> 'mask' => 0664,
<ide> 'path' => CACHE,
<ide> 'prefix' => 'cake_',
<del> 'lock' => true,
<del> 'serialize' => true,
<del> 'isWindows' => false,
<del> 'mask' => 0664
<add> 'probability' => 100,
<add> 'serialize' => true
<ide> ];
<ide>
<ide> /**
<ide><path>Cake/Cache/Engine/MemcachedEngine.php
<ide> class MemcachedEngine extends CacheEngine {
<ide> protected $_Memcached = null;
<ide>
<ide> /**
<del> * Settings
<add> * The defaults used unless overriden by runtime configuration
<ide> *
<del> * - servers = string or array of memcached servers, default => 127.0.0.1. If an
<del> * array MemcacheEngine will use them as a pool.
<del> * - compress = boolean, default => false
<del> * - persistent = string The name of the persistent connection. All configurations using
<add> * - `compress` Whether to compress data
<add> * - `duration` Specify how long items in this cache configuration last.
<add> * - `groups` List of groups or 'tags' associated to every key stored in this config.
<add> * handy for deleting a complete group from cache.
<add> * - `login` Login to access the Memcache server
<add> * - `password` Password to access the Memcache server
<add> * - `persistent` The name of the persistent connection. All configurations using
<ide> * the same persistent value will share a single underlying connection.
<del> * - serialize = string, default => php. The serializer engine used to serialize data.
<del> * Available engines are php, igbinary and json. Beside php, the memcached extension
<del> * must be compiled with the appropriate serializer support.
<del> *
<del> * @var array
<del> */
<del> protected $_config = [];
<del>
<del>/**
<del> * Default config
<del> *
<del> * The defaults used unless overriden by runtime configuration
<add> * - `prefix` Prepended to all entries. Good for when you need to share a keyspace
<add> * with either another cache config or another application.
<add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
<add> * cache::gc from ever being called automatically.
<add> * - `serialize` The serializer engine used to serialize data. Available engines are php,
<add> * igbinary and json. Beside php, the memcached extension must be compiled with the
<add> * appropriate serializer support.
<add> * - `servers` String or array of memcached servers. If an array MemcacheEngine will use
<add> * them as a pool.
<ide> *
<ide> * @var array
<ide> */
<ide> protected static $_defaultConfig = [
<del> 'servers' => ['127.0.0.1'],
<ide> 'compress' => false,
<del> 'persistent' => false,
<add> 'duration' => 3600,
<add> 'groups' => [],
<ide> 'login' => null,
<ide> 'password' => null,
<del> 'serialize' => 'php'
<add> 'persistent' => false,
<add> 'prefix' => 'cake_',
<add> 'probability' => 100,
<add> 'serialize' => 'php',
<add> 'servers' => ['127.0.0.1'],
<ide> ];
<ide>
<ide> /**
<ide><path>Cake/Cache/Engine/RedisEngine.php
<ide> class RedisEngine extends CacheEngine {
<ide> protected $_Redis = null;
<ide>
<ide> /**
<del> * Settings
<del> *
<del> * - server = string URL or ip to the Redis server host
<del> * - database = integer database number to use for connection
<del> * - port = integer port number to the Redis server (default: 6379)
<del> * - timeout = float timeout in seconds (default: 0)
<del> * - persistent = boolean Connects to the Redis server with a persistent connection (default: true)
<del> *
<del> * @var array
<del> */
<del> protected $_config = [];
<del>
<del>/**
<del> * Default config
<del> *
<ide> * The defaults used unless overriden by runtime configuration
<ide> *
<add> * - `database` database number to use for connection.
<add> * - `duration` Specify how long items in this cache configuration last.
<add> * - `groups` List of groups or 'tags' associated to every key stored in this config.
<add> * handy for deleting a complete group from cache.
<add> * - `password` Redis server password.
<add> * - `persistent` Connect to the Redis server with a persistent connection
<add> * - `port` port number to the Redis server.
<add> * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
<add> * with either another cache config or another application.
<add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
<add> * cache::gc from ever being called automatically.
<add> * - `server` URL or ip to the Redis server host.
<add> * - `timeout` timeout in seconds (float).
<add> *
<ide> * @var array
<ide> */
<ide> protected static $_defaultConfig = [
<del> 'prefix' => null,
<del> 'server' => '127.0.0.1',
<ide> 'database' => 0,
<del> 'port' => 6379,
<add> 'duration' => 3600,
<add> 'groups' => [],
<ide> 'password' => false,
<del> 'timeout' => 0,
<del> 'persistent' => true
<add> 'persistent' => true,
<add> 'port' => 6379,
<add> 'prefix' => null,
<add> 'probability' => 100,
<add> 'server' => '127.0.0.1',
<add> 'timeout' => 0
<ide> ];
<ide>
<ide> /**
<ide><path>Cake/Cache/Engine/XcacheEngine.php
<ide> class XcacheEngine extends CacheEngine {
<ide>
<ide> /**
<del> * Settings
<del> *
<del> * - PHP_AUTH_USER = xcache.admin.user, default cake
<del> * - PHP_AUTH_PW = xcache.admin.password, default cake
<del> *
<del> * @var array
<del> */
<del> protected $_config = [];
<del>
<del>/**
<del> * Default config
<add> * The defaults used unless overriden by runtime configuration
<add> *
<add> * - `duration` Specify how long items in this cache configuration last.
<add> * - `groups` List of groups or 'tags' associated to every key stored in this config.
<add> * handy for deleting a complete group from cache.
<add> * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
<add> * with either another cache config or another application.
<add> * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
<add> * cache::gc from ever being called automatically.
<add> * - `PHP_AUTH_USER` xcache.admin.user
<add> * - `PHP_AUTH_PW` xcache.admin.password
<ide> *
<ide> * @var array
<ide> */
<ide> protected static $_defaultConfig = [
<add> 'duration' => 3600,
<add> 'groups' => [],
<ide> 'prefix' => null,
<add> 'probability' => 100,
<ide> 'PHP_AUTH_USER' => 'user',
<ide> 'PHP_AUTH_PW' => 'password'
<ide> ];
<ide> public function clearGroup($group) {
<ide> protected function _auth($reverse = false) {
<ide> static $backup = [];
<ide> $keys = ['PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password'];
<del> foreach ($keys as $key => $setting) {
<add> foreach ($keys as $key => $value) {
<ide> if ($reverse) {
<ide> if (isset($backup[$key])) {
<ide> $_SERVER[$key] = $backup[$key];
<ide> protected function _auth($reverse = false) {
<ide> if (!empty($value)) {
<ide> $backup[$key] = $value;
<ide> }
<del> if (!empty($this->_config[$setting])) {
<del> $_SERVER[$key] = $this->_config[$setting];
<add> if (!empty($this->_config[$value])) {
<add> $_SERVER[$key] = $this->_config[$value];
<ide> } elseif (!empty($this->_config[$key])) {
<ide> $_SERVER[$key] = $this->_config[$key];
<ide> } else { | 7 |
PHP | PHP | replace deprecated method | fc6d4d2ca49f0475dc1a737458d29a3eee70a2bf | <ide><path>src/View/Form/FormContext.php
<ide> protected function _schemaDefault($field)
<ide> */
<ide> public function isRequired($field)
<ide> {
<del> $validator = $this->_form->validator();
<add> $validator = $this->_form->getValidator();
<ide> if (!$validator->hasField($field)) {
<ide> return false;
<ide> }
<ide><path>tests/TestCase/View/Form/FormContextTest.php
<ide> public function testValDefault()
<ide> */
<ide> public function testIsRequired()
<ide> {
<del> $this->deprecated(function () {
<del> $form = new Form();
<del> $form->validator()
<del> ->requirePresence('name')
<del> ->add('email', 'format', ['rule' => 'email']);
<add> $form = new Form();
<add> $form->getValidator()
<add> ->requirePresence('name')
<add> ->add('email', 'format', ['rule' => 'email']);
<ide>
<del> $context = new FormContext($this->request, [
<del> 'entity' => $form
<del> ]);
<del> $this->assertTrue($context->isRequired('name'));
<del> $this->assertTrue($context->isRequired('email'));
<del> $this->assertFalse($context->isRequired('body'));
<del> $this->assertFalse($context->isRequired('Prefix.body'));
<del> });
<add> $context = new FormContext($this->request, [
<add> 'entity' => $form
<add> ]);
<add> $this->assertTrue($context->isRequired('name'));
<add> $this->assertTrue($context->isRequired('email'));
<add> $this->assertFalse($context->isRequired('body'));
<add> $this->assertFalse($context->isRequired('Prefix.body'));
<ide> }
<ide>
<ide> /**
<ide> public function testAttributes()
<ide> */
<ide> public function testError()
<ide> {
<del> $this->deprecated(function () {
<del> $nestedValidator = new Validator();
<del> $nestedValidator
<del> ->add('password', 'length', ['rule' => ['minLength', 8]])
<del> ->add('confirm', 'length', ['rule' => ['minLength', 8]]);
<del> $form = new Form();
<del> $form->validator()
<del> ->add('email', 'format', ['rule' => 'email'])
<del> ->add('name', 'length', ['rule' => ['minLength', 10]])
<del> ->addNested('pass', $nestedValidator);
<del> $form->validate([
<del> 'email' => 'derp',
<del> 'name' => 'derp',
<del> 'pass' => [
<del> 'password' => 'short',
<del> 'confirm' => 'long enough',
<del> ],
<del> ]);
<add> $nestedValidator = new Validator();
<add> $nestedValidator
<add> ->add('password', 'length', ['rule' => ['minLength', 8]])
<add> ->add('confirm', 'length', ['rule' => ['minLength', 8]]);
<add> $form = new Form();
<add> $form->getValidator()
<add> ->add('email', 'format', ['rule' => 'email'])
<add> ->add('name', 'length', ['rule' => ['minLength', 10]])
<add> ->addNested('pass', $nestedValidator);
<add> $form->validate([
<add> 'email' => 'derp',
<add> 'name' => 'derp',
<add> 'pass' => [
<add> 'password' => 'short',
<add> 'confirm' => 'long enough',
<add> ],
<add> ]);
<ide>
<del> $context = new FormContext($this->request, ['entity' => $form]);
<del> $this->assertEquals([], $context->error('empty'));
<del> $this->assertEquals(['The provided value is invalid'], $context->error('email'));
<del> $this->assertEquals(['The provided value is invalid'], $context->error('name'));
<del> $this->assertEquals(['The provided value is invalid'], $context->error('pass.password'));
<del> $this->assertEquals([], $context->error('Alias.name'));
<del> $this->assertEquals([], $context->error('nope.nope'));
<add> $context = new FormContext($this->request, ['entity' => $form]);
<add> $this->assertEquals([], $context->error('empty'));
<add> $this->assertEquals(['The provided value is invalid'], $context->error('email'));
<add> $this->assertEquals(['The provided value is invalid'], $context->error('name'));
<add> $this->assertEquals(['The provided value is invalid'], $context->error('pass.password'));
<add> $this->assertEquals([], $context->error('Alias.name'));
<add> $this->assertEquals([], $context->error('nope.nope'));
<ide>
<del> $mock = $this->getMockBuilder('Cake\Validation\Validator')
<del> ->setMethods(['errors'])
<del> ->getMock();
<del> $mock->expects($this->once())
<del> ->method('errors')
<del> ->willReturn(['key' => 'should be an array, not a string']);
<del> $form->validator($mock);
<del> $form->validate([]);
<del> $context = new FormContext($this->request, ['entity' => $form]);
<del> $this->assertEquals(
<del> ['should be an array, not a string'],
<del> $context->error('key'),
<del> 'This test should not produce a PHP warning from array_values().'
<del> );
<del> });
<add> $mock = $this->getMockBuilder('Cake\Validation\Validator')
<add> ->setMethods(['errors'])
<add> ->getMock();
<add> $mock->expects($this->once())
<add> ->method('errors')
<add> ->willReturn(['key' => 'should be an array, not a string']);
<add> $form->setValidator('default', $mock);
<add> $form->validate([]);
<add> $context = new FormContext($this->request, ['entity' => $form]);
<add> $this->assertEquals(
<add> ['should be an array, not a string'],
<add> $context->error('key'),
<add> 'This test should not produce a PHP warning from array_values().'
<add> );
<ide> }
<ide>
<ide> /**
<ide> public function testError()
<ide> */
<ide> public function testHasError()
<ide> {
<del> $this->deprecated(function () {
<del> $nestedValidator = new Validator();
<del> $nestedValidator
<del> ->add('password', 'length', ['rule' => ['minLength', 8]])
<del> ->add('confirm', 'length', ['rule' => ['minLength', 8]]);
<del> $form = new Form();
<del> $form->validator()
<del> ->add('email', 'format', ['rule' => 'email'])
<del> ->add('name', 'length', ['rule' => ['minLength', 10]])
<del> ->addNested('pass', $nestedValidator);
<del> $form->validate([
<del> 'email' => 'derp',
<del> 'name' => 'derp',
<del> 'pass' => [
<del> 'password' => 'short',
<del> 'confirm' => 'long enough',
<del> ],
<del> ]);
<add> $nestedValidator = new Validator();
<add> $nestedValidator
<add> ->add('password', 'length', ['rule' => ['minLength', 8]])
<add> ->add('confirm', 'length', ['rule' => ['minLength', 8]]);
<add> $form = new Form();
<add> $form->getValidator()
<add> ->add('email', 'format', ['rule' => 'email'])
<add> ->add('name', 'length', ['rule' => ['minLength', 10]])
<add> ->addNested('pass', $nestedValidator);
<add> $form->validate([
<add> 'email' => 'derp',
<add> 'name' => 'derp',
<add> 'pass' => [
<add> 'password' => 'short',
<add> 'confirm' => 'long enough',
<add> ],
<add> ]);
<ide>
<del> $context = new FormContext($this->request, ['entity' => $form]);
<del> $this->assertTrue($context->hasError('email'));
<del> $this->assertTrue($context->hasError('name'));
<del> $this->assertFalse($context->hasError('nope'));
<del> $this->assertFalse($context->hasError('nope.nope'));
<del> $this->assertTrue($context->hasError('pass.password'));
<del> });
<add> $context = new FormContext($this->request, ['entity' => $form]);
<add> $this->assertTrue($context->hasError('email'));
<add> $this->assertTrue($context->hasError('name'));
<add> $this->assertFalse($context->hasError('nope'));
<add> $this->assertFalse($context->hasError('nope.nope'));
<add> $this->assertTrue($context->hasError('pass.password'));
<ide> }
<ide> } | 2 |
Text | Text | change wording of issue template | bd973ab0fcd2c806437cdb1b13848374fbeab7cf | <ide><path>.github/issue_template.md
<ide>
<ide> <!--
<ide> IMPORTANT
<del>> If you have a question about Next.js you should ask your question on Spectrum https://spectrum.chat/next-js
<del>> or join our Slack community at https://zeit.chat and ask in the `#next` channel
<add>If you have a question about Next.js please ask it on Spectrum https://spectrum.chat/next-js
<add>or join our Slack community at https://zeit.chat and ask it in the `#next` channel
<ide> -->
<ide>
<ide> <!-- | 1 |
Mixed | Python | remove bit of deprecated code | edbec2dbc93cbfc020a6bf8a99cccfd7e67d5096 | <ide><path>docs/templates/preprocessing/image.md
<ide> Generate batches of tensor image data with real-time data augmentation. The data
<ide> - __dim_ordering__: One of {"th", "tf"}.
<ide> "tf" mode means that the images should have shape `(samples, width, height, channels)`,
<ide> "th" mode means that the images should have shape `(samples, channels, width, height)`.
<add> It defaults to the `image_dim_ordering` value found in your
<add> Keras config file at `~/.keras/keras.json`.
<add> If you never set it, then it will be "th".
<ide>
<ide> - __Methods__:
<ide> - __fit(X)__: Required if featurewise_center or featurewise_std_normalization or zca_whitening. Compute necessary quantities on some sample data.
<ide><path>keras/preprocessing/image.py
<ide> def fit(self, X,
<ide> sigma = np.dot(flatX.T, flatX) / flatX.shape[1]
<ide> U, S, V = linalg.svd(sigma)
<ide> self.principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T)
<del>
<del>
<del>class GraphImageDataGenerator(ImageDataGenerator):
<del> '''Example of how to build a generator for a Graph model
<del> '''
<del> def next(self):
<del> bX, bY = super(GraphImageDataGenerator, self).next()
<del> return {'input': bX, 'output': bY} | 2 |
Python | Python | ignore warning raised during testing | fc1506199914b4fcdd2dfb930d9ddc0ee2ee9569 | <ide><path>numpy/ma/tests/test_core.py
<ide> __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
<ide>
<ide> import types
<add>import warnings
<ide>
<ide> import numpy
<ide> import numpy.core.fromnumeric as fromnumeric
<ide> def check_topython(self):
<ide> assert_equal(1, int(array([[[1]]])))
<ide> assert_equal(1.0, float(array([[1]])))
<ide> self.failUnlessRaises(ValueError, float, array([1,1]))
<add>
<add> warnings.simplefilter('ignore',UserWarning)
<ide> assert numpy.isnan(float(array([1],mask=[1])))
<add> warnings.simplefilter('default',UserWarning)
<ide> #TODO: Check how bool works...
<ide> #TODO: self.failUnless(bool(array([0,1])))
<ide> #TODO: self.failUnless(bool(array([0,0],mask=[0,1]))) | 1 |
Text | Text | add timeout description | 76c96da4878a8b4ca6f5c9628448fa04401a32ec | <ide><path>docs/project/test-and-docs.md
<ide> Run the entire test suite on your current repository:
<ide> * cross-compiles all the binaries for the various operating systems
<ide> * runs all the tests in the system
<ide>
<del> It can take several minutes to run all the tests. When they complete
<add> It can take approximate one hour to run all the tests. The time depends
<add> on your host performance. The default timeout is 60 minutes, which is
<add> defined in hack/make.sh(${TIMEOUT:=60m}). You can modify the timeout
<add> value on the basis of your host performance. When they complete
<ide> successfully, you see the output concludes with something like this:
<ide>
<ide> | 1 |
Python | Python | add support for xlm-roberta to run_ner script | 71b47505175111dd391a5b9de9514fbe50558bf0 | <ide><path>examples/run_ner.py
<ide> from transformers import RobertaConfig, RobertaForTokenClassification, RobertaTokenizer
<ide> from transformers import DistilBertConfig, DistilBertForTokenClassification, DistilBertTokenizer
<ide> from transformers import CamembertConfig, CamembertForTokenClassification, CamembertTokenizer
<add>from transformers import XLMRobertaConfig, XLMRobertaForTokenClassification, XLMRobertaTokenizer
<ide>
<ide> logger = logging.getLogger(__name__)
<ide>
<ide> ALL_MODELS = sum(
<del> (tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, RobertaConfig, DistilBertConfig)),
<add> (tuple(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, RobertaConfig, DistilBertConfig,
<add> CamembertConfig, XLMRobertaConfig)),
<ide> ())
<ide>
<ide> MODEL_CLASSES = {
<ide> "bert": (BertConfig, BertForTokenClassification, BertTokenizer),
<ide> "roberta": (RobertaConfig, RobertaForTokenClassification, RobertaTokenizer),
<ide> "distilbert": (DistilBertConfig, DistilBertForTokenClassification, DistilBertTokenizer),
<ide> "camembert": (CamembertConfig, CamembertForTokenClassification, CamembertTokenizer),
<add> "xlmroberta": (XLMRobertaConfig, XLMRobertaForTokenClassification, XLMRobertaTokenizer),
<ide> }
<ide>
<ide> | 1 |
PHP | PHP | fix deprecation use in components | 031d991f856bd1935a8505424462c1bbfb8bd945 | <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testAuthorizeFalse()
<ide> $Users = TableRegistry::get('Users');
<ide> $user = $Users->find('all')->hydrate(false)->first();
<ide> $this->Controller->Auth->storage()->write($user);
<del> $this->Controller->Auth->config('userModel', 'Users');
<del> $this->Controller->Auth->config('authorize', false);
<add> $this->Controller->Auth->setConfig('userModel', 'Users');
<add> $this->Controller->Auth->setConfig('authorize', false);
<ide> $this->Controller->request->addParams(['controller' => 'AuthTest', 'action' => 'add']);
<ide> $result = $this->Controller->Auth->startup($event);
<ide> $this->assertNull($result);
<ide> public function testAuthorizeFalse()
<ide> */
<ide> public function testIsAuthorizedMissingFile()
<ide> {
<del> $this->Controller->Auth->config('authorize', 'Missing');
<add> $this->Controller->Auth->setConfig('authorize', 'Missing');
<ide> $this->Controller->Auth->isAuthorized(['User' => ['id' => 1]]);
<ide> }
<ide>
<ide> public function testIsAuthorizedUsingUserInSession()
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->getMock();
<del> $this->Auth->config('authorize', ['AuthMockFour']);
<add> $this->Auth->setConfig('authorize', ['AuthMockFour']);
<ide> $this->Auth->setAuthorizeObject(0, $AuthMockFourAuthorize);
<ide>
<ide> $user = ['user' => 'mark'];
<ide> public function testIsAuthorizedUsingUserInSession()
<ide> */
<ide> public function testLoadAuthorizeResets()
<ide> {
<del> $this->Controller->Auth->config('authorize', ['Controller']);
<add> $this->Controller->Auth->setConfig('authorize', ['Controller']);
<ide> $result = $this->Controller->Auth->constructAuthorize();
<ide> $this->assertCount(1, $result);
<ide>
<ide> public function testLoadAuthorizeResets()
<ide> */
<ide> public function testLoadAuthenticateNoFile()
<ide> {
<del> $this->Controller->Auth->config('authenticate', 'Missing');
<add> $this->Controller->Auth->setConfig('authenticate', 'Missing');
<ide> $this->Controller->Auth->identify($this->Controller->request, $this->Controller->response);
<ide> }
<ide>
<ide> public function testLoadAuthenticateNoFile()
<ide> */
<ide> public function testAllConfigWithAuthorize()
<ide> {
<del> $this->Controller->Auth->config('authorize', [
<add> $this->Controller->Auth->setConfig('authorize', [
<ide> AuthComponent::ALL => ['actionPath' => 'controllers/'],
<ide> 'Controller',
<ide> ]);
<ide> $objects = array_values($this->Controller->Auth->constructAuthorize());
<ide> $result = $objects[0];
<del> $this->assertEquals('controllers/', $result->config('actionPath'));
<add> $this->assertEquals('controllers/', $result->getConfig('actionPath'));
<ide> }
<ide>
<ide> /**
<ide> public function testAllConfigWithAuthorize()
<ide> */
<ide> public function testLoadAuthenticateResets()
<ide> {
<del> $this->Controller->Auth->config('authenticate', ['Form']);
<add> $this->Controller->Auth->setConfig('authenticate', ['Form']);
<ide> $result = $this->Controller->Auth->constructAuthenticate();
<ide> $this->assertCount(1, $result);
<ide>
<ide> public function testLoadAuthenticateResets()
<ide> */
<ide> public function testAllConfigWithAuthenticate()
<ide> {
<del> $this->Controller->Auth->config('authenticate', [
<add> $this->Controller->Auth->setConfig('authenticate', [
<ide> AuthComponent::ALL => ['userModel' => 'AuthUsers'],
<ide> 'Form'
<ide> ]);
<ide> $objects = array_values($this->Controller->Auth->constructAuthenticate());
<ide> $result = $objects[0];
<del> $this->assertEquals('AuthUsers', $result->config('userModel'));
<add> $this->assertEquals('AuthUsers', $result->getConfig('userModel'));
<ide> }
<ide>
<ide> /**
<ide> public function testAllConfigWithAuthenticate()
<ide> */
<ide> public function testSameAuthenticateWithDifferentHashers()
<ide> {
<del> $this->Controller->Auth->config('authenticate', [
<add> $this->Controller->Auth->setConfig('authenticate', [
<ide> 'FormSimple' => ['className' => 'Form', 'passwordHasher' => 'Default'],
<ide> 'FormBlowfish' => ['className' => 'Form', 'passwordHasher' => 'Fallback'],
<ide> ]);
<ide> public function testLoginRedirect()
<ide> $this->Auth->request->url = 'users/login';
<ide> $this->Auth->request->env('HTTP_REFERER', false);
<ide>
<del> $this->Auth->config('loginRedirect', [
<add> $this->Auth->setConfig('loginRedirect', [
<ide> 'controller' => 'pages',
<ide> 'action' => 'display',
<ide> 'welcome'
<ide> ]);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->Auth->startup($event);
<del> $expected = Router::normalize($this->Auth->config('loginRedirect'));
<add> $expected = Router::normalize($this->Auth->getConfig('loginRedirect'));
<ide> $this->assertEquals($expected, $this->Auth->redirectUrl());
<ide>
<ide> $this->Auth->session->delete('Auth');
<ide> public function testLoginRedirect()
<ide> $this->Auth->request->addParams(['controller' => 'Posts', 'action' => 'view', 'pass' => [1]]);
<ide> $this->Auth->request->here = $url;
<ide>
<del> $this->Auth->config('authorize', 'controller');
<add> $this->Auth->setConfig('authorize', 'controller');
<ide>
<del> $this->Auth->config('loginAction', [
<add> $this->Auth->setConfig('loginAction', [
<ide> 'controller' => 'AuthTest', 'action' => 'login'
<ide> ]);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> public function testLoginRedirect()
<ide> $url = '/posts/view/1';
<ide> $this->Auth->request->addParams(['controller' => 'Posts', 'action' => 'view', 'pass' => [1]]);
<ide> $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
<del> $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $response = $this->Auth->startup($event);
<ide>
<ide> public function testLoginRedirectPost()
<ide> $this->Auth->request->env('HTTP_REFERER', Router::url('/foo/bar', true));
<ide> $this->Auth->request->env('REQUEST_METHOD', 'POST');
<ide> $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
<del> $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $response = $this->Auth->startup($event);
<ide>
<ide> public function testLoginRedirectPostNoReferer()
<ide> $this->Auth->request->addParams(['controller' => 'Posts', 'action' => 'view', 'pass' => [1]]);
<ide> $this->Auth->request->env('REQUEST_METHOD', 'POST');
<ide> $this->Auth->request->url = $this->Auth->request->here = Router::normalize($url);
<del> $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $response = $this->Auth->startup($event);
<ide>
<ide> public function testLoginRedirectQueryString()
<ide> 'refer' => 'menu'
<ide> ];
<ide>
<del> $this->Auth->config('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'AuthTest', 'action' => 'login']);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $response = $this->Auth->startup($event);
<ide>
<ide> public function testLoginRedirectQueryStringWithComplexLoginActionUrl()
<ide> ];
<ide>
<ide> $this->Auth->session->delete('Auth');
<del> $this->Auth->config('loginAction', '/auth_test/login/passed-param?a=b');
<add> $this->Auth->setConfig('loginAction', '/auth_test/login/passed-param?a=b');
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $response = $this->Auth->startup($event);
<ide>
<ide> public function testLoginRedirectDifferentBaseUrl()
<ide> $this->Auth->request->addParams(['controller' => 'Posts', 'action' => 'add']);
<ide> $this->Auth->request->url = Router::normalize($url);
<ide>
<del> $this->Auth->config('loginAction', ['controller' => 'Users', 'action' => 'login']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'Users', 'action' => 'login']);
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $response = $this->Auth->startup($event);
<ide>
<ide> public function testNoLoginRedirectForAuthenticatedUser()
<ide> $this->Auth->request->url = 'auth_test/login';
<ide>
<ide> $this->Auth->session->write('Auth.User.id', '1');
<del> $this->Auth->config('authenticate', ['Form']);
<add> $this->Auth->setConfig('authenticate', ['Form']);
<ide> $this->getMockBuilder(BaseAuthorize::class)
<ide> ->setMethods(['authorize'])
<ide> ->disableOriginalConstructor()
<ide> ->setMockClassName('NoLoginRedirectMockAuthorize')
<ide> ->getMock();
<del> $this->Auth->config('authorize', ['NoLoginRedirectMockAuthorize']);
<del> $this->Auth->config('loginAction', ['controller' => 'auth_test', 'action' => 'login']);
<add> $this->Auth->setConfig('authorize', ['NoLoginRedirectMockAuthorize']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'auth_test', 'action' => 'login']);
<ide>
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $return = $this->Auth->startup($event);
<ide> public function testDefaultToLoginRedirect()
<ide> ]);
<ide> Router::pushRequest($request);
<ide>
<del> $this->Auth->config('authorize', ['Controller']);
<add> $this->Auth->setConfig('authorize', ['Controller']);
<ide> $this->Auth->setUser(['username' => 'mariano', 'password' => 'cake']);
<del> $this->Auth->config('loginRedirect', [
<add> $this->Auth->setConfig('loginRedirect', [
<ide> 'controller' => 'something',
<ide> 'action' => 'else'
<ide> ]);
<ide> public function testRedirectToUnauthorizedRedirect()
<ide> 'session' => $this->Auth->session
<ide> ]);
<ide> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']);
<del> $this->Auth->config('authorize', ['Controller']);
<add> $this->Auth->setConfig('authorize', ['Controller']);
<ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
<ide>
<ide> $expected = ['controller' => 'no_can_do', 'action' => 'jack'];
<del> $this->Auth->config('unauthorizedRedirect', $expected);
<add> $this->Auth->setConfig('unauthorizedRedirect', $expected);
<ide>
<ide> $response = new Response();
<ide> $Controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> public function testRedirectToUnauthorizedRedirectLoginAction()
<ide> 'session' => $this->Auth->session
<ide> ]);
<ide> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']);
<del> $this->Auth->config('authorize', ['Controller']);
<add> $this->Auth->setConfig('authorize', ['Controller']);
<ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
<ide>
<del> $this->Auth->config('unauthorizedRedirect', true);
<del> $this->Auth->config('loginAction', '/users/login');
<add> $this->Auth->setConfig('unauthorizedRedirect', true);
<add> $this->Auth->setConfig('loginAction', '/users/login');
<ide>
<ide> $response = new Response();
<ide> $Controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> public function testRedirectToUnauthorizedRedirectSuppressedAuthError()
<ide> ->getMock();
<ide> $this->Auth->request = $Request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']);
<del> $this->Auth->config('authorize', ['Controller']);
<add> $this->Auth->setConfig('authorize', ['Controller']);
<ide> $this->Auth->setUser(['username' => 'admad', 'password' => 'cake']);
<ide> $expected = ['controller' => 'no_can_do', 'action' => 'jack'];
<del> $this->Auth->config('unauthorizedRedirect', $expected);
<del> $this->Auth->config('authError', false);
<add> $this->Auth->setConfig('unauthorizedRedirect', $expected);
<add> $this->Auth->setConfig('authError', false);
<ide>
<ide> $Response = new Response();
<ide> $Controller = $this->getMockBuilder('Cake\Controller\Controller')
<ide> public function testForbiddenException()
<ide> $url = '/party/on';
<ide> $this->Auth->request = $request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(['controller' => 'Party', 'action' => 'on']);
<del> $this->Auth->config([
<add> $this->Auth->setConfig([
<ide> 'authorize' => ['Controller'],
<ide> 'unauthorizedRedirect' => false
<ide> ]);
<ide> public function testNoRedirectOnLoginAction()
<ide> $url = '/AuthTest/login';
<ide> $this->Auth->request = $controller->request = new ServerRequest($url);
<ide> $this->Auth->request->addParams(['controller' => 'AuthTest', 'action' => 'login']);
<del> $this->Auth->config([
<add> $this->Auth->setConfig([
<ide> 'loginAction', ['controller' => 'AuthTest', 'action' => 'login'],
<ide> 'authorize', ['Controller']
<ide> ]);
<ide> public function testAdminRoute()
<ide>
<ide> Router::setRequestInfo($this->Auth->request);
<ide>
<del> $this->Auth->config('loginAction', [
<add> $this->Auth->setConfig('loginAction', [
<ide> 'prefix' => 'admin',
<ide> 'controller' => 'auth_test',
<ide> 'action' => 'login'
<ide> public function testAjaxLogin()
<ide> $this->Controller->request->params['action'] = 'add';
<ide>
<ide> $event = new Event('Controller.startup', $this->Controller);
<del> $this->Auth->config('ajaxLogin', 'test_element');
<add> $this->Auth->setConfig('ajaxLogin', 'test_element');
<ide> $this->Auth->RequestHandler->ajaxLayout = 'ajax2';
<ide>
<ide> $response = $this->Auth->startup($event);
<ide> public function testLoginActionRedirect()
<ide> $request->url = ltrim($url, '/');
<ide> Router::setRequestInfo($request);
<ide>
<del> $this->Auth->config('loginAction', [
<add> $this->Auth->setConfig('loginAction', [
<ide> 'prefix' => 'admin',
<ide> 'controller' => 'auth_test',
<ide> 'action' => 'login'
<ide> public function testStatelessAuthWorksWithUser()
<ide> $this->Auth->request->env('PHP_AUTH_USER', 'mariano');
<ide> $this->Auth->request->env('PHP_AUTH_PW', 'cake');
<ide>
<del> $this->Auth->config('authenticate', [
<add> $this->Auth->setConfig('authenticate', [
<ide> 'Basic' => ['userModel' => 'AuthUsers']
<ide> ]);
<del> $this->Auth->config('storage', 'Memory');
<add> $this->Auth->setConfig('storage', 'Memory');
<ide> $this->Auth->startup($event);
<ide>
<ide> $result = $this->Auth->user();
<ide> public function testStatelessAuthWorksWithUser()
<ide> */
<ide> public function testComponentSettings()
<ide> {
<del> $this->Auth->config([
<add> $this->Auth->setConfig([
<ide> 'loginAction' => ['controller' => 'people', 'action' => 'login'],
<ide> 'logoutRedirect' => ['controller' => 'people', 'action' => 'login'],
<ide> ]);
<ide> public function testComponentSettings()
<ide> ];
<ide> $this->assertEquals(
<ide> $expected['loginAction'],
<del> $this->Auth->config('loginAction')
<add> $this->Auth->getConfig('loginAction')
<ide> );
<ide> $this->assertEquals(
<ide> $expected['logoutRedirect'],
<del> $this->Auth->config('logoutRedirect')
<add> $this->Auth->getConfig('logoutRedirect')
<ide> );
<ide> }
<ide>
<ide> public function testComponentSettings()
<ide> public function testLogout()
<ide> {
<ide> $this->Auth->session->write('Auth.User.id', '1');
<del> $this->Auth->config('logoutRedirect', '/');
<add> $this->Auth->setConfig('logoutRedirect', '/');
<ide> $result = $this->Auth->logout();
<ide>
<ide> $this->assertEquals('/', $result);
<ide> public function testLogout()
<ide> */
<ide> public function testEventTriggering()
<ide> {
<del> $this->Auth->config('authenticate', [
<add> $this->Auth->setConfig('authenticate', [
<ide> 'Test' => ['className' => 'TestApp\Auth\TestAuthenticate']
<ide> ]);
<ide>
<ide> public function testAfterIdentifyForStatelessAuthentication()
<ide> $this->Auth->request->env('PHP_AUTH_USER', 'mariano');
<ide> $this->Auth->request->env('PHP_AUTH_PW', 'cake');
<ide>
<del> $this->Auth->config('authenticate', [
<add> $this->Auth->setConfig('authenticate', [
<ide> 'Basic' => ['userModel' => 'AuthUsers']
<ide> ]);
<del> $this->Auth->config('storage', 'Memory');
<add> $this->Auth->setConfig('storage', 'Memory');
<ide>
<ide> EventManager::instance()->on('Auth.afterIdentify', function (Event $event) {
<ide> $user = $event->getData(0);
<ide> public function testFlashSettings()
<ide> ->method('set')
<ide> ->with('Auth failure', ['key' => 'auth-key', 'element' => 'custom']);
<ide>
<del> $this->Auth->config('flash', [
<add> $this->Auth->setConfig('flash', [
<ide> 'key' => 'auth-key'
<ide> ]);
<ide> $this->Auth->flash('Auth failure');
<ide>
<del> $this->Auth->config('flash', [
<add> $this->Auth->setConfig('flash', [
<ide> 'key' => 'auth-key',
<ide> 'element' => 'custom'
<ide> ], false);
<ide> public function testRedirectSet()
<ide> */
<ide> public function testRedirectQueryStringRead()
<ide> {
<del> $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'users', 'action' => 'login']);
<ide> $this->Auth->request->query = ['redirect' => '/users/custom'];
<ide>
<ide> $result = $this->Auth->redirectUrl();
<ide> public function testRedirectQueryStringReadDuplicateBase()
<ide> */
<ide> public function testRedirectQueryStringReadEqualToLoginAction()
<ide> {
<del> $this->Auth->config([
<add> $this->Auth->setConfig([
<ide> 'loginAction' => ['controller' => 'users', 'action' => 'login'],
<ide> 'loginRedirect' => ['controller' => 'users', 'action' => 'home']
<ide> ]);
<ide> public function testRedirectQueryStringReadEqualToLoginAction()
<ide> */
<ide> public function testRedirectQueryStringInvalid()
<ide> {
<del> $this->Auth->config([
<add> $this->Auth->setConfig([
<ide> 'loginAction' => ['controller' => 'users', 'action' => 'login'],
<ide> 'loginRedirect' => ['controller' => 'users', 'action' => 'home']
<ide> ]);
<ide> public function testRedirectUrlWithBaseSet()
<ide>
<ide> Router::setRequestInfo($this->Auth->request);
<ide>
<del> $this->Auth->config('loginAction', ['controller' => 'users', 'action' => 'login']);
<del> $this->Auth->config('loginRedirect', ['controller' => 'users', 'action' => 'home']);
<add> $this->Auth->setConfig('loginAction', ['controller' => 'users', 'action' => 'login']);
<add> $this->Auth->setConfig('loginRedirect', ['controller' => 'users', 'action' => 'home']);
<ide>
<ide> $result = $this->Auth->redirectUrl();
<ide> $this->assertEquals('/users/home', $result);
<ide> public function testStatelessAuthNoRedirect()
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $_SESSION = [];
<ide>
<del> $this->Auth->config('authenticate', ['Basic']);
<add> $this->Auth->setConfig('authenticate', ['Basic']);
<ide> $this->Controller->request['action'] = 'add';
<ide>
<ide> $result = $this->Auth->startup($event);
<ide> public function testSessionKeyBC()
<ide>
<ide> $this->Auth->sessionKey = 'Auth.Member';
<ide> $this->assertEquals('Auth.Member', $this->Auth->sessionKey);
<del> $this->assertEquals('Auth.Member', $this->Auth->storage()->config('key'));
<add> $this->assertEquals('Auth.Member', $this->Auth->storage()->getConfig('key'));
<ide>
<ide> $this->Auth->sessionKey = false;
<ide> $this->assertInstanceOf('Cake\Auth\Storage\MemoryStorage', $this->Auth->storage());
<ide> public function testCheckAuthInConfig()
<ide> $this->assertEquals('Controller.startup', $this->Auth->authCheckCalledFrom);
<ide>
<ide> $this->Auth->authCheckCalledFrom = null;
<del> $this->Auth->config('checkAuthIn', 'Controller.initialize');
<add> $this->Auth->setConfig('checkAuthIn', 'Controller.initialize');
<ide> $this->Controller->startupProcess();
<ide> $this->assertEquals('Controller.initialize', $this->Auth->authCheckCalledFrom);
<ide> }
<ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php
<ide> public function setUp()
<ide> $this->Cookie = $controller->Cookie;
<ide> $this->request = $controller->request;
<ide>
<del> $this->Cookie->config([
<add> $this->Cookie->setConfig([
<ide> 'expires' => '+10 seconds',
<ide> 'path' => '/',
<ide> 'domain' => '',
<ide> public function testConfigKeyArray()
<ide> */
<ide> public function testSettingsCompatibility()
<ide> {
<del> $this->Cookie->config([
<add> $this->Cookie->setConfig([
<ide> 'expires' => '+10 seconds',
<ide> 'path' => '/',
<ide> 'domain' => '',
<ide> public function testSettings()
<ide> 'path' => '/'
<ide> ];
<ide> $Cookie = new CookieComponent(new ComponentRegistry(), $settings);
<del> $this->assertEquals($Cookie->config('time'), $settings['time']);
<del> $this->assertEquals($Cookie->config('path'), $settings['path']);
<add> $this->assertEquals($Cookie->getConfig('time'), $settings['time']);
<add> $this->assertEquals($Cookie->getConfig('path'), $settings['path']);
<ide> }
<ide>
<ide> /**
<ide> public function testReadInvalidCipher()
<ide> $this->request->cookies = [
<ide> 'Test' => $this->_encrypt('value'),
<ide> ];
<del> $this->Cookie->config('encryption', 'derp');
<add> $this->Cookie->setConfig('encryption', 'derp');
<ide> $this->Cookie->read('Test');
<ide> }
<ide>
<ide> public function testWriteSimple()
<ide> */
<ide> public function testWriteInvalidCipher()
<ide> {
<del> $this->Cookie->config('encryption', 'derp');
<add> $this->Cookie->setConfig('encryption', 'derp');
<ide> $this->Cookie->write('Test', 'nope');
<ide> }
<ide>
<ide> public function testWriteThanRead()
<ide> */
<ide> public function testWriteWithFalseyValue()
<ide> {
<del> $this->Cookie->config([
<add> $this->Cookie->setConfig([
<ide> 'encryption' => 'aes',
<ide> 'key' => 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^',
<ide> ]);
<ide> public function testWriteFarFuture()
<ide> */
<ide> public function testWriteHttpOnly()
<ide> {
<del> $this->Cookie->config([
<add> $this->Cookie->setConfig([
<ide> 'httpOnly' => true,
<ide> 'secure' => false
<ide> ]);
<ide> public function testReadConfigKeyWithCustomEncryptionKey()
<ide> */
<ide> public function testDeleteHttpOnly()
<ide> {
<del> $this->Cookie->config([
<add> $this->Cookie->setConfig([
<ide> 'httpOnly' => true,
<ide> 'secure' => false
<ide> ]);
<ide> protected function _encrypt($value)
<ide> $value = $this->_implode($value);
<ide> }
<ide>
<del> return 'Q2FrZQ==.' . base64_encode(Security::encrypt($value, $this->Cookie->config('key')));
<add> return 'Q2FrZQ==.' . base64_encode(Security::encrypt($value, $this->Cookie->getConfig('key')));
<ide> }
<ide> }
<ide><path>tests/TestCase/Controller/Component/FlashComponentTest.php
<ide> public function testDuplicateIgnored()
<ide> {
<ide> $this->assertNull($this->Session->read('Flash.flash'));
<ide>
<del> $this->Flash->config('duplicate', false);
<add> $this->Flash->setConfig('duplicate', false);
<ide> $this->Flash->set('This test message should appear once only');
<ide> $this->Flash->set('This test message should appear once only');
<ide> $result = $this->Session->read('Flash.flash');
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> public function testPaginateQuery()
<ide> */
<ide> public function testPaginateQueryWithBindValue()
<ide> {
<del> $config = ConnectionManager::config('test');
<add> $config = ConnectionManager::getConfig('test');
<ide> $this->skipIf(strpos($config['driver'], 'Sqlserver') !== false, 'Test temporarily broken in SQLServer');
<ide> $this->loadFixtures('Posts');
<ide> $table = TableRegistry::get('PaginatorPosts');
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php
<ide> public function testConstructorConfig()
<ide> ->getMock();
<ide> $collection = new ComponentRegistry($controller);
<ide> $requestHandler = new RequestHandlerComponent($collection, $config);
<del> $this->assertEquals(['json' => 'MyPlugin.MyJson'], $requestHandler->config('viewClassMap'));
<add> $this->assertEquals(['json' => 'MyPlugin.MyJson'], $requestHandler->getConfig('viewClassMap'));
<ide> }
<ide>
<ide> /**
<ide> public function testViewClassMapMethod()
<ide> 'json' => 'CustomJson',
<ide> 'xml' => 'Xml',
<ide> 'ajax' => 'Ajax'
<del> ];
<add> ];
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $this->RequestHandler->viewClassMap('xls', 'Excel.Excel');
<ide> public function testBeforeRedirectDisabled()
<ide>
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->RequestHandler->initialize([]);
<del> $this->RequestHandler->config('enableBeforeRedirect', false);
<add> $this->RequestHandler->setConfig('enableBeforeRedirect', false);
<ide> $this->RequestHandler->startup($event);
<ide> $this->assertNull($this->RequestHandler->beforeRedirect($event, '/posts/index', $this->Controller->response));
<ide> }
<ide> public function testCheckNotModifiedNoInfo()
<ide> public function testConstructDefaultOptions()
<ide> {
<ide> $requestHandler = new RequestHandlerComponent($this->Controller->components());
<del> $viewClass = $requestHandler->config('viewClassMap');
<add> $viewClass = $requestHandler->getConfig('viewClassMap');
<ide> $expected = [
<ide> 'json' => 'Json',
<ide> 'xml' => 'Xml',
<ide> 'ajax' => 'Ajax',
<ide> ];
<ide> $this->assertEquals($expected, $viewClass);
<ide>
<del> $inputs = $requestHandler->config('inputTypeMap');
<add> $inputs = $requestHandler->getConfig('inputTypeMap');
<ide> $this->assertArrayHasKey('json', $inputs);
<ide> $this->assertArrayHasKey('xml', $inputs);
<ide> }
<ide> public function testConstructReplaceOptions()
<ide> 'inputTypeMap' => ['json' => ['json_decode', true]]
<ide> ]
<ide> );
<del> $viewClass = $requestHandler->config('viewClassMap');
<add> $viewClass = $requestHandler->getConfig('viewClassMap');
<ide> $expected = [
<ide> 'json' => 'Json',
<ide> ];
<ide> $this->assertEquals($expected, $viewClass);
<ide>
<del> $inputs = $requestHandler->config('inputTypeMap');
<add> $inputs = $requestHandler->getConfig('inputTypeMap');
<ide> $this->assertArrayHasKey('json', $inputs);
<ide> $this->assertCount(1, $inputs);
<ide> }
<ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php
<ide> public function setUp()
<ide>
<ide> $this->Controller = new SecurityTestController($request);
<ide> $this->Controller->Security = $this->Controller->TestSecurity;
<del> $this->Controller->Security->config('blackHoleCallback', 'fail');
<add> $this->Controller->Security->setConfig('blackHoleCallback', 'fail');
<ide> $this->Security = $this->Controller->Security;
<ide> $this->Security->session = $session;
<ide> Security::setSalt('foo!');
<ide> public function testBlackholeWithBrokenCallback()
<ide> $Controller = new \TestApp\Controller\SomePagesController($request);
<ide> $event = new Event('Controller.startup', $Controller);
<ide> $Security = new SecurityComponent($Controller->components());
<del> $Security->config('blackHoleCallback', '_fail');
<add> $Security->setConfig('blackHoleCallback', '_fail');
<ide> $Security->startup($event);
<ide> $Security->blackHole($Controller, 'csrf');
<ide> }
<ide> public function testRequireAuthSucceed()
<ide> {
<ide> $this->deprecated(function () {
<ide> $_SERVER['REQUEST_METHOD'] = 'AUTH';
<del> $this->Controller->Security->config('validatePost', false);
<add> $this->Controller->Security->setConfig('validatePost', false);
<ide>
<ide> $event = new Event('Controller.startup', $this->Controller);
<ide> $this->Controller->request->addParams([
<ide> public function testValidatePostHidden()
<ide> public function testValidatePostWithDisabledFields()
<ide> {
<ide> $event = new Event('Controller.startup', $this->Controller);
<del> $this->Security->config('disabledFields', ['Model.username', 'Model.password']);
<add> $this->Security->setConfig('disabledFields', ['Model.username', 'Model.password']);
<ide> $this->Security->startup($event);
<ide> $fields = '0313460e1136e1227044399fe10a6edc0cbca279%3AModel.hidden';
<ide> $unlocked = '';
<ide> public function testFormDisabledFields()
<ide> $this->assertFalse($result);
<ide>
<ide> $this->Security->startup($event);
<del> $this->Security->config('disabledFields', ['MyModel.name']);
<add> $this->Security->setConfig('disabledFields', ['MyModel.name']);
<ide>
<ide> $this->Controller->request->data = [
<ide> 'MyModel' => ['name' => 'some data'],
<ide> public function testValidatePostDebugFormat()
<ide> */
<ide> public function testBlackholeThrowsException()
<ide> {
<del> $this->Security->config('blackHoleCallback', '');
<add> $this->Security->setConfig('blackHoleCallback', '');
<ide> $this->Security->blackHole($this->Controller, 'auth', new SecurityException('error description'));
<ide> }
<ide>
<ide> public function testBlackholeThrowsException()
<ide> */
<ide> public function testBlackholeThrowsBadRequest()
<ide> {
<del> $this->Security->config('blackHoleCallback', '');
<add> $this->Security->setConfig('blackHoleCallback', '');
<ide> $message = '';
<ide>
<ide> Configure::write('debug', false);
<ide> public function testValidatePostUnexpectedDebugToken()
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
<ide> {
<ide> $this->deprecated(function () {
<del> $this->Security->config('requireAuth', ['protected']);
<add> $this->Security->setConfig('requireAuth', ['protected']);
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = 'notEmpty';
<ide> $this->Security->authRequired($this->Controller);
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
<ide> {
<ide> $this->deprecated(function () {
<del> $this->Security->config('requireAuth', ['protected']);
<add> $this->Security->setConfig('requireAuth', ['protected']);
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = ['_Token' => 'not empty'];
<ide> $this->Security->authRequired($this->Controller);
<ide> public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
<ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed()
<ide> {
<ide> $this->deprecated(function () {
<del> $this->Security->config('requireAuth', ['protected']);
<add> $this->Security->setConfig('requireAuth', ['protected']);
<ide> $this->Controller->request->params['controller'] = 'NotAllowed';
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = ['_Token' => 'not empty'];
<ide> public function testAuthRequiredThrowsExceptionControllerNotAllowed()
<ide> public function testAuthRequiredThrowsExceptionActionNotAllowed()
<ide> {
<ide> $this->deprecated(function () {
<del> $this->Security->config('requireAuth', ['protected']);
<add> $this->Security->setConfig('requireAuth', ['protected']);
<ide> $this->Controller->request->params['controller'] = 'NotAllowed';
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = ['_Token' => 'not empty'];
<ide> public function testAuthRequiredThrowsExceptionActionNotAllowed()
<ide> public function testAuthRequired()
<ide> {
<ide> $this->deprecated(function () {
<del> $this->Security->config('requireAuth', ['protected']);
<add> $this->Security->setConfig('requireAuth', ['protected']);
<ide> $this->Controller->request->params['controller'] = 'Allowed';
<ide> $this->Controller->request->params['action'] = 'protected';
<ide> $this->Controller->request->data = ['_Token' => 'not empty']; | 6 |
Go | Go | honor the restarting state in stop | c4a00d549d0b895bb990491cbdf58aabe2891842 | <ide><path>daemon/container.go
<ide> func (container *Container) KillSig(sig int) error {
<ide> // after we send the kill signal
<ide> container.monitor.ExitOnNext()
<ide>
<add> // if the container is currently restarting we do not need to send the signal
<add> // to the process. Telling the monitor that it should exit on it's next event
<add> // loop is enough
<add> if container.State.IsRestarting() {
<add> return nil
<add> }
<add>
<ide> return container.daemon.Kill(container, sig)
<ide> }
<ide>
<ide><path>daemon/monitor.go
<ide> func (m *containerMonitor) Start() error {
<ide> time.Sleep(time.Duration(m.timeIncrement) * time.Millisecond)
<ide>
<ide> continue
<del> } else {
<del> // we still wait to set the state as stopped and ensure that the locks were released
<del> m.container.State.SetStopped(exitStatus)
<del>
<del> m.resetContainer()
<ide> }
<ide>
<ide> break
<ide> }
<ide>
<add> m.container.State.SetStopped(exitStatus)
<add>
<add> m.resetContainer()
<add>
<ide> return err
<ide> }
<ide>
<ide><path>daemon/state.go
<ide> func (s *State) String() string {
<ide> s.RLock()
<ide> defer s.RUnlock()
<ide>
<del> if s.Restarting {
<del> return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
<del> }
<del>
<ide> if s.Running {
<ide> if s.Paused {
<ide> return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
<ide> }
<add> if s.Restarting {
<add> return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
<add> }
<ide>
<ide> return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
<ide> }
<ide> func (s *State) SetStopped(exitCode int) {
<ide> func (s *State) SetRestarting(exitCode int) {
<ide> s.Lock()
<ide> if s.Running {
<del> s.Running = false
<add> // we should consider the container running when it is restarting because of
<add> // all the checks in docker around rm/stop/etc
<add> s.Running = true
<add> s.Restarting = true
<ide> s.Pid = 0
<ide> s.FinishedAt = time.Now().UTC()
<ide> s.ExitCode = exitCode | 3 |
PHP | PHP | add types to folder | 73cfe4669f8b7d9ce72faf404113f06242589e2b | <ide><path>src/Filesystem/Folder.php
<ide> class Folder
<ide> *
<ide> * @param string|null $path Path to folder
<ide> * @param bool $create Create folder if not found
<del> * @param int|false $mode Mode (CHMOD) to apply to created folder, false to ignore
<add> * @param int|null $mode Mode (CHMOD) to apply to created folder, false to ignore
<ide> */
<del> public function __construct($path = null, $create = false, $mode = false)
<add> public function __construct(?string $path = null, bool $create = false, ?int $mode = null)
<ide> {
<ide> if (empty($path)) {
<ide> $path = TMP;
<ide> public function __construct($path = null, $create = false, $mode = false)
<ide> /**
<ide> * Return current path.
<ide> *
<del> * @return string Current path
<add> * @return string|null Current path
<ide> */
<del> public function pwd()
<add> public function pwd(): ?string
<ide> {
<ide> return $this->path;
<ide> }
<ide> public function pwd()
<ide> * Change directory to $path.
<ide> *
<ide> * @param string $path Path to the directory to change to
<del> * @return string|bool The new path. Returns false on failure
<add> * @return string|bool The new path. Returns null on failure
<ide> */
<del> public function cd($path)
<add> public function cd(string $path): ?string
<ide> {
<ide> $path = $this->realpath($path);
<ide> if ($path !== false && is_dir($path)) {
<ide> return $this->path = $path;
<ide> }
<ide>
<del> return false;
<add> return null;
<ide> }
<ide>
<ide> /**
<ide> public function cd($path)
<ide> * @param bool $fullPath True returns the full path
<ide> * @return array Contents of current directory as an array, an empty array on failure
<ide> */
<del> public function read($sort = self::SORT_NAME, $exceptions = false, $fullPath = false)
<add> public function read($sort = self::SORT_NAME, $exceptions = false, bool $fullPath = false): array
<ide> {
<ide> $dirs = $files = [];
<ide>
<ide> public function read($sort = self::SORT_NAME, $exceptions = false, $fullPath = f
<ide> * Returns an array of all matching files in current directory.
<ide> *
<ide> * @param string $regexpPattern Preg_match pattern (Defaults to: .*)
<del> * @param bool $sort Whether results should be sorted.
<add> * @param string|bool $sort Whether results should be sorted.
<ide> * @return array Files that match given pattern
<ide> */
<del> public function find($regexpPattern = '.*', $sort = false)
<add> public function find(string $regexpPattern = '.*', $sort = false): array
<ide> {
<ide> list(, $files) = $this->read($sort);
<ide>
<ide> public function find($regexpPattern = '.*', $sort = false)
<ide> * Returns an array of all matching files in and below current directory.
<ide> *
<ide> * @param string $pattern Preg_match pattern (Defaults to: .*)
<del> * @param bool $sort Whether results should be sorted.
<add> * @param string|bool $sort Whether results should be sorted.
<ide> * @return array Files matching $pattern
<ide> */
<del> public function findRecursive($pattern = '.*', $sort = false)
<add> public function findRecursive(string $pattern = '.*', $sort = false): array
<ide> {
<ide> if (!$this->pwd()) {
<ide> return [];
<ide> public function findRecursive($pattern = '.*', $sort = false)
<ide> * @param bool $sort Whether results should be sorted.
<ide> * @return array Files matching pattern
<ide> */
<del> protected function _findRecursive($pattern, $sort = false)
<add> protected function _findRecursive(string $pattern, bool $sort = false): array
<ide> {
<ide> list($dirs, $files) = $this->read($sort);
<ide> $found = [];
<ide> protected function _findRecursive($pattern, $sort = false)
<ide> * @param string $path Path to check
<ide> * @return bool true if windows path, false otherwise
<ide> */
<del> public static function isWindowsPath($path)
<add> public static function isWindowsPath(string $path): bool
<ide> {
<ide> return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) === '\\\\');
<ide> }
<ide> public static function isWindowsPath($path)
<ide> * @param string $path Path to check
<ide> * @return bool true if path is absolute.
<ide> */
<del> public static function isAbsolute($path)
<add> public static function isAbsolute(string $path): bool
<ide> {
<ide> if (empty($path)) {
<ide> return false;
<ide> public static function isAbsolute($path)
<ide> * @param string $path Path to check
<ide> * @return bool True if path is registered stream wrapper.
<ide> */
<del> public static function isRegisteredStreamWrapper($path)
<add> public static function isRegisteredStreamWrapper(string $path): bool
<ide> {
<ide> return preg_match('/^[^:\/\/]+?(?=:\/\/)/', $path, $matches) &&
<ide> in_array($matches[0], stream_get_wrappers());
<ide> public static function isRegisteredStreamWrapper($path)
<ide> * @param string $path Path to transform
<ide> * @return string Path with the correct set of slashes ("\\" or "/")
<ide> */
<del> public static function normalizeFullPath($path)
<add> public static function normalizeFullPath(string $path): string
<ide> {
<ide> $to = Folder::correctSlashFor($path);
<ide> $from = ($to == '/' ? '\\' : '/');
<ide> public static function normalizeFullPath($path)
<ide> * @param string $path Path to check
<ide> * @return string Set of slashes ("\\" or "/")
<ide> */
<del> public static function correctSlashFor($path)
<add> public static function correctSlashFor(string $path): string
<ide> {
<ide> return Folder::isWindowsPath($path) ? '\\' : '/';
<ide> }
<ide> public static function correctSlashFor($path)
<ide> * @param string $path Path to check
<ide> * @return string Path with ending slash
<ide> */
<del> public static function slashTerm($path)
<add> public static function slashTerm(string $path): string
<ide> {
<ide> if (Folder::isSlashTerm($path)) {
<ide> return $path;
<ide> public static function slashTerm($path)
<ide> * @param string|array $element Element to add at end of path
<ide> * @return string Combined path
<ide> */
<del> public static function addPathElement($path, $element)
<add> public static function addPathElement(string $path, $element): string
<ide> {
<ide> $element = (array)$element;
<ide> array_unshift($element, rtrim($path, DIRECTORY_SEPARATOR));
<ide> public static function addPathElement($path, $element)
<ide> * @return bool
<ide> * @throws \InvalidArgumentException When the given `$path` argument is not an absolute path.
<ide> */
<del> public function inPath($path, $reverse = false)
<add> public function inPath(string $path, bool $reverse = false): bool
<ide> {
<ide> if (!Folder::isAbsolute($path)) {
<ide> throw new InvalidArgumentException('The $path argument is expected to be an absolute path.');
<ide> public function inPath($path, $reverse = false)
<ide> * @param array $exceptions Array of files, directories to skip.
<ide> * @return bool Success.
<ide> */
<del> public function chmod($path, $mode = false, $recursive = true, array $exceptions = [])
<add> public function chmod(string $path, ?int $mode = null, bool $recursive = true, array $exceptions = []): bool
<ide> {
<ide> if (!$mode) {
<ide> $mode = $this->mode;
<ide> public function chmod($path, $mode = false, $recursive = true, array $exceptions
<ide> * @param bool $fullPath Whether to return the full path or only the directory name.
<ide> * @return array Array of subdirectories for the provided or current path.
<ide> */
<del> public function subdirectories($path = null, $fullPath = true)
<add> public function subdirectories(?string $path = null, bool $fullPath = true): array
<ide> {
<ide> if (!$path) {
<ide> $path = $this->path;
<ide> public function subdirectories($path = null, $fullPath = true)
<ide> * @param string|null $type either 'file' or 'dir'. Null returns both files and directories
<ide> * @return array Array of nested directories and files in each directory
<ide> */
<del> public function tree($path = null, $exceptions = false, $type = null)
<add> public function tree(?string $path = null, $exceptions = false, ?string $type = null): array
<ide> {
<ide> if (!$path) {
<ide> $path = $this->path;
<ide> public function tree($path = null, $exceptions = false, $type = null)
<ide> * @param string $pathname The directory structure to create. Either an absolute or relative
<ide> * path. If the path is relative and exists in the process' cwd it will not be created.
<ide> * Otherwise relative paths will be prefixed with the current pwd().
<del> * @param int|bool $mode octal value 0755
<add> * @param int|null $mode octal value 0755
<ide> * @return bool Returns TRUE on success, FALSE on failure
<ide> */
<del> public function create($pathname, $mode = false)
<add> public function create(string $pathname, ?int $mode = null): bool
<ide> {
<ide> if (is_dir($pathname) || empty($pathname)) {
<ide> return true;
<ide> public function create($pathname, $mode = false)
<ide> *
<ide> * @return int size in bytes of current folder
<ide> */
<del> public function dirsize()
<add> public function dirsize(): int
<ide> {
<ide> $size = 0;
<ide> $directory = Folder::slashTerm($this->path);
<ide> public function dirsize()
<ide> * @param string|null $path Path of directory to delete
<ide> * @return bool Success
<ide> */
<del> public function delete($path = null)
<add> public function delete(?string $path = null): bool
<ide> {
<ide> if (!$path) {
<ide> $path = $this->pwd();
<ide> public function delete($path = null)
<ide> * @param array $options Array of options (see above).
<ide> * @return bool Success.
<ide> */
<del> public function copy($to, array $options = [])
<add> public function copy(string $to, array $options = []): bool
<ide> {
<ide> if (!$this->pwd()) {
<ide> return false;
<ide> public function copy($to, array $options = [])
<ide> * @param array $options Array of options (see above).
<ide> * @return bool Success
<ide> */
<del> public function move($to, array $options = [])
<add> public function move(string $to, array $options = []): bool
<ide> {
<ide> $options += ['from' => $this->path, 'mode' => $this->mode, 'skip' => [], 'recursive' => true];
<ide>
<ide> public function move($to, array $options = [])
<ide> * @param bool $reset Reset message stack after reading
<ide> * @return array
<ide> */
<del> public function messages($reset = true)
<add> public function messages(bool $reset = true): array
<ide> {
<ide> $messages = $this->_messages;
<ide> if ($reset) {
<ide> public function messages($reset = true)
<ide> * @param bool $reset Reset error stack after reading
<ide> * @return array
<ide> */
<del> public function errors($reset = true)
<add> public function errors(bool $reset = true): array
<ide> {
<ide> $errors = $this->_errors;
<ide> if ($reset) {
<ide> public function realpath($path)
<ide> * @param string $path Path to check
<ide> * @return bool true if path ends with slash, false otherwise
<ide> */
<del> public static function isSlashTerm($path)
<add> public static function isSlashTerm(string $path): bool
<ide> {
<ide> $lastChar = $path[strlen($path) - 1];
<ide>
<ide><path>tests/TestCase/Filesystem/FolderTest.php
<ide> public function testBasic()
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $Folder->cd(ROOT . DS . 'non-existent');
<del> $this->assertFalse($result);
<add> $this->assertNull($result);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | remove unneeded jshint directives | 43f72066e107445204aee074d7b4f184e9c05d9e | <ide><path>src/auto/injector.js
<ide> function createInjector(modulesToLoad, strictDi) {
<ide> return fn.apply(self, args);
<ide> } else {
<ide> args.unshift(null);
<del> /*jshint -W058 */ // Applying a constructor without immediate parentheses is the point here.
<del> return new (Function.prototype.bind.apply(fn, args));
<del> /*jshint +W058 */
<add> return new (Function.prototype.bind.apply(fn, args))();
<ide> }
<ide> }
<ide>
<ide> function createInjector(modulesToLoad, strictDi) {
<ide> var args = injectionArgs(Type, locals, serviceName);
<ide> // Empty object at position 0 is ignored for invocation with `new`, but required.
<ide> args.unshift(null);
<del> /*jshint -W058 */ // Applying a constructor without immediate parentheses is the point here.
<del> return new (Function.prototype.bind.apply(ctor, args));
<del> /*jshint +W058 */
<add> return new (Function.prototype.bind.apply(ctor, args))();
<ide> }
<ide>
<ide> | 1 |
Javascript | Javascript | remove var in reactandroid/src/androidtest | 9d132339f781e0234edf744e6be71389046d9bc3 | <ide><path>ReactAndroid/src/androidTest/js/TestJSToJavaParametersModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var Recording = require('NativeModules').Recording;
<add>const BatchedBridge = require('BatchedBridge');
<add>const Recording = require('NativeModules').Recording;
<ide>
<del>var TestJSToJavaParametersModule = {
<add>const TestJSToJavaParametersModule = {
<ide> returnBasicTypes: function() {
<ide> Recording.receiveBasicTypes('foo', 3.14, true, null);
<ide> },
<ide><path>ReactAndroid/src/androidTest/js/TextInputTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var React = require('React');
<del>var StyleSheet = require('StyleSheet');
<del>var Text = require('Text');
<del>var TextInput = require('TextInput');
<del>var View = require('View');
<add>const BatchedBridge = require('BatchedBridge');
<add>const React = require('React');
<add>const StyleSheet = require('StyleSheet');
<add>const Text = require('Text');
<add>const TextInput = require('TextInput');
<add>const View = require('View');
<ide>
<del>var Recording = require('NativeModules').Recording;
<add>const Recording = require('NativeModules').Recording;
<ide>
<del>var app;
<add>let app;
<ide>
<ide> class TokenizedTextExample extends React.Component {
<ide> constructor(props) {
<ide> class TextInputTestApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> container: {
<ide> padding: 5,
<ide> margin: 10,
<ide> var styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>var TextInputTestModule = {
<add>const TextInputTestModule = {
<ide> TextInputTestApp,
<ide> setValueRef: function(ref, value) {
<ide> app.refs[ref].setNativeProps({
<ide><path>ReactAndroid/src/androidTest/js/TimePickerDialogTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var TimePickerAndroid = require('TimePickerAndroid');
<del>var React = require('React');
<del>var RecordingModule = require('NativeModules').TimePickerDialogRecordingModule;
<del>var View = require('View');
<add>const BatchedBridge = require('BatchedBridge');
<add>const TimePickerAndroid = require('TimePickerAndroid');
<add>const React = require('React');
<add>const RecordingModule = require('NativeModules')
<add> .TimePickerDialogRecordingModule;
<add>const View = require('View');
<ide>
<ide> class TimePickerDialogTestApp extends React.Component {
<ide> render() {
<ide> return <View />;
<ide> }
<ide> }
<ide>
<del>var TimePickerDialogTestModule = {
<add>const TimePickerDialogTestModule = {
<ide> TimePickerDialogTestApp: TimePickerDialogTestApp,
<ide> showTimePickerDialog: function(options) {
<ide> TimePickerAndroid.open(options).then(
<ide><path>ReactAndroid/src/androidTest/js/TouchBubblingTestAppModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var Recording = require('NativeModules').Recording;
<add>const Recording = require('NativeModules').Recording;
<ide>
<del>var React = require('React');
<del>var StyleSheet = require('StyleSheet');
<del>var View = require('View');
<del>var TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<add>const React = require('React');
<add>const StyleSheet = require('StyleSheet');
<add>const View = require('View');
<add>const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<ide>
<ide> class TouchBubblingTestApp extends React.Component {
<ide> handlePress = record => {
<ide> class TouchBubblingTestApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> container: {
<ide> flexDirection: 'column',
<ide> backgroundColor: '#ccdd44',
<ide><path>ReactAndroid/src/androidTest/js/ViewRenderingTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var React = require('React');
<del>var View = require('View');
<del>var StyleSheet = require('StyleSheet');
<add>const BatchedBridge = require('BatchedBridge');
<add>const React = require('React');
<add>const View = require('View');
<add>const StyleSheet = require('StyleSheet');
<ide>
<del>var renderApplication = require('renderApplication');
<add>const renderApplication = require('renderApplication');
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> view: {
<ide> opacity: 0.75,
<ide> backgroundColor: 'rgb(255, 0, 0)',
<ide> class ViewSampleApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var updateMargins;
<add>let updateMargins;
<ide>
<ide> class MarginSampleApp extends React.Component {
<ide> state = {margin: 10};
<ide> class BorderSampleApp extends React.Component {
<ide>
<ide> class TransformSampleApp extends React.Component {
<ide> render() {
<del> var style = {
<add> const style = {
<ide> transform: [
<ide> {translateX: 20},
<ide> {translateY: 25},
<ide> class TransformSampleApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var ViewRenderingTestModule = {
<add>const ViewRenderingTestModule = {
<ide> renderViewApplication: function(rootTag) {
<ide> renderApplication(ViewSampleApp, {}, rootTag);
<ide> }, | 5 |
Text | Text | remove double "using" in reference attach docs | 0884dca124beac751964256234b3b3d4e402b21a | <ide><path>docs/reference/commandline/attach.md
<ide> detached process.
<ide> To stop a container, use `CTRL-c`. This key sequence sends `SIGKILL` to the
<ide> container. If `--sig-proxy` is true (the default),`CTRL-c` sends a `SIGINT` to
<ide> the container. You can detach from a container and leave it running using the
<del>using `CTRL-p CTRL-q` key sequence.
<add> `CTRL-p CTRL-q` key sequence.
<ide>
<ide> > **Note:**
<ide> > A process running as PID 1 inside a container is treated specially by | 1 |
Javascript | Javascript | fix randomize button | 3477764db0f074437bee27132d23d367deb4c6ef | <ide><path>examples/box/box.js
<ide> var w = 120,
<ide> h = 500,
<ide> m = [10, 50, 20, 50], // top right bottom left
<del> max = 50;
<add> min = Number.MAX_VALUE,
<add> max = Number.MIN_VALUE;
<ide>
<ide> var chart = d3.chart.box()
<ide> .width(w - m[1] - m[3])
<ide> .height(h - m[0] - m[2]);
<ide>
<ide> d3.csv("morley.csv", function(csv) {
<del> var data = [],
<del> min = Number.MAX_VALUE,
<del> max = Number.MIN_VALUE;
<add> var data = [];
<ide>
<ide> csv.forEach(function(x) {
<ide> var e = parseInt(x.Expt) - 1,
<ide> function randomize(d) {
<ide> function randomizer(d) {
<ide> var k = d3.max(d) * .2;
<ide> return function(d) {
<del> return Math.min(Math.max(0, d + k * (Math.random() - .5)), max);
<add> return Math.min(Math.max(min, d + k * (Math.random() - .5)), max);
<ide> };
<ide> } | 1 |
Python | Python | add algorithm to check binary search tree | 3e1cb70abf9997af3a4903f77cb3506a301de893 | <ide><path>data_structures/binary_tree/is_bst.py
<add>"""
<add>Author : Alexander Pantyukhin
<add>Date : November 2, 2022
<add>
<add>Task:
<add>Given the root of a binary tree, determine if it is a valid binary search
<add>tree (BST).
<add>
<add>A valid binary search tree is defined as follows:
<add>
<add>- The left subtree of a node contains only nodes with keys less than the node's key.
<add>- The right subtree of a node contains only nodes with keys greater than the node's key.
<add>- Both the left and right subtrees must also be binary search trees.
<add>
<add>Implementation notes:
<add>Depth-first search approach.
<add>
<add>leetcode: https://leetcode.com/problems/validate-binary-search-tree/
<add>
<add>Let n is the number of nodes in tree
<add>Runtime: O(n)
<add>Space: O(1)
<add>"""
<add>
<add>from __future__ import annotations
<add>
<add>from dataclasses import dataclass
<add>
<add>
<add>@dataclass
<add>class TreeNode:
<add> data: float
<add> left: TreeNode | None = None
<add> right: TreeNode | None = None
<add>
<add>
<add>def is_binary_search_tree(root: TreeNode | None) -> bool:
<add> """
<add> >>> is_binary_search_tree(TreeNode(data=2,
<add> ... left=TreeNode(data=1),
<add> ... right=TreeNode(data=3))
<add> ... )
<add> True
<add>
<add> >>> is_binary_search_tree(TreeNode(data=0,
<add> ... left=TreeNode(data=-11),
<add> ... right=TreeNode(data=3))
<add> ... )
<add> True
<add>
<add> >>> is_binary_search_tree(TreeNode(data=5,
<add> ... left=TreeNode(data=1),
<add> ... right=TreeNode(data=4, left=TreeNode(data=3)))
<add> ... )
<add> False
<add>
<add> >>> is_binary_search_tree(TreeNode(data='a',
<add> ... left=TreeNode(data=1),
<add> ... right=TreeNode(data=4, left=TreeNode(data=3)))
<add> ... )
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Each node should be type of TreeNode and data should be float.
<add>
<add> >>> is_binary_search_tree(TreeNode(data=2,
<add> ... left=TreeNode([]),
<add> ... right=TreeNode(data=4, left=TreeNode(data=3)))
<add> ... )
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Each node should be type of TreeNode and data should be float.
<add> """
<add>
<add> # Validation
<add> def is_valid_tree(node: TreeNode | None) -> bool:
<add> """
<add> >>> is_valid_tree(None)
<add> True
<add> >>> is_valid_tree('abc')
<add> False
<add> >>> is_valid_tree(TreeNode(data='not a float'))
<add> False
<add> >>> is_valid_tree(TreeNode(data=1, left=TreeNode('123')))
<add> False
<add> """
<add> if node is None:
<add> return True
<add>
<add> if not isinstance(node, TreeNode):
<add> return False
<add>
<add> try:
<add> float(node.data)
<add> except (TypeError, ValueError):
<add> return False
<add>
<add> return is_valid_tree(node.left) and is_valid_tree(node.right)
<add>
<add> if not is_valid_tree(root):
<add> raise ValueError(
<add> "Each node should be type of TreeNode and data should be float."
<add> )
<add>
<add> def is_binary_search_tree_recursive_check(
<add> node: TreeNode | None, left_bound: float, right_bound: float
<add> ) -> bool:
<add> """
<add> >>> is_binary_search_tree_recursive_check(None)
<add> True
<add> >>> is_binary_search_tree_recursive_check(TreeNode(data=1), 10, 20)
<add> False
<add> """
<add>
<add> if node is None:
<add> return True
<add>
<add> return (
<add> left_bound < node.data < right_bound
<add> and is_binary_search_tree_recursive_check(node.left, left_bound, node.data)
<add> and is_binary_search_tree_recursive_check(
<add> node.right, node.data, right_bound
<add> )
<add> )
<add>
<add> return is_binary_search_tree_recursive_check(root, -float("inf"), float("inf"))
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod() | 1 |
Text | Text | update minimum g++ version to 4.9.4 | d13a65ad68c429884434cdcd94c52b79a6d69717 | <ide><path>BUILDING.md
<ide> Depending on host platform, the selection of toolchains may vary.
<ide>
<ide> #### Unix
<ide>
<del>* GCC 4.8.5 or newer
<add>* GCC 4.9.4 or newer
<ide> * Clang 3.4.2 or newer
<ide>
<ide> #### Windows
<ide> Depending on host platform, the selection of toolchains may vary.
<ide>
<ide> Prerequisites:
<ide>
<del>* `gcc` and `g++` 4.8.5 or newer, or
<del>* `clang` and `clang++` 3.4.2 or newer
<add>* `gcc` and `g++` 4.9.4 or newer, or
<add>* `clang` and `clang++` 3.4.2 or newer (macOS: latest Xcode Command Line Tools)
<ide> * Python 2.6 or 2.7
<ide> * GNU Make 3.81 or newer
<ide> | 1 |
Javascript | Javascript | convert `pdflinkservice` to an es6 class | 8ba80729373629420d17fcf7b25156824b659502 | <ide><path>web/interfaces.js
<ide> class IPDFLinkService {
<ide> */
<ide> executeNamedAction(action) {}
<ide>
<add> /**
<add> * @param {Object} params
<add> */
<add> onFileAttachmentAnnotation({ id, filename, content, }) {}
<add>
<ide> /**
<ide> * @param {number} pageNum - page number.
<ide> * @param {Object} pageRef - reference to the page.
<ide><path>web/pdf_link_service.js
<ide> import { parseQueryString } from './ui_utils';
<ide> /**
<ide> * Performs navigation functions inside PDF, such as opening specified page,
<ide> * or destination.
<del> * @class
<ide> * @implements {IPDFLinkService}
<ide> */
<del>var PDFLinkService = (function PDFLinkServiceClosure() {
<add>class PDFLinkService {
<ide> /**
<del> * @constructs PDFLinkService
<ide> * @param {PDFLinkServiceOptions} options
<ide> */
<del> function PDFLinkService(options) {
<del> options = options || {};
<del> this.eventBus = options.eventBus || getGlobalEventBus();
<add> constructor({ eventBus, } = {}) {
<add> this.eventBus = eventBus || getGlobalEventBus();
<ide> this.baseUrl = null;
<ide> this.pdfDocument = null;
<ide> this.pdfViewer = null;
<ide> var PDFLinkService = (function PDFLinkServiceClosure() {
<ide> this._pagesRefCache = null;
<ide> }
<ide>
<del> PDFLinkService.prototype = {
<del> setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
<del> this.baseUrl = baseUrl;
<del> this.pdfDocument = pdfDocument;
<del> this._pagesRefCache = Object.create(null);
<del> },
<del>
<del> setViewer: function PDFLinkService_setViewer(pdfViewer) {
<del> this.pdfViewer = pdfViewer;
<del> },
<del>
<del> setHistory: function PDFLinkService_setHistory(pdfHistory) {
<del> this.pdfHistory = pdfHistory;
<del> },
<del>
<del> /**
<del> * @returns {number}
<del> */
<del> get pagesCount() {
<del> return this.pdfDocument ? this.pdfDocument.numPages : 0;
<del> },
<del>
<del> /**
<del> * @returns {number}
<del> */
<del> get page() {
<del> return this.pdfViewer.currentPageNumber;
<del> },
<del>
<del> /**
<del> * @param {number} value
<del> */
<del> set page(value) {
<del> this.pdfViewer.currentPageNumber = value;
<del> },
<del>
<del> /**
<del> * @param {string|Array} dest - The named, or explicit, PDF destination.
<del> */
<del> navigateTo(dest) {
<del> let goToDestination = ({ namedDest, explicitDest, }) => {
<del> // Dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
<del> let destRef = explicitDest[0], pageNumber;
<del>
<del> if (destRef instanceof Object) {
<del> pageNumber = this._cachedPageNumber(destRef);
<del>
<del> if (pageNumber === null) {
<del> // Fetch the page reference if it's not yet available. This could
<del> // only occur during loading, before all pages have been resolved.
<del> this.pdfDocument.getPageIndex(destRef).then((pageIndex) => {
<del> this.cachePageRef(pageIndex + 1, destRef);
<del> goToDestination({ namedDest, explicitDest, });
<del> }).catch(() => {
<del> console.error(`PDFLinkService.navigateTo: "${destRef}" is not ` +
<del> `a valid page reference, for dest="${dest}".`);
<del> });
<del> return;
<del> }
<del> } else if ((destRef | 0) === destRef) { // Integer
<del> pageNumber = destRef + 1;
<del> } else {
<del> console.error(`PDFLinkService.navigateTo: "${destRef}" is not ` +
<del> `a valid destination reference, for dest="${dest}".`);
<del> return;
<del> }
<del> if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
<del> console.error(`PDFLinkService.navigateTo: "${pageNumber}" is not ` +
<del> `a valid page number, for dest="${dest}".`);
<del> return;
<del> }
<add> setDocument(pdfDocument, baseUrl) {
<add> this.baseUrl = baseUrl;
<add> this.pdfDocument = pdfDocument;
<add> this._pagesRefCache = Object.create(null);
<add> }
<ide>
<del> this.pdfViewer.scrollPageIntoView({
<del> pageNumber,
<del> destArray: explicitDest,
<del> });
<add> setViewer(pdfViewer) {
<add> this.pdfViewer = pdfViewer;
<add> }
<ide>
<del> if (this.pdfHistory) { // Update the browsing history, if enabled.
<del> this.pdfHistory.push({
<del> dest: explicitDest,
<del> hash: namedDest,
<del> page: pageNumber,
<del> });
<del> }
<del> };
<del>
<del> new Promise((resolve, reject) => {
<del> if (typeof dest === 'string') {
<del> this.pdfDocument.getDestination(dest).then((destArray) => {
<del> resolve({
<del> namedDest: dest,
<del> explicitDest: destArray,
<del> });
<add> setHistory(pdfHistory) {
<add> this.pdfHistory = pdfHistory;
<add> }
<add>
<add> /**
<add> * @returns {number}
<add> */
<add> get pagesCount() {
<add> return this.pdfDocument ? this.pdfDocument.numPages : 0;
<add> }
<add>
<add> /**
<add> * @returns {number}
<add> */
<add> get page() {
<add> return this.pdfViewer.currentPageNumber;
<add> }
<add>
<add> /**
<add> * @param {number} value
<add> */
<add> set page(value) {
<add> this.pdfViewer.currentPageNumber = value;
<add> }
<add>
<add> /**
<add> * @param {string|Array} dest - The named, or explicit, PDF destination.
<add> */
<add> navigateTo(dest) {
<add> let goToDestination = ({ namedDest, explicitDest, }) => {
<add> // Dest array looks like that: <page-ref> </XYZ|/FitXXX> <args..>
<add> let destRef = explicitDest[0], pageNumber;
<add>
<add> if (destRef instanceof Object) {
<add> pageNumber = this._cachedPageNumber(destRef);
<add>
<add> if (pageNumber === null) {
<add> // Fetch the page reference if it's not yet available. This could
<add> // only occur during loading, before all pages have been resolved.
<add> this.pdfDocument.getPageIndex(destRef).then((pageIndex) => {
<add> this.cachePageRef(pageIndex + 1, destRef);
<add> goToDestination({ namedDest, explicitDest, });
<add> }).catch(() => {
<add> console.error(`PDFLinkService.navigateTo: "${destRef}" is not ` +
<add> `a valid page reference, for dest="${dest}".`);
<ide> });
<ide> return;
<ide> }
<del> resolve({
<del> namedDest: '',
<del> explicitDest: dest,
<del> });
<del> }).then((data) => {
<del> if (!(data.explicitDest instanceof Array)) {
<del> console.error(`PDFLinkService.navigateTo: "${data.explicitDest}" is` +
<del> ` not a valid destination array, for dest="${dest}".`);
<del> return;
<del> }
<del> goToDestination(data);
<add> } else if ((destRef | 0) === destRef) { // Integer
<add> pageNumber = destRef + 1;
<add> } else {
<add> console.error(`PDFLinkService.navigateTo: "${destRef}" is not ` +
<add> `a valid destination reference, for dest="${dest}".`);
<add> return;
<add> }
<add> if (!pageNumber || pageNumber < 1 || pageNumber > this.pagesCount) {
<add> console.error(`PDFLinkService.navigateTo: "${pageNumber}" is not ` +
<add> `a valid page number, for dest="${dest}".`);
<add> return;
<add> }
<add>
<add> this.pdfViewer.scrollPageIntoView({
<add> pageNumber,
<add> destArray: explicitDest,
<ide> });
<del> },
<ide>
<del> /**
<del> * @param {string|Array} dest - The PDF destination object.
<del> * @returns {string} The hyperlink to the PDF object.
<del> */
<del> getDestinationHash(dest) {
<add> if (this.pdfHistory) { // Update the browsing history, if enabled.
<add> this.pdfHistory.push({
<add> dest: explicitDest,
<add> hash: namedDest,
<add> page: pageNumber,
<add> });
<add> }
<add> };
<add>
<add> new Promise((resolve, reject) => {
<ide> if (typeof dest === 'string') {
<del> return this.getAnchorUrl('#' + escape(dest));
<add> this.pdfDocument.getDestination(dest).then((destArray) => {
<add> resolve({
<add> namedDest: dest,
<add> explicitDest: destArray,
<add> });
<add> });
<add> return;
<ide> }
<del> if (dest instanceof Array) {
<del> let str = JSON.stringify(dest);
<del> return this.getAnchorUrl('#' + escape(str));
<add> resolve({
<add> namedDest: '',
<add> explicitDest: dest,
<add> });
<add> }).then((data) => {
<add> if (!(data.explicitDest instanceof Array)) {
<add> console.error(`PDFLinkService.navigateTo: "${data.explicitDest}" is` +
<add> ` not a valid destination array, for dest="${dest}".`);
<add> return;
<ide> }
<del> return this.getAnchorUrl('');
<del> },
<del>
<del> /**
<del> * Prefix the full url on anchor links to make sure that links are resolved
<del> * relative to the current URL instead of the one defined in <base href>.
<del> * @param {String} anchor The anchor hash, including the #.
<del> * @returns {string} The hyperlink to the PDF object.
<del> */
<del> getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
<del> return (this.baseUrl || '') + anchor;
<del> },
<del>
<del> /**
<del> * @param {string} hash
<del> */
<del> setHash: function PDFLinkService_setHash(hash) {
<del> var pageNumber, dest;
<del> if (hash.indexOf('=') >= 0) {
<del> var params = parseQueryString(hash);
<del> if ('search' in params) {
<del> this.eventBus.dispatch('findfromurlhash', {
<del> source: this,
<del> query: params['search'].replace(/"/g, ''),
<del> phraseSearch: (params['phrase'] === 'true'),
<del> });
<del> }
<del> // borrowing syntax from "Parameters for Opening PDF Files"
<del> if ('nameddest' in params) {
<del> if (this.pdfHistory) {
<del> this.pdfHistory.updateNextHashParam(params.nameddest);
<del> }
<del> this.navigateTo(params.nameddest);
<del> return;
<del> }
<del> if ('page' in params) {
<del> pageNumber = (params.page | 0) || 1;
<add> goToDestination(data);
<add> });
<add> }
<add>
<add> /**
<add> * @param {string|Array} dest - The PDF destination object.
<add> * @returns {string} The hyperlink to the PDF object.
<add> */
<add> getDestinationHash(dest) {
<add> if (typeof dest === 'string') {
<add> return this.getAnchorUrl('#' + escape(dest));
<add> }
<add> if (dest instanceof Array) {
<add> let str = JSON.stringify(dest);
<add> return this.getAnchorUrl('#' + escape(str));
<add> }
<add> return this.getAnchorUrl('');
<add> }
<add>
<add> /**
<add> * Prefix the full url on anchor links to make sure that links are resolved
<add> * relative to the current URL instead of the one defined in <base href>.
<add> * @param {String} anchor The anchor hash, including the #.
<add> * @returns {string} The hyperlink to the PDF object.
<add> */
<add> getAnchorUrl(anchor) {
<add> return (this.baseUrl || '') + anchor;
<add> }
<add>
<add> /**
<add> * @param {string} hash
<add> */
<add> setHash(hash) {
<add> let pageNumber, dest;
<add> if (hash.indexOf('=') >= 0) {
<add> let params = parseQueryString(hash);
<add> if ('search' in params) {
<add> this.eventBus.dispatch('findfromurlhash', {
<add> source: this,
<add> query: params['search'].replace(/"/g, ''),
<add> phraseSearch: (params['phrase'] === 'true'),
<add> });
<add> }
<add> // borrowing syntax from "Parameters for Opening PDF Files"
<add> if ('nameddest' in params) {
<add> if (this.pdfHistory) {
<add> this.pdfHistory.updateNextHashParam(params.nameddest);
<ide> }
<del> if ('zoom' in params) {
<del> // Build the destination array.
<del> var zoomArgs = params.zoom.split(','); // scale,left,top
<del> var zoomArg = zoomArgs[0];
<del> var zoomArgNumber = parseFloat(zoomArg);
<del>
<del> if (zoomArg.indexOf('Fit') === -1) {
<del> // If the zoomArg is a number, it has to get divided by 100. If it's
<del> // a string, it should stay as it is.
<del> dest = [null, { name: 'XYZ', },
<del> zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
<del> zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
<del> (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
<del> } else {
<del> if (zoomArg === 'Fit' || zoomArg === 'FitB') {
<del> dest = [null, { name: zoomArg, }];
<del> } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
<del> (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
<del> dest = [null, { name: zoomArg, },
<del> zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
<del> } else if (zoomArg === 'FitR') {
<del> if (zoomArgs.length !== 5) {
<del> console.error('PDFLinkService_setHash: ' +
<del> 'Not enough parameters for \'FitR\'.');
<del> } else {
<del> dest = [null, { name: zoomArg, },
<del> (zoomArgs[1] | 0), (zoomArgs[2] | 0),
<del> (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
<del> }
<add> this.navigateTo(params.nameddest);
<add> return;
<add> }
<add> if ('page' in params) {
<add> pageNumber = (params.page | 0) || 1;
<add> }
<add> if ('zoom' in params) {
<add> // Build the destination array.
<add> let zoomArgs = params.zoom.split(','); // scale,left,top
<add> let zoomArg = zoomArgs[0];
<add> let zoomArgNumber = parseFloat(zoomArg);
<add>
<add> if (zoomArg.indexOf('Fit') === -1) {
<add> // If the zoomArg is a number, it has to get divided by 100. If it's
<add> // a string, it should stay as it is.
<add> dest = [null, { name: 'XYZ', },
<add> zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
<add> zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
<add> (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
<add> } else {
<add> if (zoomArg === 'Fit' || zoomArg === 'FitB') {
<add> dest = [null, { name: zoomArg, }];
<add> } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
<add> (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
<add> dest = [null, { name: zoomArg, },
<add> zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
<add> } else if (zoomArg === 'FitR') {
<add> if (zoomArgs.length !== 5) {
<add> console.error(
<add> 'PDFLinkService.setHash: Not enough parameters for "FitR".');
<ide> } else {
<del> console.error('PDFLinkService_setHash: \'' + zoomArg +
<del> '\' is not a valid zoom value.');
<add> dest = [null, { name: zoomArg, },
<add> (zoomArgs[1] | 0), (zoomArgs[2] | 0),
<add> (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
<ide> }
<add> } else {
<add> console.error(`PDFLinkService.setHash: "${zoomArg}" is not ` +
<add> 'a valid zoom value.');
<ide> }
<ide> }
<del> if (dest) {
<del> this.pdfViewer.scrollPageIntoView({
<del> pageNumber: pageNumber || this.page,
<del> destArray: dest,
<del> allowNegativeOffset: true,
<del> });
<del> } else if (pageNumber) {
<del> this.page = pageNumber; // simple page
<del> }
<del> if ('pagemode' in params) {
<del> this.eventBus.dispatch('pagemode', {
<del> source: this,
<del> mode: params.pagemode,
<del> });
<del> }
<del> } else { // Named (or explicit) destination.
<del> if ((typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) &&
<del> /^\d+$/.test(hash) && hash <= this.pagesCount) {
<del> console.warn('PDFLinkService_setHash: specifying a page number ' +
<del> 'directly after the hash symbol (#) is deprecated, ' +
<del> 'please use the "#page=' + hash + '" form instead.');
<del> this.page = hash | 0;
<del> }
<add> }
<add> if (dest) {
<add> this.pdfViewer.scrollPageIntoView({
<add> pageNumber: pageNumber || this.page,
<add> destArray: dest,
<add> allowNegativeOffset: true,
<add> });
<add> } else if (pageNumber) {
<add> this.page = pageNumber; // simple page
<add> }
<add> if ('pagemode' in params) {
<add> this.eventBus.dispatch('pagemode', {
<add> source: this,
<add> mode: params.pagemode,
<add> });
<add> }
<add> } else { // Named (or explicit) destination.
<add> if ((typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC')) &&
<add> /^\d+$/.test(hash) && hash <= this.pagesCount) {
<add> console.warn('PDFLinkService_setHash: specifying a page number ' +
<add> 'directly after the hash symbol (#) is deprecated, ' +
<add> `please use the "#page=${hash}" form instead.`);
<add> this.page = hash | 0;
<add> }
<ide>
<del> dest = unescape(hash);
<del> try {
<del> dest = JSON.parse(dest);
<add> dest = unescape(hash);
<add> try {
<add> dest = JSON.parse(dest);
<ide>
<del> if (!(dest instanceof Array)) {
<del> // Avoid incorrectly rejecting a valid named destination, such as
<del> // e.g. "4.3" or "true", because `JSON.parse` converted its type.
<del> dest = dest.toString();
<del> }
<del> } catch (ex) {}
<add> if (!(dest instanceof Array)) {
<add> // Avoid incorrectly rejecting a valid named destination, such as
<add> // e.g. "4.3" or "true", because `JSON.parse` converted its type.
<add> dest = dest.toString();
<add> }
<add> } catch (ex) {}
<ide>
<del> if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
<del> if (this.pdfHistory) {
<del> this.pdfHistory.updateNextHashParam(dest);
<del> }
<del> this.navigateTo(dest);
<del> return;
<add> if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
<add> if (this.pdfHistory) {
<add> this.pdfHistory.updateNextHashParam(dest);
<ide> }
<del> console.error('PDFLinkService_setHash: \'' + unescape(hash) +
<del> '\' is not a valid destination.');
<add> this.navigateTo(dest);
<add> return;
<ide> }
<del> },
<del>
<del> /**
<del> * @param {string} action
<del> */
<del> executeNamedAction: function PDFLinkService_executeNamedAction(action) {
<del> // See PDF reference, table 8.45 - Named action
<del> switch (action) {
<del> case 'GoBack':
<del> if (this.pdfHistory) {
<del> this.pdfHistory.back();
<del> }
<del> break;
<del>
<del> case 'GoForward':
<del> if (this.pdfHistory) {
<del> this.pdfHistory.forward();
<del> }
<del> break;
<del>
<del> case 'NextPage':
<del> if (this.page < this.pagesCount) {
<del> this.page++;
<del> }
<del> break;
<del>
<del> case 'PrevPage':
<del> if (this.page > 1) {
<del> this.page--;
<del> }
<del> break;
<del>
<del> case 'LastPage':
<del> this.page = this.pagesCount;
<del> break;
<del>
<del> case 'FirstPage':
<del> this.page = 1;
<del> break;
<add> console.error(`PDFLinkService.setHash: "${unescape(hash)}" is not ` +
<add> 'a valid destination.');
<add> }
<add> }
<ide>
<del> default:
<del> break; // No action according to spec
<del> }
<add> /**
<add> * @param {string} action
<add> */
<add> executeNamedAction(action) {
<add> // See PDF reference, table 8.45 - Named action
<add> switch (action) {
<add> case 'GoBack':
<add> if (this.pdfHistory) {
<add> this.pdfHistory.back();
<add> }
<add> break;
<ide>
<del> this.eventBus.dispatch('namedaction', {
<del> source: this,
<del> action,
<del> });
<del> },
<del>
<del> /**
<del> * @param {Object} params
<del> */
<del> onFileAttachmentAnnotation(params = {}) {
<del> this.eventBus.dispatch('fileattachmentannotation', {
<del> source: this,
<del> id: params.id,
<del> filename: params.filename,
<del> content: params.content,
<del> });
<del> },
<del>
<del> /**
<del> * @param {number} pageNum - page number.
<del> * @param {Object} pageRef - reference to the page.
<del> */
<del> cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
<del> var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
<del> this._pagesRefCache[refStr] = pageNum;
<del> },
<del>
<del> _cachedPageNumber: function PDFLinkService_cachedPageNumber(pageRef) {
<del> var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
<del> return (this._pagesRefCache && this._pagesRefCache[refStr]) || null;
<del> },
<del> };
<del>
<del> function isValidExplicitDestination(dest) {
<del> if (!(dest instanceof Array)) {
<del> return false;
<del> }
<del> var destLength = dest.length, allowNull = true;
<del> if (destLength < 2) {
<del> return false;
<del> }
<del> var page = dest[0];
<del> if (!(typeof page === 'object' &&
<del> typeof page.num === 'number' && (page.num | 0) === page.num &&
<del> typeof page.gen === 'number' && (page.gen | 0) === page.gen) &&
<del> !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
<del> return false;
<del> }
<del> var zoom = dest[1];
<del> if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
<del> return false;
<del> }
<del> switch (zoom.name) {
<del> case 'XYZ':
<del> if (destLength !== 5) {
<del> return false;
<add> case 'GoForward':
<add> if (this.pdfHistory) {
<add> this.pdfHistory.forward();
<ide> }
<ide> break;
<del> case 'Fit':
<del> case 'FitB':
<del> return destLength === 2;
<del> case 'FitH':
<del> case 'FitBH':
<del> case 'FitV':
<del> case 'FitBV':
<del> if (destLength !== 3) {
<del> return false;
<add>
<add> case 'NextPage':
<add> if (this.page < this.pagesCount) {
<add> this.page++;
<ide> }
<ide> break;
<del> case 'FitR':
<del> if (destLength !== 6) {
<del> return false;
<add>
<add> case 'PrevPage':
<add> if (this.page > 1) {
<add> this.page--;
<ide> }
<del> allowNull = false;
<ide> break;
<add>
<add> case 'LastPage':
<add> this.page = this.pagesCount;
<add> break;
<add>
<add> case 'FirstPage':
<add> this.page = 1;
<add> break;
<add>
<ide> default:
<del> return false;
<add> break; // No action according to spec
<ide> }
<del> for (var i = 2; i < destLength; i++) {
<del> var param = dest[i];
<del> if (!(typeof param === 'number' || (allowNull && param === null))) {
<add>
<add> this.eventBus.dispatch('namedaction', {
<add> source: this,
<add> action,
<add> });
<add> }
<add>
<add> /**
<add> * @param {Object} params
<add> */
<add> onFileAttachmentAnnotation({ id, filename, content, }) {
<add> this.eventBus.dispatch('fileattachmentannotation', {
<add> source: this,
<add> id,
<add> filename,
<add> content,
<add> });
<add> }
<add>
<add> /**
<add> * @param {number} pageNum - page number.
<add> * @param {Object} pageRef - reference to the page.
<add> */
<add> cachePageRef(pageNum, pageRef) {
<add> let refStr = pageRef.num + ' ' + pageRef.gen + ' R';
<add> this._pagesRefCache[refStr] = pageNum;
<add> }
<add>
<add> _cachedPageNumber(pageRef) {
<add> let refStr = pageRef.num + ' ' + pageRef.gen + ' R';
<add> return (this._pagesRefCache && this._pagesRefCache[refStr]) || null;
<add> }
<add>}
<add>
<add>function isValidExplicitDestination(dest) {
<add> if (!(dest instanceof Array)) {
<add> return false;
<add> }
<add> let destLength = dest.length, allowNull = true;
<add> if (destLength < 2) {
<add> return false;
<add> }
<add> let page = dest[0];
<add> if (!(typeof page === 'object' &&
<add> typeof page.num === 'number' && (page.num | 0) === page.num &&
<add> typeof page.gen === 'number' && (page.gen | 0) === page.gen) &&
<add> !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
<add> return false;
<add> }
<add> let zoom = dest[1];
<add> if (!(typeof zoom === 'object' && typeof zoom.name === 'string')) {
<add> return false;
<add> }
<add> switch (zoom.name) {
<add> case 'XYZ':
<add> if (destLength !== 5) {
<add> return false;
<add> }
<add> break;
<add> case 'Fit':
<add> case 'FitB':
<add> return destLength === 2;
<add> case 'FitH':
<add> case 'FitBH':
<add> case 'FitV':
<add> case 'FitBV':
<add> if (destLength !== 3) {
<add> return false;
<add> }
<add> break;
<add> case 'FitR':
<add> if (destLength !== 6) {
<ide> return false;
<ide> }
<add> allowNull = false;
<add> break;
<add> default:
<add> return false;
<add> }
<add> for (let i = 2; i < destLength; i++) {
<add> let param = dest[i];
<add> if (!(typeof param === 'number' || (allowNull && param === null))) {
<add> return false;
<ide> }
<del> return true;
<ide> }
<add> return true;
<add>}
<ide>
<del> return PDFLinkService;
<del>})();
<del>
<del>var SimpleLinkService = (function SimpleLinkServiceClosure() {
<del> function SimpleLinkService() {}
<del>
<del> SimpleLinkService.prototype = {
<del> /**
<del> * @returns {number}
<del> */
<del> get page() {
<del> return 0;
<del> },
<del> /**
<del> * @param {number} value
<del> */
<del> set page(value) {},
<del> /**
<del> * @param dest - The PDF destination object.
<del> */
<del> navigateTo(dest) {},
<del> /**
<del> * @param dest - The PDF destination object.
<del> * @returns {string} The hyperlink to the PDF object.
<del> */
<del> getDestinationHash(dest) {
<del> return '#';
<del> },
<del> /**
<del> * @param hash - The PDF parameters/hash.
<del> * @returns {string} The hyperlink to the PDF object.
<del> */
<del> getAnchorUrl(hash) {
<del> return '#';
<del> },
<del> /**
<del> * @param {string} hash
<del> */
<del> setHash(hash) {},
<del> /**
<del> * @param {string} action
<del> */
<del> executeNamedAction(action) {},
<del> /**
<del> * @param {Object} params
<del> */
<del> onFileAttachmentAnnotation(params) {},
<del> /**
<del> * @param {number} pageNum - page number.
<del> * @param {Object} pageRef - reference to the page.
<del> */
<del> cachePageRef(pageNum, pageRef) {},
<del> };
<del> return SimpleLinkService;
<del>})();
<add>class SimpleLinkService {
<add> /**
<add> * @returns {number}
<add> */
<add> get page() {
<add> return 0;
<add> }
<add> /**
<add> * @param {number} value
<add> */
<add> set page(value) {}
<add> /**
<add> * @param dest - The PDF destination object.
<add> */
<add> navigateTo(dest) {}
<add> /**
<add> * @param dest - The PDF destination object.
<add> * @returns {string} The hyperlink to the PDF object.
<add> */
<add> getDestinationHash(dest) {
<add> return '#';
<add> }
<add> /**
<add> * @param hash - The PDF parameters/hash.
<add> * @returns {string} The hyperlink to the PDF object.
<add> */
<add> getAnchorUrl(hash) {
<add> return '#';
<add> }
<add> /**
<add> * @param {string} hash
<add> */
<add> setHash(hash) {}
<add> /**
<add> * @param {string} action
<add> */
<add> executeNamedAction(action) {}
<add> /**
<add> * @param {Object} params
<add> */
<add> onFileAttachmentAnnotation({ id, filename, content, }) {}
<add> /**
<add> * @param {number} pageNum - page number.
<add> * @param {Object} pageRef - reference to the page.
<add> */
<add> cachePageRef(pageNum, pageRef) {}
<add>}
<ide>
<ide> export {
<ide> PDFLinkService, | 2 |
Go | Go | adjust test sleep timing to avoid spurious failure | 81c334fa56eab0f9e85c9f6745efa34bbb1b444b | <ide><path>pkg/integration/utils.go
<ide> func RandomTmpDirPath(s string, platform string) string {
<ide> return filepath.ToSlash(path) // Using /
<ide> }
<ide>
<del>// ConsumeWithSpeed reads chunkSize bytes from reader after every interval.
<del>// Returns total read bytes.
<add>// ConsumeWithSpeed reads chunkSize bytes from reader before sleeping
<add>// for interval duration. Returns total read bytes. Send true to the
<add>// stop channel to return before reading to EOF on the reader.
<ide> func ConsumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) {
<ide> buffer := make([]byte, chunkSize)
<ide> for {
<add> var readBytes int
<add> readBytes, err = reader.Read(buffer)
<add> n += readBytes
<add> if err != nil {
<add> if err == io.EOF {
<add> err = nil
<add> }
<add> return
<add> }
<ide> select {
<ide> case <-stop:
<ide> return
<del> default:
<del> var readBytes int
<del> readBytes, err = reader.Read(buffer)
<del> n += readBytes
<del> if err != nil {
<del> if err == io.EOF {
<del> err = nil
<del> }
<del> return
<del> }
<del> time.Sleep(interval)
<add> case <-time.After(interval):
<ide> }
<ide> }
<ide> }
<ide><path>pkg/integration/utils_test.go
<ide> func TestConsumeWithSpeed(t *testing.T) {
<ide> reader := strings.NewReader("1234567890")
<ide> chunksize := 2
<ide>
<del> bytes1, err := ConsumeWithSpeed(reader, chunksize, 1*time.Millisecond, nil)
<add> bytes1, err := ConsumeWithSpeed(reader, chunksize, 1*time.Second, nil)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestConsumeWithSpeedWithStop(t *testing.T) {
<ide> stopIt <- true
<ide> }()
<ide>
<del> bytes1, err := ConsumeWithSpeed(reader, chunksize, 2*time.Millisecond, stopIt)
<add> bytes1, err := ConsumeWithSpeed(reader, chunksize, 20*time.Millisecond, stopIt)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> } | 2 |
Javascript | Javascript | move the `getfilename` helper function to the core | 0351c7eff49ba2357575a5bf1084059c98bb91a8 | <ide><path>extensions/b2g/viewer.js
<ide> var PDFViewerApplication = {
<ide>
<ide> setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
<ide> this.url = url;
<del> var title = PDFJS.getFileName(url) || url;
<add> var title = PDFJS.getFilenameFromUrl(url) || url;
<ide> try {
<ide> title = decodeURIComponent(title);
<ide> } catch (e) {
<ide><path>src/display/annotation_layer.js
<ide> var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
<ide> var AnnotationType = sharedUtil.AnnotationType;
<ide> var Util = sharedUtil.Util;
<ide> var addLinkAttributes = sharedUtil.addLinkAttributes;
<add>var getFilenameFromUrl = sharedUtil.getFilenameFromUrl;
<ide> var warn = sharedUtil.warn;
<ide> var CustomStyle = displayDOMUtils.CustomStyle;
<ide>
<ide> var FileAttachmentAnnotationElement = (
<ide> function FileAttachmentAnnotationElement(parameters) {
<ide> AnnotationElement.call(this, parameters, true);
<ide>
<del> this.filename = parameters.data.file.filename;
<add> this.filename = getFilenameFromUrl(parameters.data.file.filename);
<ide> this.content = parameters.data.file.content;
<ide> }
<ide>
<ide><path>src/shared/util.js
<ide> var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
<ide> font: 'font'
<ide> };
<ide>
<add>// Gets the file name from a given URL.
<add>function getFilenameFromUrl(url) {
<add> var anchor = url.indexOf('#');
<add> var query = url.indexOf('?');
<add> var end = Math.min(
<add> anchor > 0 ? anchor : url.length,
<add> query > 0 ? query : url.length);
<add> return url.substring(url.lastIndexOf('/', end) + 1, end);
<add>}
<add>PDFJS.getFilenameFromUrl = getFilenameFromUrl;
<add>
<ide> // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
<ide> // absolute URL, it will be returned as is.
<ide> function combineUrl(baseUrl, url) {
<ide> exports.combineUrl = combineUrl;
<ide> exports.createPromiseCapability = createPromiseCapability;
<ide> exports.deprecated = deprecated;
<ide> exports.error = error;
<add>exports.getFilenameFromUrl = getFilenameFromUrl;
<ide> exports.getLookupTableFactory = getLookupTableFactory;
<ide> exports.info = info;
<ide> exports.isArray = isArray;
<ide><path>test/unit/util_spec.js
<ide> /* globals expect, it, describe, combineUrl, Dict, isDict, Name, PDFJS,
<ide> stringToPDFString, isExternalLinkTargetSet, LinkTarget,
<del> removeNullCharacters */
<add> removeNullCharacters, getFilenameFromUrl */
<ide>
<ide> 'use strict';
<ide>
<ide> describe('util', function() {
<add> describe('getFilenameFromUrl', function() {
<add> it('should get the filename from an absolute URL', function() {
<add> var url = 'http://server.org/filename.pdf';
<add> var result = getFilenameFromUrl(url);
<add> var expected = 'filename.pdf';
<add> expect(result).toEqual(expected);
<add> });
<add>
<add> it('should get the filename from a relative URL', function() {
<add> var url = '../../filename.pdf';
<add> var result = getFilenameFromUrl(url);
<add> var expected = 'filename.pdf';
<add> expect(result).toEqual(expected);
<add> });
<add> });
<ide>
<ide> describe('combineUrl', function() {
<ide> it('absolute url with protocol stays as is', function() {
<ide><path>web/pdf_attachment_view.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>/* globals getFileName, PDFJS */
<add>/* globals PDFJS */
<ide>
<ide> 'use strict';
<ide>
<ide> var PDFAttachmentView = (function PDFAttachmentViewClosure() {
<ide>
<ide> for (var i = 0; i < attachmentsCount; i++) {
<ide> var item = attachments[names[i]];
<del> var filename = getFileName(item.filename);
<add> var filename = PDFJS.getFilenameFromUrl(item.filename);
<ide> var div = document.createElement('div');
<ide> div.className = 'attachmentsItem';
<ide> var button = document.createElement('button');
<ide><path>web/pdf_viewer.component.js
<ide> /*jshint globalstrict: false */
<ide> /* globals PDFJS, PDFViewer, PDFPageView, TextLayerBuilder, PDFLinkService,
<ide> DefaultTextLayerFactory, AnnotationLayerBuilder, PDFHistory,
<del> DefaultAnnotationLayerFactory, getFileName, DownloadManager,
<del> ProgressBar */
<add> DefaultAnnotationLayerFactory, DownloadManager, ProgressBar */
<ide>
<ide> // Initializing PDFJS global object (if still undefined)
<ide> if (typeof PDFJS === 'undefined') {
<ide> if (typeof PDFJS === 'undefined') {
<ide> PDFJS.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
<ide> PDFJS.PDFHistory = PDFHistory;
<ide>
<del> PDFJS.getFileName = getFileName;
<ide> PDFJS.DownloadManager = DownloadManager;
<ide> PDFJS.ProgressBar = ProgressBar;
<ide> }).call((typeof window === 'undefined') ? this : window);
<ide><path>web/ui_utils.js
<ide> var MAX_AUTO_SCALE = 1.25;
<ide> var SCROLLBAR_PADDING = 40;
<ide> var VERTICAL_PADDING = 5;
<ide>
<del>function getFileName(url) {
<del> var anchor = url.indexOf('#');
<del> var query = url.indexOf('?');
<del> var end = Math.min(
<del> anchor > 0 ? anchor : url.length,
<del> query > 0 ? query : url.length);
<del> return url.substring(url.lastIndexOf('/', end) + 1, end);
<del>}
<del>
<ide> /**
<ide> * Returns scale factor for the canvas. It makes sense for the HiDPI displays.
<ide> * @return {Object} The object with horizontal (sx) and vertical (sy)
<ide><path>web/viewer.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>/* globals PDFJS, PDFBug, FirefoxCom, Stats, ProgressBar,
<del> DownloadManager, getFileName, getPDFFileNameFromURL,
<del> PDFHistory, Preferences, SidebarView, ViewHistory, Stats,
<del> PDFThumbnailViewer, URL, noContextMenuHandler, SecondaryToolbar,
<del> PasswordPrompt, PDFPresentationMode, PDFDocumentProperties, HandTool,
<del> Promise, PDFLinkService, PDFOutlineView, PDFAttachmentView,
<del> OverlayManager, PDFFindController, PDFFindBar, PDFViewer,
<del> PDFRenderingQueue, PresentationModeState, parseQueryString,
<del> RenderingStates, UNKNOWN_SCALE, DEFAULT_SCALE_VALUE,
<add>/* globals PDFJS, PDFBug, FirefoxCom, Stats, ProgressBar, DownloadManager,
<add> getPDFFileNameFromURL, PDFHistory, Preferences, SidebarView,
<add> ViewHistory, Stats, PDFThumbnailViewer, URL, noContextMenuHandler,
<add> SecondaryToolbar, PasswordPrompt, PDFPresentationMode,
<add> PDFDocumentProperties, HandTool, Promise, PDFLinkService,
<add> PDFOutlineView, PDFAttachmentView, OverlayManager,
<add> PDFFindController, PDFFindBar, PDFViewer, PDFRenderingQueue,
<add> PresentationModeState, parseQueryString, RenderingStates,
<add> UNKNOWN_SCALE, DEFAULT_SCALE_VALUE,
<ide> IGNORE_CURRENT_POSITION_ON_ZOOM: true */
<ide>
<ide> 'use strict';
<ide> var PDFViewerApplication = {
<ide> setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
<ide> this.url = url;
<ide> try {
<del> this.setTitle(decodeURIComponent(getFileName(url)) || url);
<add> this.setTitle(decodeURIComponent(PDFJS.getFilenameFromUrl(url)) || url);
<ide> } catch (e) {
<ide> // decodeURIComponent may throw URIError,
<ide> // fall back to using the unprocessed url in that case | 8 |
Javascript | Javascript | update norwegian locale | d536c4d863b9317418f105ede75ce5fbc73544fb | <ide><path>locale/nb.js
<ide> },
<ide> relativeTime : {
<ide> future : 'om %s',
<del> past : 'for %s siden',
<add> past : '%s siden',
<ide> s : 'noen sekunder',
<ide> m : 'ett minutt',
<ide> mm : '%d minutter',
<ide>
<ide> return nb;
<ide>
<del>}));
<ide>\ No newline at end of file
<add>})); | 1 |
Javascript | Javascript | split fresh packs by time | 3270275ffeada636769a48fac8c079f7e78993de | <ide><path>lib/cache/PackFileCacheStrategy.js
<ide> makeSerializable(
<ide>
<ide> const MIN_CONTENT_SIZE = 1024 * 1024; // 1 MB
<ide> const CONTENT_COUNT_TO_MERGE = 10;
<add>const MIN_ITEMS_IN_FRESH_PACK = 100;
<ide> const MAX_ITEMS_IN_FRESH_PACK = 50000;
<add>const MAX_TIME_IN_FRESH_PACK = 1 * 60 * 1000; // 1 min
<ide>
<ide> class PackItemInfo {
<ide> /**
<ide> class Pack {
<ide> this.itemInfo = new Map();
<ide> /** @type {string[]} */
<ide> this.requests = [];
<add> this.requestsTimeout = undefined;
<ide> /** @type {Map<string, PackItemInfo>} */
<ide> this.freshContent = new Map();
<ide> /** @type {(undefined | PackContent)[]} */
<ide> class Pack {
<ide> this.maxAge = maxAge;
<ide> }
<ide>
<add> _addRequest(identifier) {
<add> this.requests.push(identifier);
<add> if (this.requestsTimeout === undefined) {
<add> this.requestsTimeout = setTimeout(() => {
<add> this.requests.push(undefined);
<add> this.requestsTimeout = undefined;
<add> }, MAX_TIME_IN_FRESH_PACK);
<add> }
<add> }
<add>
<ide> /**
<ide> * @param {string} identifier unique name for the resource
<ide> * @param {string | null} etag etag of the resource
<ide> * @returns {any} cached content
<ide> */
<ide> get(identifier, etag) {
<ide> const info = this.itemInfo.get(identifier);
<del> this.requests.push(identifier);
<add> this._addRequest(identifier);
<ide> if (info === undefined) {
<ide> return undefined;
<ide> }
<ide> class Pack {
<ide> if (info === undefined) {
<ide> const newInfo = new PackItemInfo(identifier, etag, data);
<ide> this.itemInfo.set(identifier, newInfo);
<del> this.requests.push(identifier);
<add> this._addRequest(identifier);
<ide> this.freshContent.set(identifier, newInfo);
<ide> } else {
<ide> const loc = info.location;
<ide> if (loc >= 0) {
<del> this.requests.push(identifier);
<add> this._addRequest(identifier);
<ide> this.freshContent.set(identifier, info);
<ide> const content = this.content[loc];
<ide> content.delete(identifier);
<ide> class Pack {
<ide> }
<ide>
<ide> _persistFreshContent() {
<del> if (this.freshContent.size > 0) {
<del> const packCount = Math.ceil(
<del> this.freshContent.size / MAX_ITEMS_IN_FRESH_PACK
<del> );
<del> const itemsPerPack = Math.ceil(this.freshContent.size / packCount);
<del> this.logger.log(`${this.freshContent.size} fresh items in cache`);
<del> const packs = Array.from({ length: packCount }, () => {
<add> const itemsCount = this.freshContent.size;
<add> if (itemsCount > 0) {
<add> const packCount = Math.ceil(itemsCount / MAX_ITEMS_IN_FRESH_PACK);
<add> const itemsPerPack = Math.ceil(itemsCount / packCount);
<add> const packs = [];
<add> let i = 0;
<add> let ignoreNextTimeTick = false;
<add> const createNextPack = () => {
<ide> const loc = this._findLocation();
<ide> this.content[loc] = null; // reserve
<del> return {
<add> const pack = {
<ide> /** @type {Set<string>} */
<ide> items: new Set(),
<ide> /** @type {Map<string, any>} */
<ide> map: new Map(),
<ide> loc
<ide> };
<del> });
<del> let i = 0;
<del> let pack = packs[0];
<del> let packIndex = 0;
<add> packs.push(pack);
<add> return pack;
<add> };
<add> let pack = createNextPack();
<add> if (this.requestsTimeout !== undefined)
<add> clearTimeout(this.requestsTimeout);
<ide> for (const identifier of this.requests) {
<add> if (identifier === undefined) {
<add> if (ignoreNextTimeTick) {
<add> ignoreNextTimeTick = false;
<add> } else if (pack.items.size >= MIN_ITEMS_IN_FRESH_PACK) {
<add> i = 0;
<add> pack = createNextPack();
<add> }
<add> continue;
<add> }
<ide> const info = this.freshContent.get(identifier);
<ide> if (info === undefined) continue;
<ide> pack.items.add(identifier);
<ide> class Pack {
<ide> this.freshContent.delete(identifier);
<ide> if (++i > itemsPerPack) {
<ide> i = 0;
<del> pack = packs[++packIndex];
<add> pack = createNextPack();
<add> ignoreNextTimeTick = true;
<ide> }
<ide> }
<add> this.requests.length = 0;
<ide> for (const pack of packs) {
<ide> this.content[pack.loc] = new PackContent(
<ide> pack.items,
<ide> new Set(pack.items),
<ide> new PackContentItems(pack.map)
<ide> );
<ide> }
<add> this.logger.log(
<add> `${itemsCount} fresh items in cache put into pack ${
<add> packs.length > 1
<add> ? packs
<add> .map(pack => `${pack.loc} (${pack.items.size} items)`)
<add> .join(", ")
<add> : packs[0].loc
<add> }`
<add> );
<ide> }
<ide> }
<ide>
<ide> class Pack {
<ide> addToMergedMap.push(async map => {
<ide> // unpack existing content
<ide> // after that values are accessible in .content
<del> await content.unpack();
<add> await content.unpack(
<add> "it should be merged with other small pack contents"
<add> );
<ide> for (const [identifier, value] of content.content) {
<ide> map.set(identifier, value);
<ide> }
<ide> class Pack {
<ide> usedItems,
<ide> new Set(usedItems),
<ide> async () => {
<del> await content.unpack();
<add> await content.unpack(
<add> "it should be splitted into used and unused items"
<add> );
<ide> const map = new Map();
<ide> for (const identifier of usedItems) {
<ide> map.set(identifier, content.content.get(identifier));
<ide> class Pack {
<ide> unusedItems,
<ide> usedOfUnusedItems,
<ide> async () => {
<del> await content.unpack();
<add> await content.unpack(
<add> "it should be splitted into used and unused items"
<add> );
<ide> const map = new Map();
<ide> for (const identifier of unusedItems) {
<ide> map.set(identifier, content.content.get(identifier));
<ide> class Pack {
<ide> this.content[loc] =
<ide> items.size > 0
<ide> ? new PackContent(items, usedItems, async () => {
<del> await content.unpack();
<add> await content.unpack(
<add> "it contains old items that should be garbage collected"
<add> );
<ide> const map = new Map();
<ide> for (const identifier of items) {
<ide> map.set(identifier, content.content.get(identifier));
<ide> class Pack {
<ide> const content = this.content[i];
<ide> if (content !== undefined) {
<ide> write(content.items);
<del> writeSeparate(content.getLazyContentItems(), { name: `${i}` });
<add> content.writeLazy(lazy => writeSeparate(lazy, { name: `${i}` }));
<ide> } else {
<ide> write(undefined); // undefined marks an empty content slot
<ide> }
<ide> makeSerializable(
<ide> );
<ide>
<ide> class PackContent {
<add> /*
<add> This class can be in these states:
<add> | this.lazy | this.content | this.outdated | state
<add> A1 | undefined | Map | false | fresh content
<add> A2 | undefined | Map | true | (will not happen)
<add> B1 | lazy () => {} | undefined | false | not deserialized
<add> B2 | lazy () => {} | undefined | true | not deserialized, but some items has been removed
<add> C1 | lazy* () => {} | Map | false | deserialized
<add> C2 | lazy* () => {} | Map | true | deserialized, and some items has been removed
<add>
<add> this.used is a subset of this.items.
<add> this.items is a subset of this.content.keys() resp. this.lazy().map.keys()
<add> When this.outdated === false, this.items === this.content.keys() resp. this.lazy().map.keys()
<add> When this.outdated === true, this.items should be used to recreated this.lazy/this.content.
<add> When this.lazy and this.content is set, they contain the same data.
<add> this.get must only be called with a valid item from this.items.
<add> In state C this.lazy is unMemoized
<add> */
<add>
<ide> /**
<ide> * @param {Set<string>} items keys
<ide> * @param {Set<string>} usedItems used keys
<ide> class PackContent {
<ide> */
<ide> constructor(items, usedItems, dataOrFn, logger, lazyName) {
<ide> this.items = items;
<del> /** @type {function(): Promise<PackContentItems> | PackContentItems } */
<add> /** @type {function(): Promise<PackContentItems> | PackContentItems} */
<ide> this.lazy = typeof dataOrFn === "function" ? dataOrFn : undefined;
<ide> /** @type {Map<string, any>} */
<ide> this.content = typeof dataOrFn === "function" ? undefined : dataOrFn.map;
<ide> class PackContent {
<ide> if (this.content) {
<ide> return this.content.get(identifier);
<ide> }
<add>
<add> // We are in state B
<ide> const { lazyName } = this;
<ide> let timeMessage;
<ide> if (lazyName) {
<ide> class PackContent {
<ide> if (timeMessage) {
<ide> this.logger.timeEnd(timeMessage);
<ide> }
<add> // Move to state C
<ide> this.content = map;
<ide> this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
<ide> return map.get(identifier);
<ide> class PackContent {
<ide> if (timeMessage) {
<ide> this.logger.timeEnd(timeMessage);
<ide> }
<add> // Move to state C
<ide> this.content = map;
<ide> this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
<ide> return map.get(identifier);
<ide> }
<ide> }
<ide>
<ide> /**
<add> * @param {string} reason explanation why unpack is necessary
<ide> * @returns {void | Promise} maybe a promise if lazy
<ide> */
<del> unpack() {
<add> unpack(reason) {
<ide> if (this.content) return;
<add>
<add> // Move from state B to C
<ide> if (this.lazy) {
<ide> const { lazyName } = this;
<ide> let timeMessage;
<ide> class PackContent {
<ide> timeMessage = `unpack cache content ${lazyName} (${formatSize(
<ide> this.getSize()
<ide> )})`;
<add> this.logger.log(
<add> `starting to unpack cache content ${lazyName} (${formatSize(
<add> this.getSize()
<add> )}) because ${reason}`
<add> );
<ide> this.logger.time(timeMessage);
<ide> }
<ide> const value = this.lazy();
<ide> class PackContent {
<ide> }
<ide>
<ide> /**
<del> * @returns {function(): PackContentItems | Promise<PackContentItems>} lazy content items
<add> * @template T
<add> * @param {function(any): function(): Promise<PackContentItems> | PackContentItems} write write function
<add> * @returns {void}
<ide> */
<del> getLazyContentItems() {
<del> if (!this.outdated && this.lazy) return this.lazy;
<add> writeLazy(write) {
<add> if (!this.outdated && this.lazy) {
<add> // State B1 or C1
<add> // this.lazy is still the valid deserialized version
<add> write(this.lazy);
<add> return;
<add> }
<ide> if (!this.outdated && this.content) {
<add> // State A1
<ide> const map = new Map(this.content);
<del> return (this.lazy = memoize(() => new PackContentItems(map)));
<add> // Move to state C1
<add> this.lazy = SerializerMiddleware.unMemoizeLazy(
<add> write(() => new PackContentItems(map))
<add> );
<add> return;
<ide> }
<del> this.outdated = false;
<ide> if (this.content) {
<del> return (this.lazy = memoize(() => {
<del> /** @type {Map<string, any>} */
<del> const map = new Map();
<del> for (const item of this.items) {
<del> map.set(item, this.content.get(item));
<del> }
<del> return new PackContentItems(map);
<del> }));
<add> // State A2 or C2
<add> /** @type {Map<string, any>} */
<add> const map = new Map();
<add> for (const item of this.items) {
<add> map.set(item, this.content.get(item));
<add> }
<add> // Move to state C1
<add> this.outdated = false;
<add> this.content = map;
<add> this.lazy = SerializerMiddleware.unMemoizeLazy(
<add> write(() => new PackContentItems(map))
<add> );
<add> return;
<ide> }
<del> const lazy = this.lazy;
<del> return (this.lazy = () => {
<del> const value = lazy();
<del> if (value instanceof Promise) {
<del> return value.then(data => {
<add> // State B2
<add> const { lazyName } = this;
<add> let timeMessage;
<add> if (lazyName) {
<add> // only log once
<add> this.lazyName = undefined;
<add> timeMessage = `unpack cache content ${lazyName} (${formatSize(
<add> this.getSize()
<add> )})`;
<add> this.logger.log(
<add> `starting to unpack cache content ${lazyName} (${formatSize(
<add> this.getSize()
<add> )}) because it's outdated and need to be serialized`
<add> );
<add> this.logger.time(timeMessage);
<add> }
<add> const value = this.lazy();
<add> this.outdated = false;
<add> if (value instanceof Promise) {
<add> // Move to state B1
<add> this.lazy = write(() =>
<add> value.then(data => {
<add> if (timeMessage) {
<add> this.logger.timeEnd(timeMessage);
<add> }
<ide> const oldMap = data.map;
<ide> /** @type {Map<string, any>} */
<ide> const map = new Map();
<ide> for (const item of this.items) {
<ide> map.set(item, oldMap.get(item));
<ide> }
<add> // Move to state C1 (or maybe C2)
<add> this.content = map;
<add> this.lazy = SerializerMiddleware.unMemoizeLazy(this.lazy);
<add>
<ide> return new PackContentItems(map);
<del> });
<del> } else {
<del> const oldMap = value.map;
<del> /** @type {Map<string, any>} */
<del> const map = new Map();
<del> for (const item of this.items) {
<del> map.set(item, oldMap.get(item));
<del> }
<del> return new PackContentItems(map);
<add> })
<add> );
<add> } else {
<add> // Move to state C1
<add> if (timeMessage) {
<add> this.logger.timeEnd(timeMessage);
<ide> }
<del> });
<add> const oldMap = value.map;
<add> /** @type {Map<string, any>} */
<add> const map = new Map();
<add> for (const item of this.items) {
<add> map.set(item, oldMap.get(item));
<add> }
<add> this.content = map;
<add> this.lazy = write(() => new PackContentItems(map));
<add> }
<ide> }
<ide> }
<ide>
<ide> class PackFileCacheStrategy {
<ide> const packPromise = this.packPromise;
<ide> if (packPromise === undefined) return Promise.resolve();
<ide> const reportProgress = ProgressPlugin.getReporter(this.compiler);
<del> this.packPromise = undefined;
<ide> return (this.storePromise = packPromise
<ide> .then(pack => {
<ide> if (!pack.invalid) return;
<add> this.packPromise = undefined;
<ide> this.logger.log(`Storing pack...`);
<ide> let promise;
<ide> const newBuildDependencies = new Set();
<ide><path>lib/serialization/ObjectMiddleware.js
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> } else if (SerializerMiddleware.isLazy(item, this)) {
<ide> throw new Error("Not implemented");
<ide> } else {
<del> result.push(
<del> SerializerMiddleware.serializeLazy(item, data =>
<del> this.serialize([data], context)
<del> )
<add> const data = SerializerMiddleware.serializeLazy(item, data =>
<add> this.serialize([data], context)
<ide> );
<add> SerializerMiddleware.setLazySerializedValue(item, data);
<add> result.push(data);
<ide> }
<ide> } else if (item === undefined) {
<ide> result.push(ESCAPE, ESCAPE_UNDEFINED);
<ide><path>lib/util/serialization.js
<ide> module.exports = {
<ide> );
<ide> };
<ide> context.writeSeparate = (value, options) => {
<del> context.write(
<del> SerializerMiddleware.createLazy(value, fileMiddleware, options)
<add> const lazy = SerializerMiddleware.createLazy(
<add> value,
<add> fileMiddleware,
<add> options
<ide> );
<add> context.write(lazy);
<add> return lazy;
<ide> };
<ide> }
<ide> }), | 3 |
Python | Python | remove extraenous whitespace (pep8) | e7a8a02ba5d480616929145e003c01d836b7874b | <ide><path>celery/models.py
<ide> class PeriodicTaskMeta(models.Model):
<ide> """Information about a Periodic Task."""
<ide> name = models.CharField(_(u"name"), max_length=255, unique=True)
<ide> last_run_at = models.DateTimeField(_(u"last time run"),
<del> blank=True,
<add> blank=True,
<ide> default=datetime.fromtimestamp(0))
<ide> total_run_count = models.PositiveIntegerField(_(u"total run count"),
<ide> default=0) | 1 |
Text | Text | remove vagrant references from contributing.md | 149af8a3f37e1f21929f1365525f1508fb9cf022 | <ide><path>CONTRIBUTING.md
<ide> npm install
<ide> rake
<ide> ```
<ide>
<del>For those having issues with some of the build tool dependencies, an optional VagrantFile is provided.
<del>
<del>Using Vagrant to build latest version of Ember.js is quite simple. Just
<del>follow these 4 steps:
<del>
<del>1. Install Virtual Box - [Download](https://www.virtualbox.org/wiki/Downloads)
<del>
<del>2. Install Vagrant - [Download](http://downloads.vagrantup.com/)
<del>
<del>3. Retrieve chef cookbooks
<del>~~~
<del>git submodule init
<del>git submodule update
<del>~~~
<del>4. Lauch your vagrant virtual machine
<del>~~~
<del>vagrant up
<del>vagrant ssh
<del>~~~
<del>5. Use it!
<del>~~~
<del>cd /vagrant
<del>bundle install
<del>rake dist
<del>rake test
<del>...
<del>~~~
<del>
<ide> # Pull Requests
<ide>
<ide> We love pull requests. Here's a quick guide: | 1 |
Javascript | Javascript | fix flaky test-crypto-classes.js | 3e4f34cdb95bd05f84393ed8c0d3559edc90eb8f | <ide><path>test/parallel/test-crypto-classes.js
<ide> const TEST_CASES = {
<ide> if (!common.hasFipsCrypto) {
<ide> TEST_CASES.Cipher = ['aes192', 'secret'];
<ide> TEST_CASES.Decipher = ['aes192', 'secret'];
<add> TEST_CASES.DiffieHellman = [256];
<ide> }
<ide>
<ide> for (const [clazz, args] of Object.entries(TEST_CASES)) { | 1 |
Javascript | Javascript | remove context usage in progressplugin | 15997e2324465c884f883267186e5d89d450c5c4 | <ide><path>lib/ProgressPlugin.js
<ide> const schema = require("../schemas/plugins/ProgressPlugin.json");
<ide>
<ide> /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
<ide> /** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */
<add>/** @typedef {import("./Compiler")} Compiler */
<ide>
<ide> const createDefaultHandler = profile => {
<ide> let lineCaretPosition = 0;
<ide> const createDefaultHandler = profile => {
<ide> return defaultHandler;
<ide> };
<ide>
<add>/**
<add> * @callback ReportProgress
<add> * @param {number} p
<add> * @param {...string[]} [args]
<add> * @returns {void}
<add> */
<add>
<add>/** @type {WeakMap<Compiler,ReportProgress>} */
<add>const progressReporters = new WeakMap();
<add>
<ide> class ProgressPlugin {
<add> /**
<add> * @param {Compiler} compiler the current compiler
<add> * @returns {ReportProgress} a progress reporter, if any
<add> */
<add> static getReporter(compiler) {
<add> return progressReporters.get(compiler);
<add> }
<add>
<ide> /**
<ide> * @param {ProgressPluginArgument} options options
<ide> */
<ide> class ProgressPlugin {
<ide> const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
<ide> compilation.hooks[name].intercept({
<ide> name: "ProgressPlugin",
<del> context: true,
<del> call: () => {
<add> call() {
<ide> handler(percentage, title);
<ide> },
<del> tap: (context, tap) => {
<del> if (context) {
<del> // p is percentage from 0 to 1
<del> // args is any number of messages in a hierarchical matter
<del> context.reportProgress = (p, ...args) => {
<del> handler(percentage, title, tap.name, ...args);
<del> };
<del> }
<add> tap(tap) {
<add> // p is percentage from 0 to 1
<add> // args is any number of messages in a hierarchical matter
<add> progressReporters.set(compilation.compiler, (p, ...args) => {
<add> handler(percentage, title, tap.name, ...args);
<add> });
<ide> handler(percentage, title, tap.name);
<ide> }
<ide> });
<ide> });
<ide> });
<ide> compiler.hooks.emit.intercept({
<ide> name: "ProgressPlugin",
<del> context: true,
<del> call: () => {
<add> call() {
<ide> handler(0.95, "emitting");
<ide> },
<del> tap: (context, tap) => {
<del> if (context) {
<del> context.reportProgress = (p, ...args) => {
<del> handler(0.95, "emitting", tap.name, ...args);
<del> };
<del> }
<add> tap(tap) {
<add> progressReporters.set(compiler, (p, ...args) => {
<add> handler(0.95, "emitting", tap.name, ...args);
<add> });
<ide> handler(0.95, "emitting", tap.name);
<ide> }
<ide> });
<ide> compiler.hooks.afterEmit.intercept({
<ide> name: "ProgressPlugin",
<del> context: true,
<del> call: () => {
<add> call() {
<ide> handler(0.98, "after emitting");
<ide> },
<del> tap: (context, tap) => {
<del> if (context) {
<del> context.reportProgress = (p, ...args) => {
<del> handler(0.98, "after emitting", tap.name, ...args);
<del> };
<del> }
<add> tap(tap) {
<add> progressReporters.set(compiler, (p, ...args) => {
<add> handler(0.98, "after emitting", tap.name, ...args);
<add> });
<ide> handler(0.98, "after emitting", tap.name);
<ide> }
<ide> });
<ide><path>lib/SourceMapDevToolPlugin.js
<ide> const path = require("path");
<ide> const validateOptions = require("schema-utils");
<ide> const { ConcatSource, RawSource } = require("webpack-sources");
<ide> const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
<add>const ProgressPlugin = require("./ProgressPlugin");
<ide> const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
<ide> const createHash = require("./util/createHash");
<ide>
<ide> class SourceMapDevToolPlugin {
<ide> new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
<ide>
<ide> compilation.hooks.afterOptimizeChunkAssets.tap(
<del> /** @type {TODO} */ ({
<del> name: "SourceMapDevToolPlugin",
<del> context: true
<del> }),
<del> /** @type {TODO} */
<del> /** @param {any} context @param {Chunk[]} chunks @returns {void} */
<del> ((context, chunks) => {
<add> "SourceMapDevToolPlugin",
<add> chunks => {
<ide> const chunkGraph = compilation.chunkGraph;
<ide> const moduleToSourceNameMapping = new Map();
<ide> const reportProgress =
<del> context && context.reportProgress
<del> ? context.reportProgress
<del> : () => {};
<add> ProgressPlugin.getReporter(compilation.compiler) || (() => {});
<ide>
<ide> const files = [];
<ide> for (const chunk of chunks) {
<ide> class SourceMapDevToolPlugin {
<ide> }
<ide> });
<ide> reportProgress(1.0);
<del> })
<add> }
<ide> );
<ide> });
<ide> }
<ide><path>test/configCases/plugins/progress-plugin/webpack.config.js
<ide> module.exports = {
<ide> apply: compiler => {
<ide> compiler.hooks.compilation.tap("CustomPlugin", compilation => {
<ide> compilation.hooks.optimize.tap(
<del> {
<del> name: "CustomPlugin",
<del> context: true
<del> },
<del> context => {
<del> context.reportProgress(0, "custom category", "custom message");
<add> "CustomPlugin",
<add> () => {
<add> const reportProgress = webpack.ProgressPlugin.getReporter(compiler);
<add> reportProgress(0, "custom category", "custom message");
<ide> }
<ide> );
<ide> }); | 3 |
PHP | PHP | fix docblock and typehint for getcontrollerclass() | 88ee2803f40757448e76ceb25e96ba8fb2754c44 | <ide><path>src/Http/ControllerFactory.php
<ide> public function create(ServerRequest $request, Response $response)
<ide> * Determine the controller class name based on current request and controller param
<ide> *
<ide> * @param \Cake\Http\ServerRequest $request The request to build a controller for.
<del> * @return string|false
<add> * @return string|null
<ide> */
<del> public function getControllerClass(ServerRequest $request)
<add> public function getControllerClass(ServerRequest $request): ?string
<ide> {
<ide> $pluginPath = $controller = null;
<ide> $namespace = 'Controller'; | 1 |
Text | Text | release notes for 3.0.3 | 42f1932b520a90ae6f8e11246a0992e5f8983bd7 | <ide><path>docs/topics/release-notes.md
<ide> You can determine your currently installed version using `pip freeze`:
<ide>
<ide> ## 3.0.x series
<ide>
<add>
<add>### 3.0.3
<add>
<add>**Date**: [8th January 2015][3.0.3-milestone].
<add>
<add>* Fix `MinValueValidator` on `models.DateField`. ([#2369][gh2369])
<add>* Fix serializer missing context when pagination is used. ([#2355][gh2355])
<add>* Namespaced router URLs are now supported by the `DefaultRouter`. ([#2351][gh2351])
<add>* `required=False` allows omission of value for output. ([#2342][gh2342])
<add>* Use textarea input for `models.TextField`. ([#2340][gh2340])
<add>* Use custom `ListSerializer` for pagination if required. ([#2331][gh2331], [#2327][gh2327])
<add>* Better behavior with null and '' for blank HTML fields. ([#2330][gh2330])
<add>* Ensure fields in `exclude` are model fields. ([#2319][gh2319])
<add>* Fix `IntegerField` and `max_length` argument incompatibility. ([#2317][gh2317])
<add>* Fix the YAML encoder for 3.0 serializers. ([#2315][gh2315], [#2283][gh2283])
<add>* Fix the behavior of empty HTML fields. ([#2311][gh2311], [#1101][gh1101])
<add>* Fix Metaclass attribute depth ignoring fields attribute. ([#2287][gh2287])
<add>* Fix `format_suffix_patterns` to work with Django's `i18n_patterns`. ([#2278][gh2278])
<add>* Ability to customize router URLs for custom actions, using `url_path`. ([#2010][gh2010])
<add>
<ide> ### 3.0.2
<ide>
<ide> **Date**: [17th December 2014][3.0.2-milestone].
<ide> For older release notes, [please see the GitHub repo](old-release-notes).
<ide> [gh2290]: https://github.com/tomchristie/django-rest-framework/issues/2290
<ide> [gh2291]: https://github.com/tomchristie/django-rest-framework/issues/2291
<ide> [gh2294]: https://github.com/tomchristie/django-rest-framework/issues/2294
<add><!-- 3.0.3 -->
<add>[gh1101]: https://github.com/tomchristie/django-rest-framework/issues/1101
<add>[gh2010]: https://github.com/tomchristie/django-rest-framework/issues/2010
<add>[gh2278]: https://github.com/tomchristie/django-rest-framework/issues/2278
<add>[gh2283]: https://github.com/tomchristie/django-rest-framework/issues/2283
<add>[gh2287]: https://github.com/tomchristie/django-rest-framework/issues/2287
<add>[gh2311]: https://github.com/tomchristie/django-rest-framework/issues/2311
<add>[gh2315]: https://github.com/tomchristie/django-rest-framework/issues/2315
<add>[gh2317]: https://github.com/tomchristie/django-rest-framework/issues/2317
<add>[gh2319]: https://github.com/tomchristie/django-rest-framework/issues/2319
<add>[gh2327]: https://github.com/tomchristie/django-rest-framework/issues/2327
<add>[gh2330]: https://github.com/tomchristie/django-rest-framework/issues/2330
<add>[gh2331]: https://github.com/tomchristie/django-rest-framework/issues/2331
<add>[gh2340]: https://github.com/tomchristie/django-rest-framework/issues/2340
<add>[gh2342]: https://github.com/tomchristie/django-rest-framework/issues/2342
<add>[gh2351]: https://github.com/tomchristie/django-rest-framework/issues/2351
<add>[gh2355]: https://github.com/tomchristie/django-rest-framework/issues/2355
<add>[gh2369]: https://github.com/tomchristie/django-rest-framework/issues/2369 | 1 |
PHP | PHP | add configuration for security debug in formhelper | 73cd942326e117bb28cb47545eda6b2233221644 | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _csrfField()
<ide> public function end(array $secureAttributes = [])
<ide> {
<ide> $out = '';
<add>
<ide> if ($this->requestType !== 'get' &&
<ide> !empty($this->request['_Token'])
<ide> ) {
<ide> public function secure(array $fields = [], array $secureAttributes = [])
<ide> if (empty($this->request['_Token'])) {
<ide> return null;
<ide> }
<add> if (empty($secureAttributes['debugSecurity'])) {
<add> $secureAttributes['debugSecurity'] = Configure::read('debug');
<add> }
<ide>
<ide> $tokenData = $this->_buildFieldToken(
<ide> $this->_lastAction,
<ide> public function secure(array $fields = [], array $secureAttributes = [])
<ide> 'value' => $tokenData['unlocked'],
<ide> ]);
<ide> $out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
<del> if (Configure::read('debug')) {
<add> if ($secureAttributes['debugSecurity']) {
<ide> $tokenDebug = array_merge($secureAttributes, [
<ide> 'value' => urlencode(json_encode([
<ide> $this->_lastAction, | 1 |
PHP | PHP | fix failing test caused by addition of testshell | 7b9acc5c1693c8db2a1d542b3bbda021f2593d70 | <ide><path>lib/Cake/Test/Case/Console/Command/CommandListShellTest.php
<ide> public function testSortPlugin() {
<ide> $expected = "/\[.*TestPlugin.*\]\\v*[ ]+example/";
<ide> $this->assertPattern($expected, $output);
<ide>
<del> $expected = "/\[.*Core.*\]\\v*[ ]+acl, api, bake, command_list, console, i18n, schema, testsuite/";
<add> $expected = "/\[.*Core.*\]\\v*[ ]+acl, api, bake, command_list, console, i18n, schema, test, testsuite/";
<ide> $this->assertPattern($expected, $output);
<ide> }
<ide> | 1 |
PHP | PHP | add assertsentcount method and test | 3343c3361864c212caa555cc972409deccc91230 | <ide><path>src/Illuminate/Http/Client/Factory.php
<ide> public function assertNothingSent()
<ide> );
<ide> }
<ide>
<add> /**
<add> * Assert how many requests have been recorded.
<add> *
<add> * @param $count
<add> * @return void
<add> */
<add> public function assertSentCount($count)
<add> {
<add> PHPUnit::assertCount($count, $this->recorded);
<add> }
<add>
<ide> /**
<ide> * Assert that every created response sequence is empty.
<ide> *
<ide><path>tests/Http/HttpClientTest.php
<ide> public function testNoRequestIsNotBeingSent()
<ide> $this->factory->assertNothingSent();
<ide> }
<ide>
<add> public function testRequestCount()
<add> {
<add> $this->factory->fake();
<add> $this->factory->assertSentCount(0);
<add>
<add> $this->factory->post('http://foo.com/form', [
<add> 'name' => 'Taylor',
<add> ]);
<add>
<add> $this->factory->assertSentCount(1);
<add>
<add> $this->factory->post('http://foo.com/form', [
<add> 'name' => 'Jim',
<add> ]);
<add>
<add> $this->factory->assertSentCount(2);
<add> }
<add>
<ide> public function testCanSendMultipartData()
<ide> {
<ide> $this->factory->fake(); | 2 |
PHP | PHP | switch usage to hash where possible | 19e0d8d946eaa544652fd46a04b872c9637c1634 | <ide><path>lib/Cake/Configure/IniReader.php
<ide> protected function _parseNestedValues($values) {
<ide> $value = false;
<ide> }
<ide> if (strpos($key, '.') !== false) {
<del> $values = Set::insert($values, $key, $value);
<add> $values = Hash::insert($values, $key, $value);
<ide> } else {
<ide> $values[$key] = $value;
<ide> }
<ide><path>lib/Cake/Console/Command/AclShell.php
<ide> App::uses('ComponentCollection', 'Controller');
<ide> App::uses('AclComponent', 'Controller/Component');
<ide> App::uses('DbAcl', 'Model');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * Shell for ACL management. This console is known to have issues with zend.ze1_compatibility_mode
<ide> protected function _getNodeId($class, $identifier) {
<ide> $identifier = var_export($identifier, true);
<ide> }
<ide> $this->error(__d('cake_console', 'Could not find node using reference "%s"', $identifier));
<add> return;
<ide> }
<del> return Set::extract($node, "0.{$class}.id");
<add> return Hash::get($node, "0.{$class}.id");
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Console/Command/ConsoleShell.php
<ide> public function main($command = null) {
<ide> break;
<ide> case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
<ide> $router = Router::getInstance();
<del> $this->out(implode("\n", Set::extract($router->routes, '{n}.0')));
<add> $this->out(implode("\n", Hash::extract($router->routes, '{n}.0')));
<ide> break;
<ide> case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
<ide> if ($url = eval('return array' . $tmp[1] . ';')) {
<ide><path>lib/Cake/Console/Command/Task/ExtractTask.php
<ide> App::uses('AppShell', 'Console/Command');
<ide> App::uses('File', 'Utility');
<ide> App::uses('Folder', 'Utility');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * Language string extractor
<ide> protected function _processValidationRules($field, $rules, $file, $domain) {
<ide> return;
<ide> }
<ide>
<del> $dims = Set::countDim($rules);
<add> $dims = Hash::dimensions($rules);
<ide> if ($dims == 1 || ($dims == 2 && isset($rules['message']))) {
<ide> $rules = array($rules);
<ide> }
<ide><path>lib/Cake/Controller/Component/Acl/DbAcl.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> App::uses('AclInterface', 'Controller/Component/Acl');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * DbAcl implements an ACL control system in the database. ARO's and ACO's are
<ide><path>lib/Cake/Controller/Component/Acl/IniAcl.php
<ide> class IniAcl extends Object implements AclInterface {
<ide> public $config = null;
<ide>
<ide> /**
<del> * The Set::classicExtract() path to the user/aro identifier in the
<add> * The Hash::extract() path to the user/aro identifier in the
<ide> * acl.ini file. This path will be used to extract the string
<ide> * representation of a user used in the ini file.
<ide> *
<ide> public function check($aro, $aco, $action = null) {
<ide> $aclConfig = $this->config;
<ide>
<ide> if (is_array($aro)) {
<del> $aro = Set::classicExtract($aro, $this->userPath);
<add> $aro = Hash::get($aro, $this->userPath);
<ide> }
<ide>
<ide> if (isset($aclConfig[$aro]['deny'])) {
<ide><path>lib/Cake/Controller/Component/Acl/PhpAcl.php
<ide> public function addRole(array $aro) {
<ide> // detect cycles
<ide> $roles = $this->roles($dependency);
<ide>
<del> if (in_array($role, Set::flatten($roles))) {
<add> if (in_array($role, Hash::flatten($roles))) {
<ide> $path = '';
<ide>
<ide> foreach ($roles as $roleDependencies) {
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthenticate.php
<ide> * @link http://cakephp.org CakePHP(tm) Project
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<del>
<ide> App::uses('Security', 'Utility');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * Base Authentication class with common methods and properties.
<ide> abstract class BaseAuthenticate {
<ide> */
<ide> public function __construct(ComponentCollection $collection, $settings) {
<ide> $this->_Collection = $collection;
<del> $this->settings = Set::merge($this->settings, $settings);
<add> $this->settings = Hash::merge($this->settings, $settings);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Controller/Component/Auth/BaseAuthorize.php
<ide> * @link http://cakephp.org CakePHP(tm) Project
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * Abstract base authorization adapter for AuthComponent.
<ide> public function __construct(ComponentCollection $collection, $settings = array()
<ide> $this->_Collection = $collection;
<ide> $controller = $collection->getController();
<ide> $this->controller($controller);
<del> $this->settings = Set::merge($this->settings, $settings);
<add> $this->settings = Hash::merge($this->settings, $settings);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Controller/Component/AuthComponent.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide>
<del>
<ide> App::uses('Component', 'Controller');
<ide> App::uses('Router', 'Routing');
<ide> App::uses('Security', 'Utility');
<ide> App::uses('Debugger', 'Utility');
<add>App::uses('Hash', 'Utility');
<ide> App::uses('CakeSession', 'Model/Datasource');
<ide> App::uses('BaseAuthorize', 'Controller/Component/Auth');
<ide> App::uses('BaseAuthenticate', 'Controller/Component/Auth');
<ide> public function constructAuthorize() {
<ide> return;
<ide> }
<ide> $this->_authorizeObjects = array();
<del> $config = Set::normalize($this->authorize);
<add> $config = Hash::normalize((array)$this->authorize);
<ide> $global = array();
<ide> if (isset($config[AuthComponent::ALL])) {
<ide> $global = $config[AuthComponent::ALL];
<ide> public function constructAuthenticate() {
<ide> return;
<ide> }
<ide> $this->_authenticateObjects = array();
<del> $config = Set::normalize($this->authenticate);
<add> $config = Hash::normalize((array)$this->authenticate);
<ide> $global = array();
<ide> if (isset($config[AuthComponent::ALL])) {
<ide> $global = $config[AuthComponent::ALL];
<ide><path>lib/Cake/Controller/Component/CookieComponent.php
<ide>
<ide> App::uses('Component', 'Controller');
<ide> App::uses('Security', 'Utility');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * Cookie Component.
<ide> public function write($key, $value = null, $encrypt = true, $expires = null) {
<ide> if (!isset($this->_values[$this->name][$names[0]])) {
<ide> $this->_values[$this->name][$names[0]] = array();
<ide> }
<del> $this->_values[$this->name][$names[0]] = Set::insert($this->_values[$this->name][$names[0]], $names[1], $value);
<add> $this->_values[$this->name][$names[0]] = Hash::insert($this->_values[$this->name][$names[0]], $names[1], $value);
<ide> $this->_write('[' . implode('][', $names) . ']', $value);
<ide> }
<ide> }
<ide> public function read($key = null) {
<ide> }
<ide>
<ide> if (!empty($names[1])) {
<del> return Set::extract($this->_values[$this->name][$key], $names[1]);
<add> return Hash::get($this->_values[$this->name][$key], $names[1]);
<ide> }
<ide> return $this->_values[$this->name][$key];
<ide> }
<ide> public function delete($key) {
<ide> }
<ide> $names = explode('.', $key, 2);
<ide> if (isset($this->_values[$this->name][$names[0]])) {
<del> $this->_values[$this->name][$names[0]] = Set::remove($this->_values[$this->name][$names[0]], $names[1]);
<add> $this->_values[$this->name][$names[0]] = Hash::remove($this->_values[$this->name][$names[0]], $names[1]);
<ide> }
<ide> $this->_delete('[' . implode('][', $names) . ']');
<ide> }
<ide><path>lib/Cake/Controller/Component/PaginatorComponent.php
<ide> * @since CakePHP(tm) v 2.0
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * This component is used to handle automatic model data pagination. The primary way to use this
<ide> public function paginate($object = null, $scope = array(), $whitelist = array())
<ide> 'pageCount' => $pageCount,
<ide> 'order' => $order,
<ide> 'limit' => $limit,
<del> 'options' => Set::diff($options, $defaults),
<add> 'options' => Hash::diff($options, $defaults),
<ide> 'paramType' => $options['paramType']
<ide> );
<ide> if (!isset($this->Controller->request['paging'])) {
<ide><path>lib/Cake/Controller/Component/SecurityComponent.php
<ide>
<ide> App::uses('Component', 'Controller');
<ide> App::uses('String', 'Utility');
<add>App::uses('Hash', 'Utility');
<ide> App::uses('Security', 'Utility');
<ide>
<ide> /**
<ide> protected function _validatePost(Controller $controller) {
<ide> $unlocked = explode('|', $unlocked);
<ide>
<ide> $lockedFields = array();
<del> $fields = Set::flatten($check);
<add> $fields = Hash::flatten($check);
<ide> $fieldList = array_keys($fields);
<ide> $multi = array();
<ide>
<ide><path>lib/Cake/Core/Object.php
<ide> protected function _set($properties = array()) {
<ide> *
<ide> * @param array $properties The name of the properties to merge.
<ide> * @param string $class The class to merge the property with.
<del> * @param boolean $normalize Set to true to run the properties through Set::normalize() before merging.
<add> * @param boolean $normalize Set to true to run the properties through Hash::normalize() before merging.
<ide> * @return void
<ide> */
<ide> protected function _mergeVars($properties, $class, $normalize = true) {
<ide> protected function _mergeVars($properties, $class, $normalize = true) {
<ide> $this->{$var} != $classProperties[$var]
<ide> ) {
<ide> if ($normalize) {
<del> $classProperties[$var] = Set::normalize($classProperties[$var]);
<del> $this->{$var} = Set::normalize($this->{$var});
<add> $classProperties[$var] = Hash::normalize($classProperties[$var]);
<add> $this->{$var} = Hash::normalize($this->{$var});
<ide> }
<del> $this->{$var} = Set::merge($classProperties[$var], $this->{$var});
<add> $this->{$var} = Hash::merge($classProperties[$var], $this->{$var});
<ide> }
<ide> }
<ide> }
<ide><path>lib/Cake/Model/Behavior/AclBehavior.php
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> App::uses('AclNode', 'Model');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * ACL behavior
<ide> public function afterDelete(Model $model) {
<ide> $types = array($types);
<ide> }
<ide> foreach ($types as $type) {
<del> $node = Set::extract($this->node($model, null, $type), "0.{$type}.id");
<add> $node = Hash::extract($this->node($model, null, $type), "0.{$type}.id");
<ide> if (!empty($node)) {
<ide> $model->{$type}->delete($node);
<ide> }
<ide><path>lib/Cake/Model/Behavior/ContainableBehavior.php
<ide> public function containments(Model $Model, $contain, $containments = array(), $t
<ide> $key = $option;
<ide> $optionKey = true;
<ide> if (!empty($newChildren)) {
<del> $children = Set::merge($children, $newChildren);
<add> $children = Hash::merge($children, $newChildren);
<ide> }
<ide> }
<ide> if ($optionKey && isset($children[$key])) {
<ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> public function generateTreeList(Model $Model, $conditions = null, $keyPath = nu
<ide> }
<ide>
<ide> if ($valuePath == null) {
<del> $valuePath = array('{0}{1}', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
<add> $valuePath = array('%s%s', '{n}.tree_prefix', '{n}.' . $Model->alias . '.' . $Model->displayField);
<ide>
<ide> } elseif (is_string($valuePath)) {
<del> $valuePath = array('{0}{1}', '{n}.tree_prefix', $valuePath);
<add> $valuePath = array('%s%s', '{n}.tree_prefix', $valuePath);
<ide>
<ide> } else {
<ide> $valuePath[0] = '{' . (count($valuePath) - 1) . '}' . $valuePath[0];
<ide> public function generateTreeList(Model $Model, $conditions = null, $keyPath = nu
<ide> if (empty($results)) {
<ide> return array();
<ide> }
<del> return Set::combine($results, $keyPath, $valuePath);
<add> return Hash::combine($results, $keyPath, $valuePath);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Model/Datasource/CakeSession.php
<ide> public static function id($id = null) {
<ide> */
<ide> public static function delete($name) {
<ide> if (self::check($name)) {
<del> self::_overwrite($_SESSION, Set::remove($_SESSION, $name));
<add> self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
<ide> return (self::check($name) == false);
<ide> }
<ide> self::_setError(2, __d('cake_dev', "%s doesn't exist", $name));
<ide> protected static function _configureSession() {
<ide> if (isset($sessionConfig['defaults'])) {
<ide> $defaults = self::_defaultConfig($sessionConfig['defaults']);
<ide> if ($defaults) {
<del> $sessionConfig = Set::merge($defaults, $sessionConfig);
<add> $sessionConfig = Hash::merge($defaults, $sessionConfig);
<ide> }
<ide> }
<ide> if (!isset($sessionConfig['ini']['session.cookie_secure']) && env('HTTPS')) {
<ide><path>lib/Cake/Model/Datasource/Database/Postgres.php
<ide> protected function _quoteFunctionField($match) {
<ide> $match[1] = $this->name($match[1]);
<ide> } elseif (!$constant) {
<ide> $parts = explode('.', $match[1]);
<del> if (!Set::numeric($parts)) {
<add> if (!Hash::numeric($parts)) {
<ide> $match[1] = $this->name($match[1]);
<ide> }
<ide> }
<ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> protected function _mergeAssociation(&$data, &$merge, $association, $type, $self
<ide> if ($mergeKeys[0] === $dataKeys[0] || $mergeKeys === $dataKeys) {
<ide> $data[$association][$association] = $merge[0][$association];
<ide> } else {
<del> $diff = Set::diff($dataAssocTmp, $mergeAssocTmp);
<add> $diff = Hash::diff($dataAssocTmp, $mergeAssocTmp);
<ide> $data[$association] = array_merge($merge[0][$association], $diff);
<ide> }
<ide> } elseif ($selfJoin && array_key_exists($association, $merge[0])) {
<ide> protected function _matchRecords(Model $model, $conditions = null) {
<ide> return false;
<ide> }
<ide> $conditions = $this->conditions(array(
<del> $model->primaryKey => Set::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
<add> $model->primaryKey => Hash::extract($idList, "{n}.{$model->alias}.{$model->primaryKey}")
<ide> ));
<ide> }
<ide> return $conditions;
<ide> public function fields(Model $model, $alias = null, $fields = array(), $quote =
<ide> } else {
<ide> if (strpos($fields[$i], ',') === false) {
<ide> $build = explode('.', $fields[$i]);
<del> if (!Set::numeric($build)) {
<add> if (!Hash::numeric($build)) {
<ide> $fields[$i] = $this->name(implode('.', $build));
<ide> }
<ide> }
<ide> public function fields(Model $model, $alias = null, $fields = array(), $quote =
<ide> $field[1] = $this->name($alias . '.' . $field[1]);
<ide> } else {
<ide> $field[0] = explode('.', $field[1]);
<del> if (!Set::numeric($field[0])) {
<add> if (!Hash::numeric($field[0])) {
<ide> $field[0] = implode('.', array_map(array(&$this, 'name'), $field[0]));
<ide> $fields[$i] = preg_replace('/\(' . $field[1] . '\)/', '(' . $field[0] . ')', $fields[$i], 1);
<ide> }
<ide><path>lib/Cake/Model/Model.php
<ide> public function save($data = null, $validate = true, $fieldList = array()) {
<ide> $this->getEventManager()->dispatch($event);
<ide> }
<ide> if (!empty($this->data)) {
<del> $success = Set::merge($success, $this->data);
<add> $success = Hash::merge($success, $this->data);
<ide> }
<ide> $this->data = false;
<ide> $this->_clearCache();
<ide> protected function _saveMulti($joined, $id, $db) {
<ide> 'fields' => $associationForeignKey,
<ide> ));
<ide>
<del> $oldLinks = Set::extract($links, "{n}.{$associationForeignKey}");
<add> $oldLinks = Hash::extract($links, "{n}.{$associationForeignKey}");
<ide> if (!empty($oldLinks)) {
<ide> if ($keepExisting && !empty($newJoins)) {
<ide> $conditions[$associationForeignKey] = array_diff($oldLinks, $newJoins);
<ide> protected function _prepareUpdateFields($data) {
<ide> */
<ide> public function saveAll($data = null, $options = array()) {
<ide> $options = array_merge(array('validate' => 'first'), $options);
<del> if (Set::numeric(array_keys($data))) {
<add> if (Hash::numeric(array_keys($data))) {
<ide> if ($options['validate'] === 'only') {
<ide> return $this->validateMany($data, $options);
<ide> }
<ide> public function deleteAll($conditions, $cascade = true, $callbacks = false) {
<ide> return false;
<ide> }
<ide>
<del> $ids = Set::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
<add> $ids = Hash::extract($ids, "{n}.{$this->alias}.{$this->primaryKey}");
<ide> if (empty($ids)) {
<ide> return true;
<ide> }
<ide> protected function _findList($state, $query, $results = array()) {
<ide> return array();
<ide> }
<ide> $lst = $query['list'];
<del> return Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
<add> return Hash::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath']);
<ide> }
<ide> }
<ide>
<ide> protected function _findThreaded($state, $query, $results = array()) {
<ide> if (isset($query['parent'])) {
<ide> $parent = $query['parent'];
<ide> }
<del> return Set::nest($results, array(
<del> 'idPath' => '/' . $this->alias . '/' . $this->primaryKey,
<del> 'parentPath' => '/' . $this->alias . '/' . $parent
<add> return Hash::nest($results, array(
<add> 'idPath' => '{n}.' . $this->alias . '.' . $this->primaryKey,
<add> 'parentPath' => '{n}.' . $this->alias . '.' . $parent
<ide> ));
<ide> }
<ide> }
<ide><path>lib/Cake/Network/CakeRequest.php
<ide> public function __construct($url = null, $parseEnvironment = true) {
<ide> * into a single array. Variables prefixed with `data` will overwrite those without.
<ide> *
<ide> * If you have mixed POST values be careful not to make any top level keys numeric
<del> * containing arrays. Set::merge() is used to merge data, and it has possibly
<add> * containing arrays. Hash::merge() is used to merge data, and it has possibly
<ide> * unexpected behavior in this situation.
<ide> *
<ide> * @return void
<ide> protected function _processPost() {
<ide> $this->data = $data;
<ide> } else {
<ide> unset($this->data['data']);
<del> $this->data = Set::merge($this->data, $data);
<add> $this->data = Hash::merge($this->data, $data);
<ide> }
<ide> }
<ide> }
<ide> public function is($type) {
<ide> public function addDetector($name, $options) {
<ide> $name = strtolower($name);
<ide> if (isset($this->_detectors[$name]) && isset($options['options'])) {
<del> $options = Set::merge($this->_detectors[$name], $options);
<add> $options = Hash::merge($this->_detectors[$name], $options);
<ide> }
<ide> $this->_detectors[$name] = $options;
<ide> }
<ide> public static function acceptLanguage($language = null) {
<ide> public function data($name) {
<ide> $args = func_get_args();
<ide> if (count($args) == 2) {
<del> $this->data = Set::insert($this->data, $name, $args[1]);
<add> $this->data = Hash::insert($this->data, $name, $args[1]);
<ide> return $this;
<ide> }
<del> return Set::classicExtract($this->data, $name);
<add> return Hash::get($this->data, $name);
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Network/Email/CakeEmail.php
<ide> protected function _render($content) {
<ide>
<ide> $msg = array();
<ide>
<del> $contentIds = array_filter((array)Set::classicExtract($this->_attachments, '{s}.contentId'));
<add> $contentIds = array_filter((array)Hash::extract($this->_attachments, '{s}.contentId'));
<ide> $hasInlineAttachments = count($contentIds) > 0;
<ide> $hasAttachments = !empty($this->_attachments);
<ide> $hasMultipleTypes = count($rendered) > 1;
<ide><path>lib/Cake/Network/Http/HttpSocket.php
<ide> public function __construct($config = array()) {
<ide> $this->_configUri($config['request']['uri']);
<ide> unset($config['request']['uri']);
<ide> }
<del> $this->config = Set::merge($this->config, $config);
<add> $this->config = Hash::merge($this->config, $config);
<ide> }
<ide> parent::__construct($this->config);
<ide> }
<ide> public function request($request = array()) {
<ide> }
<ide> $request['uri'] = $this->url($request['uri']);
<ide> $request['uri'] = $this->_parseUri($request['uri'], true);
<del> $this->request = Set::merge($this->request, array_diff_key($this->config['request'], array('cookies' => true)), $request);
<add> $this->request = Hash::merge($this->request, array_diff_key($this->config['request'], array('cookies' => true)), $request);
<ide>
<ide> $this->_configUri($this->request['uri']);
<ide>
<ide> public function get($uri = null, $query = array(), $request = array()) {
<ide> $uri = $this->_buildUri($uri);
<ide> }
<ide>
<del> $request = Set::merge(array('method' => 'GET', 'uri' => $uri), $request);
<add> $request = Hash::merge(array('method' => 'GET', 'uri' => $uri), $request);
<ide> return $this->request($request);
<ide> }
<ide>
<ide> public function get($uri = null, $query = array(), $request = array()) {
<ide> * @return mixed Result of request, either false on failure or the response to the request.
<ide> */
<ide> public function post($uri = null, $data = array(), $request = array()) {
<del> $request = Set::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
<add> $request = Hash::merge(array('method' => 'POST', 'uri' => $uri, 'body' => $data), $request);
<ide> return $this->request($request);
<ide> }
<ide>
<ide> public function post($uri = null, $data = array(), $request = array()) {
<ide> * @return mixed Result of request
<ide> */
<ide> public function put($uri = null, $data = array(), $request = array()) {
<del> $request = Set::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
<add> $request = Hash::merge(array('method' => 'PUT', 'uri' => $uri, 'body' => $data), $request);
<ide> return $this->request($request);
<ide> }
<ide>
<ide> public function put($uri = null, $data = array(), $request = array()) {
<ide> * @return mixed Result of request
<ide> */
<ide> public function delete($uri = null, $data = array(), $request = array()) {
<del> $request = Set::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
<add> $request = Hash::merge(array('method' => 'DELETE', 'uri' => $uri, 'body' => $data), $request);
<ide> return $this->request($request);
<ide> }
<ide>
<ide> protected function _configUri($uri = null) {
<ide> 'uri' => array_intersect_key($uri, $this->config['request']['uri'])
<ide> )
<ide> );
<del> $this->config = Set::merge($this->config, $config);
<del> $this->config = Set::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
<add> $this->config = Hash::merge($this->config, $config);
<add> $this->config = Hash::merge($this->config, array_intersect_key($this->config['request']['uri'], $this->config));
<ide> return true;
<ide> }
<ide>
<ide><path>lib/Cake/Routing/Route/CakeRoute.php
<ide> protected function _writeUrl($params) {
<ide> $named = array();
<ide> foreach ($params['named'] as $key => $value) {
<ide> if (is_array($value)) {
<del> $flat = Set::flatten($value, '][');
<add> $flat = Hash::flatten($value, '][');
<ide> foreach ($flat as $namedKey => $namedValue) {
<ide> $named[] = $key . "[$namedKey]" . $separator . rawurlencode($namedValue);
<ide> }
<ide><path>lib/Cake/Routing/Router.php
<ide> protected static function _handleNoRoute($url) {
<ide> }
<ide> }
<ide>
<del> list($args, $named) = array(Set::filter($args, true), Set::filter($named, true));
<add> list($args, $named) = array(Hash::filter($args), Hash::filter($named));
<ide> foreach (self::$_prefixes as $prefix) {
<ide> if (!empty($url[$prefix])) {
<ide> $url['action'] = str_replace($prefix . '_', '', $url['action']);
<ide> protected static function _handleNoRoute($url) {
<ide> if (!empty($named)) {
<ide> foreach ($named as $name => $value) {
<ide> if (is_array($value)) {
<del> $flattend = Set::flatten($value, '][');
<add> $flattend = Hash::flatten($value, '][');
<ide> foreach ($flattend as $namedKey => $namedValue) {
<ide> $output .= '/' . $name . "[$namedKey]" . self::$_namedConfig['separator'] . rawurlencode($namedValue);
<ide> }
<ide><path>lib/Cake/Test/Case/Console/ShellTest.php
<ide> public function testMergeVars() {
<ide> $this->assertEquals($expected, $this->Shell->tasks);
<ide>
<ide> $expected = array('Fixture' => null, 'DbConfig' => array('one', 'two'));
<del> $this->assertEquals($expected, Set::normalize($this->Shell->tasks), 'Normalized results are wrong.');
<add> $this->assertEquals($expected, Hash::normalize($this->Shell->tasks), 'Normalized results are wrong.');
<ide> $this->assertEquals(array('Comment', 'Posts'), $this->Shell->uses, 'Merged models are wrong.');
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php
<ide> public function beforeFind($query) {
<ide> public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
<ide> if ($conditions == 'popular') {
<ide> $conditions = array($this->name . '.' . $this->primaryKey . ' > ' => '1');
<del> $options = Set::merge($fields, compact('conditions'));
<add> $options = Hash::merge($fields, compact('conditions'));
<ide> return parent::find('all', $options);
<ide> }
<ide> return parent::find($conditions, $fields);
<ide> public function testPaginate() {
<ide> $Controller->request->query = array();
<ide> $Controller->constructClasses();
<ide>
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(array(1, 2, 3), $results);
<ide>
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerComment'), '{n}.PaginatorControllerComment.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerComment'), '{n}.PaginatorControllerComment.id');
<ide> $this->assertEquals(array(1, 2, 3, 4, 5, 6), $results);
<ide>
<ide> $Controller->modelClass = null;
<ide>
<ide> $Controller->uses[0] = 'Plugin.PaginatorControllerPost';
<del> $results = Set::extract($Controller->Paginator->paginate(), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate(), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(array(1, 2, 3), $results);
<ide>
<ide> $Controller->request->params['named'] = array('page' => '-1');
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
<ide> $this->assertEquals(array(1, 2, 3), $results);
<ide>
<ide> $Controller->request->params['named'] = array('sort' => 'PaginatorControllerPost.id', 'direction' => 'asc');
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
<ide> $this->assertEquals(array(1, 2, 3), $results);
<ide>
<ide> $Controller->request->params['named'] = array('sort' => 'PaginatorControllerPost.id', 'direction' => 'desc');
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
<ide> $this->assertEquals(array(3, 2, 1), $results);
<ide>
<ide> $Controller->request->params['named'] = array('sort' => 'id', 'direction' => 'desc');
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
<ide> $this->assertEquals(array(3, 2, 1), $results);
<ide>
<ide> $Controller->request->params['named'] = array('sort' => 'NotExisting.field', 'direction' => 'desc');
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page'], 'Invalid field in query %s');
<ide> $this->assertEquals(array(1, 2, 3), $results);
<ide>
<ide> $Controller->request->params['named'] = array(
<ide> 'sort' => 'PaginatorControllerPost.author_id', 'direction' => 'allYourBase'
<ide> );
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals(array('PaginatorControllerPost.author_id' => 'asc'), $Controller->PaginatorControllerPost->lastQueries[1]['order'][0]);
<ide> $this->assertEquals(array(1, 3, 2), $results);
<ide>
<ide> public function testPaginateExtraParams() {
<ide> $Controller->request->params['named'] = array('page' => '-1', 'contain' => array('PaginatorControllerComment'));
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
<del> $this->assertEquals(array(1, 2, 3), Set::extract($result, '{n}.PaginatorControllerPost.id'));
<add> $this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
<ide> $this->assertTrue(!isset($Controller->PaginatorControllerPost->lastQueries[1]['contain']));
<ide>
<ide> $Controller->request->params['named'] = array('page' => '-1');
<ide> public function testPaginateExtraParams() {
<ide> );
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<ide> $this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
<del> $this->assertEquals(array(1, 2, 3), Set::extract($result, '{n}.PaginatorControllerPost.id'));
<add> $this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
<ide> $this->assertTrue(isset($Controller->PaginatorControllerPost->lastQueries[1]['contain']));
<ide>
<ide> $Controller->Paginator->settings = array(
<ide> public function testPaginateExtraParams() {
<ide> ),
<ide> );
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<del> $this->assertEquals(array(2, 3), Set::extract($result, '{n}.PaginatorControllerPost.id'));
<add> $this->assertEquals(array(2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
<ide> $this->assertEquals(array('PaginatorControllerPost.id > ' => '1'), $Controller->PaginatorControllerPost->lastQueries[1]['conditions']);
<ide>
<ide> $Controller->request->params['named'] = array('limit' => 12);
<ide> public function testPaginateSpecialType() {
<ide> );
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<ide>
<del> $this->assertEquals(array(2, 3), Set::extract($result, '{n}.PaginatorControllerPost.id'));
<add> $this->assertEquals(array(2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
<ide> $this->assertEquals(
<ide> $Controller->PaginatorControllerPost->lastQueries[1]['conditions'],
<ide> array('PaginatorControllerPost.id > ' => '1')
<ide> public function testDefaultPaginateParams() {
<ide> 'maxLimit' => 10,
<ide> 'paramType' => 'named'
<ide> );
<del> $results = Set::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<add> $results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
<ide> $this->assertEquals('PaginatorControllerPost.id DESC', $Controller->params['paging']['PaginatorControllerPost']['order']);
<ide> $this->assertEquals(array(3, 2, 1), $results);
<ide> }
<ide> public function testPaginateOrderVirtualField() {
<ide> 'paramType' => 'named'
<ide> );
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<del> $this->assertEquals(array(4, 3, 2), Set::extract($result, '{n}.PaginatorControllerPost.offset_test'));
<add> $this->assertEquals(array(4, 3, 2), Hash::extract($result, '{n}.PaginatorControllerPost.offset_test'));
<ide>
<ide> $Controller->request->params['named'] = array('sort' => 'offset_test', 'direction' => 'asc');
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<ide> public function testPaginateOrderVirtualFieldJoinedModel() {
<ide> 'paramType' => 'named'
<ide> );
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<del> $this->assertEquals(array(4, 2, 2), Set::extract($result, '{n}.PaginatorAuthor.joined_offset'));
<add> $this->assertEquals(array(4, 2, 2), Hash::extract($result, '{n}.PaginatorAuthor.joined_offset'));
<ide>
<ide> $Controller->request->params['named'] = array('sort' => 'PaginatorAuthor.joined_offset', 'direction' => 'asc');
<ide> $result = $Controller->Paginator->paginate('PaginatorControllerPost');
<del> $this->assertEquals(array(2, 2, 4), Set::extract($result, '{n}.PaginatorAuthor.joined_offset'));
<add> $this->assertEquals(array(2, 2, 4), Hash::extract($result, '{n}.PaginatorAuthor.joined_offset'));
<ide> }
<ide>
<ide> /**
<ide> public function testPaginateOrderVirtualFieldSharedWithRealField() {
<ide> );
<ide> $Controller->passedArgs = array('sort' => 'PaginatorControllerPost.title', 'dir' => 'asc');
<ide> $result = $Controller->paginate('PaginatorControllerComment');
<del> $this->assertEquals(array(1, 2, 3, 4, 5, 6), Set::extract($result, '{n}.PaginatorControllerComment.id'));
<add> $this->assertEquals(array(1, 2, 3, 4, 5, 6), Hash::extract($result, '{n}.PaginatorControllerComment.id'));
<ide> }
<ide>
<ide> /**
<ide><path>lib/Cake/Test/Case/Controller/ControllerTest.php
<ide> public function beforeFind($query) {
<ide> public function find($type = 'first', $options = array()) {
<ide> if ($type == 'popular') {
<ide> $conditions = array($this->name . '.' . $this->primaryKey . ' > ' => '1');
<del> $options = Set::merge($options, compact('conditions'));
<add> $options = Hash::merge($options, compact('conditions'));
<ide> return parent::find('all', $options);
<ide> }
<ide> return parent::find($type, $options);
<ide> public function testMergeVars() {
<ide>
<ide> $this->assertEquals(0, count(array_diff_key($TestController->helpers, array_flip($helpers))));
<ide> $this->assertEquals(0, count(array_diff($TestController->uses, $uses)));
<del> $this->assertEquals(count(array_diff_assoc(Set::normalize($TestController->components), Set::normalize($components))), 0);
<add> $this->assertEquals(count(array_diff_assoc(Hash::normalize($TestController->components), Hash::normalize($components))), 0);
<ide>
<ide> $expected = array('ControllerComment', 'ControllerAlias', 'ControllerPost');
<ide> $this->assertEquals($expected, $TestController->uses, '$uses was merged incorrectly, ControllerTestAppController models should be last.');
<ide> public function testPaginateBackwardsCompatibility() {
<ide> $expected = array('page' => 1, 'limit' => 20, 'maxLimit' => 100, 'paramType' => 'named');
<ide> $this->assertEquals($expected, $Controller->paginate);
<ide>
<del> $results = Set::extract($Controller->paginate('ControllerPost'), '{n}.ControllerPost.id');
<add> $results = Hash::extract($Controller->paginate('ControllerPost'), '{n}.ControllerPost.id');
<ide> $this->assertEquals(array(1, 2, 3), $results);
<ide>
<ide> $Controller->passedArgs = array();
<ide><path>lib/Cake/Test/Case/Model/AclNodeTest.php
<ide> public function setUp() {
<ide> */
<ide> public function testNode() {
<ide> $Aco = new DbAcoTest();
<del> $result = Set::extract($Aco->node('Controller1'), '{n}.DbAcoTest.id');
<add> $result = Hash::extract($Aco->node('Controller1'), '{n}.DbAcoTest.id');
<ide> $expected = array(2, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::extract($Aco->node('Controller1/action1'), '{n}.DbAcoTest.id');
<add> $result = Hash::extract($Aco->node('Controller1/action1'), '{n}.DbAcoTest.id');
<ide> $expected = array(3, 2, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::extract($Aco->node('Controller2/action1'), '{n}.DbAcoTest.id');
<add> $result = Hash::extract($Aco->node('Controller2/action1'), '{n}.DbAcoTest.id');
<ide> $expected = array(7, 6, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::extract($Aco->node('Controller1/action2'), '{n}.DbAcoTest.id');
<add> $result = Hash::extract($Aco->node('Controller1/action2'), '{n}.DbAcoTest.id');
<ide> $expected = array(5, 2, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::extract($Aco->node('Controller1/action1/record1'), '{n}.DbAcoTest.id');
<add> $result = Hash::extract($Aco->node('Controller1/action1/record1'), '{n}.DbAcoTest.id');
<ide> $expected = array(4, 3, 2, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::extract($Aco->node('Controller2/action1/record1'), '{n}.DbAcoTest.id');
<add> $result = Hash::extract($Aco->node('Controller2/action1/record1'), '{n}.DbAcoTest.id');
<ide> $expected = array(8, 7, 6, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::extract($Aco->node('Controller2/action3'), '{n}.DbAcoTest.id');
<del> $this->assertNull($result);
<add> $this->assertFalse($Aco->node('Controller2/action3'));
<ide>
<del> $result = Set::extract($Aco->node('Controller2/action3/record5'), '{n}.DbAcoTest.id');
<del> $this->assertNull($result);
<add> $this->assertFalse($Aco->node('Controller2/action3/record5'));
<ide>
<ide> $result = $Aco->node('');
<ide> $this->assertEquals(null, $result);
<ide> public function testNodeWithDuplicatePathSegments() {
<ide> public function testNodeArrayFind() {
<ide> $Aro = new DbAroTest();
<ide> Configure::write('DbAclbindMode', 'string');
<del> $result = Set::extract($Aro->node(array('DbAroUserTest' => array('id' => '1', 'foreign_key' => '1'))), '{n}.DbAroTest.id');
<add> $result = Hash::extract($Aro->node(array('DbAroUserTest' => array('id' => '1', 'foreign_key' => '1'))), '{n}.DbAroTest.id');
<ide> $expected = array(3, 2, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> Configure::write('DbAclbindMode', 'array');
<del> $result = Set::extract($Aro->node(array('DbAroUserTest' => array('id' => 4, 'foreign_key' => 2))), '{n}.DbAroTest.id');
<add> $result = Hash::extract($Aro->node(array('DbAroUserTest' => array('id' => 4, 'foreign_key' => 2))), '{n}.DbAroTest.id');
<ide> $expected = array(4);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testNodeObjectFind() {
<ide> $Aro = new DbAroTest();
<ide> $Model = new DbAroUserTest();
<ide> $Model->id = 1;
<del> $result = Set::extract($Aro->node($Model), '{n}.DbAroTest.id');
<add> $result = Hash::extract($Aro->node($Model), '{n}.DbAroTest.id');
<ide> $expected = array(3, 2, 1);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $Model->id = 2;
<del> $result = Set::extract($Aro->node($Model), '{n}.DbAroTest.id');
<add> $result = Hash::extract($Aro->node($Model), '{n}.DbAroTest.id');
<ide> $expected = array(4, 2, 1);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testNodeActionAuthorize() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $node = $Aro->node(array('TestPlugin.TestPluginAuthUser' => array('id' => 1, 'user' => 'mariano')));
<del> $result = Set::extract($node, '0.DbAroTest.id');
<add> $result = Hash::get($node, '0.DbAroTest.id');
<ide> $expected = $Aro->id;
<ide> $this->assertEquals($expected, $result);
<ide> CakePlugin::unload('TestPlugin');
<ide><path>lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php
<ide> public function testMixedCreateUpdateWithArrayLocale() {
<ide> $translations = array('title' => 'Title', 'content' => 'Content');
<ide> $TestModel->bindTranslation($translations, false);
<ide> $result = $TestModel->read(null, 1);
<del> $result['Title'] = Set::sort($result['Title'], '{n}.id', 'asc');
<del> $result['Content'] = Set::sort($result['Content'], '{n}.id', 'asc');
<add> $result['Title'] = Hash::sort($result['Title'], '{n}.id', 'asc');
<add> $result['Content'] = Hash::sort($result['Content'], '{n}.id', 'asc');
<ide> $expected = array(
<ide> 'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated', 'locale' => 'cze', 'title' => 'Titulek #1', 'content' => 'Upraveny obsah #1'),
<ide> 'Title' => array(
<ide><path>lib/Cake/Test/Case/Model/BehaviorCollectionTest.php
<ide> public function afterFind(Model $model, $results, $primary) {
<ide> return null;
<ide> break;
<ide> case 'modify':
<del> return Set::extract($results, "{n}.{$model->alias}");
<add> return Hash::extract($results, "{n}.{$model->alias}");
<ide> break;
<ide> }
<ide> }
<ide> public function testBehaviorSaveCallbacks() {
<ide> $this->assertSame($expected, $result);
<ide>
<ide> $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify'));
<del> $expected = Set::insert($record, 'Sample.name', 'sample99 modified before');
<add> $expected = Hash::insert($record, 'Sample.name', 'sample99 modified before');
<ide> $Sample->create();
<ide> $result = $Sample->save($record);
<ide> $expected['Sample']['id'] = $Sample->id;
<ide> public function testBehaviorSaveCallbacks() {
<ide> $this->assertSame($record, $Sample->save($record));
<ide>
<ide> $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'on'));
<del> $expected = Set::merge($record, array('Sample' => array('aftersave' => 'modified after on create')));
<add> $expected = Hash::merge($record, array('Sample' => array('aftersave' => 'modified after on create')));
<ide> $Sample->create();
<ide> $result = $Sample->save($record);
<ide> $expected['Sample']['id'] = $Sample->id;
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify', 'afterSave' => 'modify'));
<del> $expected = Set::merge($record, array('Sample' => array('name' => 'sample99 modified before modified after on create')));
<add> $expected = Hash::merge($record, array('Sample' => array('name' => 'sample99 modified before modified after on create')));
<ide> $Sample->create();
<ide> $result = $Sample->save($record);
<ide> $expected['Sample']['id'] = $Sample->id;
<ide> public function testBehaviorSaveCallbacks() {
<ide> $record2 = $Sample->read(null, 1);
<ide>
<ide> $Sample->Behaviors->attach('Test', array('afterSave' => 'on'));
<del> $expected = Set::merge($record2, array('Sample' => array('aftersave' => 'modified after')));
<add> $expected = Hash::merge($record2, array('Sample' => array('aftersave' => 'modified after')));
<ide> $Sample->create();
<ide> $this->assertSame($expected, $Sample->save($record2));
<ide>
<ide> $Sample->Behaviors->attach('Test', array('afterSave' => 'modify'));
<del> $expected = Set::merge($record2, array('Sample' => array('name' => 'sample1 modified after')));
<add> $expected = Hash::merge($record2, array('Sample' => array('name' => 'sample1 modified after')));
<ide> $Sample->create();
<ide> $this->assertSame($expected, $Sample->save($record2));
<ide> }
<ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php
<ide> public function testFindThreadedNoParent() {
<ide> $this->loadFixtures('Apple', 'Sample');
<ide> $Apple = new Apple();
<ide> $result = $Apple->find('threaded');
<del> $result = Set::extract($result, '{n}.children');
<add> $result = Hash::extract($result, '{n}.children');
<ide> $expected = array(array(), array(), array(), array(), array(), array(), array());
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testFindThreaded() {
<ide> $Model = new Person();
<ide> $Model->recursive = -1;
<ide> $result = $Model->find('threaded');
<del> $result = Set::extract($result, '{n}.children');
<add> $result = Hash::extract($result, '{n}.children');
<ide> $expected = array(array(), array(), array(), array(), array(), array(), array());
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> public function testGenerateFindList() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del> $result = Set::combine(
<add> $result = Hash::combine(
<ide> $TestModel->find('all', array(
<ide> 'order' => 'Article.title ASC',
<ide> 'fields' => array('id', 'title')
<ide> public function testGenerateFindList() {
<ide> );
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::combine(
<add> $result = Hash::combine(
<ide> $TestModel->find('all', array(
<ide> 'order' => 'Article.title ASC'
<ide> )),
<ide> public function testGenerateFindList() {
<ide>
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::combine(
<add> $result = Hash::combine(
<ide> $TestModel->find('all', array(
<ide> 'order' => 'Article.title ASC'
<ide> )),
<ide> public function testGenerateFindList() {
<ide>
<ide> $this->assertEquals($expected, $result);
<ide>
<del> $result = Set::combine(
<add> $result = Hash::combine(
<ide> $TestModel->find('all', array(
<ide> 'order' => 'Article.title ASC',
<ide> 'fields' => array('id', 'title', 'user_id')
<ide> public function testVirtualFieldsOrder() {
<ide>
<ide> $Post->Author->virtualFields = array('joined' => 'Post.id * Author.id');
<ide> $result = $Post->find('all');
<del> $result = Set::extract('{n}.Author.joined', $result);
<add> $result = Hash::extract($result, '{n}.Author.joined');
<ide> $expected = array(1, 6, 3);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $Post->find('all', array('order' => array('Author.joined' => 'ASC')));
<del> $result = Set::extract('{n}.Author.joined', $result);
<add> $result = Hash::extract($result, '{n}.Author.joined');
<ide> $expected = array(1, 3, 6);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $Post->find('all', array('order' => array('Author.joined' => 'DESC')));
<del> $result = Set::extract('{n}.Author.joined', $result);
<add> $result = Hash::extract($result, '{n}.Author.joined');
<ide> $expected = array(6, 3, 1);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide><path>lib/Cake/Test/Case/Model/ModelWriteTest.php
<ide> public function testCounterCacheWithSelfJoin() {
<ide> $Category = new CategoryThread();
<ide> $Category->belongsTo['ParentCategory']['counterCache'] = 'child_count';
<ide> $Category->updateCounterCache(array('parent_id' => 5));
<del> $result = Set::extract($Category->find('all', array('conditions' => array('CategoryThread.id' => 5))), '{n}.CategoryThread.child_count');
<add> $result = Hash::extract($Category->find('all', array('conditions' => array('CategoryThread.id' => 5))), '{n}.CategoryThread.child_count');
<ide> $expected = array(1);
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> public function testSaveHabtmNoPrimaryData() {
<ide> $TestModel->id = 2;
<ide> $TestModel->save($data);
<ide> $result = $TestModel->findById(2);
<del> $result['Item'] = Set::sort($result['Item'], '{n}.id', 'asc');
<add> $result['Item'] = Hash::sort($result['Item'], '{n}.id', 'asc');
<ide> $expected = array(
<ide> 'Portfolio' => array(
<ide> 'id' => 2,
<ide> public function testUpdateSavingBlankValues() {
<ide> public function testUpdateMultiple() {
<ide> $this->loadFixtures('Comment', 'Article', 'User', 'CategoryThread');
<ide> $TestModel = new Comment();
<del> $result = Set::extract($TestModel->find('all'), '{n}.Comment.user_id');
<add> $result = Hash::extract($TestModel->find('all'), '{n}.Comment.user_id');
<ide> $expected = array('2', '4', '1', '1', '1', '2');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $TestModel->updateAll(array('Comment.user_id' => 5), array('Comment.user_id' => 2));
<del> $result = Set::combine($TestModel->find('all'), '{n}.Comment.id', '{n}.Comment.user_id');
<add> $result = Hash::combine($TestModel->find('all'), '{n}.Comment.id', '{n}.Comment.user_id');
<ide> $expected = array(1 => 5, 2 => 4, 3 => 1, 4 => 1, 5 => 1, 6 => 5);
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> public function testUpdateMultiple() {
<ide> array('Comment.user_id' => 5)
<ide> );
<ide> $this->assertFalse(empty($result));
<del> $result = Set::extract(
<add> $result = Hash::extract(
<ide> $TestModel->find('all', array(
<ide> 'conditions' => array(
<ide> 'Comment.user_id' => 5
<ide> public function testSaveAllDeepAssociated() {
<ide> 'First new comment',
<ide> 'Second new comment'
<ide> );
<del> $result = Set::extract(Set::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<add> $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $TestModel->Comment->User->field('id', array('user' => 'newuser', 'password' => 'newuserpass'));
<ide> public function testSaveAllDeepAssociated() {
<ide> 'Third new comment',
<ide> 'Fourth new comment'
<ide> );
<del> $result = Set::extract(Set::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<add> $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $TestModel->Comment->Attachment->field('id', array('attachment' => 'deepsaved'));
<ide> public function testSaveAllHasMany() {
<ide> 'First new comment',
<ide> 'Second new comment'
<ide> );
<del> $result = Set::extract(Set::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<add> $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $result = $TestModel->saveAll(
<ide> public function testSaveAllHasMany() {
<ide> 'Second new comment',
<ide> 'Third new comment'
<ide> );
<del> $result = Set::extract(Set::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<add> $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> $TestModel->beforeSaveReturn = false;
<ide> public function testSaveAllHasMany() {
<ide> 'Second new comment',
<ide> 'Third new comment'
<ide> );
<del> $result = Set::extract(Set::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<add> $result = Hash::extract(Hash::sort($result['Comment'], '{n}.id', 'ASC'), '{n}.comment');
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide><path>lib/Cake/Test/Case/Network/Http/HttpSocketTest.php
<ide> public function testRequest() {
<ide> foreach ($tests as $i => $test) {
<ide> if (strpos($i, 'reset') === 0) {
<ide> foreach ($test as $path => $val) {
<del> $expectation = Set::insert($expectation, $path, $val);
<add> $expectation = Hash::insert($expectation, $path, $val);
<ide> }
<ide> continue;
<ide> }
<ide>
<ide> if (isset($test['expectation'])) {
<del> $expectation = Set::merge($expectation, $test['expectation']);
<add> $expectation = Hash::merge($expectation, $test['expectation']);
<ide> }
<ide> $this->Socket->request($test['request']);
<ide>
<ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testFormInputRequiredDetection() {
<ide>
<ide> $result = $this->Form->input('Contact.non_existing');
<ide> $expected = array(
<del> 'div' => array('class' => 'input text required'),
<add> 'div' => array('class' => 'input text'),
<ide> 'label' => array('for' => 'ContactNonExisting'),
<ide> 'Non Existing',
<ide> '/label',
<ide><path>lib/Cake/Utility/Debugger.php
<ide> public static function trace($options = array()) {
<ide> 'scope' => null,
<ide> 'exclude' => array('call_user_func_array', 'trigger_error')
<ide> );
<del> $options = Set::merge($defaults, $options);
<add> $options = Hash::merge($defaults, $options);
<ide>
<ide> $backtrace = debug_backtrace();
<ide> $count = count($backtrace);
<ide><path>lib/Cake/Utility/Hash.php
<ide> public static function remove(array $data, $path) {
<ide> /**
<ide> * Creates an associative array using `$keyPath` as the path to build its keys, and optionally
<ide> * `$valuePath` as path to get the values. If `$valuePath` is not specified, all values will be initialized
<del> * to null (useful for Set::merge). You can optionally group the values by what is obtained when
<add> * to null (useful for Hash::merge). You can optionally group the values by what is obtained when
<ide> * following the path specified in `$groupPath`.
<ide> *
<ide> * @param array $data Array from where to extract keys and values
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupP
<ide> * Usage:
<ide> *
<ide> * {{{
<del> * $result = Set::format($users, array('{n}.User.id', '{n}.User.name'), '%s : %s');
<add> * $result = Hash::format($users, array('{n}.User.id', '{n}.User.name'), '%s : %s');
<ide> * }}}
<ide> *
<ide> * The `$format` string can use any format options that `vsprintf()` and `sprintf()` do.
<ide> public static function format(array $data, array $paths, $format) {
<ide> }
<ide>
<ide> for ($i = 0; $i < $count; $i++) {
<del> $extracted[] = Set::extract($data, $paths[$i]);
<add> $extracted[] = self::extract($data, $paths[$i]);
<ide> }
<ide> $out = array();
<ide> $data = $extracted;
<ide> public static function maxDimensions(array $data) {
<ide> $depth = array();
<ide> if (is_array($data) && reset($data) !== false) {
<ide> foreach ($data as $value) {
<del> $depth[] = Hash::dimensions((array)$value) + 1;
<add> $depth[] = self::dimensions((array)$value) + 1;
<ide> }
<ide> }
<ide> return max($depth);
<ide> public static function normalize(array $data, $assoc = true) {
<ide> * @param mixed $data The data to nest.
<ide> * @param array $options Options are:
<ide> * @return array of results, nested
<del> * @see Set::extract()
<add> * @see Hash::extract()
<ide> */
<ide> public static function nest(array $data, $options = array()) {
<ide> if (!$data) {
<ide><path>lib/Cake/View/Helper.php
<ide> public function setEntity($entity, $setScope = false) {
<ide> if ($setScope === true) {
<ide> $this->_modelScope = $entity;
<ide> }
<del> $parts = array_values(Set::filter(explode('.', $entity), true));
<add> $parts = array_values(Hash::filter(explode('.', $entity)));
<ide> if (empty($parts)) {
<ide> return;
<ide> }
<ide> public function value($options = array(), $field = null, $key = 'value') {
<ide>
<ide> $entity = $this->entity();
<ide> if (!empty($data) && !empty($entity)) {
<del> $result = Set::extract(implode('.', $entity), $data);
<add> $result = Hash::get($data, implode('.', $entity));
<ide> }
<ide>
<ide> $habtmKey = $this->field();
<ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> protected function _isRequiredField($validateProperties) {
<ide> return true;
<ide> } elseif (is_array($validateProperties)) {
<ide>
<del> $dims = Set::countDim($validateProperties);
<add> $dims = Hash::dimensions($validateProperties);
<ide> if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) {
<ide> $validateProperties = array($validateProperties);
<ide> }
<ide> public function tagIsInvalid() {
<ide> if (empty($errors)) {
<ide> return false;
<ide> }
<del> $errors = Set::classicExtract($errors, join('.', $entity));
<add> $errors = Hash::get($errors, join('.', $entity));
<ide> return $errors === null ? false : $errors;
<ide> }
<ide>
<ide> protected function _secure($lock, $field = null, $value = null) {
<ide> if (!$field) {
<ide> $field = $this->entity();
<ide> } elseif (is_string($field)) {
<del> $field = Set::filter(explode('.', $field), true);
<add> $field = Hash::filter(explode('.', $field));
<ide> }
<ide>
<ide> foreach ($this->_unlockedFields as $unlockField) {
<ide><path>lib/Cake/View/Helper/NumberHelper.php
<ide> class NumberHelper extends AppHelper {
<ide> * @throws CakeException When the engine class could not be found.
<ide> */
<ide> public function __construct(View $View, $settings = array()) {
<del> $settings = Set::merge(array('engine' => 'CakeNumber'), $settings);
<add> $settings = Hash::merge(array('engine' => 'CakeNumber'), $settings);
<ide> parent::__construct($View, $settings);
<ide> list($plugin, $engineClass) = pluginSplit($settings['engine'], true);
<ide> App::uses($engineClass, $plugin . 'Utility');
<ide><path>lib/Cake/View/Helper/TextHelper.php
<ide> class TextHelper extends AppHelper {
<ide> * @throws CakeException when the engine class could not be found.
<ide> */
<ide> public function __construct(View $View, $settings = array()) {
<del> $settings = Set::merge(array('engine' => 'String'), $settings);
<add> $settings = Hash::merge(array('engine' => 'String'), $settings);
<ide> parent::__construct($View, $settings);
<ide> list($plugin, $engineClass) = pluginSplit($settings['engine'], true);
<ide> App::uses($engineClass, $plugin . 'Utility');
<ide><path>lib/Cake/View/Helper/TimeHelper.php
<ide> class TimeHelper extends AppHelper {
<ide> * @throws CakeException When the engine class could not be found.
<ide> */
<ide> public function __construct(View $View, $settings = array()) {
<del> $settings = Set::merge(array('engine' => 'CakeTime'), $settings);
<add> $settings = Hash::merge(array('engine' => 'CakeTime'), $settings);
<ide> parent::__construct($View, $settings);
<ide> list($plugin, $engineClass) = pluginSplit($settings['engine'], true);
<ide> App::uses($engineClass, $plugin . 'Utility'); | 43 |
PHP | PHP | remove dev garbage | b6783597d24a701cc83dcf8f89e9911fff7889f6 | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> use Cake\ORM\Association\BelongsToMany;
<ide> use Cake\ORM\Association\HasMany;
<ide> use Cake\ORM\Association\HasOne;
<del>use Cake\ORM\BehaviorRegistry;
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\Query;
<ide> use Cake\ORM\RulesChecker; | 1 |
Text | Text | add pypi version badge | 03310cc33ae800a36f17a421c8114e0e6616ccb6 | <ide><path>README.md
<ide> # Django REST framework
<ide>
<ide> [![build-status-image]][travis]
<add>[![pypi-version]][pypi]
<ide>
<ide> **Awesome web-browseable Web APIs.**
<ide>
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide>
<ide> [build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
<ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
<add>[pypi-version]: https://pypip.in/version/djangorestframework/badge.svg
<add>[pypi]: https://pypi.python.org/pypi/djangorestframework
<ide> [twitter]: https://twitter.com/_tomchristie
<ide> [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
<ide> [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X | 1 |
Go | Go | print a warning if dm is using a loopback file | a2c4c0cd3a2e5b58b36718290cb7c31f99f6495e | <ide><path>api/client/info.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> if info.DriverStatus != nil {
<ide> for _, pair := range info.DriverStatus {
<ide> fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1])
<add>
<add> // print a warning if devicemapper is using a loopback file
<add> if pair[0] == "Data loop file" {
<add> fmt.Fprintf(cli.err, " WARNING: Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.")
<add> }
<ide> }
<add>
<ide> }
<ide> ioutils.FprintfIfNotEmpty(cli.out, "Execution Driver: %s\n", info.ExecutionDriver)
<ide> ioutils.FprintfIfNotEmpty(cli.out, "Logging Driver: %s\n", info.LoggingDriver) | 1 |
Ruby | Ruby | add missing hash, eql?, == to various node classes | 6d225a9870aea1fa25ab71774206d08d5b216355 | <ide><path>lib/arel/nodes/bind_param.rb
<ide> def initialize(value)
<ide> super()
<ide> end
<ide>
<del> def ==(other)
<add> def hash
<add> [self.class, self.value].hash
<add> end
<add>
<add> def eql?(other)
<ide> other.is_a?(BindParam) &&
<ide> value == other.value
<ide> end
<add> alias :== :eql?
<ide>
<ide> def nil?
<ide> value.nil?
<ide><path>lib/arel/nodes/false.rb
<ide> def hash
<ide> def eql? other
<ide> self.class == other.class
<ide> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/function.rb
<ide> def eql? other
<ide> self.alias == other.alias &&
<ide> self.distinct == other.distinct
<ide> end
<add> alias :== :eql?
<add>
<ide> end
<ide>
<ide> %w{
<ide><path>lib/arel/nodes/terminal.rb
<ide> def hash
<ide> def eql? other
<ide> self.class == other.class
<ide> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/true.rb
<ide> def hash
<ide> def eql? other
<ide> self.class == other.class
<ide> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/values_list.rb
<ide> def initialize(rows)
<ide> @rows = rows
<ide> super()
<ide> end
<add>
<add> def hash
<add> @rows.hash
<add> end
<add>
<add> def eql? other
<add> self.class == other.class &&
<add> self.rows == other.rows
<add> end
<add> alias :== :eql?
<ide> end
<ide> end
<ide> end
<ide><path>lib/arel/nodes/window.rb
<ide> def hash
<ide> def eql? other
<ide> self.class == other.class
<ide> end
<add> alias :== :eql?
<ide> end
<ide>
<ide> class Preceding < Unary
<ide><path>test/test_nodes.rb
<add># frozen_string_literal: true
<add>require 'helper'
<add>
<add>module Arel
<add> module Nodes
<add> class TestNodes < Minitest::Test
<add> def test_every_arel_nodes_have_hash_eql_eqeq_from_same_class
<add> # #descendants code from activesupport
<add> node_descendants = []
<add> ObjectSpace.each_object(Arel::Nodes::Node.singleton_class) do |k|
<add> next if k.respond_to?(:singleton_class?) && k.singleton_class?
<add> node_descendants.unshift k unless k == self
<add> end
<add> node_descendants.delete(Arel::Nodes::Node)
<add>
<add> bad_node_descendants = node_descendants.reject do |subnode|
<add> eqeq_owner = subnode.instance_method(:==).owner
<add> eql_owner = subnode.instance_method(:eql?).owner
<add> hash_owner = subnode.instance_method(:hash).owner
<add>
<add> eqeq_owner < Arel::Nodes::Node &&
<add> eqeq_owner == eql_owner &&
<add> eqeq_owner == hash_owner
<add> end
<add>
<add> problem_msg = 'Some subclasses of Arel::Nodes::Node do not have a' \
<add> ' #== or #eql? or #hash defined from the same class as the others'
<add> assert_empty bad_node_descendants, problem_msg
<add> end
<add>
<add>
<add> end
<add> end
<add>end | 8 |
Javascript | Javascript | fix slight documentation typo | a816a017861473d6f19223a2d311f7fe25cc12d8 | <ide><path>packages/ember-routing/lib/system/route.js
<ide> Ember.Route = Ember.Object.extend(Ember.ActionHandler, {
<ide> /**
<ide> The name of the view to use by default when rendering this routes template.
<ide>
<del> When a rendering a template, the route will, by default, determine the
<add> When rendering a template, the route will, by default, determine the
<ide> template and view to use from the name of the route itself. If you need to
<ide> define a specific view, set this property.
<ide> | 1 |
Go | Go | add leaveall support | 1ac72c85cb86ac8bc1948c0f9258aa272c412cd2 | <ide><path>libnetwork/controller.go
<ide> type NetworkController interface {
<ide> // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
<ide> NetworkByID(id string) (Network, error)
<ide>
<add> // LeaveAll accepts a container id and attempts to leave all endpoints that the container has joined
<add> LeaveAll(id string) error
<add>
<ide> // GC triggers immediate garbage collection of resources which are garbage collected.
<ide> GC()
<ide> }
<ide><path>libnetwork/endpoint.go
<ide> func (ep *endpoint) Join(containerID string, options ...EndpointOption) error {
<ide> ep.joinLeaveStart()
<ide> defer func() {
<ide> ep.joinLeaveEnd()
<del> if err != nil {
<del> if e := ep.Leave(containerID); e != nil {
<del> log.Warnf("couldnt leave endpoint : %v", ep.name, err)
<del> }
<del> }
<ide> }()
<ide>
<ide> ep.Lock()
<ide> func (ep *endpoint) Join(containerID string, options ...EndpointOption) error {
<ide> if err != nil {
<ide> return err
<ide> }
<add> defer func() {
<add> if err != nil {
<add> if err = driver.Leave(nid, epid); err != nil {
<add> log.Warnf("driver leave failed while rolling back join: %v", err)
<add> }
<add> }
<add> }()
<ide>
<ide> err = ep.buildHostsFiles()
<ide> if err != nil {
<ide> func (ep *endpoint) Join(containerID string, options ...EndpointOption) error {
<ide>
<ide> sb, err := ctrlr.sandboxAdd(sboxKey, !container.config.useDefaultSandBox, ep)
<ide> if err != nil {
<del> return err
<add> return fmt.Errorf("failed sandbox add: %v", err)
<ide> }
<ide> defer func() {
<ide> if err != nil {
<ide><path>libnetwork/error.go
<ide> func (ij ErrInvalidJoin) BadRequest() {}
<ide> type ErrNoContainer struct{}
<ide>
<ide> func (nc ErrNoContainer) Error() string {
<del> return "a container has already joined the endpoint"
<add> return "no container is attached to the endpoint"
<ide> }
<ide>
<ide> // Maskable denotes the type of this error
<ide><path>libnetwork/libnetwork_test.go
<ide> func TestEndpointJoin(t *testing.T) {
<ide> t.Fatalf("Expected an empty sandbox key for an empty endpoint. Instead found a non-empty sandbox key: %s", info.SandboxKey())
<ide> }
<ide>
<add> defer controller.LeaveAll(containerID)
<add>
<ide> err = ep1.Join(containerID,
<ide> libnetwork.JoinOptionHostname("test"),
<ide> libnetwork.JoinOptionDomainname("docker.io"),
<ide> func TestEndpointJoin(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del>
<ide> defer func() {
<ide> err = ep1.Leave(containerID)
<ide> runtime.LockOSThread()
<ide> func TestEndpointJoin(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del>
<del> if ep1.ContainerInfo().ID() != ep2.ContainerInfo().ID() {
<del> t.Fatalf("ep1 and ep2 returned different container info")
<del> }
<del>
<add> runtime.LockOSThread()
<ide> defer func() {
<ide> err = ep2.Leave(containerID)
<add> runtime.LockOSThread()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> }()
<ide>
<add> if ep1.ContainerInfo().ID() != ep2.ContainerInfo().ID() {
<add> t.Fatalf("ep1 and ep2 returned different container info")
<add> }
<add>
<ide> checkSandbox(t, info)
<add>
<ide> }
<ide>
<ide> func TestEndpointJoinInvalidContainerId(t *testing.T) {
<ide> func TestEndpointDeleteWithActiveContainer(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer func() {
<add> err = ep.Delete()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> defer controller.LeaveAll(containerID)
<ide>
<ide> err = ep.Join(containerID,
<ide> libnetwork.JoinOptionHostname("test"),
<ide> func TestEndpointDeleteWithActiveContainer(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<del>
<del> err = ep.Delete()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<ide> }()
<ide>
<ide> err = ep.Delete()
<ide> func TestEndpointMultipleJoins(t *testing.T) {
<ide> }
<ide> }()
<ide>
<add> defer controller.LeaveAll(containerID)
<add>
<ide> err = ep.Join(containerID,
<ide> libnetwork.JoinOptionHostname("test"),
<ide> libnetwork.JoinOptionDomainname("docker.io"),
<ide> func TestEndpointMultipleJoins(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestLeaveAll(t *testing.T) {
<add> if !netutils.IsRunningInContainer() {
<add> defer netutils.SetupTestNetNS(t)()
<add> }
<add>
<add> n, err := createTestNetwork(bridgeNetType, "testnetwork", options.Generic{
<add> netlabel.GenericData: options.Generic{
<add> "BridgeName": "testnetwork",
<add> "AllowNonDefaultBridge": true,
<add> },
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := n.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> ep1, err := n.CreateEndpoint("ep1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := ep1.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> ep2, err := n.CreateEndpoint("ep2")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer func() {
<add> if err := ep2.Delete(); err != nil {
<add> t.Fatal(err)
<add> }
<add> }()
<add>
<add> err = ep1.Join("leaveall")
<add> if err != nil {
<add> t.Fatalf("Failed to join ep1: %v", err)
<add> }
<add> runtime.LockOSThread()
<add>
<add> err = ep2.Join("leaveall")
<add> if err != nil {
<add> t.Fatalf("Failed to join ep2: %v", err)
<add> }
<add> runtime.LockOSThread()
<add>
<add> err = ep1.Leave("leaveall")
<add> if err != nil {
<add> t.Fatalf("Failed to leave ep1: %v", err)
<add> }
<add> runtime.LockOSThread()
<add>
<add> err = controller.LeaveAll("leaveall")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> runtime.LockOSThread()
<add>}
<add>
<ide> func TestEndpointInvalidLeave(t *testing.T) {
<ide> if !netutils.IsRunningInContainer() {
<ide> defer netutils.SetupTestNetNS(t)()
<ide> func TestEndpointInvalidLeave(t *testing.T) {
<ide> }
<ide> }
<ide>
<add> defer controller.LeaveAll(containerID)
<add>
<ide> err = ep.Join(containerID,
<ide> libnetwork.JoinOptionHostname("test"),
<ide> libnetwork.JoinOptionDomainname("docker.io"),
<ide> func TestEndpointInvalidLeave(t *testing.T) {
<ide> if _, ok := err.(libnetwork.InvalidContainerIDError); !ok {
<ide> t.Fatalf("Failed for unexpected reason: %v", err)
<ide> }
<del>
<ide> }
<ide>
<ide> func TestEndpointUpdateParent(t *testing.T) {
<ide> func TestEndpointUpdateParent(t *testing.T) {
<ide> }
<ide> }()
<ide>
<add> defer controller.LeaveAll(containerID)
<ide> err = ep1.Join(containerID,
<ide> libnetwork.JoinOptionHostname("test1"),
<ide> libnetwork.JoinOptionDomainname("docker.io"),
<ide> func TestEndpointUpdateParent(t *testing.T) {
<ide> }
<ide> }()
<ide>
<add> defer controller.LeaveAll("container2")
<ide> err = ep2.Join("container2",
<ide> libnetwork.JoinOptionHostname("test2"),
<ide> libnetwork.JoinOptionDomainname("docker.io"),
<ide> func TestEndpointUpdateParent(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> defer func() {
<del> err = ep2.Leave("container2")
<del> runtime.LockOSThread()
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> }()
<add> err = ep2.Leave("container2")
<add> runtime.LockOSThread()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<ide> }
<ide>
<ide> func TestEnableIPv6(t *testing.T) {
<ide> resolvConfPath := "/tmp/libnetwork_test/resolv.conf"
<ide> defer os.Remove(resolvConfPath)
<ide>
<add> defer controller.LeaveAll(containerID)
<ide> err = ep1.Join(containerID,
<ide> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<ide> runtime.LockOSThread()
<ide> func TestResolvConf(t *testing.T) {
<ide> resolvConfPath := "/tmp/libnetwork_test/resolv.conf"
<ide> defer os.Remove(resolvConfPath)
<ide>
<add> defer controller.LeaveAll(containerID)
<ide> err = ep1.Join(containerID,
<ide> libnetwork.JoinOptionResolvConfPath(resolvConfPath))
<ide> runtime.LockOSThread()
<ide><path>libnetwork/sandbox/route_linux.go
<ide> func programGateway(path string, gw net.IP, isAdd bool) error {
<ide> return nsInvoke(path, func(nsFD int) error { return nil }, func(callerFD int) error {
<ide> gwRoutes, err := netlink.RouteGet(gw)
<ide> if err != nil {
<del> return fmt.Errorf("route for the gateway could not be found: %v", err)
<add> return fmt.Errorf("route for the gateway %s could not be found: %v", gw, err)
<ide> }
<ide>
<ide> if isAdd {
<ide> func programRoute(path string, dest *net.IPNet, nh net.IP) error {
<ide> return nsInvoke(path, func(nsFD int) error { return nil }, func(callerFD int) error {
<ide> gwRoutes, err := netlink.RouteGet(nh)
<ide> if err != nil {
<del> return fmt.Errorf("route for the next hop could not be found: %v", err)
<add> return fmt.Errorf("route for the next hop %s could not be found: %v", nh, err)
<ide> }
<ide>
<ide> return netlink.RouteAdd(&netlink.Route{
<ide><path>libnetwork/sandboxdata.go
<ide> package libnetwork
<ide>
<ide> import (
<ide> "container/heap"
<add> "fmt"
<ide> "sync"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> func (eh *epHeap) Pop() interface{} {
<ide>
<ide> func (s *sandboxData) updateGateway(ep *endpoint) error {
<ide> sb := s.sandbox()
<del> if err := sb.UnsetGateway(); err != nil {
<del> return err
<del> }
<ide>
<del> if err := sb.UnsetGatewayIPv6(); err != nil {
<del> return err
<del> }
<add> sb.UnsetGateway()
<add> sb.UnsetGatewayIPv6()
<ide>
<ide> if ep == nil {
<ide> return nil
<ide> func (s *sandboxData) updateGateway(ep *endpoint) error {
<ide> ep.Unlock()
<ide>
<ide> if err := sb.SetGateway(joinInfo.gw); err != nil {
<del> return err
<add> return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
<ide> }
<ide>
<ide> if err := sb.SetGatewayIPv6(joinInfo.gw6); err != nil {
<del> return err
<add> return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
<ide> }
<ide>
<ide> return nil
<ide> func (s *sandboxData) addEndpoint(ep *endpoint) error {
<ide> }
<ide>
<ide> if err := sb.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
<del> return err
<add> return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
<ide> }
<ide> }
<ide>
<ide> if joinInfo != nil {
<ide> // Set up non-interface routes.
<ide> for _, r := range ep.joinInfo.StaticRoutes {
<ide> if err := sb.AddStaticRoute(r); err != nil {
<del> return err
<add> return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
<ide> }
<ide> }
<ide> }
<ide> func (s *sandboxData) addEndpoint(ep *endpoint) error {
<ide> }
<ide> }
<ide>
<del> s.Lock()
<del> s.refCnt++
<del> s.Unlock()
<del>
<ide> return nil
<ide> }
<ide>
<del>func (s *sandboxData) rmEndpoint(ep *endpoint) int {
<add>func (s *sandboxData) rmEndpoint(ep *endpoint) {
<ide> ep.Lock()
<ide> joinInfo := ep.joinInfo
<ide> ep.Unlock()
<ide> func (s *sandboxData) rmEndpoint(ep *endpoint) int {
<ide> if highEpBefore != highEpAfter {
<ide> s.updateGateway(highEpAfter)
<ide> }
<del>
<del> s.Lock()
<del> s.refCnt--
<del> refCnt := s.refCnt
<del> s.Unlock()
<del>
<del> if refCnt == 0 {
<del> s.sandbox().Destroy()
<del> }
<del>
<del> return refCnt
<ide> }
<ide>
<ide> func (s *sandboxData) sandbox() sandbox.Sandbox {
<ide> func (c *controller) sandboxAdd(key string, create bool, ep *endpoint) (sandbox.
<ide> if !ok {
<ide> sb, err := sandbox.NewSandbox(key, create)
<ide> if err != nil {
<del> return nil, err
<add> return nil, fmt.Errorf("failed to create new sandbox: %v", err)
<ide> }
<ide>
<ide> sData = &sandboxData{
<ide> func (c *controller) sandboxRm(key string, ep *endpoint) {
<ide> sData := c.sandboxes[key]
<ide> c.Unlock()
<ide>
<del> if sData.rmEndpoint(ep) == 0 {
<del> c.Lock()
<del> delete(c.sandboxes, key)
<del> c.Unlock()
<del> }
<add> sData.rmEndpoint(ep)
<ide> }
<ide>
<ide> func (c *controller) sandboxGet(key string) sandbox.Sandbox {
<ide> func (c *controller) sandboxGet(key string) sandbox.Sandbox {
<ide>
<ide> return sData.sandbox()
<ide> }
<add>
<add>func (c *controller) LeaveAll(id string) error {
<add> c.Lock()
<add> sData, ok := c.sandboxes[sandbox.GenerateKey(id)]
<add> c.Unlock()
<add>
<add> if !ok {
<add> c.Unlock()
<add> return fmt.Errorf("could not find sandbox for container id %s", id)
<add> }
<add>
<add> sData.Lock()
<add> eps := make([]*endpoint, len(sData.endpoints))
<add> for i, ep := range sData.endpoints {
<add> eps[i] = ep
<add> }
<add> sData.Unlock()
<add>
<add> for _, ep := range eps {
<add> if err := ep.Leave(id); err != nil {
<add> logrus.Warnf("Failed leaving endpoint id %s: %v\n", ep.ID(), err)
<add> }
<add> }
<add>
<add> sData.sandbox().Destroy()
<add> delete(c.sandboxes, sandbox.GenerateKey(id))
<add>
<add> return nil
<add>}
<ide><path>libnetwork/sandboxdata_test.go
<ide> func TestSandboxAddEmpty(t *testing.T) {
<ide> ctrlr := createEmptyCtrlr()
<ide> ep := createEmptyEndpoint()
<ide>
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep); err != nil {
<add> if _, err := ctrlr.sandboxAdd(sandbox.GenerateKey("sandbox1"), true, ep); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if ctrlr.sandboxes["sandbox1"].refCnt != 1 {
<del> t.Fatalf("Unexpected sandbox ref count. Expected 1, got %d",
<del> ctrlr.sandboxes["sandbox1"].refCnt)
<del> }
<add> ctrlr.sandboxRm(sandbox.GenerateKey("sandbox1"), ep)
<ide>
<del> ctrlr.sandboxRm("sandbox1", ep)
<add> ctrlr.LeaveAll("sandbox1")
<ide> if len(ctrlr.sandboxes) != 0 {
<ide> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<ide> }
<ide> func TestSandboxAddMultiPrio(t *testing.T) {
<ide> ep2.container.config.prio = 2
<ide> ep3.container.config.prio = 3
<ide>
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep1); err != nil {
<del> t.Fatal(err)
<del> }
<add> sKey := sandbox.GenerateKey("sandbox1")
<ide>
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep2); err != nil {
<add> if _, err := ctrlr.sandboxAdd(sKey, true, ep1); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep3); err != nil {
<add> if _, err := ctrlr.sandboxAdd(sKey, true, ep2); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if ctrlr.sandboxes["sandbox1"].refCnt != 3 {
<del> t.Fatalf("Unexpected sandbox ref count. Expected 3, got %d",
<del> ctrlr.sandboxes["sandbox1"].refCnt)
<add> if _, err := ctrlr.sandboxAdd(sKey, true, ep3); err != nil {
<add> t.Fatal(err)
<ide> }
<ide>
<del> if ctrlr.sandboxes["sandbox1"].endpoints[0] != ep3 {
<add> if ctrlr.sandboxes[sKey].endpoints[0] != ep3 {
<ide> t.Fatal("Expected ep3 to be at the top of the heap. But did not find ep3 at the top of the heap")
<ide> }
<ide>
<del> ctrlr.sandboxRm("sandbox1", ep3)
<add> ctrlr.sandboxRm(sKey, ep3)
<ide>
<del> if ctrlr.sandboxes["sandbox1"].endpoints[0] != ep2 {
<add> if ctrlr.sandboxes[sKey].endpoints[0] != ep2 {
<ide> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap")
<ide> }
<ide>
<del> ctrlr.sandboxRm("sandbox1", ep2)
<add> ctrlr.sandboxRm(sKey, ep2)
<ide>
<del> if ctrlr.sandboxes["sandbox1"].endpoints[0] != ep1 {
<add> if ctrlr.sandboxes[sKey].endpoints[0] != ep1 {
<ide> t.Fatal("Expected ep1 to be at the top of the heap after removing ep2. But did not find ep1 at the top of the heap")
<ide> }
<ide>
<ide> // Re-add ep3 back
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep3); err != nil {
<add> if _, err := ctrlr.sandboxAdd(sKey, true, ep3); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if ctrlr.sandboxes["sandbox1"].endpoints[0] != ep3 {
<add> if ctrlr.sandboxes[sKey].endpoints[0] != ep3 {
<ide> t.Fatal("Expected ep3 to be at the top of the heap after adding ep3 back. But did not find ep3 at the top of the heap")
<ide> }
<ide>
<del> ctrlr.sandboxRm("sandbox1", ep3)
<del> ctrlr.sandboxRm("sandbox1", ep1)
<add> ctrlr.sandboxRm(sKey, ep3)
<add> ctrlr.sandboxRm(sKey, ep1)
<add>
<add> if err := ctrlr.LeaveAll("sandbox1"); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> if len(ctrlr.sandboxes) != 0 {
<ide> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<ide> }
<ide> func TestSandboxAddSamePrio(t *testing.T) {
<ide> ep1.network = &network{name: "aaa"}
<ide> ep2.network = &network{name: "bbb"}
<ide>
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep1); err != nil {
<del> t.Fatal(err)
<del> }
<add> sKey := sandbox.GenerateKey("sandbox1")
<ide>
<del> if _, err := ctrlr.sandboxAdd("sandbox1", true, ep2); err != nil {
<add> if _, err := ctrlr.sandboxAdd(sKey, true, ep1); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> if ctrlr.sandboxes["sandbox1"].refCnt != 2 {
<del> t.Fatalf("Unexpected sandbox ref count. Expected 2, got %d",
<del> ctrlr.sandboxes["sandbox1"].refCnt)
<add> if _, err := ctrlr.sandboxAdd(sKey, true, ep2); err != nil {
<add> t.Fatal(err)
<ide> }
<ide>
<del> if ctrlr.sandboxes["sandbox1"].endpoints[0] != ep1 {
<add> if ctrlr.sandboxes[sKey].endpoints[0] != ep1 {
<ide> t.Fatal("Expected ep1 to be at the top of the heap. But did not find ep1 at the top of the heap")
<ide> }
<ide>
<del> ctrlr.sandboxRm("sandbox1", ep1)
<add> ctrlr.sandboxRm(sKey, ep1)
<ide>
<del> if ctrlr.sandboxes["sandbox1"].endpoints[0] != ep2 {
<add> if ctrlr.sandboxes[sKey].endpoints[0] != ep2 {
<ide> t.Fatal("Expected ep2 to be at the top of the heap after removing ep3. But did not find ep2 at the top of the heap")
<ide> }
<ide>
<del> ctrlr.sandboxRm("sandbox1", ep2)
<add> ctrlr.sandboxRm(sKey, ep2)
<add>
<add> if err := ctrlr.LeaveAll("sandbox1"); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> if len(ctrlr.sandboxes) != 0 {
<ide> t.Fatalf("controller sandboxes is not empty. len = %d", len(ctrlr.sandboxes))
<ide> } | 7 |
PHP | PHP | improve char coverage | b742179af9124cadd8eca3000eca0b5b50ed256f | <ide><path>src/Illuminate/Support/Str.php
<ide> protected static function charsArray()
<ide> }
<ide>
<ide> return $charsArray = [
<del> 'a' => ['à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ā', 'ą', 'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ', 'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ', 'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ'],
<del> 'b' => ['б', 'β', 'Ъ', 'Ь', 'ب'],
<add> '0' => ['°', '₀'],
<add> '1' => ['¹', '₁'],
<add> '2' => ['²', '₂'],
<add> '3' => ['³', '₃'],
<add> '4' => ['⁴', '₄'],
<add> '5' => ['⁵', '₅'],
<add> '6' => ['⁶', '₆'],
<add> '7' => ['⁷', '₇'],
<add> '8' => ['⁸', '₈'],
<add> '9' => ['⁹', '₉'],
<add> 'a' => ['à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ā', 'ą', 'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ', 'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ', 'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', 'အ', 'ာ', 'ါ', 'ǻ', 'ǎ', 'ª', 'ა', 'अ'],
<add> 'b' => ['б', 'β', 'Ъ', 'Ь', 'ب', 'ဗ', 'ბ'],
<ide> 'c' => ['ç', 'ć', 'č', 'ĉ', 'ċ'],
<del> 'd' => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ', 'д', 'δ', 'د', 'ض'],
<del> 'e' => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ', 'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ', 'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э', 'є', 'ə'],
<del> 'f' => ['ф', 'φ', 'ف'],
<del> 'g' => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ج'],
<del> 'h' => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه'],
<del> 'i' => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į', 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ', 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'і', 'ї', 'и'],
<del> 'j' => ['ĵ', 'ј', 'Ј'],
<del> 'k' => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك'],
<del> 'l' => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل'],
<del> 'm' => ['м', 'μ', 'م'],
<del> 'n' => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن'],
<del> 'o' => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő', 'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό', 'о', 'و', 'θ'],
<del> 'p' => ['п', 'π'],
<del> 'r' => ['ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر'],
<del> 's' => ['ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص'],
<del> 't' => ['ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط'],
<del> 'u' => ['ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ', 'ự', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у'],
<del> 'v' => ['в'],
<del> 'w' => ['ŵ', 'ω', 'ώ'],
<del> 'x' => ['χ'],
<del> 'y' => ['ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ', 'ϋ', 'ύ', 'ΰ', 'ي'],
<del> 'z' => ['ź', 'ž', 'ż', 'з', 'ζ', 'ز'],
<del> 'aa' => ['ع'],
<del> 'ae' => ['ä', 'æ'],
<del> 'ch' => ['ч'],
<add> 'd' => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ', 'д', 'δ', 'د', 'ض', 'ဍ', 'ဒ', 'დ'],
<add> 'e' => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ', 'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ', 'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э', 'є', 'ə', 'ဧ', 'ေ', 'ဲ', 'ე', 'ए'],
<add> 'f' => ['ф', 'φ', 'ف', 'ƒ', 'ფ'],
<add> 'g' => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ج', 'ဂ', 'გ'],
<add> 'h' => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه', 'ဟ', 'ှ', 'ჰ'],
<add> 'i' => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į', 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ', 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'і', 'ї', 'и', 'ဣ', 'ိ', 'ီ', 'ည်', 'ǐ', 'ი', 'इ'],
<add> 'j' => ['ĵ', 'ј', 'Ј', 'ჯ'],
<add> 'k' => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك', 'က', 'კ', 'ქ'],
<add> 'l' => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل', 'လ', 'ლ'],
<add> 'm' => ['м', 'μ', 'م', 'မ', 'მ'],
<add> 'n' => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن', 'န', 'ნ'],
<add> 'o' => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő', 'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό', 'о', 'و', 'θ', 'ို', 'ǒ', 'ǿ', 'º', 'ო', 'ओ'],
<add> 'p' => ['п', 'π', 'ပ', 'პ'],
<add> 'q' => ['ყ'],
<add> 'r' => ['ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر', 'რ'],
<add> 's' => ['ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص', 'စ', 'ſ', 'ს'],
<add> 't' => ['ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط', 'ဋ', 'တ', 'ŧ', 'თ', 'ტ'],
<add> 'u' => ['ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ', 'ự', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у', 'ဉ', 'ု', 'ူ', 'ǔ', 'ǖ', 'ǘ', 'ǚ', 'ǜ', 'უ', 'उ'],
<add> 'v' => ['в', 'ვ', 'ϐ'],
<add> 'w' => ['ŵ', 'ω', 'ώ', 'ဝ', 'ွ'],
<add> 'x' => ['χ', 'ξ'],
<add> 'y' => ['ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ', 'ϋ', 'ύ', 'ΰ', 'ي', 'ယ'],
<add> 'z' => ['ź', 'ž', 'ż', 'з', 'ζ', 'ز', 'ဇ', 'ზ'],
<add> 'aa' => ['ع', 'आ'],
<add> 'ae' => ['ä', 'æ', 'ǽ'],
<add> 'ai' => ['ऐ'],
<add> 'at' => ['@'],
<add> 'ch' => ['ч', 'ჩ', 'ჭ'],
<ide> 'dj' => ['ђ', 'đ'],
<del> 'dz' => ['џ'],
<del> 'gh' => ['غ'],
<del> 'kh' => ['х', 'خ'],
<add> 'dz' => ['џ', 'ძ'],
<add> 'ei' => ['ऍ'],
<add> 'gh' => ['غ', 'ღ'],
<add> 'ii' => ['ई'],
<add> 'ij' => ['ij'],
<add> 'kh' => ['х', 'خ', 'ხ'],
<ide> 'lj' => ['љ'],
<ide> 'nj' => ['њ'],
<ide> 'oe' => ['ö', 'œ'],
<add> 'oi' => ['ऑ'],
<add> 'oii' => ['ऒ'],
<ide> 'ps' => ['ψ'],
<del> 'sh' => ['ш'],
<add> 'sh' => ['ш', 'შ'],
<ide> 'shch' => ['щ'],
<ide> 'ss' => ['ß'],
<del> 'th' => ['þ', 'ث', 'ذ', 'ظ'],
<del> 'ts' => ['ц'],
<add> 'sx' => ['ŝ'],
<add> 'th' => ['þ', 'ϑ', 'ث', 'ذ', 'ظ'],
<add> 'ts' => ['ц', 'ც', 'წ'],
<ide> 'ue' => ['ü'],
<add> 'uu' => ['ऊ'],
<ide> 'ya' => ['я'],
<ide> 'yu' => ['ю'],
<del> 'zh' => ['ж'],
<add> 'zh' => ['ж', 'ჟ'],
<ide> '(c)' => ['©'],
<del> 'A' => ['Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ', 'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Å', 'Ā', 'Ą', 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ', 'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ', 'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А'],
<del> 'B' => ['Б', 'Β'],
<add> 'A' => ['Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ', 'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Å', 'Ā', 'Ą', 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ', 'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ', 'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А', 'Ǻ', 'Ǎ'],
<add> 'B' => ['Б', 'Β', 'ब'],
<ide> 'C' => ['Ç', 'Ć', 'Č', 'Ĉ', 'Ċ'],
<ide> 'D' => ['Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'],
<ide> 'E' => ['É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ', 'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ', 'Ἑ', 'Ἒ', 'Ἓ', 'Ἔ', 'Ἕ', 'Έ', 'Ὲ', 'Е', 'Ё', 'Э', 'Є', 'Ə'],
<ide> 'F' => ['Ф', 'Φ'],
<ide> 'G' => ['Ğ', 'Ġ', 'Ģ', 'Г', 'Ґ', 'Γ'],
<del> 'H' => ['Η', 'Ή'],
<del> 'I' => ['Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į', 'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ', 'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї'],
<add> 'H' => ['Η', 'Ή', 'Ħ'],
<add> 'I' => ['Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į', 'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ', 'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї', 'Ǐ', 'ϒ'],
<ide> 'K' => ['К', 'Κ'],
<del> 'L' => ['Ĺ', 'Ł', 'Л', 'Λ', 'Ļ'],
<add> 'L' => ['Ĺ', 'Ł', 'Л', 'Λ', 'Ļ', 'Ľ', 'Ŀ', 'ल'],
<ide> 'M' => ['М', 'Μ'],
<ide> 'N' => ['Ń', 'Ñ', 'Ň', 'Ņ', 'Ŋ', 'Н', 'Ν'],
<del> 'O' => ['Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ', 'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ø', 'Ō', 'Ő', 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ', 'Ὸ', 'Ό', 'О', 'Θ', 'Ө'],
<add> 'O' => ['Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ', 'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ø', 'Ō', 'Ő', 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ', 'Ὸ', 'Ό', 'О', 'Θ', 'Ө', 'Ǒ', 'Ǿ'],
<ide> 'P' => ['П', 'Π'],
<del> 'R' => ['Ř', 'Ŕ', 'Р', 'Ρ'],
<add> 'R' => ['Ř', 'Ŕ', 'Р', 'Ρ', 'Ŗ'],
<ide> 'S' => ['Ş', 'Ŝ', 'Ș', 'Š', 'Ś', 'С', 'Σ'],
<ide> 'T' => ['Ť', 'Ţ', 'Ŧ', 'Ț', 'Т', 'Τ'],
<del> 'U' => ['Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự', 'Û', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У'],
<add> 'U' => ['Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự', 'Û', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У', 'Ǔ', 'Ǖ', 'Ǘ', 'Ǚ', 'Ǜ'],
<ide> 'V' => ['В'],
<del> 'W' => ['Ω', 'Ώ'],
<del> 'X' => ['Χ'],
<del> 'Y' => ['Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ', 'Ы', 'Й', 'Υ', 'Ϋ'],
<add> 'W' => ['Ω', 'Ώ', 'Ŵ'],
<add> 'X' => ['Χ', 'Ξ'],
<add> 'Y' => ['Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ', 'Ы', 'Й', 'Υ', 'Ϋ', 'Ŷ'],
<ide> 'Z' => ['Ź', 'Ž', 'Ż', 'З', 'Ζ'],
<del> 'AE' => ['Ä', 'Æ'],
<add> 'AE' => ['Ä', 'Æ', 'Ǽ'],
<ide> 'CH' => ['Ч'],
<ide> 'DJ' => ['Ђ'],
<ide> 'DZ' => ['Џ'],
<add> 'GX' => ['Ĝ'],
<add> 'HX' => ['Ĥ'],
<add> 'IJ' => ['IJ'],
<add> 'JX' => ['Ĵ'],
<ide> 'KH' => ['Х'],
<ide> 'LJ' => ['Љ'],
<ide> 'NJ' => ['Њ'],
<del> 'OE' => ['Ö'],
<add> 'OE' => ['Ö', 'Œ'],
<ide> 'PS' => ['Ψ'],
<ide> 'SH' => ['Ш'],
<ide> 'SHCH' => ['Щ'], | 1 |
Text | Text | move glen keane to collaborator emeritus | e57fbab9178f4e82f3cc31ce5f2b51964137d98b | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Michaël Zasso** <[email protected]> (he/him)
<ide> * [thefourtheye](https://github.com/thefourtheye) -
<ide> **Sakthipriyan Vairamani** <[email protected]> (he/him)
<del>* [thekemkid](https://github.com/thekemkid) -
<del>**Glen Keane** <[email protected]> (he/him)
<ide> * [TimothyGu](https://github.com/TimothyGu) -
<ide> **Tiancheng "Timothy" Gu** <[email protected]> (he/him)
<ide> * [tniessen](https://github.com/tniessen) -
<ide> For information about the governance of the Node.js project, see
<ide> **Alexander Makarenko** <[email protected]>
<ide> * [firedfox](https://github.com/firedfox) -
<ide> **Daniel Wang** <[email protected]>
<add>* [glentiki](https://github.com/glentiki) -
<add>**Glen Keane** <[email protected]> (he/him)
<ide> * [imran-iq](https://github.com/imran-iq) -
<ide> **Imran Iqbal** <[email protected]>
<ide> * [imyller](https://github.com/imyller) - | 1 |
Ruby | Ruby | move legacy cache and caskroom code to `compat/*` | 76e65ca070c0142f05ba2fcaf05fb6931c929547 | <ide><path>Library/Homebrew/cask/lib/hbc.rb
<ide> module Hbc
<ide>
<ide> def self.init
<ide> Cache.ensure_cache_exists
<del> Cache.delete_legacy_cache
<del>
<del> Caskroom.migrate_caskroom_from_repo_to_prefix
<ide> Caskroom.ensure_caskroom_exists
<ide> end
<ide>
<ide><path>Library/Homebrew/cask/lib/hbc/cache.rb
<ide> def ensure_cache_exists
<ide> odebug "Creating Cache at #{Hbc.cache}"
<ide> Hbc.cache.mkpath
<ide> end
<del>
<del> def delete_legacy_cache
<del> legacy_cache = HOMEBREW_CACHE.join("Casks")
<del> return unless legacy_cache.exist?
<del>
<del> ohai "Deleting legacy cache at #{legacy_cache}..."
<del> FileUtils.remove_entry_secure(legacy_cache)
<del> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/cask/lib/hbc/caskroom.rb
<ide> module Hbc
<ide> module Caskroom
<ide> module_function
<ide>
<del> def migrate_caskroom_from_repo_to_prefix
<del> repo_caskroom = HOMEBREW_REPOSITORY.join("Caskroom")
<del> return if Hbc.caskroom.exist?
<del> return unless repo_caskroom.directory?
<del>
<del> ohai "Moving Caskroom from HOMEBREW_REPOSITORY to HOMEBREW_PREFIX"
<del>
<del> if Hbc.caskroom.parent.writable?
<del> FileUtils.mv repo_caskroom, Hbc.caskroom
<del> else
<del> opoo "#{Hbc.caskroom.parent} is not writable, sudo is needed to move the Caskroom."
<del> SystemCommand.run("/bin/mv", args: [repo_caskroom, Hbc.caskroom.parent], sudo: true)
<del> end
<del> end
<del>
<ide> def ensure_caskroom_exists
<ide> return if Hbc.caskroom.exist?
<ide>
<ide><path>Library/Homebrew/compat/hbc.rb
<ide> require "compat/hbc/cask_loader"
<ide> require "compat/hbc/cli/update"
<add>require "compat/hbc/cache"
<add>require "compat/hbc/caskroom"
<add>
<add>module Hbc
<add> class << self
<add> prepend(
<add> Module.new do
<add> def init
<add> Cache.delete_legacy_cache
<add> Caskroom.migrate_caskroom_from_repo_to_prefix
<add>
<add> super
<add> end
<add> end,
<add> )
<add> end
<add>end
<ide><path>Library/Homebrew/compat/hbc/cache.rb
<add>module Hbc
<add> module Cache
<add> module_function
<add>
<add> def delete_legacy_cache
<add> legacy_cache = HOMEBREW_CACHE.join("Casks")
<add> return unless legacy_cache.exist?
<add>
<add> ohai "Deleting legacy cache at #{legacy_cache}"
<add> FileUtils.remove_entry_secure(legacy_cache)
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/compat/hbc/caskroom.rb
<add>module Hbc
<add> module Caskroom
<add> module_function
<add>
<add> def migrate_caskroom_from_repo_to_prefix
<add> repo_caskroom = HOMEBREW_REPOSITORY.join("Caskroom")
<add> return if Hbc.caskroom.exist?
<add> return unless repo_caskroom.directory?
<add>
<add> ohai "Moving Caskroom from HOMEBREW_REPOSITORY to HOMEBREW_PREFIX"
<add>
<add> if Hbc.caskroom.parent.writable?
<add> FileUtils.mv repo_caskroom, Hbc.caskroom
<add> else
<add> opoo "#{Hbc.caskroom.parent} is not writable, sudo is needed to move the Caskroom."
<add> SystemCommand.run("/bin/mv", args: [repo_caskroom, Hbc.caskroom.parent], sudo: true)
<add> end
<add> end
<add> end
<add>end | 6 |
Javascript | Javascript | handle multiple errors in boundaries | d8441cd725bcc3bc4f5be7d21be0f3788fde9590 | <ide><path>src/renderers/dom/fiber/ReactDOMFiber.js
<ide> var ReactDOM = {
<ide> render(element : ReactElement<any>, container : DOMContainerElement, callback: ?Function) {
<ide> warnAboutUnstableUse();
<ide> let root;
<add>
<ide> if (!container._reactRootContainer) {
<ide> root = container._reactRootContainer = DOMRenderer.mountContainer(element, container, callback);
<ide> } else {
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide>
<ide> 'use strict';
<ide>
<add>import type { TrappedError } from 'ReactFiberErrorBoundary';
<ide> import type { Fiber } from 'ReactFiber';
<ide> import type { FiberRoot } from 'ReactFiberRoot';
<ide> import type { HostConfig } from 'ReactFiberReconciler';
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide>
<ide> // Now that the tree has been committed, we can handle errors.
<ide> if (allTrappedErrors) {
<del> // TODO: handle multiple errors with distinct boundaries.
<del> handleError(allTrappedErrors[0]);
<add> handleErrors(allTrappedErrors);
<ide> }
<ide> }
<ide>
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> throw error;
<ide> }
<ide> const trappedError = trapError(failedUnitOfWork, error);
<del> handleError(trappedError);
<add> handleErrors([trappedError]);
<ide> }
<ide> }
<ide>
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> // We're the only work scheduled.
<ide> nextScheduledRoot = root;
<ide> lastScheduledRoot = root;
<add>
<ide> scheduleDeferredCallback(performDeferredWork);
<ide> }
<ide> }
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> throw error;
<ide> }
<ide> const trappedError = trapError(failedUnitOfWork, error);
<del> handleError(trappedError);
<add> handleErrors([trappedError]);
<ide> }
<ide> }
<ide>
<ide> module.exports = function<T, P, I, TI, C>(config : HostConfig<T, P, I, TI, C>) {
<ide> }
<ide> }
<ide>
<del> function handleError(trappedError) {
<del> const boundary = trappedError.boundary;
<del> const error = trappedError.error;
<del> if (!boundary) {
<del> throw error;
<add> function scheduleErrorBoundaryWork(boundary : Fiber, priority) : FiberRoot {
<add> let root = null;
<add> let fiber = boundary;
<add> while (fiber) {
<add> fiber.pendingWorkPriority = priority;
<add> if (fiber.alternate) {
<add> fiber.alternate.pendingWorkPriority = priority;
<add> }
<add> if (!fiber.return) {
<add> if (fiber.tag === HostContainer) {
<add> // We found the root.
<add> // Remember it so we can update it.
<add> root = ((fiber.stateNode : any) : FiberRoot);
<add> break;
<add> } else {
<add> throw new Error('Invalid root');
<add> }
<add> }
<add> fiber = fiber.return;
<add> }
<add> if (!root) {
<add> throw new Error('Could not find root from the boundary.');
<ide> }
<add> return root;
<add> }
<ide>
<del> try {
<del> // Give error boundary a chance to update its state
<del> acknowledgeErrorInBoundary(boundary, error);
<del>
<del> // We will process an update caused by an error boundary with synchronous priority.
<del> // This leaves us free to not keep track of whether a boundary has errored.
<del> // If it errors again, we will just catch the error and synchronously propagate it higher.
<del>
<del> // First, traverse upwards and set pending synchronous priority on the whole tree.
<del> let fiber = boundary;
<del> while (fiber) {
<del> fiber.pendingWorkPriority = SynchronousPriority;
<del> if (fiber.alternate) {
<del> fiber.alternate.pendingWorkPriority = SynchronousPriority;
<add> function handleErrors(initialTrappedErrors : Array<TrappedError>) : void {
<add> let nextTrappedErrors = initialTrappedErrors;
<add> let firstUncaughtError = null;
<add>
<add> // In each phase, we will attempt to pass errors to boundaries and re-render them.
<add> // If we get more errors, we propagate them to higher boundaries in the next iterations.
<add> while (nextTrappedErrors) {
<add> const trappedErrors = nextTrappedErrors;
<add> nextTrappedErrors = null;
<add>
<add> // Pass errors to all affected boundaries.
<add> const affectedBoundaries : Set<Fiber> = new Set();
<add> trappedErrors.forEach(trappedError => {
<add> const boundary = trappedError.boundary;
<add> const error = trappedError.error;
<add> if (!boundary) {
<add> firstUncaughtError = firstUncaughtError || error;
<add> return;
<ide> }
<del> if (!fiber.return) {
<del> if (fiber.tag === HostContainer) {
<del> // We found the root.
<del> // Now go to the second phase and update it synchronously.
<del> break;
<del> } else {
<del> throw new Error('Invalid root');
<add> // Don't visit boundaries twice.
<add> if (affectedBoundaries.has(boundary)) {
<add> return;
<add> }
<add> // Give error boundary a chance to update its state.
<add> try {
<add> acknowledgeErrorInBoundary(boundary, error);
<add> affectedBoundaries.add(boundary);
<add> } catch (nextError) {
<add> // If it throws, propagate the error.
<add> nextTrappedErrors = nextTrappedErrors || [];
<add> nextTrappedErrors.push(trapError(boundary, nextError));
<add> }
<add> });
<add>
<add> // We will process an update caused by each error boundary synchronously.
<add> affectedBoundaries.forEach(boundary => {
<add> // FIXME: We only specify LowPriority here so that setState() calls from the error
<add> // boundaries are respected. Instead we should set default priority level or something
<add> // like this. Reconsider this piece when synchronous scheduling is in place.
<add> const priority = LowPriority;
<add> const root = scheduleErrorBoundaryWork(boundary, priority);
<add> // This should use findNextUnitOfWork() when synchronous scheduling is implemented.
<add> let fiber = cloneFiber(root.current, priority);
<add> try {
<add> while (fiber) {
<add> // TODO: this is the only place where we recurse and it's unfortunate.
<add> // (This may potentially get us into handleErrors() again.)
<add> fiber = performUnitOfWork(fiber, true);
<ide> }
<add> } catch (nextError) {
<add> // If it throws, propagate the error.
<add> nextTrappedErrors = nextTrappedErrors || [];
<add> nextTrappedErrors.push(trapError(boundary, nextError));
<ide> }
<del> fiber = fiber.return;
<del> }
<del>
<del> if (!fiber) {
<del> throw new Error('Could not find an error boundary root.');
<del> }
<add> });
<add> }
<ide>
<del> // Find the work in progress tree.
<del> const root : FiberRoot = (fiber.stateNode : any);
<del> fiber = root.current.alternate;
<add> // Surface the first error uncaught by the boundaries to the user.
<add> if (firstUncaughtError) {
<add> // We need to make sure any future root can get scheduled despite these errors.
<add> // Currently after throwing, nothing gets scheduled because these fields are set.
<add> // FIXME: this is likely a wrong fix! It's still better than ignoring updates though.
<add> nextScheduledRoot = null;
<add> lastScheduledRoot = null;
<ide>
<del> // Perform all the work synchronously.
<del> while (fiber) {
<del> fiber = performUnitOfWork(fiber, true);
<del> }
<del> } catch (nextError) {
<del> // Propagate error to the next boundary or rethrow.
<del> const nextTrappedError = trapError(boundary, nextError);
<del> handleError(nextTrappedError);
<add> // Throw any unhandled errors.
<add> throw firstUncaughtError;
<ide> }
<ide> }
<ide> | 2 |
Text | Text | add record type to summary | ea55c7a319523528916f5b8ff1038bf9320d5fd8 | <ide><path>README.md
<ide> Immutable data cannot be changed once created, leading to much simpler
<ide> application development, no defensive copying, and enabling advanced memoization
<ide> techniques.
<ide>
<del>`Immutable` provides `List`, `Stack`, `Map`,
<del>`OrderedMap`, and `Set` by using persistent [hash maps tries](http://en.wikipedia.org/wiki/Hash_array_mapped_trie)
<add>`Immutable` provides `List`, `Stack`, `Map`, `OrderedMap`, `Record`
<add>and `Set` by using persistent [hash maps tries](http://en.wikipedia.org/wiki/Hash_array_mapped_trie)
<ide> and [vector tries](http://hypirion.com/musings/understanding-persistent-vector-pt-1)
<ide> as popularized by Clojure and Scala. They achieve efficiency on modern
<ide> JavaScript VMs by using structural sharing and minimizing the need to copy or | 1 |
Text | Text | add v3.28.7 to changelog | afceac756c098b270719da08faa169fdc1b6b3f3 | <ide><path>CHANGELOG.md
<ide> - [#19542](https://github.com/emberjs/ember.js/pull/19542) [BUGFIX] Fix initializer test blueprints
<ide> - [#19589](https://github.com/emberjs/ember.js/pull/19589) [BUGFIX] Don’t include type-tests in build output
<ide>
<add>## v3.28.7 (December 1, 2021)
<add>
<add>- [#19854](https://github.com/emberjs/ember.js/pull/19854) [BUGFIX] Fix implicit injections deprecation for routes to cover previously missed cases
<add>- [#19857](https://github.com/emberjs/ember.js/pull/19857) [BUGFIX] Improve assert message in default store for when routes have dynamic segments but no model hook
<add>
<ide> ## v3.28.6 (November 4, 2021)
<ide>
<ide> - [#19683](https://github.com/emberjs/ember.js/pull/19683) Ensure super.willDestroy is called correctly in Router's willDestroy | 1 |
Javascript | Javascript | initialize inputbuf to zero | 946c4e2a887eaadb920d90f29ec2e181dfe55bb8 | <ide><path>pdf.js
<ide> var CCITTFaxStream = (function() {
<ide> this.row = 0;
<ide> this.nextLine2D = this.encoding < 0;
<ide> this.inputBits = 0;
<del> this.inputBuf = EOF;
<add> this.inputBuf = 0;
<ide> this.outputBits = 0;
<ide> this.buf = EOF;
<ide>
<ide> var PDFDoc = (function() {
<ide> if (find(stream, 'startxref', 1024, true)) {
<ide> stream.skip(9);
<ide> var ch;
<del> while (Lexer.isSpace(ch = stream.getChar())){}
<add> while (Lexer.isSpace(ch = stream.getChar())) {}
<ide> var str = '';
<ide> while ((ch - '0') <= 9) {
<ide> str += ch; | 1 |
Python | Python | add uuid as a dependency if python <= 2.4 | 45f98c88a7dc30056b7e4b25432e4dbbe1005fd2 | <ide><path>setup.py
<ide> def run(self):
<ide> py_major_version = py_version_info[0]
<ide> py_minor_version = py_version_info[1]
<ide>
<del>if (py_major_version == 2 and py_minor_version <=5) or py_major_version < 2:
<add>if (py_major_version == 2 and py_minor_version <=5):
<ide> install_requires.append("multiprocessing==2.6.2.1")
<ide>
<add>if (py_major_version == 2 and py_minor_version <= 4):
<add> install_requires.append("uuid")
<add>
<ide> if os.path.exists("README.rst"):
<ide> long_description = codecs.open("README.rst", "r", "utf-8").read()
<ide> else: | 1 |
PHP | PHP | use phpdotenv methods instead of getenv/putenv | c7c85b1ad6ffab9f21f8931b7acf2d1b2b891679 | <ide><path>src/Illuminate/Foundation/Bootstrap/DetectEnvironment.php
<ide> public function bootstrap(Application $app)
<ide> {
<ide> try
<ide> {
<add> Dotenv::makeMutable();
<add>
<ide> Dotenv::load($app['path.base'], $app->environmentFile());
<ide> }
<ide> catch (InvalidArgumentException $e)
<ide><path>src/Illuminate/Foundation/Testing/ApplicationTrait.php
<ide> <?php namespace Illuminate\Foundation\Testing;
<ide>
<add>use Dotenv;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Contracts\Auth\Authenticatable as UserContract;
<ide>
<ide> trait ApplicationTrait {
<ide> */
<ide> protected function refreshApplication()
<ide> {
<del> putenv('APP_ENV=testing');
<del>
<add> Dotenv::setEnvironmentVariable('APP_ENV', 'testing');
<add>
<ide> $this->app = $this->createApplication();
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/helpers.php
<ide> function view($view = null, $data = array(), $mergeData = array())
<ide> */
<ide> function env($key, $default = null)
<ide> {
<del> $value = getenv($key);
<add> $value = Dotenv::findEnvironmentVariable($key);
<ide>
<del> if ($value === false) return value($default);
<add> if ($value === null) return value($default);
<ide>
<ide> switch (strtolower($value))
<ide> { | 3 |
Python | Python | set version to v3.0.0.dev9 | e14bf9decb3a278fc03c2f3f743c64f18cacc5f7 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "3.0.0.dev9"
<add>__version__ = "3.0.0.dev10"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Text | Text | add opera to browser list | 2580bde8acc18f9589a188c261dccc1b02d2e275 | <ide><path>.github/ISSUE_TEMPLATE.md
<ide> https://plnkr.co or similar (you can use this template as a starting point: http
<ide> <!-- Check whether this is still an issue in the most recent stable or in the snapshot AngularJS
<ide> version (https://code.angularjs.org/snapshot/) -->
<ide>
<del>**Browser:** [all | Chrome XX | Firefox XX | Edge XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
<add>**Browser:** [all | Chrome XX | Firefox XX | Edge XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView | Opera XX ]
<ide> <!-- All browsers where this could be reproduced (and Operating System if relevant) -->
<ide>
<ide> **Anything else:** | 1 |
Go | Go | move implicit pull test to use local registry | 641c1808e187ed86d8b614e49e8e6da5146201e3 | <ide><path>integration-cli/docker_cli_pull_local_test.go
<ide> func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *check.C) {
<ide>
<ide> dockerCmd(c, "--config", tmp, "pull", repoName)
<ide> }
<add>
<add>// TestRunImplicitPullWithNoTag should pull implicitely only the default tag (latest)
<add>func (s *DockerRegistrySuite) TestRunImplicitPullWithNoTag(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add> repo := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
<add> repoTag1 := fmt.Sprintf("%v:latest", repo)
<add> repoTag2 := fmt.Sprintf("%v:t1", repo)
<add> // tag the image and upload it to the private registry
<add> dockerCmd(c, "tag", "busybox", repoTag1)
<add> dockerCmd(c, "tag", "busybox", repoTag2)
<add> dockerCmd(c, "push", repo)
<add> dockerCmd(c, "rmi", repoTag1)
<add> dockerCmd(c, "rmi", repoTag2)
<add>
<add> out, _, err := dockerCmdWithError("run", repo)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(out, checker.Contains, fmt.Sprintf("Unable to find image '%s:latest' locally", repo))
<add>
<add> // There should be only one line for repo, the one with repo:latest
<add> outImageCmd, _, err := dockerCmdWithError("images", repo)
<add> splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n")
<add> c.Assert(splitOutImageCmd, checker.HasLen, 2)
<add>}
<ide><path>integration-cli/docker_cli_pull_test.go
<ide> func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *check.C) {
<ide> c.Assert(splitLatest, checker.DeepEquals, splitCurrent, check.Commentf("busybox:latest was changed after pulling all tags"))
<ide> }
<ide>
<del>// TestRunImplicitPullWithNoTagOnlyPullDefaultTag should pull implicitely only the default tag (latest)
<del>func (s *DockerHubPullSuite) TestRunImplicitPullWithNoTagOnlyPullDefaultTag(c *check.C) {
<del> // run with an image we don't have
<del> testRequires(c, DaemonIsLinux)
<del> out := s.Cmd(c, "run", "busybox")
<del>
<del> c.Assert(out, checker.Contains, "Unable to find image 'busybox:latest' locally")
<del>
<del> // There should be only one line for busybox, the one with busybox:latest
<del> outImageCmd := s.Cmd(c, "images", "busybox")
<del> splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n")
<del> c.Assert(splitOutImageCmd, checker.HasLen, 2)
<del>}
<del>
<ide> // TestPullClientDisconnect kills the client during a pull operation and verifies that the operation
<ide> // gets cancelled.
<ide> // | 2 |
Python | Python | add regularization and constraints to layers | 6cde6df7a5eefec715ed95bf28cee5a53a25035a | <ide><path>keras/layers/core.py
<ide> from six.moves import zip
<ide> srng = RandomStreams()
<ide>
<add>def l1(lam):
<add> def l1wrap(g,p):
<add> g += T.sgn(p) * lam
<add> return g
<add> return l1wrap
<add>
<add>def l2(lam):
<add> def l2wrap(g,p):
<add> g += p * lam
<add> return g
<add> return l2wrap
<add>
<add>def maxnorm(m):
<add> def maxnorm_wrap(p):
<add> norms = T.sqrt(T.sum(T.sqr(p), axis=0))
<add> desired = T.clip(norms, 0, m)
<add> p = p * (desired / (1e-7 + norms))
<add> return p
<add> return maxnorm_wrap
<add>
<add>def nonneg(p):
<add> p *= T.ge(p,0)
<add> return p
<add>
<add>def ident(g,*l):
<add> return g
<add>
<add>
<ide> class Layer(object):
<ide> def connect(self, previous_layer):
<ide> self.previous_layer = previous_layer
<ide> class Dropout(Layer):
<ide> def __init__(self, p):
<ide> self.p = p
<ide> self.params = []
<add> self.regularizer = []
<add> self.constraint = []
<ide>
<ide> def output(self, train):
<ide> X = self.get_input(train)
<ide> class Activation(Layer):
<ide> def __init__(self, activation):
<ide> self.activation = activations.get(activation)
<ide> self.params = []
<add> self.regularizer = []
<add> self.constraint = []
<ide>
<ide> def output(self, train):
<ide> X = self.get_input(train)
<ide> class Reshape(Layer):
<ide> def __init__(self, *dims):
<ide> self.dims = dims
<ide> self.params = []
<add> self.regularizer = []
<add> self.constraint = []
<ide>
<ide> def output(self, train):
<ide> X = self.get_input(train)
<ide> class Flatten(Layer):
<ide> '''
<ide> def __init__(self):
<ide> self.params = []
<add> self.regularizer = []
<add> self.constraint = []
<ide>
<ide> def output(self, train):
<ide> X = self.get_input(train)
<ide> class RepeatVector(Layer):
<ide> def __init__(self, n):
<ide> self.n = n
<ide> self.params = []
<add> self.regularizer = []
<add> self.constraint = []
<ide>
<ide> def output(self, train):
<ide> X = self.get_input(train)
<ide> class Dense(Layer):
<ide> '''
<ide> Just your regular fully connected NN layer.
<ide> '''
<del> def __init__(self, input_dim, output_dim, init='uniform', activation='linear', weights=None):
<add> def __init__(self, input_dim, output_dim, init='uniform', activation='linear', weights=None, regularizer=[ident, ident], constraint=[ident, ident]):
<ide> self.init = initializations.get(init)
<ide> self.activation = activations.get(activation)
<ide> self.input_dim = input_dim
<ide> def __init__(self, input_dim, output_dim, init='uniform', activation='linear', w
<ide>
<ide> self.params = [self.W, self.b]
<ide>
<add> self.regularizer = regularizer
<add> self.constraint = constraint
<add>
<ide> if weights is not None:
<ide> self.set_weights(weights)
<ide>
<ide> class TimeDistributedDense(Layer):
<ide> Tensor output dimensions: (nb_sample, shared_dimension, output_dim)
<ide>
<ide> '''
<del> def __init__(self, input_dim, output_dim, init='uniform', activation='linear', weights=None):
<add> def __init__(self, input_dim, output_dim, init='uniform', activation='linear', weights=None, regularizer=[ident, ident], constraint=[ident, ident]):
<ide> self.init = initializations.get(init)
<ide> self.activation = activations.get(activation)
<ide> self.input_dim = input_dim
<ide> def __init__(self, input_dim, output_dim, init='uniform', activation='linear', w
<ide>
<ide> self.params = [self.W, self.b]
<ide>
<add> self.regularizer = regularizer
<add> self.constraint = constraint
<add>
<ide> if weights is not None:
<ide> self.set_weights(weights)
<ide>
<ide><path>keras/models.py
<ide> class Sequential(object):
<ide> def __init__(self):
<ide> self.layers = []
<ide> self.params = []
<add> self.regularizer = []
<add> self.constraint = []
<ide>
<ide> def add(self, layer):
<ide> self.layers.append(layer)
<ide> if len(self.layers) > 1:
<ide> self.layers[-1].connect(self.layers[-2])
<ide> self.params += [p for p in layer.params]
<add> self.regularizer += [r for r in layer.regularizer]
<add> self.constraint += [c for c in layer.constraint]
<ide>
<ide> def compile(self, optimizer, loss, class_mode="categorical"):
<ide> self.optimizer = optimizers.get(optimizer)
<ide> def compile(self, optimizer, loss, class_mode="categorical"):
<ide> raise Exception("Invalid class mode:" + str(class_mode))
<ide> self.class_mode = class_mode
<ide>
<del> updates = self.optimizer.get_updates(self.params, train_loss)
<add> updates = self.optimizer.get_updates(self.params, self.regularizer, self.constraint, train_loss)
<ide>
<ide> self._train = theano.function([self.X, self.y], train_loss,
<ide> updates=updates, allow_input_downcast=True)
<ide><path>keras/optimizers.py
<ide> def get_gradients(self, cost, params):
<ide> norm = T.sqrt(sum([T.sum(g**2) for g in grads]))
<ide> grads = [clip_norm(g, c, norm) for g in grads]
<ide>
<del> new_grads = []
<del> for p, g in zip(params, grads):
<del> if hasattr(self, 'l1') and self.l1 > 0:
<del> g += T.sgn(p) * self.l1
<del>
<del> if hasattr(self, 'l2') and self.l2 > 0:
<del> g += p * self.l2
<del>
<del> if hasattr(self, 'maxnorm') and self.maxnorm > 0:
<del> norms = T.sqrt(T.sum(T.sqr(p), axis=0))
<del> desired = T.clip(norms, 0, self.maxnorm)
<del> p = p * (desired / (1e-7 + norms))
<del>
<del> new_grads.append(g)
<del> return new_grads
<add> return grads
<ide>
<ide>
<ide> class SGD(Optimizer):
<ide> def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False, *args, **kwar
<ide> self.__dict__.update(locals())
<ide> self.iterations = shared_scalar(0)
<ide>
<del> def get_updates(self, params, cost):
<add> def get_updates(self, params, regularizers, constraints, cost):
<ide> grads = self.get_gradients(cost, params)
<ide> lr = self.lr * (1.0 / (1.0 + self.decay * self.iterations))
<ide> updates = [(self.iterations, self.iterations+1.)]
<ide>
<del> for p, g in zip(params, grads):
<add> for p, g, r, c in zip(params, grads, regularizers, constraints):
<add> g = r(g,p)
<ide> m = shared_zeros(p.get_value().shape) # momentum
<ide> v = self.momentum * m - lr * g # velocity
<ide> updates.append((m, v))
<ide> def get_updates(self, params, cost):
<ide> new_p = p + self.momentum * v - lr * g
<ide> else:
<ide> new_p = p + v
<add>
<add> new_p = c(new_p)
<ide> updates.append((p, new_p))
<ide> return updates
<ide>
<ide> class RMSprop(Optimizer):
<ide> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-6, *args, **kwargs):
<ide> self.__dict__.update(locals())
<ide>
<del> def get_updates(self, params, cost):
<add> def get_updates(self, params, regularizers, constraints, cost):
<ide> grads = self.get_gradients(cost, params)
<ide> accumulators = [shared_zeros(p.get_value().shape) for p in params]
<ide> updates = []
<ide>
<del> for p, g, a in zip(params, grads, accumulators):
<add> for p, g, a, r, c in zip(params, grads, accumulators, regularizers, constraints):
<add> g = r(g,p)
<ide> new_a = self.rho * a + (1 - self.rho) * g ** 2 # update accumulator
<ide> updates.append((a, new_a))
<ide>
<ide> new_p = p - self.lr * g / T.sqrt(new_a + self.epsilon)
<add> new_p = c(new_p)
<ide> updates.append((p, new_p))
<ide> return updates
<ide>
<ide> class Adagrad(Optimizer):
<ide> def __init__(self, lr=0.01, epsilon=1e-6, *args, **kwargs):
<ide> self.__dict__.update(locals())
<ide>
<del> def get_updates(self, params, cost):
<add> def get_updates(self, params, regularizers, constraints, cost):
<ide> grads = self.get_gradients(cost, params)
<ide> accumulators = [shared_zeros(p.get_value().shape) for p in params]
<ide> updates = []
<ide>
<del> for p, g, a in zip(params, grads, accumulators):
<add> for p, g, a, r, c in zip(params, grads, accumulators, regularizers, constraints):
<add> g = r(g,p)
<ide> new_a = a + g ** 2 # update accumulator
<ide> updates.append((a, new_a))
<ide>
<ide> new_p = p - self.lr * g / T.sqrt(new_a + self.epsilon)
<add> new_p = c(new_p)
<ide> updates.append((p, new_p))
<ide> return updates
<ide>
<ide> class Adadelta(Optimizer):
<ide> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, *args, **kwargs):
<ide> self.__dict__.update(locals())
<ide>
<del> def get_updates(self, params, cost):
<add> def get_updates(self, params, regularizers, constraints, cost):
<ide> grads = self.get_gradients(cost, params)
<ide> accumulators = [shared_zeros(p.get_value().shape) for p in params]
<ide> delta_accumulators = [shared_zeros(p.get_value().shape) for p in params]
<ide> updates = []
<ide>
<del> for p, g, a, d_a in zip(params, grads, accumulators, delta_accumulators):
<add> for p, g, a, d_a, r, c in zip(params, grads, accumulators, delta_accumulators, regularizers, constraints):
<add> g = r(g,p)
<ide> new_a = self.rho * a + (1 - self.rho) * g ** 2 # update accumulator
<ide> updates.append((a, new_a))
<ide>
<ide> # use the new accumulator and the *old* delta_accumulator
<ide> update = g * T.sqrt(d_a + self.epsilon) / T.sqrt(new_a + self.epsilon)
<ide>
<ide> new_p = p - self.lr * update
<add> new_p = c(new_p)
<ide> updates.append((p, new_p))
<ide>
<ide> # update delta_accumulator
<ide> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, kappa=1-1e-
<ide> self.__dict__.update(locals())
<ide> self.iterations = shared_scalar(0)
<ide>
<del> def get_updates(self, params, cost):
<add> def get_updates(self, params, regularizers, constraints, cost):
<ide> grads = self.get_gradients(cost, params)
<ide> updates = [(self.iterations, self.iterations+1.)]
<ide>
<ide> def get_updates(self, params, cost):
<ide> # the update below seems missing from the paper, but is obviously required
<ide> beta_2_t = self.beta_2 * (self.kappa**i)
<ide>
<del> for p, g in zip(params, grads):
<add> for p, g, r, c in zip(params, grads, regularizers, constraints):
<add> g = r(g,p)
<ide> m = theano.shared(p.get_value() * 0.) # zero init of moment
<ide> v = theano.shared(p.get_value() * 0.) # zero init of velocity
<ide>
<ide> def get_updates(self, params, cost):
<ide> v_b_t = v_t / (1 - beta_2_t)
<ide>
<ide> p_t = p - self.lr * m_b_t / (T.sqrt(v_b_t) + self.epsilon)
<del>
<add>
<add> p_t = c(p_t)
<ide> updates.append((m, m_t))
<ide> updates.append((v, v_t))
<ide> updates.append((p, p_t)) | 3 |
Ruby | Ruby | improve i18n reloader to only reload once | 90bff9c3f52113515a80d732b43786bda0311749 | <ide><path>activesupport/lib/active_support/i18n_railtie.rb
<ide> def self.initialize_i18n(app)
<ide> reloader = app.config.file_watcher.new(I18n.load_path.dup, directories) do
<ide> I18n.load_path.keep_if { |p| File.exist?(p) }
<ide> I18n.load_path |= reloadable_paths.flat_map(&:existent)
<del>
<del> I18n.reload!
<ide> end
<ide>
<ide> app.reloaders << reloader | 1 |
Javascript | Javascript | remove unnecessary commented code | 28c2330665750134979144dba6d956b441cb7f02 | <ide><path>test/unit/effects.js
<ide> jQuery.each({
<ide> elem = elem[ 0 ];
<ide>
<ide> if ( t_w == "show" ) {
<del> // equals( elem.style.display, "block", "Showing, display should block: " + elem.style.display);
<del> // }
<del>
<del> // if ( t_w == "hide"||t_w == "show" ) {
<del> // ok(f_w === "" ? elem.style.width === f_w : elem.style.width.indexOf(f_w) === 0, "Width must be reset to " + f_w + ": " + elem.style.width);
<del> // }
<del>
<del> // if ( t_h == "hide"||t_h == "show" ) {
<del> // ok(f_h === "" ? elem.style.height === f_h : elem.style.height.indexOf(f_h) === 0, "Height must be reset to " + f_h + ": " + elem.style.height);
<ide> equals( elem.style.display, "block", "Showing, display should block: " + elem.style.display );
<ide> }
<ide>
<ide> jQuery.each({
<ide> cur_o = 1;
<ide> }
<ide>
<del> // if ( t_o == "hide" || t_o == "show" ) {
<del> // equals(cur_o, f_o, "Opacity must be reset to " + f_o + ": " + cur_o);
<del> // }
<del>
<del> // if ( t_w == "hide" ) {
<del> // equals(elem.style.display, "none", "Hiding, display should be none: " + elem.style.display);
<del>
<ide> if ( t_o == "hide" || t_o == "show" ) {
<ide> equals( cur_o, f_o, "Opacity must be reset to " + f_o + ": " + cur_o );
<ide> } | 1 |
Javascript | Javascript | fix warnings in uiexplorer example pages | 528cf68fa0794614c28f3194daa69d645753204d | <ide><path>Examples/UIExplorer/UIExplorerBlock.js
<ide> */
<ide> 'use strict';
<ide>
<del>var React = require('react-native');
<add>var React = require('react');
<add>var ReactNative = require('react-native');
<ide> var {
<ide> StyleSheet,
<ide> Text,
<ide> View,
<del>} = React;
<add>} = ReactNative;
<ide>
<ide> var UIExplorerBlock = React.createClass({
<ide> propTypes: {
<ide><path>Examples/UIExplorer/UIExplorerPage.js
<ide> */
<ide> 'use strict';
<ide>
<del>var React = require('react-native');
<add>var React = require('react');
<add>var ReactNative = require('react-native');
<ide> var {
<ide> ScrollView,
<ide> StyleSheet,
<ide> View,
<del>} = React;
<add>} = ReactNative;
<ide>
<ide> var UIExplorerTitle = require('./UIExplorerTitle');
<ide>
<ide><path>Examples/UIExplorer/UIExplorerTitle.js
<ide> */
<ide> 'use strict';
<ide>
<del>var React = require('react-native');
<add>var React = require('react');
<add>var ReactNative = require('react-native');
<ide> var {
<ide> StyleSheet,
<ide> Text,
<ide> View,
<del>} = React;
<add>} = ReactNative;
<ide>
<ide> var UIExplorerTitle = React.createClass({
<ide> render: function() {
<ide><path>Examples/UIExplorer/createExamplePage.js
<ide> */
<ide> 'use strict';
<ide>
<del>var React = require('react-native');
<add>var React = require('react');
<add>var ReactNative = require('react-native');
<ide> var {
<ide> Platform,
<del>} = React;
<del>var ReactNative = require('ReactNative');
<add>} = ReactNative;
<ide> var UIExplorerBlock = require('./UIExplorerBlock');
<ide> var UIExplorerPage = require('./UIExplorerPage');
<ide>
<ide> var createExamplePage = function(title: ?string, exampleModule: ExampleModule)
<ide> }
<ide> title += ' (' + platform + ' only)';
<ide> }
<del> // Hack warning: This is a hack because the www UI explorer requires
<del> // renderComponent to be called.
<add> // Hack warning: This is a hack because the www UI explorer used to
<add> // require render to be called. It should just return elements now.
<ide> var originalRender = React.render;
<del> // $FlowFixMe React.renderComponent was deprecated in 0.12, should this be React.render?
<del> var originalRenderComponent = React.renderComponent;
<ide> var originalIOSRender = ReactNative.render;
<del> var originalIOSRenderComponent = ReactNative.renderComponent;
<ide> var renderedComponent;
<ide> // TODO remove typecasts when Flow bug #6560135 is fixed
<ide> // and workaround is removed from react-native.js
<ide> (React: Object).render =
<del> (React: Object).renderComponent =
<ide> (ReactNative: Object).render =
<del> (ReactNative: Object).renderComponent =
<ide> function(element, container) {
<ide> renderedComponent = element;
<ide> };
<ide> var createExamplePage = function(title: ?string, exampleModule: ExampleModule)
<ide> });
<ide> }
<ide> (React: Object).render = originalRender;
<del> (React: Object).renderComponent = originalRenderComponent;
<ide> (ReactNative: Object).render = originalIOSRender;
<del> (ReactNative: Object).renderComponent = originalIOSRenderComponent;
<ide> return (
<ide> <UIExplorerBlock
<ide> key={i} | 4 |
Python | Python | fix tests for changes to inflection structure | 113d53ab6c7ec902a002d8508a28c8aba3faf7a0 | <ide><path>spacy/tests/lang/ja/test_tokenizer.py
<ide> def test_ja_tokenizer_sub_tokens(
<ide> [
<ide> (
<ide> "取ってつけた",
<del> ("五段-ラ行,連用形-促音便", "", "下一段-カ行,連用形-一般", "助動詞-タ,終止形-一般"),
<add> ("五段-ラ行;連用形-促音便", "", "下一段-カ行;連用形-一般", "助動詞-タ;終止形-一般"),
<ide> ("トッ", "テ", "ツケ", "タ"),
<ide> ),
<ide> ],
<ide> def test_ja_tokenizer_inflections_reading_forms(
<ide> ja_tokenizer, text, inflections, reading_forms
<ide> ):
<ide> tokens = ja_tokenizer(text)
<del> test_inflections = [",".join(tt.morph.get("inflection")) for tt in tokens]
<add> test_inflections = [tt.morph.get("inflection")[0] for tt in tokens]
<ide> assert test_inflections == list(inflections)
<ide> test_readings = [tt.morph.get("reading")[0] for tt in tokens]
<ide> assert test_readings == list(reading_forms) | 1 |
Go | Go | mark some test-helpers as helpers | 060e55d7dd8e304631dd2a3c0ab2d571b0054bd3 | <ide><path>integration-cli/check_test.go
<ide> func (s *DockerSwarmSuite) SetUpTest(c *testing.T) {
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) AddDaemon(c *testing.T, joinSwarm, manager bool) *daemon.Daemon {
<add> c.Helper()
<ide> d := daemon.New(c, dockerBinary, dockerdBinary,
<ide> testdaemon.WithEnvironment(testEnv.Execution),
<ide> testdaemon.WithSwarmPort(defaultSwarmPort+s.portIndex),
<ide><path>integration-cli/daemon/daemon.go
<ide> type Daemon struct {
<ide> // This will create a directory such as d123456789 in the folder specified by $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
<ide> // The daemon will not automatically start.
<ide> func New(t testing.TB, dockerBinary string, dockerdBinary string, ops ...daemon.Option) *Daemon {
<add> t.Helper()
<ide> ops = append(ops, daemon.WithDockerdBinary(dockerdBinary))
<ide> d := daemon.New(t, ops...)
<ide> return &Daemon{
<ide> func (d *Daemon) inspectFieldWithError(name, field string) (string, error) {
<ide>
<ide> // CheckActiveContainerCount returns the number of active containers
<ide> // FIXME(vdemeester) should re-use ActivateContainers in some way
<del>func (d *Daemon) CheckActiveContainerCount(c *testing.T) (interface{}, string) {
<add>func (d *Daemon) CheckActiveContainerCount(t *testing.T) (interface{}, string) {
<add> t.Helper()
<ide> out, err := d.Cmd("ps", "-q")
<del> assert.NilError(c, err)
<add> assert.NilError(t, err)
<ide> if len(strings.TrimSpace(out)) == 0 {
<ide> return 0, ""
<ide> } | 2 |
Ruby | Ruby | clarify behavior of json_escape, update examples | 7ce68406934c50a2ce3079bea4fd34936388c26a | <ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb
<ide> def html_escape_once(s)
<ide> # them inside a script tag to avoid XSS vulnerability:
<ide> #
<ide> # <script>
<del> # var currentUser = <%= json_escape current_user.to_json %>;
<add> # var currentUser = <%= raw json_escape(current_user.to_json) %>;
<ide> # </script>
<ide> #
<add> # It is necessary to +raw+ the result of +json_escape+, so that quotation marks
<add> # don't get converted to <tt>"</tt> entities. +json_escape+ doesn't
<add> # automatically flag the result as HTML safe, since the raw value is unsafe to
<add> # use inside HTML attributes.
<add> #
<add> # If you need to output JSON elsewhere in your HTML, you can just do something
<add> # like this, as any unsafe characters (including quotation marks) will be
<add> # automatically escaped for you:
<add> #
<add> # <div data-user-info="<%= current_user.to_json %>">...</div>
<add> #
<ide> # WARNING: this helper only works with valid JSON. Using this on non-JSON values
<ide> # will open up serious XSS vulnerabilities. For example, if you replace the
<ide> # +current_user.to_json+ in the example above with user input instead, the browser
<ide> def html_escape_once(s)
<ide> # is recommended that you always apply this helper (other libraries, such as the
<ide> # JSON gem, do not provide this kind of protection by default; also some gems
<ide> # might override +to_json+ to bypass Active Support's encoder).
<del> #
<del> # The output of this helper method is marked as HTML safe so that you can directly
<del> # include it inside a <tt><script></tt> tag as shown above.
<del> #
<del> # However, it is NOT safe to use the output of this inside an HTML attribute,
<del> # because quotation marks are not escaped. Doing so might break your page's layout.
<del> # If you intend to use this inside an HTML attribute, you should use the
<del> # +html_escape+ helper (or its +h+ alias) instead:
<del> #
<del> # <div data-user-info="<%= h current_user.to_json %>">...</div>
<del> #
<ide> def json_escape(s)
<ide> result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
<ide> s.html_safe? ? result.html_safe : result | 1 |
Javascript | Javascript | prevent viewer from zooming on cmd+mousewheel | 34d3b96b52fe95531b0a4ff14659edabcc6ba9ee | <ide><path>web/viewer.js
<ide> function handleMouseWheel(evt) {
<ide> if (PresentationMode.active) {
<ide> evt.preventDefault();
<ide> PDFViewerApplication.mouseScroll(ticks * MOUSE_WHEEL_DELTA_FACTOR);
<del> } else if (evt.ctrlKey) { // Only zoom the pages, not the entire viewer
<add> } else if (evt.ctrlKey || evt.metaKey) {
<add> // Only zoom the pages, not the entire viewer
<ide> evt.preventDefault();
<ide> PDFViewerApplication[direction](Math.abs(ticks));
<ide> } | 1 |
Javascript | Javascript | add two chars to numbertoidentifier | 6ef9ea8f2778ff6f0209b62424aafc5a317a2ead | <ide><path>lib/Template.js
<ide> const { compareIds } = require("./util/comparators");
<ide> const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
<ide> const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
<ide> const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
<add>const NUMBER_OF_IDENTIFIER_START_CHARS = DELTA_A_TO_Z * 2 + 2; // a-z A-Z _ $
<add>const NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS =
<add> NUMBER_OF_IDENTIFIER_START_CHARS + 10; // a-z A-Z _ $ 0-9
<ide> const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g;
<ide> const INDENT_MULTILINE_REGEX = /^\t/gm;
<ide> const LINE_SEPARATOR_REGEX = /\r?\n/g;
<ide> class Template {
<ide> .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, "");
<ide> }
<ide>
<del> // map number to a single character a-z, A-Z or <_ + number> if number is too big
<add> // map number to a single character a-z, A-Z or mulitple characters if number is too big
<ide> /**
<del> *
<ide> * @param {number} n number to convert to ident
<ide> * @returns {string} returns single character ident
<ide> */
<ide> static numberToIdentifier(n) {
<add> if (n >= NUMBER_OF_IDENTIFIER_START_CHARS) {
<add> // use multiple letters
<add> return (
<add> Template.numberToIdentifier(n % NUMBER_OF_IDENTIFIER_START_CHARS) +
<add> Template.numberToIdentifierContinuation(
<add> Math.floor(n / NUMBER_OF_IDENTIFIER_START_CHARS)
<add> )
<add> );
<add> }
<add>
<ide> // lower case
<ide> if (n < DELTA_A_TO_Z) {
<ide> return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
<ide> }
<add> n -= DELTA_A_TO_Z;
<ide>
<ide> // upper case
<del> if (n < DELTA_A_TO_Z * 2) {
<del> return String.fromCharCode(
<del> START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z
<add> if (n < DELTA_A_TO_Z) {
<add> return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
<add> }
<add>
<add> if (n === DELTA_A_TO_Z) return "_";
<add> return "$";
<add> }
<add>
<add> /**
<add> * @param {number} n number to convert to ident
<add> * @returns {string} returns single character ident
<add> */
<add> static numberToIdentifierContinuation(n) {
<add> if (n >= NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS) {
<add> // use multiple letters
<add> return (
<add> Template.numberToIdentifierContinuation(
<add> n % NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS
<add> ) +
<add> Template.numberToIdentifierContinuation(
<add> Math.floor(n / NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS)
<add> )
<ide> );
<ide> }
<ide>
<del> // use multiple letters
<del> return (
<del> Template.numberToIdentifier(n % (2 * DELTA_A_TO_Z)) +
<del> Template.numberToIdentifier(Math.floor(n / (2 * DELTA_A_TO_Z)))
<del> );
<add> // lower case
<add> if (n < DELTA_A_TO_Z) {
<add> return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
<add> }
<add> n -= DELTA_A_TO_Z;
<add>
<add> // upper case
<add> if (n < DELTA_A_TO_Z) {
<add> return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
<add> }
<add> n -= DELTA_A_TO_Z;
<add>
<add> // numbers
<add> if (n < 10) {
<add> return `${n}`;
<add> }
<add>
<add> if (n === 10) return "_";
<add> return "$";
<ide> }
<ide>
<ide> /**
<ide> class Template {
<ide> }
<ide>
<ide> module.exports = Template;
<add>module.exports.NUMBER_OF_IDENTIFIER_START_CHARS = NUMBER_OF_IDENTIFIER_START_CHARS;
<add>module.exports.NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS = NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS;
<ide><path>lib/optimize/MangleExportsPlugin.js
<ide> "use strict";
<ide>
<ide> const { UsageState } = require("../ModuleGraph");
<del>const { numberToIdentifier } = require("../Template");
<add>const {
<add> numberToIdentifier,
<add> NUMBER_OF_IDENTIFIER_START_CHARS,
<add> NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS
<add>} = require("../Template");
<ide> const { assignDeterministicIds } = require("../ids/IdHelpers");
<ide> const {
<ide> concatComparators,
<ide> const mangleExportsInfo = (exportsInfo, canBeArray) => {
<ide> e.usedName = name;
<ide> return true;
<ide> },
<del> [26, 52],
<del> 52,
<add> [
<add> NUMBER_OF_IDENTIFIER_START_CHARS,
<add> NUMBER_OF_IDENTIFIER_START_CHARS * NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS
<add> ],
<add> NUMBER_OF_IDENTIFIER_CONTINUATION_CHARS,
<ide> usedNames.size
<ide> );
<ide> }; | 2 |
Ruby | Ruby | fix typo s/with/without/ | 8e1b28ad7f33128c8cbea955088950c41ab7c3be | <ide><path>activerecord/test/cases/adapters/postgresql/prepared_statements_test.rb
<ide> class PreparedStatementsTest < ActiveRecord::PostgreSQLTestCase
<ide> fixtures :developers
<ide>
<ide> def setup
<del> @conn = ActiveRecord::Base.establish_connection :arunit_with_prepared_statements
<add> @conn = ActiveRecord::Base.establish_connection :arunit_without_prepared_statements
<ide> end
<ide>
<ide> def teardown
<ide><path>activerecord/test/support/config.rb
<ide> def read_config
<ide> def expand_config(config)
<ide> config["connections"].each do |adapter, connection|
<ide> dbs = [["arunit", "activerecord_unittest"], ["arunit2", "activerecord_unittest2"],
<del> ["arunit_with_prepared_statements", "activerecord_unittest"]]
<add> ["arunit_without_prepared_statements", "activerecord_unittest"]]
<ide> dbs.each do |name, dbname|
<ide> unless connection[name].is_a?(Hash)
<ide> connection[name] = { "database" => connection[name] } | 2 |
Ruby | Ruby | add helper methods to token class | f2112d67618fdff48dc6bba410c08e337f81774b | <ide><path>Library/Homebrew/version.rb
<ide> def inspect
<ide> "#<#{self.class.name} #{value.inspect}>"
<ide> end
<ide>
<add> def hash
<add> value.hash
<add> end
<add>
<add> def to_f
<add> value.to_f
<add> end
<add>
<add> def to_i
<add> value.to_i
<add> end
<add>
<ide> def to_s
<ide> value.to_s
<ide> end
<ide> def <=>(other)
<ide> end
<ide> end
<ide>
<add> def null?
<add> true
<add> end
<add>
<ide> def inspect
<ide> "#<#{self.class.name}>"
<ide> end | 1 |
Javascript | Javascript | fuuuu our require() sux | bbc4779f4d61c7fce2f9e14e0155ff0cdb3d749d | <ide><path>vendor/underscore.js
<ide> // Export the Underscore object for **Node.js** and **"CommonJS"**, with
<ide> // backwards-compatibility for the old `require()` API. If we're not in
<ide> // CommonJS, add `_` to the global object.
<del> if (typeof exports !== 'undefined') {
<del> if (typeof module !== 'undefined' && module.exports) {
<del> exports = module.exports = _;
<del> }
<del> exports._ = _;
<del> } else if (typeof define === 'function' && define.amd) {
<del> // Register as a named module with AMD.
<del> define('underscore', function() {
<del> return _;
<del> });
<del> } else {
<del> // Exported as a string, for Closure Compiler "advanced" mode.
<del> root['_'] = _;
<del> }
<add> module.exports = _;
<ide>
<ide> // Current version.
<ide> _.VERSION = '1.2.2'; | 1 |
Javascript | Javascript | use commands to send focus and blur to textinput | 7a8e10dac83b6a43e4cea7e92df0dcfbcf3ad3ac | <ide><path>Libraries/Components/TextInput/RCTMultilineTextInputNativeComponent.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<add>import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<add>import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<add>import * as React from 'react';
<add>
<add>type NativeType = HostComponent<mixed>;
<add>
<add>interface NativeCommands {
<add> +focus: (viewRef: React.ElementRef<NativeType>) => void;
<add> +blur: (viewRef: React.ElementRef<NativeType>) => void;
<add>}
<add>
<add>export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
<add> supportedCommands: ['focus', 'blur'],
<add>});
<add>
<add>const SinglelineTextInputNativeComponent: HostComponent<mixed> = requireNativeComponent<mixed>(
<add> 'RCTMultilineTextInputView',
<add>);
<add>
<add>export default SinglelineTextInputNativeComponent;
<ide><path>Libraries/Components/TextInput/RCTSingelineTextInputNativeComponent.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {HostComponent} from '../../Renderer/shims/ReactNativeTypes';
<add>import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<add>import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<add>import * as React from 'react';
<add>
<add>type NativeType = HostComponent<mixed>;
<add>
<add>interface NativeCommands {
<add> +focus: (viewRef: React.ElementRef<NativeType>) => void;
<add> +blur: (viewRef: React.ElementRef<NativeType>) => void;
<add>}
<add>
<add>export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
<add> supportedCommands: ['focus', 'blur'],
<add>});
<add>
<add>const SinglelineTextInputNativeComponent: HostComponent<mixed> = requireNativeComponent<mixed>(
<add> 'RCTSinglelineTextInputView',
<add>);
<add>
<add>export default SinglelineTextInputNativeComponent;
<ide><path>Libraries/Components/TextInput/TextInput.js
<ide> let RCTSinglelineTextInputView;
<ide> if (Platform.OS === 'android') {
<ide> AndroidTextInput = require('./AndroidTextInputNativeComponent').default;
<ide> } else if (Platform.OS === 'ios') {
<del> RCTMultilineTextInputView = requireNativeComponent(
<del> 'RCTMultilineTextInputView',
<del> );
<del> RCTSinglelineTextInputView = requireNativeComponent(
<del> 'RCTSinglelineTextInputView',
<del> );
<add> RCTMultilineTextInputView = require('./RCTMultilineTextInputNativeComponent.js')
<add> .default;
<add> RCTSinglelineTextInputView = require('./RCTSingelineTextInputNativeComponent.js')
<add> .default;
<ide> }
<ide>
<ide> export type ChangeEvent = SyntheticEvent< | 3 |
Python | Python | fix reference to xlnet | fcdb85e9d2da979d368ed5b8f7350cfe9b6a7d69 | <ide><path>src/transformers/training_args.py
<ide> class TrainingArguments:
<ide> Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the
<ide> main process.
<ide> past_index (:obj:`int`, `optional`, defaults to -1):
<del> Some models like :doc:`TransformerXL <../model_doc/transformerxl>` or :doc`XLNet <../model_doc/xlnet>` can
<add> Some models like :doc:`TransformerXL <../model_doc/transformerxl>` or :doc:`XLNet <../model_doc/xlnet>` can
<ide> make use of the past hidden states for their predictions. If this argument is set to a positive int, the
<ide> ``Trainer`` will use the corresponding output (usually index 2) as the past state and feed it to the model
<ide> at the next training step under the keyword argument ``mems``. | 1 |
PHP | PHP | remove extra line | 3e2cd1dd40668c4e35ed5358e1f4dc4ffcf8ce99 | <ide><path>src/Illuminate/Cache/CacheManager.php
<ide> <?php namespace Illuminate\Cache;
<ide>
<del>
<ide> use Closure;
<ide> use Illuminate\Support\Manager;
<ide> | 1 |
Go | Go | use correct platform matcher for containerd | fcc42d56828f5a1f0068247cdcefc25c47965885 | <ide><path>distribution/pull_v2_unix.go
<ide> package distribution // import "github.com/docker/docker/distribution"
<ide>
<ide> import (
<ide> "context"
<add> "sort"
<ide>
<ide> "github.com/containerd/containerd/platforms"
<ide> "github.com/docker/distribution"
<ide> func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekClo
<ide>
<ide> func filterManifests(manifests []manifestlist.ManifestDescriptor, p specs.Platform) []manifestlist.ManifestDescriptor {
<ide> p = platforms.Normalize(withDefault(p))
<del> m := platforms.NewMatcher(p)
<add> m := platforms.Only(p)
<ide> var matches []manifestlist.ManifestDescriptor
<ide> for _, desc := range manifests {
<ide> if m.Match(toOCIPlatform(desc.Platform)) {
<ide> func filterManifests(manifests []manifestlist.ManifestDescriptor, p specs.Platfo
<ide> }
<ide> }
<ide>
<add> sort.SliceStable(matches, func(i, j int) bool {
<add> return m.Less(toOCIPlatform(matches[i].Platform), toOCIPlatform(matches[j].Platform))
<add> })
<add>
<ide> // deprecated: backwards compatibility with older versions that didn't compare variant
<ide> if len(matches) == 0 && p.Architecture == "arm" {
<ide> p = platforms.Normalize(p) | 1 |
Text | Text | fix mixin class name in viewsets docs example | 77dd334026cb2f8a45b817c4577f5d5ea6a2671a | <ide><path>docs/api-guide/viewsets.md
<ide> You may need to provide custom `ViewSet` classes that do not have the full set o
<ide>
<ide> To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions:
<ide>
<del> class CreateListRetrieveViewSet(mixins.CreateMixin,
<del> mixins.ListMixin,
<del> mixins.RetrieveMixin,
<add> class CreateListRetrieveViewSet(mixins.CreateModelMixin,
<add> mixins.ListModelMixin,
<add> mixins.RetrieveModelMixin,
<ide> viewsets.GenericViewSet):
<ide> """
<ide> A viewset that provides `retrieve`, `update`, and `list` actions. | 1 |
Go | Go | add two configurable options to awslogs driver | 512ac778bfe9743848c71318c9e6785a78307155 | <ide><path>daemon/logger/awslogs/cloudwatchlogs.go
<ide> const (
<ide> datetimeFormatKey = "awslogs-datetime-format"
<ide> multilinePatternKey = "awslogs-multiline-pattern"
<ide> credentialsEndpointKey = "awslogs-credentials-endpoint"
<del> batchPublishFrequency = 5 * time.Second
<add> forceFlushIntervalKey = "awslogs-force-flush-interval-seconds"
<add> maxBufferedEventsKey = "awslogs-max-buffered-events"
<add>
<add> defaultForceFlushInterval = 5 * time.Second
<add> defaultMaxBufferedEvents = 4096
<ide>
<ide> // See: http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_PutLogEvents.html
<ide> perEventBytes = 26
<ide> const (
<ide> )
<ide>
<ide> type logStream struct {
<del> logStreamName string
<del> logGroupName string
<del> logCreateGroup bool
<del> logNonBlocking bool
<del> multilinePattern *regexp.Regexp
<del> client api
<del> messages chan *logger.Message
<del> lock sync.RWMutex
<del> closed bool
<del> sequenceToken *string
<add> logStreamName string
<add> logGroupName string
<add> logCreateGroup bool
<add> logNonBlocking bool
<add> forceFlushInterval time.Duration
<add> multilinePattern *regexp.Regexp
<add> client api
<add> messages chan *logger.Message
<add> lock sync.RWMutex
<add> closed bool
<add> sequenceToken *string
<ide> }
<ide>
<ide> var _ logger.SizedLogger = &logStream{}
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide>
<ide> logNonBlocking := info.Config["mode"] == "non-blocking"
<ide>
<add> forceFlushInterval := defaultForceFlushInterval
<add> if info.Config[forceFlushIntervalKey] != "" {
<add> forceFlushIntervalAsInt, err := strconv.Atoi(info.Config[forceFlushIntervalKey])
<add> if err != nil {
<add> return nil, err
<add> }
<add> forceFlushInterval = time.Duration(forceFlushIntervalAsInt) * time.Second
<add> }
<add>
<add> maxBufferedEvents := int(defaultMaxBufferedEvents)
<add> if info.Config[maxBufferedEventsKey] != "" {
<add> maxBufferedEvents, err = strconv.Atoi(info.Config[maxBufferedEventsKey])
<add> if err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<ide> if info.Config[logStreamKey] != "" {
<ide> logStreamName = info.Config[logStreamKey]
<ide> }
<ide> func New(info logger.Info) (logger.Logger, error) {
<ide> }
<ide>
<ide> containerStream := &logStream{
<del> logStreamName: logStreamName,
<del> logGroupName: logGroupName,
<del> logCreateGroup: logCreateGroup,
<del> logNonBlocking: logNonBlocking,
<del> multilinePattern: multilinePattern,
<del> client: client,
<del> messages: make(chan *logger.Message, 4096),
<add> logStreamName: logStreamName,
<add> logGroupName: logGroupName,
<add> logCreateGroup: logCreateGroup,
<add> logNonBlocking: logNonBlocking,
<add> forceFlushInterval: forceFlushInterval,
<add> multilinePattern: multilinePattern,
<add> client: client,
<add> messages: make(chan *logger.Message, maxBufferedEvents),
<ide> }
<ide>
<ide> creationDone := make(chan bool)
<ide> var newTicker = func(freq time.Duration) *time.Ticker {
<ide> func (l *logStream) collectBatch(created chan bool) {
<ide> // Wait for the logstream/group to be created
<ide> <-created
<del> ticker := newTicker(batchPublishFrequency)
<add> flushInterval := l.forceFlushInterval
<add> if flushInterval <= 0 {
<add> flushInterval = defaultForceFlushInterval
<add> }
<add> ticker := newTicker(flushInterval)
<ide> var eventBuffer []byte
<ide> var eventBufferTimestamp int64
<ide> var batch = newEventBatch()
<ide> func (l *logStream) collectBatch(created chan bool) {
<ide> // If event buffer is older than batch publish frequency flush the event buffer
<ide> if eventBufferTimestamp > 0 && len(eventBuffer) > 0 {
<ide> eventBufferAge := t.UnixNano()/int64(time.Millisecond) - eventBufferTimestamp
<del> eventBufferExpired := eventBufferAge >= int64(batchPublishFrequency)/int64(time.Millisecond)
<add> eventBufferExpired := eventBufferAge >= int64(flushInterval)/int64(time.Millisecond)
<ide> eventBufferNegative := eventBufferAge < 0
<ide> if eventBufferExpired || eventBufferNegative {
<ide> l.processEvent(batch, eventBuffer, eventBufferTimestamp)
<ide> func ValidateLogOpt(cfg map[string]string) error {
<ide> case datetimeFormatKey:
<ide> case multilinePatternKey:
<ide> case credentialsEndpointKey:
<add> case forceFlushIntervalKey:
<add> case maxBufferedEventsKey:
<ide> default:
<ide> return fmt.Errorf("unknown log opt '%s' for %s log driver", key, name)
<ide> }
<ide> func ValidateLogOpt(cfg map[string]string) error {
<ide> return fmt.Errorf("must specify valid value for log opt '%s': %v", logCreateGroupKey, err)
<ide> }
<ide> }
<add> if cfg[forceFlushIntervalKey] != "" {
<add> if value, err := strconv.Atoi(cfg[forceFlushIntervalKey]); err != nil || value <= 0 {
<add> return fmt.Errorf("must specify a positive integer for log opt '%s': %v", forceFlushIntervalKey, cfg[forceFlushIntervalKey])
<add> }
<add> }
<add> if cfg[maxBufferedEventsKey] != "" {
<add> if value, err := strconv.Atoi(cfg[maxBufferedEventsKey]); err != nil || value <= 0 {
<add> return fmt.Errorf("must specify a positive integer for log opt '%s': %v", maxBufferedEventsKey, cfg[maxBufferedEventsKey])
<add> }
<add> }
<ide> _, datetimeFormatKeyExists := cfg[datetimeFormatKey]
<ide> _, multilinePatternKeyExists := cfg[multilinePatternKey]
<ide> if datetimeFormatKeyExists && multilinePatternKeyExists {
<ide><path>daemon/logger/awslogs/cloudwatchlogs_test.go
<ide> func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) {
<ide> Timestamp: time.Now().Add(time.Second),
<ide> })
<ide>
<del> // Fire ticker batchPublishFrequency seconds later
<del> ticks <- time.Now().Add(batchPublishFrequency + time.Second)
<add> // Fire ticker defaultForceFlushInterval seconds later
<add> ticks <- time.Now().Add(defaultForceFlushInterval + time.Second)
<ide>
<del> // Verify single multiline event is flushed after maximum event buffer age (batchPublishFrequency)
<add> // Verify single multiline event is flushed after maximum event buffer age (defaultForceFlushInterval)
<ide> argument := <-mockClient.putLogEventsArgument
<ide> assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
<ide> assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
<ide> func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) {
<ide> Timestamp: time.Now().Add(time.Second),
<ide> })
<ide>
<del> // Fire ticker another batchPublishFrequency seconds later
<del> ticks <- time.Now().Add(2*batchPublishFrequency + time.Second)
<add> // Fire ticker another defaultForceFlushInterval seconds later
<add> ticks <- time.Now().Add(2*defaultForceFlushInterval + time.Second)
<ide>
<ide> // Verify the event buffer is truly flushed - we should only receive a single event
<ide> argument = <-mockClient.putLogEventsArgument
<ide> func TestCollectBatchMultilinePatternMaxEventSize(t *testing.T) {
<ide> })
<ide>
<ide> // Fire ticker
<del> ticks <- time.Now().Add(batchPublishFrequency)
<add> ticks <- time.Now().Add(defaultForceFlushInterval)
<ide>
<ide> // Verify multiline events
<ide> // We expect a maximum sized event with no new line characters and a
<ide> func TestValidateLogOptionsDatetimeFormatAndMultilinePattern(t *testing.T) {
<ide> assert.Check(t, is.Equal(err.Error(), conflictingLogOptionsError), "Received invalid error")
<ide> }
<ide>
<add>func TestValidateLogOptionsForceFlushIntervalSeconds(t *testing.T) {
<add> cfg := map[string]string{
<add> forceFlushIntervalKey: "0",
<add> logGroupKey: groupName,
<add> }
<add> nonPositiveIntegerLogOptionsError := "must specify a positive integer for log opt 'awslogs-force-flush-interval-seconds': 0"
<add>
<add> err := ValidateLogOpt(cfg)
<add> assert.Check(t, err != nil, "Expected an error")
<add> assert.Check(t, is.Equal(err.Error(), nonPositiveIntegerLogOptionsError), "Received invalid error")
<add>
<add> cfg[forceFlushIntervalKey] = "-1"
<add> nonPositiveIntegerLogOptionsError = "must specify a positive integer for log opt 'awslogs-force-flush-interval-seconds': -1"
<add>
<add> err = ValidateLogOpt(cfg)
<add> assert.Check(t, err != nil, "Expected an error")
<add> assert.Check(t, is.Equal(err.Error(), nonPositiveIntegerLogOptionsError), "Received invalid error")
<add>
<add> cfg[forceFlushIntervalKey] = "a"
<add> nonPositiveIntegerLogOptionsError = "must specify a positive integer for log opt 'awslogs-force-flush-interval-seconds': a"
<add>
<add> err = ValidateLogOpt(cfg)
<add> assert.Check(t, err != nil, "Expected an error")
<add> assert.Check(t, is.Equal(err.Error(), nonPositiveIntegerLogOptionsError), "Received invalid error")
<add>
<add> cfg[forceFlushIntervalKey] = "10"
<add>
<add> err = ValidateLogOpt(cfg)
<add> assert.Check(t, err == nil, "Unexpected error")
<add>}
<add>
<add>func TestValidateLogOptionsMaxBufferedEvents(t *testing.T) {
<add> cfg := map[string]string{
<add> maxBufferedEventsKey: "0",
<add> logGroupKey: groupName,
<add> }
<add> nonPositiveIntegerLogOptionsError := "must specify a positive integer for log opt 'awslogs-max-buffered-events': 0"
<add>
<add> err := ValidateLogOpt(cfg)
<add> assert.Check(t, err != nil, "Expected an error")
<add> assert.Check(t, is.Equal(err.Error(), nonPositiveIntegerLogOptionsError), "Received invalid error")
<add>
<add> cfg[maxBufferedEventsKey] = "-1"
<add> nonPositiveIntegerLogOptionsError = "must specify a positive integer for log opt 'awslogs-max-buffered-events': -1"
<add>
<add> err = ValidateLogOpt(cfg)
<add> assert.Check(t, err != nil, "Expected an error")
<add> assert.Check(t, is.Equal(err.Error(), nonPositiveIntegerLogOptionsError), "Received invalid error")
<add>
<add> cfg[maxBufferedEventsKey] = "a"
<add> nonPositiveIntegerLogOptionsError = "must specify a positive integer for log opt 'awslogs-max-buffered-events': a"
<add>
<add> err = ValidateLogOpt(cfg)
<add> assert.Check(t, err != nil, "Expected an error")
<add> assert.Check(t, is.Equal(err.Error(), nonPositiveIntegerLogOptionsError), "Received invalid error")
<add>
<add> cfg[maxBufferedEventsKey] = "10"
<add>
<add> err = ValidateLogOpt(cfg)
<add> assert.Check(t, err == nil, "Unexpected error")
<add>}
<add>
<ide> func TestCreateTagSuccess(t *testing.T) {
<ide> mockClient := newMockClient()
<ide> info := logger.Info{ | 2 |
Go | Go | add more native driver options | 83618c2b81c561cd77fd70eca90b2b251f61fcc1 | <ide><path>runtime/execdriver/native/configuration/parse.go
<ide> import (
<ide> "github.com/dotcloud/docker/pkg/libcontainer"
<ide> "os/exec"
<ide> "path/filepath"
<add> "strconv"
<ide> "strings"
<ide> )
<ide>
<ide> type Action func(*libcontainer.Container, interface{}, string) error
<ide>
<ide> var actions = map[string]Action{
<del> "cap.add": addCap,
<del> "cap.drop": dropCap,
<del> "fs.readonly": readonlyFs,
<del> "ns.add": addNamespace,
<del> "ns.drop": dropNamespace,
<del> "net.join": joinNetNamespace,
<add> "cap.add": addCap, // add a cap
<add> "cap.drop": dropCap, // drop a cap
<add>
<add> "ns.add": addNamespace, // add a namespace
<add> "ns.drop": dropNamespace, // drop a namespace when cloning
<add>
<add> "net.join": joinNetNamespace, // join another containers net namespace
<add> // "net.veth.mac": vethMacAddress, // set the mac address for the veth
<add>
<add> "cgroups.cpu_shares": cpuShares, // set the cpu shares
<add> "cgroups.memory": memory, // set the memory limit
<add> "cgroups.memory_swap": memorySwap, // set the memory swap limit
<add>
<add> "apparmor_profile": apparmorProfile, // set the apparmor profile to apply
<add>
<add> "fs.readonly": readonlyFs, // make the rootfs of the container read only
<add>}
<add>
<add>func apparmorProfile(container *libcontainer.Container, context interface{}, value string) error {
<add> container.Context["apparmor_profile"] = value
<add> return nil
<add>}
<add>
<add>func cpuShares(container *libcontainer.Container, context interface{}, value string) error {
<add> if container.Cgroups == nil {
<add> return fmt.Errorf("cannot set cgroups when they are disabled")
<add> }
<add> v, err := strconv.ParseInt(value, 0, 64)
<add> if err != nil {
<add> return err
<add> }
<add> container.Cgroups.CpuShares = v
<add> return nil
<add>}
<add>
<add>func memory(container *libcontainer.Container, context interface{}, value string) error {
<add> if container.Cgroups == nil {
<add> return fmt.Errorf("cannot set cgroups when they are disabled")
<add> }
<add> v, err := strconv.ParseInt(value, 0, 64)
<add> if err != nil {
<add> return err
<add> }
<add> container.Cgroups.Memory = v
<add> return nil
<add>}
<add>
<add>func memorySwap(container *libcontainer.Container, context interface{}, value string) error {
<add> if container.Cgroups == nil {
<add> return fmt.Errorf("cannot set cgroups when they are disabled")
<add> }
<add> v, err := strconv.ParseInt(value, 0, 64)
<add> if err != nil {
<add> return err
<add> }
<add> container.Cgroups.MemorySwap = v
<add> return nil
<ide> }
<ide>
<ide> func addCap(container *libcontainer.Container, context interface{}, value string) error {
<ide> func joinNetNamespace(container *libcontainer.Container, context interface{}, va
<ide> return nil
<ide> }
<ide>
<add>func vethMacAddress(container *libcontainer.Container, context interface{}, value string) error {
<add> var veth *libcontainer.Network
<add>
<add> for _, network := range container.Networks {
<add> if network.Type == "veth" {
<add> veth = network
<add> break
<add> }
<add> }
<add> if veth == nil {
<add> return fmt.Errorf("not veth configured for container")
<add> }
<add> veth.Context["mac"] = value
<add> return nil
<add>}
<add>
<ide> // configureCustomOptions takes string commands from the user and allows modification of the
<ide> // container's default configuration.
<ide> // | 1 |
Java | Java | fix checkstyle violation | 4f4b9f6b1ba80175c174f328f36f3720667fbdd9 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.java
<ide> public String encodeURL(String url) {
<ide> }
<ide>
<ide>
<add> /**
<add> * Runtime exception to get far enough (to ResourceUrlProviderExposingInterceptor)
<add> * where it can be re-thrown as ServletRequestBindingException to result in
<add> * a 400 response.
<add> */
<ide> @SuppressWarnings("serial")
<ide> static class LookupPathIndexException extends IllegalArgumentException {
<ide> | 1 |
Ruby | Ruby | calculate types on construction | f4767bc8448d3d606149618cb279234dfcf803e7 | <ide><path>activerecord/lib/active_record/reflection.rb
<ide> def klass
<ide> @klass ||= active_record.send(:compute_type, class_name)
<ide> end
<ide>
<add> attr_reader :type, :foreign_type
<add>
<ide> def initialize(*args)
<ide> super
<ide> @collection = [:has_many, :has_and_belongs_to_many].include?(macro)
<ide> @automatic_inverse_of = nil
<add> @type = options[:as] && "#{options[:as]}_type"
<add> @foreign_type = options[:foreign_type] || "#{name}_type"
<ide> end
<ide>
<ide> # Returns a new, unsaved instance of the associated class. +attributes+ will
<ide> def foreign_key
<ide> @foreign_key ||= options[:foreign_key] || derive_foreign_key
<ide> end
<ide>
<del> def foreign_type
<del> @foreign_type ||= options[:foreign_type] || "#{name}_type"
<del> end
<del>
<del> def type
<del> @type ||= options[:as] && "#{options[:as]}_type"
<del> end
<del>
<ide> def primary_key_column
<ide> klass.columns_hash[klass.primary_key]
<ide> end | 1 |
Python | Python | update run_ner.py with id2label config | 82a2b76c950deb0cf7e7d8ba75ea2ad1ae089503 | <ide><path>examples/pytorch/token-classification/run_ner.py
<ide> def get_label_list(labels):
<ide> config = AutoConfig.from_pretrained(
<ide> model_args.config_name if model_args.config_name else model_args.model_name_or_path,
<ide> num_labels=num_labels,
<add> label2id=label_to_id,
<add> id2label={i: l for l, i in label_to_id.items()},
<ide> finetuning_task=data_args.task_name,
<ide> cache_dir=model_args.cache_dir,
<ide> revision=model_args.model_revision, | 1 |
Python | Python | add trailing slashes for hub api client | 03af9a0aa9384cd86215bdf1918da96828fb22aa | <ide><path>libcloud/container/utils/docker.py
<ide> def get_repository(self, repository_name, namespace='library'):
<ide> :return: The details of the repository
<ide> :rtype: ``object``
<ide> """
<del> path = '/v2/repositories/%s/%s' % (namespace, repository_name)
<add> path = '/v2/repositories/%s/%s/' % (namespace, repository_name)
<ide> response = self.connection.request(path)
<ide> return response.object
<ide>
<ide> def get_image(self, repository_name, tag='latest', namespace='library'):
<ide> :return: A container image
<ide> :rtype: :class:`libcloud.container.base.ContainerImage`
<ide> """
<del> path = '/v2/repositories/%s/%s/tags/%s' \
<add> path = '/v2/repositories/%s/%s/tags/%s/' \
<ide> % (namespace, repository_name, tag)
<ide> response = self.connection.request(path)
<ide> return self._to_image(repository_name, response.object) | 1 |
Ruby | Ruby | set timeout to 10 seconds instead of retrying | cc634b2d50cc0e8c1e8a38196f4bcdad4e0a69b6 | <ide><path>Library/Homebrew/cask/lib/hbc/system_command.rb
<ide> def write_input_to(raw_stdin)
<ide> end
<ide>
<ide> def each_line_from(sources)
<del> tries = 3
<del>
<ide> loop do
<del> selected_sources = IO.select(sources, [], [], 1)
<add> selected_sources = IO.select(sources, [], [], 10)
<ide>
<del> if selected_sources.nil?
<del> next unless (tries -= 1).zero?
<del> odebug "IO#select failed, skipping line."
<del> break
<del> end
<add> break if selected_sources.nil?
<ide>
<ide> readable_sources = selected_sources[0].delete_if(&:eof?)
<ide> | 1 |
Python | Python | add tests np.meshgrid for higher dimensional grids | 3cdb33f02298c3544f7a3bc312c42422a2a7b971 | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_simple(self):
<ide> [0.64864341, 0.79115165, 0.96098397]]))
<ide>
<ide>
<add># Run test using: python3 runtests.py -t numpy.lib.tests.test_function_base
<ide> class TestMeshgrid:
<ide>
<ide> def test_simple(self):
<ide> def test_writeback(self):
<ide> assert_equal(x[0, :], 0)
<ide> assert_equal(x[1, :], X)
<ide>
<add> def test_higher_dimensions(self):
<add> a, b, c = np.meshgrid([0], [1, 1], [2, 2])
<add> assert_equal(a, [[[0, 0]], [[0, 0]]])
<add> assert_equal(b, [[[1, 1]], [[1, 1]]])
<add> assert_equal(c, [[[2, 2]], [[2, 2]]])
<add>
<add> a, b, c, d, e = np.meshgrid(*([0] * i for i in range(1, 6)))
<add> expected_shape = (2, 1, 3, 4, 5)
<add> assert_equal(a.shape, expected_shape)
<add> assert_equal(b.shape, expected_shape)
<add> assert_equal(c.shape, expected_shape)
<add> assert_equal(d.shape, expected_shape)
<add> assert_equal(e.shape, expected_shape)
<add>
<ide>
<ide> class TestPiecewise:
<ide> | 1 |
Python | Python | parametrize ufunc generic loop tests | b1622aceb4cb39bdd71ed958f3d86c55d7ca7cb0 | <ide><path>numpy/core/tests/test_ufunc.py
<ide> def test_extobj_refcount(self):
<ide> assert_raises(TypeError, np.add, 1, 2, extobj=[4096], parrot=True)
<ide>
<ide>
<add>class TestUfuncGenericLoops(object):
<add> """Test generic loops.
<add>
<add> The loops to be tested are:
<add>
<add> PyUFunc_ff_f_As_dd_d
<add> PyUFunc_ff_f
<add> PyUFunc_dd_d
<add> PyUFunc_gg_g
<add> PyUFunc_FF_F_As_DD_D
<add> PyUFunc_DD_D
<add> PyUFunc_FF_F
<add> PyUFunc_GG_G
<add> PyUFunc_OO_O
<add> PyUFunc_OO_O_method
<add> PyUFunc_f_f_As_d_d
<add> PyUFunc_d_d
<add> PyUFunc_f_f
<add> PyUFunc_g_g
<add> PyUFunc_F_F_As_D_D
<add> PyUFunc_F_F
<add> PyUFunc_D_D
<add> PyUFunc_G_G
<add> PyUFunc_O_O
<add> PyUFunc_O_O_method
<add> PyUFunc_On_Om
<add>
<add> Where:
<add>
<add> f -- float
<add> d -- double
<add> g -- long double
<add> F -- complex float
<add> D -- complex double
<add> G -- complex long double
<add> O -- python object
<add>
<add> It is difficult to assure that each of these loops is entered from the
<add> Python level as the special cased loops are a moving target and the
<add> corresponding types are architecture dependent. We probably need to
<add> define C level testing ufuncs to get at them. For the time being, I've
<add> just looked at the signatures registered in the build directory to find
<add> relevant functions.
<add>
<add> """
<add> np_dtypes = [
<add> (np.single, np.single), (np.single, np.double),
<add> (np.csingle, np.csingle), (np.csingle, np.cdouble),
<add> (np.double, np.double), (np.longdouble, np.longdouble),
<add> (np.cdouble, np.cdouble), (np.clongdouble, np.clongdouble)]
<add>
<add> @pytest.mark.parametrize('input_dtype,output_dtype', np_dtypes)
<add> def test_unary_PyUFunc(self, input_dtype, output_dtype, f=np.exp, x=0, y=1):
<add> xs = np.full(10, input_dtype(x), dtype=output_dtype)
<add> assert_almost_equal(f(xs), y)
<add>
<add> def f2(x, y):
<add> return x**y
<add>
<add> @pytest.mark.parametrize('input_dtype,output_dtype', np_dtypes)
<add> def test_binary_PyUFunc(self, input_dtype, output_dtype, f=f2, x=0, y=1):
<add> xs = np.full(10, input_dtype(x), dtype=output_dtype)
<add> assert_almost_equal(f(xs, xs), y)
<add>
<add> # class to use in testing object method loops
<add> class foo(object):
<add> def conjugate(self):
<add> return np.bool_(1)
<add>
<add> def logical_xor(self, obj):
<add> return np.bool_(1)
<add>
<add> def test_unary_PyUFunc_O_O(self):
<add> x = np.ones(10, dtype=object)
<add> assert_(np.all(np.abs(x) == 1))
<add>
<add> def test_unary_PyUFunc_O_O_method(self, foo=foo):
<add> x = np.full(10, foo(), dtype=object)
<add> assert_(np.all(np.conjugate(x) == True))
<add>
<add> def test_binary_PyUFunc_OO_O(self):
<add> x = np.ones(10, dtype=object)
<add> assert_(np.all(np.add(x, x) == 2))
<add>
<add> def test_binary_PyUFunc_OO_O_method(self, foo=foo):
<add> x = np.full(10, foo(), dtype=object)
<add> assert_(np.all(np.logical_xor(x, x)))
<add>
<add> def test_binary_PyUFunc_On_Om_method(self, foo=foo):
<add> x = np.full((10, 2, 3), foo(), dtype=object)
<add> assert_(np.all(np.logical_xor(x, x)))
<add>
<add>
<ide> class TestUfunc(object):
<ide> def test_pickle(self):
<ide> for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
<ide> def test_reduceat_shifting_sum(self):
<ide> idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel()
<ide> assert_array_equal(np.add.reduceat(x, idx)[::2], [1, 3, 5, 7])
<ide>
<del> def test_generic_loops(self):
<del> """Test generic loops.
<del>
<del> The loops to be tested are:
<del>
<del> PyUFunc_ff_f_As_dd_d
<del> PyUFunc_ff_f
<del> PyUFunc_dd_d
<del> PyUFunc_gg_g
<del> PyUFunc_FF_F_As_DD_D
<del> PyUFunc_DD_D
<del> PyUFunc_FF_F
<del> PyUFunc_GG_G
<del> PyUFunc_OO_O
<del> PyUFunc_OO_O_method
<del> PyUFunc_f_f_As_d_d
<del> PyUFunc_d_d
<del> PyUFunc_f_f
<del> PyUFunc_g_g
<del> PyUFunc_F_F_As_D_D
<del> PyUFunc_F_F
<del> PyUFunc_D_D
<del> PyUFunc_G_G
<del> PyUFunc_O_O
<del> PyUFunc_O_O_method
<del> PyUFunc_On_Om
<del>
<del> Where:
<del>
<del> f -- float
<del> d -- double
<del> g -- long double
<del> F -- complex float
<del> D -- complex double
<del> G -- complex long double
<del> O -- python object
<del>
<del> It is difficult to assure that each of these loops is entered from the
<del> Python level as the special cased loops are a moving target and the
<del> corresponding types are architecture dependent. We probably need to
<del> define C level testing ufuncs to get at them. For the time being, I've
<del> just looked at the signatures registered in the build directory to find
<del> relevant functions.
<del>
<del> """
<del> fone = np.exp
<del> ftwo = lambda x, y: x**y
<del> fone_val = 1
<del> ftwo_val = 1
<del>
<del> # check unary PyUFunc_f_f_As_d_d
<del> msg = "PyUFunc_f_f_As_d_d"
<del> x = np.full(10, np.single(0), dtype=np.double)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_F_F_As_D_D
<del> msg = "PyUFunc_F_F_As_D_D"
<del> x = np.full(10, np.csingle(0), dtype=np.cdouble)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_f_f.
<del> msg = "PyUFunc_f_f"
<del> x = np.zeros(10, dtype=np.single)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_d_d.
<del> msg = "PyUFunc_d_d"
<del> x = np.zeros(10, dtype=np.double)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_g_g.
<del> msg = "PyUFunc_g_g"
<del> x = np.zeros(10, dtype=np.longdouble)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_F_F.
<del> msg = "PyUFunc_F_F"
<del> x = np.zeros(10, dtype=np.csingle)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_D_D.
<del> msg = "PyUFunc_D_D"
<del> x = np.zeros(10, dtype=np.cdouble)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del> # check unary PyUFunc_G_G.
<del> msg = "PyUFunc_G_G"
<del> x = np.zeros(10, dtype=np.clongdouble)
<del> assert_almost_equal(fone(x), fone_val, err_msg=msg)
<del>
<del> # check binary PyUFunc_FF_F_As_DD_D
<del> msg = "PyUFunc_FF_F_As_DD_D"
<del> x = np.full(10, np.csingle(1), dtype=np.cdouble)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_ff_f_As_dd_d
<del> msg = "PyUFunc_ff_f_As_dd_d"
<del> x = np.full(10, np.single(1), dtype=np.double)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_ff_f.
<del> msg = "PyUFunc_ff_f"
<del> x = np.ones(10, dtype=np.single)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_dd_d.
<del> msg = "PyUFunc_dd_d"
<del> x = np.ones(10, dtype=np.double)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_gg_g.
<del> msg = "PyUFunc_gg_g"
<del> x = np.ones(10, dtype=np.longdouble)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_FF_F.
<del> msg = "PyUFunc_FF_F"
<del> x = np.ones(10, dtype=np.csingle)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_DD_D.
<del> msg = "PyUFunc_DD_D"
<del> x = np.ones(10, dtype=np.cdouble)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del> # check binary PyUFunc_GG_G.
<del> msg = "PyUFunc_GG_G"
<del> x = np.ones(10, dtype=np.clongdouble)
<del> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg)
<del>
<del> # class to use in testing object method loops
<del> class foo(object):
<del> def conjugate(self):
<del> return np.bool_(1)
<del>
<del> def logical_xor(self, obj):
<del> return np.bool_(1)
<del>
<del> # check unary PyUFunc_O_O
<del> msg = "PyUFunc_O_O"
<del> x = np.ones(10, dtype=object)
<del> assert_(np.all(np.abs(x) == 1), msg)
<del> # check unary PyUFunc_O_O_method
<del> msg = "PyUFunc_O_O_method"
<del> x = np.full(10, foo(), dtype=object)
<del> assert_(np.all(np.conjugate(x) == True), msg)
<del>
<del> # check binary PyUFunc_OO_O
<del> msg = "PyUFunc_OO_O"
<del> x = np.ones(10, dtype=object)
<del> assert_(np.all(np.add(x, x) == 2), msg)
<del> # check binary PyUFunc_OO_O_method
<del> msg = "PyUFunc_OO_O_method"
<del> x = np.full(10, foo(), dtype=object)
<del> assert_(np.all(np.logical_xor(x, x)), msg)
<del> # check binary PyUFunc_On_Om_method
<del> msg = "PyUFunc_On_Om_method"
<del> x = np.full((10, 2, 3), foo(), dtype=object)
<del> assert_(np.all(np.logical_xor(x, x)), msg)
<del>
<ide> def test_all_ufunc(self):
<ide> """Try to check presence and results of all ufuncs.
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 1f0b7763a4cfce873a52e14fa0405e18c8b344fb | <ide><path>src/Illuminate/Routing/CompiledRouteCollection.php
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Support\Collection;
<del>use Illuminate\Support\Str;
<ide> use Symfony\Component\Routing\Matcher\CompiledUrlMatcher;
<ide> use Symfony\Component\Routing\RequestContext;
<ide> | 1 |
Javascript | Javascript | allow strict equality in angular expressions | a179a9a96eda5c566bda8a70ac8a75822c936a68 | <ide><path>src/ng/parse.js
<ide> var OPERATORS = {
<ide> '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
<ide> '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
<ide> '=':noop,
<add> '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
<add> '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
<ide> '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
<ide> '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
<ide> '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
<ide> function lex(text, csp){
<ide> continue;
<ide> } else {
<ide> var ch2 = ch + peek(),
<add> ch3 = ch2 + peek(2),
<ide> fn = OPERATORS[ch],
<del> fn2 = OPERATORS[ch2];
<del> if (fn2) {
<add> fn2 = OPERATORS[ch2],
<add> fn3 = OPERATORS[ch3];
<add> if (fn3) {
<add> tokens.push({index:index, text:ch3, fn:fn3});
<add> index += 3;
<add> } else if (fn2) {
<ide> tokens.push({index:index, text:ch2, fn:fn2});
<ide> index += 2;
<ide> } else if (fn) {
<ide> function lex(text, csp){
<ide> return chars.indexOf(lastCh) != -1;
<ide> }
<ide>
<del> function peek() {
<del> return index + 1 < text.length ? text.charAt(index + 1) : false;
<add> function peek(i) {
<add> var num = i || 1;
<add> return index + num < text.length ? text.charAt(index + num) : false;
<ide> }
<ide> function isNumber(ch) {
<ide> return '0' <= ch && ch <= '9';
<ide> function parser(text, json, $filter, csp){
<ide> function equality() {
<ide> var left = relational();
<ide> var token;
<del> if ((token = expect('==','!='))) {
<add> if ((token = expect('==','!=','===','!=='))) {
<ide> left = binaryFn(left, token.fn, equality());
<ide> }
<ide> return left;
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> expect(tokens[1].text).toEqual('b');
<ide> });
<ide>
<del> it('should tokenize relation', function() {
<del> var tokens = lex("! == != < > <= >=");
<add> it('should tokenize relation and equality', function() {
<add> var tokens = lex("! == != < > <= >= === !==");
<ide> expect(tokens[0].text).toEqual('!');
<ide> expect(tokens[1].text).toEqual('==');
<ide> expect(tokens[2].text).toEqual('!=');
<ide> expect(tokens[3].text).toEqual('<');
<ide> expect(tokens[4].text).toEqual('>');
<ide> expect(tokens[5].text).toEqual('<=');
<ide> expect(tokens[6].text).toEqual('>=');
<add> expect(tokens[7].text).toEqual('===');
<add> expect(tokens[8].text).toEqual('!==');
<ide> });
<ide>
<ide> it('should tokenize statements', function() {
<ide> describe('parser', function() {
<ide> expect(scope.$eval("false")).toBeFalsy();
<ide> expect(scope.$eval("!true")).toBeFalsy();
<ide> expect(scope.$eval("1==1")).toBeTruthy();
<add> expect(scope.$eval("1==true")).toBeTruthy();
<add> expect(scope.$eval("1===1")).toBeTruthy();
<add> expect(scope.$eval("1==='1'")).toBeFalsy();
<add> expect(scope.$eval("1===true")).toBeFalsy();
<add> expect(scope.$eval("'true'===true")).toBeFalsy();
<add> expect(scope.$eval("1!==2")).toBeTruthy();
<add> expect(scope.$eval("1!=='1'")).toBeTruthy();
<ide> expect(scope.$eval("1!=2")).toBeTruthy();
<ide> expect(scope.$eval("1<2")).toBeTruthy();
<ide> expect(scope.$eval("1<=1")).toBeTruthy();
<ide> expect(scope.$eval("1>2")).toEqual(1>2);
<ide> expect(scope.$eval("2>=1")).toEqual(2>=1);
<del> expect(scope.$eval("true==2<3")).toEqual(true === 2<3);
<add> expect(scope.$eval("true==2<3")).toEqual(true == 2<3);
<add> expect(scope.$eval("true===2<3")).toEqual(true === 2<3);
<ide> });
<ide>
<ide> it('should parse logical', function() { | 2 |
Python | Python | fix ud-train script | 5dddb30e5bd1822cc29d8188748f022e97d0df85 | <ide><path>spacy/cli/ud_train.py
<ide> def initialize_pipeline(nlp, docs, golds, config):
<ide> class Config(object):
<ide> def __init__(self, vectors=None, max_doc_length=10, multitask_tag=True,
<ide> multitask_sent=True, nr_epoch=30, batch_size=1000, dropout=0.2):
<del> for key, value in locals():
<add> for key, value in locals().items():
<ide> setattr(self, key, value)
<ide>
<ide> @classmethod
<ide> def __init__(self, ud_path, treebank, **cfg):
<ide> corpus=("UD corpus to train and evaluate on, e.g. en, es_ancora, etc",
<ide> "positional", None, str),
<ide> parses_dir=("Directory to write the development parses", "positional", None, Path),
<del> config=("Path to json formatted config file", "positional", None, Config.load),
<add> config=("Path to json formatted config file", "positional"),
<ide> limit=("Size limit", "option", "n", int)
<ide> )
<ide> def main(ud_dir, parses_dir, config, corpus, limit=0):
<add> config = Config.load(config)
<ide> paths = TreebankPaths(ud_dir, corpus)
<ide> if not (parses_dir / corpus).exists():
<ide> (parses_dir / corpus).mkdir() | 1 |
Mixed | Ruby | fix issue with expression index in insert_all | 3315cc76e03f651864383c07f6cd8f5c4d840d0a | <ide><path>activerecord/CHANGELOG.md
<add>* Resolve issue with insert_all unique_by option when used with expression index.
<add>
<add> When the `:unique_by` option of `ActiveRecord::Persistence.insert_all` and
<add> `ActiveRecord::Persistence.upsert_all` was used with the name of an expression index, an error
<add> was raised. Adding a guard around the formatting behavior for the `:unique_by` corrects this.
<add>
<add> Usage:
<add>
<add> ```ruby
<add> create_table :books, id: :integer, force: true do |t|
<add> t.column :name, :string
<add> t.index "lower(name)", unique: true
<add> end
<add>
<add> Book.insert_all [{ name: "MyTest" }], unique_by: :index_books_on_lower_name
<add> ```
<add>
<add> Fixes #39516.
<add>
<add> *Austen Madden*
<add>
<ide> * Add basic support for CHECK constraints to database migrations.
<ide>
<ide> Usage:
<ide><path>activerecord/lib/active_record/insert_all.rb
<ide> def extract_types_from_columns_on(table_name, keys:)
<ide> end
<ide>
<ide> def format_columns(columns)
<del> quote_columns(columns).join(",")
<add> columns.respond_to?(:map) ? quote_columns(columns).join(",") : columns
<ide> end
<ide>
<ide> def quote_columns(columns)
<ide><path>activerecord/test/cases/helper.rb
<ide> def supports_default_expression?
<ide> supports_savepoints?
<ide> supports_partial_index?
<ide> supports_partitioned_indexes?
<add> supports_expression_index?
<ide> supports_insert_returning?
<ide> supports_insert_on_duplicate_skip?
<ide> supports_insert_on_duplicate_update?
<ide><path>activerecord/test/cases/insert_all_test.rb
<ide> def test_insert_all_and_upsert_all_with_index_finding_options
<ide> end
<ide> end
<ide>
<add> def test_insert_all_and_upsert_all_with_expression_index
<add> skip unless supports_expression_index? && supports_insert_conflict_target?
<add>
<add> book = Book.create!(external_id: "abc")
<add>
<add> assert_no_difference "Book.count" do
<add> Book.insert_all [{ external_id: "ABC" }], unique_by: :index_books_on_lower_external_id
<add> end
<add>
<add> Book.upsert_all [{ external_id: "Abc" }], unique_by: :index_books_on_lower_external_id
<add>
<add> assert_equal "Abc", book.reload.external_id
<add> end
<add>
<ide> def test_insert_all_and_upsert_all_raises_when_index_is_missing
<ide> skip unless supports_insert_conflict_target?
<ide>
<ide><path>activerecord/test/schema/schema.rb
<ide> t.column :difficulty, :integer, **default_zero
<ide> t.column :cover, :string, default: "hard"
<ide> t.string :isbn, **case_sensitive_options
<add> t.string :external_id
<ide> t.datetime :published_on
<ide> t.boolean :boolean_status
<ide> t.index [:author_id, :name], unique: true
<ide> t.index :isbn, where: "published_on IS NOT NULL", unique: true
<add> t.index "(lower(external_id))", unique: true if supports_expression_index?
<ide>
<ide> t.datetime :created_at
<ide> t.datetime :updated_at | 5 |
Python | Python | update parser imports | 00e6186d761188f26b30637d06da680d64d50166 | <ide><path>tutorials/image/cifar10/cifar10_eval.py
<ide>
<ide> import cifar10
<ide>
<del>parser = argparse.ArgumentParser()
<add>parser = cifar10.parser
<ide>
<ide> parser.add_argument('--eval_dir', type=str, default='/tmp/cifar10_eval', help='Directory where to write event logs.')
<ide>
<ide><path>tutorials/image/cifar10/cifar10_multi_gpu_train.py
<ide> import tensorflow as tf
<ide> import cifar10
<ide>
<del>parser = argparse.ArgumentParser()
<add>parser = cifar10.parser
<ide>
<ide> parser.add_argument('--train_dir', type=str, default='/tmp/cifar10_train', help='Directory where to write event logs and checkpoint.')
<ide>
<ide><path>tutorials/image/cifar10/cifar10_train.py
<ide> import tensorflow as tf
<ide>
<ide> import cifar10
<del>from cifar10 import FLAGS
<ide>
<ide> parser = cifar10.parser
<ide> | 3 |
Javascript | Javascript | fix stdio sockets creation | b74a6da5d004fa43f88475d95b1ca910206eccb7 | <ide><path>lib/internal/child_process.js
<ide> function flushStdio(subprocess) {
<ide>
<ide>
<ide> function createSocket(pipe, readable) {
<del> var s = new net.Socket({ handle: pipe });
<del>
<del> if (readable) {
<del> s.writable = false;
<del> s.readable = true;
<del> } else {
<del> s.writable = true;
<del> s.readable = false;
<del> }
<del>
<del> return s;
<add> return net.Socket({ handle: pipe, readable, writable: !readable });
<ide> }
<ide>
<ide>
<ide><path>test/async-hooks/test-pipewrap.js
<ide> function onexit() {
<ide> // Usually it is just one event, but it can be more.
<ide> assert.ok(ioEvents >= 3, `at least 3 stdout io events, got ${ioEvents}`);
<ide>
<del> checkInvocations(pipe1, { init: 1, before: 2, after: 2 },
<add> checkInvocations(pipe1, { init: 1, before: 1, after: 1 },
<ide> 'pipe wrap when sleep.spawn was called');
<ide> checkInvocations(pipe2, { init: 1, before: ioEvents, after: ioEvents },
<ide> 'pipe wrap when sleep.spawn was called'); | 2 |
Mixed | Text | fix more links | 882b61a7eef16b373c769339e4246322b75922ad | <ide><path>GOVERNANCE.md
<ide> * [Technical Steering Committee](#technical-steering-committee)
<ide> * [TSC Meetings](#tsc-meetings)
<ide> * [Collaborator Nominations](#collaborator-nominations)
<del> * [Onboarding](#./onboarding)
<add> * [Onboarding](#onboarding)
<ide> * [Consensus Seeking Process](#consensus-seeking-process)
<ide>
<ide> <!-- /TOC -->
<ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Matteo Collina** <[email protected]> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<ide> **Michael Dawson** <[email protected]> (he/him)
<del>* [mildsunrise](https://github.com/mildsunrise)
<add>* [mildsunrise](https://github.com/mildsunrise) -
<ide> **Alba Mendez** <[email protected]> (she/her)
<ide> * [misterdjules](https://github.com/misterdjules) -
<ide> **Julien Gilli** <[email protected]>
<ide><path>doc/guides/collaborator-guide.md
<ide> If you cannot find who to cc for a file, `git shortlog -n -s <file>` may help.
<ide>
<ide> ["Merge Pull Request"]: https://help.github.com/articles/merging-a-pull-request/#merging-a-pull-request-on-github
<ide> [Deprecation]: https://en.wikipedia.org/wiki/Deprecation
<del>[Stability Index]: doc/api/documentation.md#stability-index
<add>[Stability Index]: ../api/documentation.md#stability-index
<ide> [TSC]: https://github.com/nodejs/TSC
<del>[`--pending-deprecation`]: doc/api/cli.md#--pending-deprecation
<del>[`--throw-deprecation`]: doc/api/cli.md#--throw-deprecation
<add>[`--pending-deprecation`]: ../api/cli.md#--pending-deprecation
<add>[`--throw-deprecation`]: ../api/cli.md#--throw-deprecation
<ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils
<del>[backporting guide]: doc/guides/backporting-to-release-lines.md
<del>[commit message guidelines]: ./doc/guides/contributing/pull-requests.md#commit-message-guidelines
<add>[backporting guide]: backporting-to-release-lines.md
<add>[commit message guidelines]: contributing/pull-requests.md#commit-message-guidelines
<ide> [commit-example]: https://github.com/nodejs/node/commit/b636ba8186
<ide> [git-node]: https://github.com/nodejs/node-core-utils/blob/master/docs/git-node.md
<ide> [git-node-metadata]: https://github.com/nodejs/node-core-utils/blob/master/docs/git-node.md#git-node-metadata
<ide><path>doc/guides/doc-style-guide.md
<ide> See also API documentation structure overview in [doctools README][].
<ide> [Javascript type]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types
<ide> [serial commas]: https://en.wikipedia.org/wiki/Serial_comma
<ide> [plugin]: https://editorconfig.org/#download
<del>[doctools README]: ../tools/doc/README.md
<add>[doctools README]: ../../tools/doc/README.md
<ide><path>onboarding.md
<ide> onboarding session.
<ide> organization (not just Collaborators on Node.js core) have access. Its
<ide> contents should not be shared externally.
<ide> * You can find the full moderation policy
<del> [here](https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md).
<add> [here](https://github.com/nodejs/admin/blob/master/Moderation-Policy.md).
<ide>
<ide> ## Reviewing PRs
<ide>
<ide><path>tools/doc/checkLinks.js
<ide> function findMarkdownFilesRecursively(dirPath) {
<ide> if (
<ide> entry.isDirectory() &&
<ide> entry.name !== 'api' &&
<add> entry.name !== 'fixtures' &&
<add> entry.name !== 'changelogs' &&
<ide> entry.name !== 'deps' &&
<ide> entry.name !== 'node_modules'
<ide> ) { | 6 |
Java | Java | add missing completable marbles (07/18a) | 4a744153e9cea4e32f4c88bc49893e0b13b85359 | <ide><path>src/main/java/io/reactivex/Completable.java
<ide> private static NullPointerException toNpe(Throwable ex) {
<ide> * Returns a Completable instance which manages a resource along
<ide> * with a custom Completable instance while the subscription is active.
<ide> * <p>
<add> * <img width="640" height="388" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.using.png" alt="">
<add> * <p>
<ide> * This overload disposes eagerly before the terminal event is emitted.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> public static <R> Completable using(Callable<R> resourceSupplier,
<ide> * with a custom Completable instance while the subscription is active and performs eager or lazy
<ide> * resource disposition.
<ide> * <p>
<add> * <img width="640" height="332" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.using.b.png" alt="">
<add> * <p>
<ide> * If this overload performs a lazy cancellation after the terminal event is emitted.
<ide> * Exceptions thrown at this time will be delivered to RxJavaPlugins only.
<ide> * <dl>
<ide> public static <R> Completable using(
<ide> /**
<ide> * Wraps the given CompletableSource into a Completable
<ide> * if not already Completable.
<add> * <p>
<add> * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.wrap.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public static Completable wrap(CompletableSource source) {
<ide> /**
<ide> * Returns a Completable that emits the a terminated event of either this Completable
<ide> * or the other Completable whichever fires first.
<add> * <p>
<add> * <img width="640" height="484" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.ambWith.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Completable ambWith(CompletableSource other) {
<ide> * will subscribe to the {@code next} ObservableSource. An error event from this Completable will be
<ide> * propagated to the downstream subscriber and will result in skipping the subscription of the
<ide> * Observable.
<add> * <p>
<add> * <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.o.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code andThen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <T> Observable<T> andThen(ObservableSource<T> next) {
<ide> * will subscribe to the {@code next} Flowable. An error event from this Completable will be
<ide> * propagated to the downstream subscriber and will result in skipping the subscription of the
<ide> * Publisher.
<add> * <p>
<add> * <img width="640" height="249" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.p.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer
<ide> public final <T> Flowable<T> andThen(Publisher<T> next) {
<ide> * will subscribe to the {@code next} SingleSource. An error event from this Completable will be
<ide> * propagated to the downstream subscriber and will result in skipping the subscription of the
<ide> * Single.
<add> * <p>
<add> * <img width="640" height="437" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.s.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code andThen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <T> Single<T> andThen(SingleSource<T> next) {
<ide> * will subscribe to the {@code next} MaybeSource. An error event from this Completable will be
<ide> * propagated to the downstream subscriber and will result in skipping the subscription of the
<ide> * Maybe.
<add> * <p>
<add> * <img width="640" height="280" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.m.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code andThen} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <T> Maybe<T> andThen(MaybeSource<T> next) {
<ide> * Returns a Completable that first runs this Completable
<ide> * and then the other completable.
<ide> * <p>
<add> * <img width="640" height="437" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.andThen.c.png" alt="">
<add> * <p>
<ide> * This is an alias for {@link #concatWith(CompletableSource)}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> public final Completable andThen(CompletableSource next) {
<ide> /**
<ide> * Calls the specified converter function during assembly time and returns its resulting value.
<ide> * <p>
<add> * <img width="640" height="751" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.as.png" alt="">
<add> * <p>
<ide> * This allows fluent conversion to any other type.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> public final <R> R as(@NonNull CompletableConverter<? extends R> converter) {
<ide> /**
<ide> * Subscribes to and awaits the termination of this Completable instance in a blocking manner and
<ide> * rethrows any exception emitted.
<add> * <p>
<add> * <img width="640" height="432" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingAwait.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code blockingAwait} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final void blockingAwait() {
<ide> /**
<ide> * Subscribes to and awaits the termination of this Completable instance in a blocking manner
<ide> * with a specific timeout and rethrows any exception emitted within the timeout window.
<add> * <p>
<add> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingAwait.t.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code blockingAwait} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final boolean blockingAwait(long timeout, TimeUnit unit) {
<ide> /**
<ide> * Subscribes to this Completable instance and blocks until it terminates, then returns null or
<ide> * the emitted exception if any.
<add> * <p>
<add> * <img width="640" height="435" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingGet.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Throwable blockingGet() {
<ide> /**
<ide> * Subscribes to this Completable instance and blocks until it terminates or the specified timeout
<ide> * elapses, then returns null for normal termination or the emitted exception if any.
<add> * <p>
<add> * <img width="640" height="348" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.blockingGet.t.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Throwable blockingGet(long timeout, TimeUnit unit) {
<ide> * subscribes to the result Completable, caches its terminal event
<ide> * and relays/replays it to observers.
<ide> * <p>
<add> * <img width="640" height="375" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.cache.png" alt="">
<add> * <p>
<ide> * Note that this operator doesn't allow disposing the connection
<ide> * of the upstream source.
<ide> * <dl>
<ide> public final Completable cache() {
<ide> /**
<ide> * Calls the given transformer function with this instance and returns the function's resulting
<ide> * Completable.
<add> * <p>
<add> * <img width="640" height="625" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.compose.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code compose} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> private Completable timeout0(long timeout, TimeUnit unit, Scheduler scheduler, C
<ide>
<ide> /**
<ide> * Allows fluent conversion to another type via a function callback.
<add> * <p>
<add> * <img width="640" height="751" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Completable.to.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code to} does not operate by default on a particular {@link Scheduler}.</dd> | 1 |
Javascript | Javascript | convert the `filespec` to a "normal" class | 22a066e6578e5c88cd3d6ae1bb50cd31541500a0 | <ide><path>src/core/file_spec.js
<ide> import { isDict, isStream } from "./primitives.js";
<ide> import { stringToPDFString, warn } from "../shared/util.js";
<ide>
<add>function pickPlatformItem(dict) {
<add> // Look for the filename in this order:
<add> // UF, F, Unix, Mac, DOS
<add> if (dict.has("UF")) {
<add> return dict.get("UF");
<add> } else if (dict.has("F")) {
<add> return dict.get("F");
<add> } else if (dict.has("Unix")) {
<add> return dict.get("Unix");
<add> } else if (dict.has("Mac")) {
<add> return dict.get("Mac");
<add> } else if (dict.has("DOS")) {
<add> return dict.get("DOS");
<add> }
<add> return null;
<add>}
<add>
<ide> /**
<ide> * "A PDF file can refer to the contents of another file by using a File
<ide> * Specification (PDF 1.1)", see the spec (7.11) for more details.
<ide> * NOTE: Only embedded files are supported (as part of the attachments support)
<ide> * TODO: support the 'URL' file system (with caching if !/V), portable
<ide> * collections attributes and related files (/RF)
<ide> */
<del>var FileSpec = (function FileSpecClosure() {
<del> // eslint-disable-next-line no-shadow
<del> function FileSpec(root, xref) {
<add>class FileSpec {
<add> constructor(root, xref) {
<ide> if (!root || !isDict(root)) {
<ide> return;
<ide> }
<ide> var FileSpec = (function FileSpecClosure() {
<ide> }
<ide> }
<ide>
<del> function pickPlatformItem(dict) {
<del> // Look for the filename in this order:
<del> // UF, F, Unix, Mac, DOS
<del> if (dict.has("UF")) {
<del> return dict.get("UF");
<del> } else if (dict.has("F")) {
<del> return dict.get("F");
<del> } else if (dict.has("Unix")) {
<del> return dict.get("Unix");
<del> } else if (dict.has("Mac")) {
<del> return dict.get("Mac");
<del> } else if (dict.has("DOS")) {
<del> return dict.get("DOS");
<add> get filename() {
<add> if (!this._filename && this.root) {
<add> var filename = pickPlatformItem(this.root) || "unnamed";
<add> this._filename = stringToPDFString(filename)
<add> .replace(/\\\\/g, "\\")
<add> .replace(/\\\//g, "/")
<add> .replace(/\\/g, "/");
<ide> }
<del> return null;
<add> return this._filename;
<ide> }
<ide>
<del> FileSpec.prototype = {
<del> get filename() {
<del> if (!this._filename && this.root) {
<del> var filename = pickPlatformItem(this.root) || "unnamed";
<del> this._filename = stringToPDFString(filename)
<del> .replace(/\\\\/g, "\\")
<del> .replace(/\\\//g, "/")
<del> .replace(/\\/g, "/");
<del> }
<del> return this._filename;
<del> },
<del> get content() {
<del> if (!this.contentAvailable) {
<del> return null;
<del> }
<del> if (!this.contentRef && this.root) {
<del> this.contentRef = pickPlatformItem(this.root.get("EF"));
<del> }
<del> var content = null;
<del> if (this.contentRef) {
<del> var xref = this.xref;
<del> var fileObj = xref.fetchIfRef(this.contentRef);
<del> if (fileObj && isStream(fileObj)) {
<del> content = fileObj.getBytes();
<del> } else {
<del> warn(
<del> "Embedded file specification points to non-existing/invalid " +
<del> "content"
<del> );
<del> }
<add> get content() {
<add> if (!this.contentAvailable) {
<add> return null;
<add> }
<add> if (!this.contentRef && this.root) {
<add> this.contentRef = pickPlatformItem(this.root.get("EF"));
<add> }
<add> var content = null;
<add> if (this.contentRef) {
<add> var xref = this.xref;
<add> var fileObj = xref.fetchIfRef(this.contentRef);
<add> if (fileObj && isStream(fileObj)) {
<add> content = fileObj.getBytes();
<ide> } else {
<del> warn("Embedded file specification does not have a content");
<add> warn(
<add> "Embedded file specification points to non-existing/invalid content"
<add> );
<ide> }
<del> return content;
<del> },
<del> get serializable() {
<del> return {
<del> filename: this.filename,
<del> content: this.content,
<del> };
<del> },
<del> };
<del> return FileSpec;
<del>})();
<add> } else {
<add> warn("Embedded file specification does not have a content");
<add> }
<add> return content;
<add> }
<add>
<add> get serializable() {
<add> return {
<add> filename: this.filename,
<add> content: this.content,
<add> };
<add> }
<add>}
<ide>
<ide> export { FileSpec }; | 1 |
Python | Python | add list_images method to the vsphere driver | 48f0eebc5cd01399937ea439677d252ba20a9f97 | <ide><path>libcloud/compute/drivers/vsphere.py
<ide> from libcloud.common.types import InvalidCredsError
<ide> from libcloud.compute.base import NodeDriver
<ide> from libcloud.compute.base import NodeLocation
<add>from libcloud.compute.base import NodeImage
<ide> from libcloud.compute.base import Node
<ide> from libcloud.compute.types import NodeState, Provider
<ide> from libcloud.utils.networking import is_public_subnet
<ide> def list_locations(self):
<ide>
<ide> return locations
<ide>
<add> @wrap_non_libcloud_exceptions
<add> def list_images(self):
<add> """
<add> List available images (templates).
<add> """
<add> server = self.connection.client
<add>
<add> names = ['name', 'config.uuid', 'config.template']
<add> properties = server._retrieve_properties_traversal(
<add> property_names=names,
<add> from_node=None,
<add> obj_type=MORTypes.VirtualMachine)
<add>
<add> images = []
<add> for prop in properties:
<add> id = None
<add> name = None
<add> is_template = False
<add>
<add> for item in prop.PropSet:
<add> if item.Name == 'config.uuid':
<add> id = item.Val
<add> if item.Name == 'name':
<add> name = item.Val
<add> elif item.Name == 'config.template':
<add> is_template = item.Val
<add>
<add> if is_template:
<add> image = NodeImage(id=id, name=name, driver=self)
<add> images.append(image)
<add>
<add> return images
<add>
<ide> @wrap_non_libcloud_exceptions
<ide> def list_nodes(self):
<ide> vm_paths = self.connection.client.get_registered_vms() | 1 |
Go | Go | move cpu variant checks into platform matcher | 50f39e724707ef121a988e422eb52045d3754802 | <ide><path>daemon/create.go
<ide> import (
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> networktypes "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/container"
<add> "github.com/docker/docker/daemon/images"
<ide> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/pkg/idtools"
<ide> func (daemon *Daemon) containerCreate(opts createOpts) (containertypes.Container
<ide> Variant: img.Variant,
<ide> }
<ide>
<del> if !platforms.Only(p).Match(imgPlat) {
<add> if !images.OnlyPlatformWithFallback(p).Match(imgPlat) {
<ide> warnings = append(warnings, fmt.Sprintf("The requested image's platform (%s) does not match the detected host platform (%s) and no specific platform was requested", platforms.Format(imgPlat), platforms.Format(p)))
<ide> }
<ide> }
<ide><path>daemon/images/image.go
<ide> func (i *ImageService) manifestMatchesPlatform(img *image.Image, platform specs.
<ide> return false
<ide> }
<ide>
<add> // Note we are comparing against manifest lists here, which we expect to always have a CPU variant set (where applicable).
<add> // So there is no need for the fallback matcher here.
<ide> comparer := platforms.Only(platform)
<ide>
<ide> var (
<ide> func (i *ImageService) GetImage(refOrID string, platform *specs.Platform) (retIm
<ide> p := *platform
<ide> // Note that `platforms.Only` will fuzzy match this for us
<ide> // For example: an armv6 image will run just fine an an armv7 CPU, without emulation or anything.
<del> if !platforms.Only(p).Match(imgPlat) {
<del> // Sometimes image variant is not populated due to legacy builders
<del> // We still should support falling back here.
<del> if imgPlat.OS == platform.OS && imgPlat.Architecture == platform.Architecture && imgPlat.Variant == "" {
<del> logrus.WithField("image", refOrID).WithField("platform", platforms.Format(p)).Debug("Image platform cpu variant is not populated, but otherwise it matches what was requested")
<del> return
<del> }
<del>
<del> // In some cases the image config can actually be wrong (e.g. classic `docker build` may not handle `--platform` correctly)
<del> // So we'll look up the manifest list that coresponds to this imaage to check if at least the manifest list says it is the correct image.
<del> if i.manifestMatchesPlatform(retImg, p) {
<del> return
<del> }
<del>
<del> // This allows us to tell clients that we don't have the image they asked for
<del> // Where this gets hairy is the image store does not currently support multi-arch images, e.g.:
<del> // An image `foo` may have a multi-arch manifest, but the image store only fetches the image for a specific platform
<del> // The image store does not store the manifest list and image tags are assigned to architecture specific images.
<del> // So we can have a `foo` image that is amd64 but the user requested armv7. If the user looks at the list of images.
<del> // This may be confusing.
<del> // The alternative to this is to return a errdefs.Conflict error with a helpful message, but clients will not be
<del> // able to automatically tell what causes the conflict.
<del> retErr = errdefs.NotFound(errors.Errorf("image with reference %s was found but does not match the specified platform: wanted %s, actual: %s", refOrID, platforms.Format(p), platforms.Format(imgPlat)))
<add> if OnlyPlatformWithFallback(p).Match(imgPlat) {
<ide> return
<ide> }
<add> // In some cases the image config can actually be wrong (e.g. classic `docker build` may not handle `--platform` correctly)
<add> // So we'll look up the manifest list that coresponds to this imaage to check if at least the manifest list says it is the correct image.
<add> if i.manifestMatchesPlatform(retImg, p) {
<add> return
<add> }
<add>
<add> // This allows us to tell clients that we don't have the image they asked for
<add> // Where this gets hairy is the image store does not currently support multi-arch images, e.g.:
<add> // An image `foo` may have a multi-arch manifest, but the image store only fetches the image for a specific platform
<add> // The image store does not store the manifest list and image tags are assigned to architecture specific images.
<add> // So we can have a `foo` image that is amd64 but the user requested armv7. If the user looks at the list of images.
<add> // This may be confusing.
<add> // The alternative to this is to return a errdefs.Conflict error with a helpful message, but clients will not be
<add> // able to automatically tell what causes the conflict.
<add> retErr = errdefs.NotFound(errors.Errorf("image with reference %s was found but does not match the specified platform: wanted %s, actual: %s", refOrID, platforms.Format(p), platforms.Format(imgPlat)))
<ide> }()
<ide> ref, err := reference.ParseAnyReference(refOrID)
<ide> if err != nil {
<ide> func (i *ImageService) GetImage(refOrID string, platform *specs.Platform) (retIm
<ide>
<ide> return nil, ErrImageDoesNotExist{ref}
<ide> }
<add>
<add>// OnlyPlatformWithFallback uses `platforms.Only` with a fallback to handle the case where the platform
<add>// being matched does not have a CPU variant.
<add>//
<add>// The reason for this is that CPU variant is not even if the official image config spec as of this writing.
<add>// See: https://github.com/opencontainers/image-spec/pull/809
<add>// Since Docker tends to compare platforms from the image config, we need to handle this case.
<add>func OnlyPlatformWithFallback(p specs.Platform) platforms.Matcher {
<add> return &onlyFallbackMatcher{only: platforms.Only(p), p: platforms.Normalize(p)}
<add>}
<add>
<add>type onlyFallbackMatcher struct {
<add> only platforms.Matcher
<add> p specs.Platform
<add>}
<add>
<add>func (m *onlyFallbackMatcher) Match(other specs.Platform) bool {
<add> if m.only.Match(other) {
<add> // It matches, no reason to fallback
<add> return true
<add> }
<add> if other.Variant != "" {
<add> // If there is a variant then this fallback does not apply, and there is no match
<add> return false
<add> }
<add> otherN := platforms.Normalize(other)
<add> otherN.Variant = "" // normalization adds a default variant... which is the whole problem with `platforms.Only`
<add>
<add> return m.p.OS == otherN.OS &&
<add> m.p.Architecture == otherN.Architecture
<add>}
<ide><path>daemon/images/images_test.go
<add>package images
<add>
<add>import (
<add> "testing"
<add>
<add> specs "github.com/opencontainers/image-spec/specs-go/v1"
<add> "gotest.tools/v3/assert"
<add>)
<add>
<add>func TestOnlyPlatformWithFallback(t *testing.T) {
<add> p := specs.Platform{
<add> OS: "linux",
<add> Architecture: "arm",
<add> Variant: "v8",
<add> }
<add>
<add> // Check no variant
<add> assert.Assert(t, OnlyPlatformWithFallback(p).Match(specs.Platform{
<add> OS: p.OS,
<add> Architecture: p.Architecture,
<add> }))
<add> // check with variant
<add> assert.Assert(t, OnlyPlatformWithFallback(p).Match(specs.Platform{
<add> OS: p.OS,
<add> Architecture: p.Architecture,
<add> Variant: p.Variant,
<add> }))
<add> // Make sure non-matches are false.
<add> assert.Assert(t, !OnlyPlatformWithFallback(p).Match(specs.Platform{
<add> OS: p.OS,
<add> Architecture: "amd64",
<add> }))
<add>} | 3 |
Python | Python | add unit test for ticket #273 | 60417381250675c9f40d0153a5c43e0751a40b89 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_swap_real(self, level=rlevel):
<ide> assert_equal(N.arange(4,dtype='<c8').imag.max(),0.0)
<ide> assert_equal(N.arange(4,dtype='>c8').real.max(),3.0)
<ide> assert_equal(N.arange(4,dtype='<c8').real.max(),3.0)
<add>
<add> def check_multiple_assign(self, level=rlevel):
<add> """Ticket #273"""
<add> a = N.zeros((3,1),int)
<add> a[[1,2]] = 1
<ide>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.