content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
fix broken imports
9579cad57ad3c1dea32c8cfac84e968a7bd5f72a
<ide><path>packages/ember-views/lib/views/states/default.js <del>import { <del> EmberError <del>} from 'ember-debug'; <add>import { Error as EmberError } from 'ember-debug'; <ide> <ide> export default { <ide> // appendChild is only legal while rendering the buffer. <ide> appendChild() { <del> throw new EmberError('You can\'t use appendChild outside of the rendering process'); <add> throw new EmberError( <add> "You can't use appendChild outside of the rendering process" <add> ); <ide> }, <ide> <ide> // Handle events from `Ember.EventDispatcher` <ide> handleEvent() { <ide> return true; // continue event propagation <ide> }, <ide> <del> rerender() { }, <add> rerender() {}, <ide> <del> destroy() { } <add> destroy() {} <ide> }; <ide><path>packages/ember/lib/index.js <ide> Ember.overrideChains = metal.overrideChains; <ide> Ember.beginPropertyChanges = metal.beginPropertyChanges; <ide> Ember.endPropertyChanges = metal.endPropertyChanges; <ide> Ember.changeProperties = metal.changeProperties; <del>Ember.platform = { <add>Ember.platform = { <ide> defineProperty: true, <ide> hasPropertyAccessors: true <ide> }; <ide> Ember.aliasMethod = metal.aliasMethod; <ide> Ember.observer = metal.observer; <ide> Ember.mixin = metal.mixin; <ide> Ember.Mixin = metal.Mixin; <del>Ember.bind = metal.bind; <del>Ember.Binding = metal.Binding; <del> <ide> <ide> Object.defineProperty(Ember, 'ENV', { <del> get() { return ENV; }, <add> get() { <add> return ENV; <add> }, <ide> enumerable: false <ide> }); <ide> <ide> Object.defineProperty(Ember, 'ENV', { <ide> @private <ide> */ <ide> Object.defineProperty(Ember, 'lookup', { <del> get() { return context.lookup; }, <del> set(value) { context.lookup = value; }, <add> get() { <add> return context.lookup; <add> }, <add> set(value) { <add> context.lookup = value; <add> }, <ide> enumerable: false <ide> }); <ide> <ide> Ember.EXTEND_PROTOTYPES = ENV.EXTEND_PROTOTYPES; <ide> <ide> // BACKWARDS COMPAT ACCESSORS FOR ENV FLAGS <ide> Object.defineProperty(Ember, 'LOG_STACKTRACE_ON_DEPRECATION', { <del> get() { return ENV.LOG_STACKTRACE_ON_DEPRECATION; }, <del> set(value) { ENV.LOG_STACKTRACE_ON_DEPRECATION = !!value; }, <add> get() { <add> return ENV.LOG_STACKTRACE_ON_DEPRECATION; <add> }, <add> set(value) { <add> ENV.LOG_STACKTRACE_ON_DEPRECATION = !!value; <add> }, <ide> enumerable: false <ide> }); <ide> <ide> Object.defineProperty(Ember, 'LOG_VERSION', { <del> get() { return ENV.LOG_VERSION; }, <del> set(value) { ENV.LOG_VERSION = !!value; }, <add> get() { <add> return ENV.LOG_VERSION; <add> }, <add> set(value) { <add> ENV.LOG_VERSION = !!value; <add> }, <ide> enumerable: false <ide> }); <ide> <ide> if (DEBUG) { <ide> Object.defineProperty(Ember, 'MODEL_FACTORY_INJECTIONS', { <del> get() { return false; }, <add> get() { <add> return false; <add> }, <ide> set() { <del> deprecate( <del> 'Ember.MODEL_FACTORY_INJECTIONS is no longer required', <del> false, <del> { <del> id: 'ember-metal.model_factory_injections', <del> until: '2.17.0', <del> url: 'https://emberjs.com/deprecations/v2.x/#toc_id-ember-metal-model_factory_injections' <del> } <del> ); <add> deprecate('Ember.MODEL_FACTORY_INJECTIONS is no longer required', false, { <add> id: 'ember-metal.model_factory_injections', <add> until: '2.17.0', <add> url: <add> 'https://emberjs.com/deprecations/v2.x/#toc_id-ember-metal-model_factory_injections' <add> }); <ide> }, <ide> enumerable: false <ide> }); <ide> } <ide> <ide> Object.defineProperty(Ember, 'LOG_BINDINGS', { <del> get() { return ENV.LOG_BINDINGS; }, <del> set(value) { ENV.LOG_BINDINGS = !!value; }, <add> get() { <add> return ENV.LOG_BINDINGS; <add> }, <add> set(value) { <add> ENV.LOG_BINDINGS = !!value; <add> }, <ide> enumerable: false <ide> }); <ide> <ide> import { <ide> deprecatingAlias, <ide> and, <ide> or, <del> any, <ide> <ide> // reduced computed macros <ide> sum, <ide> computed.readOnly = readOnly; <ide> computed.deprecatingAlias = deprecatingAlias; <ide> computed.and = and; <ide> computed.or = or; <del>computed.any = any; <ide> <ide> computed.sum = sum; <ide> computed.min = min; <ide> Ember.LinkComponent = LinkComponent; <ide> <ide> Object.defineProperty(Ember, '_setComponentManager', { <ide> enumerable: false, <del> get() { return componentManager; } <add> get() { <add> return componentManager; <add> } <ide> }); <ide> <ide> if (ENV.EXTEND_PROTOTYPES.String) { <ide> if (ENV.EXTEND_PROTOTYPES.String) { <ide> }; <ide> } <ide> <del>let EmberHandlebars = Ember.Handlebars = Ember.Handlebars || {}; <del>let EmberHTMLBars = Ember.HTMLBars = Ember.HTMLBars || {}; <del>let EmberHandleBarsUtils = EmberHandlebars.Utils = EmberHandlebars.Utils || {}; <add>let EmberHandlebars = (Ember.Handlebars = Ember.Handlebars || {}); <add>let EmberHTMLBars = (Ember.HTMLBars = Ember.HTMLBars || {}); <add>let EmberHandleBarsUtils = (EmberHandlebars.Utils = <add> EmberHandlebars.Utils || {}); <ide> <ide> EmberHTMLBars.template = EmberHandlebars.template = template; <ide> EmberHandleBarsUtils.escapeExpression = escapeExpression; <ide> import * as views from 'ember-views'; <ide> <ide> Ember.$ = views.jQuery; <ide> <del>Ember.ViewTargetActionSupport = views.ViewTargetActionSupport; <del> <ide> Ember.ViewUtils = { <ide> isSimpleClick: views.isSimpleClick, <ide> getViewElement: views.getViewElement, <ide> import * as extensionSupport from 'ember-extension-support'; <ide> Ember.DataAdapter = extensionSupport.DataAdapter; <ide> Ember.ContainerDebugAdapter = extensionSupport.ContainerDebugAdapter; <ide> <del> <ide> if (has('ember-template-compiler')) { <ide> require('ember-template-compiler'); <ide> } <ide> runLoadHooks('Ember'); <ide> */ <ide> export default Ember; <ide> <del> <ide> /* globals module */ <ide> if (IS_NODE) { <ide> module.exports = Ember;
2
Go
Go
add struct tags on v2 remote tags struct
4925d98d1f638e9439e19b6c89c608a64a281a39
<ide><path>registry/session_v2.go <ide> func (r *Session) PutV2ImageManifest(ep *Endpoint, imageName, tagName string, si <ide> } <ide> <ide> type remoteTags struct { <del> Name string <del> Tags []string <add> Name string `json:"name"` <add> Tags []string `json:"tags"` <ide> } <ide> <ide> // Given a repository name, returns a json array of string tags
1
Javascript
Javascript
add support for finished after .destroy()"
2fa7d33e74d069f7a3c42b355d34452e902b2132
<ide><path>lib/_http_incoming.js <ide> IncomingMessage.prototype._destroy = function _destroy(err, cb) { <ide> this.emit('aborted'); <ide> } <ide> <del> // If aborted destroy socket. <del> if (this.socket && this.aborted) { <add> // If aborted and the underlying socket is not already destroyed, <add> // destroy it. <add> // We have to check if the socket is already destroyed because finished <add> // does not call the callback when this methdod is invoked from `_http_client` <add> // in `test/parallel/test-http-client-spurious-aborted.js` <add> if (this.socket && !this.socket.destroyed && this.aborted) { <ide> this.socket.destroy(err); <ide> const cleanup = finished(this.socket, (e) => { <ide> cleanup(); <ide><path>lib/internal/streams/end-of-stream.js <ide> const { <ide> validateObject, <ide> } = require('internal/validators'); <ide> <del>function isSocket(stream) { <del> return ( <del> typeof stream.connect === 'function' && <del> typeof stream.setNoDelay === 'function' && <del> typeof stream.setKeepAlive === 'function' <del> ); <del>} <del> <ide> function isRequest(stream) { <ide> return stream.setHeader && typeof stream.abort === 'function'; <ide> } <ide> function eos(stream, options, callback) { <ide> let willEmitClose = isServerResponse(stream) || ( <ide> state && <ide> state.autoDestroy && <del> (state.emitClose || isSocket(stream)) && <add> state.emitClose && <ide> state.closed === false && <ide> isReadable(stream) === readable && <ide> isWritable(stream) === writable <ide><path>lib/net.js <ide> Socket.prototype._destroy = function(exception, cb) { <ide> <ide> this._handle.close(() => { <ide> debug('emit close'); <del> if (this._writableState) { <del> this._writableState.closed = true; <del> } <del> if (this._readableState) { <del> this._readableState.closed = true; <del> } <ide> this.emit('close', isException); <ide> }); <ide> this._handle.onread = noop; <ide> Server.prototype._emitCloseIfDrained = function() { <ide> <ide> function emitCloseNT(self) { <ide> debug('SERVER: emit close'); <del> if (self._writableState) { <del> self._writableState.closed = true; <del> } <del> if (self._readableState) { <del> self._readableState.closed = true; <del> } <ide> self.emit('close'); <ide> } <ide> <ide><path>test/parallel/test-net-finished.js <del>'use strict'; <del>const common = require('../common'); <del>const net = require('net'); <del>const { finished } = require('stream'); <del> <del>const server = net.createServer(function(con) { <del> con.on('close', common.mustCall()); <del>}); <del> <del>server.listen(0, common.mustCall(function() { <del> const con = net.connect({ <del> port: this.address().port <del> }) <del> .on('connect', () => { <del> finished(con, common.mustCall()); <del> con.destroy(); <del> finished(con, common.mustCall()); <del> con.on('close', common.mustCall(() => { <del> finished(con, common.mustCall(() => { <del> server.close(); <del> })); <del> })); <del> }) <del> .end(); <del>}));
4
Ruby
Ruby
reduce noise by including fileutils
e0c4fd5b720192cfeb06ba8bfffbc58113057bc1
<ide><path>Library/Homebrew/test/test_keg.rb <ide> require 'stringio' <ide> <ide> class LinkTests < Test::Unit::TestCase <add> include FileUtils <add> <ide> def setup <ide> @formula = TestBall.new <ide> shutup do <ide> def setup <ide> @old_stdout = $stdout <ide> $stdout = StringIO.new <ide> <del> FileUtils.mkpath HOMEBREW_PREFIX/"bin" <add> mkpath HOMEBREW_PREFIX/"bin" <ide> end <ide> <ide> def test_linking_keg <ide> def test_linking_fails_when_already_linked <ide> end <ide> <ide> def test_linking_fails_when_files_exist <del> FileUtils.touch HOMEBREW_PREFIX/"bin/helloworld" <add> touch HOMEBREW_PREFIX/"bin/helloworld" <ide> assert_raise RuntimeError do <ide> shutup { @keg.link } <ide> end <ide> end <ide> <ide> def test_link_overwrite <del> FileUtils.touch HOMEBREW_PREFIX/"bin/helloworld" <add> touch HOMEBREW_PREFIX/"bin/helloworld" <ide> @mode.overwrite = true <ide> assert_equal 3, @keg.link(@mode) <ide> end <ide> <ide> def test_link_overwrite_broken_symlinks <del> FileUtils.cd HOMEBREW_PREFIX/"bin" do <del> FileUtils.ln_s "nowhere", "helloworld" <add> cd HOMEBREW_PREFIX/"bin" do <add> ln_s "nowhere", "helloworld" <ide> end <ide> @mode.overwrite = true <ide> assert_equal 3, @keg.link(@mode) <ide> end <ide> <ide> def test_link_overwrite_dryrun <del> FileUtils.touch HOMEBREW_PREFIX/"bin/helloworld" <add> touch HOMEBREW_PREFIX/"bin/helloworld" <ide> @mode.overwrite = true <ide> @mode.dry_run = true <ide> <ide> def teardown <ide> <ide> $stdout = @old_stdout <ide> <del> FileUtils.rmtree HOMEBREW_PREFIX/"bin" <add> rmtree HOMEBREW_PREFIX/"bin" <ide> end <ide> end
1
Javascript
Javascript
make sure `.data("events")` still works, for now
c82dbf1928f54385e83df9ec6de47616f83fe682
<ide><path>src/data.js <ide> jQuery.extend({ <ide> return; <ide> } <ide> <del> var thisCache, ret, <add> var privateCache, thisCache, ret, <ide> internalKey = jQuery.expando, <ide> getByName = typeof name === "string", <ide> <ide> jQuery.extend({ <ide> <ide> // Only defining an ID for JS objects if its cache already exists allows <ide> // the code to shortcut on the same path as a DOM node with no cache <del> id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; <add> id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando, <add> isEvents = name === "events"; <ide> <ide> // Avoid doing any more work than we need to when trying to get data on an <ide> // object that has no data at all <del> if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { <add> if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { <ide> return; <ide> } <ide> <ide> jQuery.extend({ <ide> if ( !cache[ id ] ) { <ide> cache[ id ] = {}; <ide> <del> // Avoids exposing jQuery metadata on plain JS objects when the object <add> // Avoids exposing jQuery metadata on plain JS objects when the object <ide> // is serialized using JSON.stringify <ide> if ( !isNode ) { <ide> cache[ id ].toJSON = jQuery.noop; <ide> jQuery.extend({ <ide> } <ide> } <ide> <del> thisCache = cache[ id ]; <add> privateCache = thisCache = cache[ id ]; <ide> <ide> // jQuery data() is stored in a separate object inside the object's internal data <ide> // cache in order to avoid key collisions between internal data and user-defined <ide> jQuery.extend({ <ide> <ide> // Users should not attempt to inspect the internal events object using jQuery.data, <ide> // it is undocumented and subject to change. But does anyone listen? No. <del> if ( name === "events" && !thisCache[name] ) { <del> return thisCache[ internalKey ] && thisCache[ internalKey ].events; <add> if ( isEvents && !thisCache[ name ] ) { <add> return privateCache.events; <ide> } <ide> <ide> // Check for both converted-to-camel and non-converted data property names
1
Ruby
Ruby
convert structs to a regular class
497b1350bbfb35ea3e57f5b8363d5d8605930aa6
<ide><path>actionview/lib/action_view/digestor.rb <ide> def self.tree(name, finder, injected = [], partial = false, seen = {}) <ide> node = seen[template.identifier] = Node.create(name, logical_name, template, partial) <ide> <ide> deps = DependencyTracker.find_dependencies(name, template, finder.view_paths) <del> deps.each do |dep_file| <add> deps.uniq { |n| n.gsub(%r|/_|, "/") }.each do |dep_file| <ide> node.children << tree(dep_file, finder, [], true, seen) <ide> end <del> injected.each do |template| <del> node.children << Injected.new(template, nil, nil) <add> injected.each do |injected_dep| <add> node.children << Injected.new(injected_dep, nil, nil) <ide> end <ide> node <ide> end <ide> else <del> seen[name] = Missing.new(name, logical_name, nil) <add> seen[name] ||= Missing.new(name, logical_name, nil) <ide> end <ide> end <ide> <del> class Node < Struct.new(:name, :logical_name, :template, :children) <add> class Node <add> attr_reader :name, :logical_name, :template, :children <ide> def self.class_for(partial) <ide> partial ? Partial : Node <ide> end <ide> def self.create(name, logical_name, template, partial) <ide> end <ide> <ide> def initialize(name, logical_name, template, children = []) <del> super <add> @name = name <add> @logical_name = logical_name <add> @template = template <add> @children = children <ide> end <ide> <ide> def to_dep(finder) <del> Digestor.new(name, finder, partial: true) <add> Digestor.new(name, finder, partial: false) <ide> end <ide> <ide> def digest(stack = []) <ide> def dependency_digest(stack) <ide> <ide> class Partial < Node <ide> def to_dep(finder) <del> PartialDigestor.new(name, finder, partial: false) <add> PartialDigestor.new(name, finder, partial: true) <ide> end <ide> end <ide>
1
Python
Python
detect partial examples dags for google
388736bf97a4313f81aadbeecbb99e5fcb145c31
<ide><path>tests/always/test_project_structure.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <del> <add>import ast <ide> import glob <ide> import itertools <ide> import mmap <ide> import os <ide> import unittest <add>from typing import List <ide> <ide> from parameterized import parameterized <ide> <ide> def test_providers_modules_should_have_tests(self): <ide> ) <ide> <ide> <add>def get_imports_from_file(filepath: str): <add> with open(filepath) as py_file: <add> content = py_file.read() <add> doc_node = ast.parse(content, filepath) <add> import_names: List[str] = [] <add> for current_node in ast.walk(doc_node): <add> if not isinstance(current_node, (ast.Import, ast.ImportFrom)): <add> continue <add> for alias in current_node.names: <add> name = alias.name <add> fullname = f'{current_node.module}.{name}' if isinstance(current_node, ast.ImportFrom) else name <add> import_names.append(fullname) <add> return import_names <add> <add> <add>def filepath_to_module(filepath: str): <add> filepath = os.path.relpath(os.path.abspath(filepath), ROOT_FOLDER) <add> return filepath.replace("/", ".")[: -(len('.py'))] <add> <add> <add>def get_classes_from_file(filepath: str): <add> with open(filepath) as py_file: <add> content = py_file.read() <add> doc_node = ast.parse(content, filepath) <add> module = filepath_to_module(filepath) <add> results: List[str] = [] <add> for current_node in ast.walk(doc_node): <add> if not isinstance(current_node, ast.ClassDef): <add> continue <add> name = current_node.name <add> if not name.endswith("Operator") and not name.endswith("Sensor") and not name.endswith("Operator"): <add> continue <add> results.append(f"{module}.{name}") <add> return results <add> <add> <ide> class TestGoogleProviderProjectStructure(unittest.TestCase): <ide> MISSING_EXAMPLE_DAGS = { <ide> ('cloud', 'adls_to_gcs'), <ide> class TestGoogleProviderProjectStructure(unittest.TestCase): <ide> ('ads', 'ads_to_gcs'), <ide> } <ide> <add> MISSING_EXAMPLES_FOR_OPERATORS = { <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueueDeleteOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueueResumeOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueuePauseOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueuePurgeOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksTaskGetOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksTasksListOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksTaskDeleteOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueueGetOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueueUpdateOperator', <add> 'airflow.providers.google.cloud.operators.tasks.CloudTasksQueuesListOperator', <add> # Deprecated operator. Ignore it. <add> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service' <add> '.CloudDataTransferServiceS3ToGCSOperator', <add> # Deprecated operator. Ignore it. <add> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service' <add> '.CloudDataTransferServiceGCSToGCSOperator', <add> # Base operator. Ignore it. <add> 'airflow.providers.google.cloud.operators.cloud_sql.CloudSQLBaseOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocSubmitHadoopJobOperator', <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocInstantiateInlineWorkflowTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocInstantiateWorkflowTemplateOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocScaleClusterOperator', <add> # Base operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocJobBaseOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocSubmitSparkJobOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocSubmitSparkSqlJobOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocSubmitHiveJobOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocSubmitPigJobOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.dataproc.DataprocSubmitPySparkJobOperator', <add> 'airflow.providers.google.cloud.operators.mlengine.MLEngineTrainingCancelJobOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.mlengine.MLEngineManageModelOperator', <add> # Deprecated operator. Ignore it <add> 'airflow.providers.google.cloud.operators.mlengine.MLEngineManageVersionOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPGetStoredInfoTypeOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPReidentifyContentOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPCreateDeidentifyTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPCreateDLPJobOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPUpdateDeidentifyTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPDeidentifyContentOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPGetDLPJobTriggerOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPListDeidentifyTemplatesOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPGetDeidentifyTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPListInspectTemplatesOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPListStoredInfoTypesOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPUpdateInspectTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPDeleteDLPJobOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPListJobTriggersOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPCancelDLPJobOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPGetDLPJobOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPGetInspectTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPListInfoTypesOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPDeleteDeidentifyTemplateOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPListDLPJobsOperator', <add> 'airflow.providers.google.cloud.operators.dlp.CloudDLPRedactImageOperator', <add> 'airflow.providers.google.cloud.operators.datastore.CloudDatastoreDeleteOperationOperator', <add> 'airflow.providers.google.cloud.operators.datastore.CloudDatastoreGetOperationOperator', <add> # Base operator. Ignore it <add> 'airflow.providers.google.cloud.operators.compute.ComputeEngineBaseOperator', <add> 'airflow.providers.google.cloud.sensors.gcs.GCSObjectExistenceSensor', <add> 'airflow.providers.google.cloud.sensors.gcs.GCSObjectUpdateSensor', <add> 'airflow.providers.google.cloud.sensors.gcs.GCSObjectsWtihPrefixExistenceSensor', <add> 'airflow.providers.google.cloud.sensors.gcs.GCSUploadSessionCompleteSensor', <add> } <add> <ide> def test_example_dags(self): <ide> operators_modules = itertools.chain( <ide> *[self.find_resource_files(resource_type=d) for d in ["operators", "sensors", "transfers"]] <ide> def has_example_dag(operator_set): <ide> "Can you remove it from the list of missing example, please?" <ide> ) <ide> <del> @parameterized.expand( <del> [ <del> ( <del> resource_type, <del> suffix, <add> def test_missing_example_for_operator(self): <add> missing_operators = [] <add> <add> for resource_type in ["operators", "sensors", "tranfers"]: <add> operator_files = set( <add> self.find_resource_files(top_level_directory="airflow", resource_type=resource_type) <ide> ) <del> for suffix in ["_system.py", "_system_helper.py"] <del> for resource_type in ["operators", "sensors", "tranfers"] <del> ] <add> for filepath in operator_files: <add> service_name = os.path.basename(filepath)[: -(len(".py"))] <add> example_dags = list( <add> glob.glob( <add> f"{ROOT_FOLDER}/airflow/providers/google/*/example_dags/example_{service_name}*.py" <add> ) <add> ) <add> if not example_dags: <add> # Ignore. We have separate tests that detect this. <add> continue <add> example_paths = { <add> path for example_dag in example_dags for path in get_imports_from_file(example_dag) <add> } <add> example_paths = { <add> path for path in example_paths if f'.{resource_type}.{service_name}.' in path <add> } <add> print("example_paths=", example_paths) <add> operators_paths = set(get_classes_from_file(f"{ROOT_FOLDER}/{filepath}")) <add> missing_operators.extend(operators_paths - example_paths) <add> self.assertEqual(set(missing_operators), self.MISSING_EXAMPLES_FOR_OPERATORS) <add> <add> @parameterized.expand( <add> itertools.product(["_system.py", "_system_helper.py"], ["operators", "sensors", "tranfers"]) <ide> ) <ide> def test_detect_invalid_system_tests(self, resource_type, filename_suffix): <ide> operators_tests = self.find_resource_files(top_level_directory="tests", resource_type=resource_type)
1
Mixed
Ruby
remove some references to orderedhash
0dd76540327be58999b0cb7584277724e60486d3
<ide><path>activesupport/lib/active_support/core_ext/object/json.rb <ide> # The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting <ide> # their default behavior. That said, we need to define the basic to_json method in all of them, <ide> # otherwise they will always use to_json gem implementation, which is backwards incompatible in <del># several cases (for instance, the JSON implementation for Hash does not work) with inheritance <del># and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json. <add># several cases (for instance, the JSON implementation for Hash does not work) with inheritance. <ide> # <ide> # On the other hand, we should avoid conflict with ::JSON.{generate,dump}(obj). Unfortunately, the <ide> # JSON gem's encoder relies on its own to_json implementation to encode objects. Since it always <ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> require "active_support/core_ext/hash" <ide> require "bigdecimal" <ide> require "active_support/core_ext/string/access" <del>require "active_support/ordered_hash" <ide> require "active_support/core_ext/object/conversions" <ide> require "active_support/core_ext/date/conversions" <ide> require "active_support/core_ext/object/deep_dup" <ide><path>activesupport/test/core_ext/object/to_query_test.rb <ide> # frozen_string_literal: true <ide> <ide> require_relative "../../abstract_unit" <del>require "active_support/ordered_hash" <ide> require "active_support/core_ext/object/to_query" <ide> require "active_support/core_ext/string/output_safety" <ide> <ide><path>activesupport/test/hash_with_indifferent_access_test.rb <ide> require "active_support/core_ext/hash" <ide> require "bigdecimal" <ide> require "active_support/core_ext/string/access" <del>require "active_support/ordered_hash" <ide> require "active_support/core_ext/object/conversions" <ide> require "active_support/core_ext/object/deep_dup" <ide> require "active_support/inflections" <ide><path>guides/source/active_support_core_extensions.md <ide> NOTE: Defined in `active_support/core_ext/object/with_options.rb`. <ide> <ide> ### JSON support <ide> <del>Active Support provides a better implementation of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash`, `OrderedHash` and `Process::Status` need special handling in order to provide a proper JSON representation. <add>Active Support provides a better implementation of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash` and `Process::Status` need special handling in order to provide a proper JSON representation. <ide> <ide> NOTE: Defined in `active_support/core_ext/object/json.rb`. <ide>
5
Javascript
Javascript
fix gjslint errors
edd92c9db29f69ef092399dce877ff66e89ac4f4
<ide><path>fonts.js <ide> CFF.prototype = { <ide> return null; <ide> }, <ide> <del> getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs, properties) { <add> getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs, <add> properties) { <ide> var charstrings = []; <ide> var missings = []; <ide> <ide><path>pdf.js <ide> var PartialEvaluator = (function() { <ide> <ide> var fontName = fontDict.get('Name'); <ide> if (!fontName) <del> fontName = xref.fetchIfRef(descriptor.get('FontName'));; <add> fontName = xref.fetchIfRef(descriptor.get('FontName')); <ide> assertWellFormed(IsName(fontName), 'invalid font name'); <ide> fontName = fontName.name.replace(/[\+,\-]/g, '_'); <ide>
2
PHP
PHP
fix cs error
a92f798d43a3caf4db2af944dbccc8063a995f48
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> public function testStartupNullAction(): void <ide> $this->Auth->setConfig([ <ide> 'authenticate' => ['Form'], <ide> 'authorize' => false, <del> 'loginAction' => ['controller' => 'auth_test', 'action' => 'login'] <add> 'loginAction' => ['controller' => 'auth_test', 'action' => 'login'], <ide> ]); <ide> <ide> $event = new Event('Controller.startup', $this->Controller);
1
Text
Text
change example link to be equal to query property
3096a772fb1ec088a0c87b08cd259a5d8fe310a6
<ide><path>docs/api-reference/next/link.md <ide> function Home() { <ide> export default Home <ide> ``` <ide> <del>The above example will be a link to `/about?name=Zeit`. You can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects). <add>The above example will be a link to `/about?name=ZEIT`. You can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects). <ide> <ide> ## Replace the URL instead of push <ide>
1
Text
Text
fix typo in releases.md
ed6a5ff4b43130c4cd0684e7ebb2af7c18ff7d16
<ide><path>Releases.md <ide> Circle CI will automatically run the tests and publish to npm with the version y <ide> <ide> ### Step 3: Write the release notes <ide> <del>Write the release notes, or post in [React Native Core Contributors](https://www.facebook.com/groups/reactnativeoss/) that the RC is ready to find a voluteer. You can also use [react-native-release-notes](https://github.com/knowbody/react-native-release-notes) to generate a draft of release notes. <add>Write the release notes, or post in [React Native Core Contributors](https://www.facebook.com/groups/reactnativeoss/) that the RC is ready to find a volunteer. You can also use [react-native-release-notes](https://github.com/knowbody/react-native-release-notes) to generate a draft of release notes. <ide> <ide> To go through all the commits that went into a release, one way is to use the GitHub compare view: <ide>
1
Java
Java
fix typos and suppress warnings in jdbctemplate
c79c4c6e253d97399e118c3f08b2e032df94f3f4
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java <ide> /* <del> * Copyright 2002-2010 the original author or authors. <add> * Copyright 2002-2012 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { <ide> /** <ide> * If this variable is set to true then all results from a stored procedure call <ide> * that don't have a corresponding SqlOutParameter declaration will be bypassed. <del> * All other results processng will be take place unless the variable <del> * <code>skipResultsProcessing</code> is set to <code>true</code> <add> * All other results processing will be take place unless the variable <add> * <code>skipResultsProcessing</code> is set to <code>true</code>. <ide> */ <ide> private boolean skipUndeclaredResults = false; <ide> <ide> public int getQueryTimeout() { <ide> } <ide> <ide> /** <del> * Set whether results processing should be skipped. Can be used to optimize callable <add> * Set whether results processing should be skipped. Can be used to optimize callable <ide> * statement processing when we know that no results are being passed back - the processing <del> * of out parameter will still take place. This can be used to avoid a bug in some older <add> * of out parameter will still take place. This can be used to avoid a bug in some older <ide> * Oracle JDBC drivers like 10.1.0.2. <ide> */ <ide> public void setSkipResultsProcessing(boolean skipResultsProcessing) { <ide> public boolean isSkipResultsProcessing() { <ide> } <ide> <ide> /** <del> * Set whether undelared results should be skipped. <add> * Set whether undeclared results should be skipped. <ide> */ <ide> public void setSkipUndeclaredResults(boolean skipUndeclaredResults) { <ide> this.skipUndeclaredResults = skipUndeclaredResults; <ide> public Map<String, Object> doInCallableStatement(CallableStatement cs) throws SQ <ide> * Extract returned ResultSets from the completed stored procedure. <ide> * @param cs JDBC wrapper for the stored procedure <ide> * @param updateCountParameters Parameter list of declared update count parameters for the stored procedure <del> * @param resultSetParameters Parameter list of declared resturn resultSet parameters for the stored procedure <add> * @param resultSetParameters Parameter list of declared resultSet parameters for the stored procedure <ide> * @return Map that contains returned results <ide> */ <add> @SuppressWarnings("rawtypes") <ide> protected Map<String, Object> extractReturnedResults( <ide> CallableStatement cs, List updateCountParameters, List resultSetParameters, int updateCount) <ide> throws SQLException { <ide> protected Map<String, Object> extractOutputParameters(CallableStatement cs, List <ide> * @param param the corresponding stored procedure parameter <ide> * @return Map that contains returned results <ide> */ <del> @SuppressWarnings("unchecked") <add> @SuppressWarnings({ "unchecked", "rawtypes" }) <ide> protected Map<String, Object> processResultSet(ResultSet rs, ResultSetSupportingSqlParameter param) throws SQLException { <ide> if (rs == null) { <ide> return Collections.emptyMap(); <ide> protected void applyStatementSettings(Statement stmt) throws SQLException { <ide> /** <ide> * Create a new ArgPreparedStatementSetter using the args passed in. This method allows the <ide> * creation to be overridden by sub-classes. <del> * @param args object array woth arguments <add> * @param args object array with arguments <ide> * @return the new PreparedStatementSetter <ide> */ <ide> protected PreparedStatementSetter newArgPreparedStatementSetter(Object[] args) { <ide> protected PreparedStatementSetter newArgPreparedStatementSetter(Object[] args) { <ide> /** <ide> * Create a new ArgTypePreparedStatementSetter using the args and argTypes passed in. <ide> * This method allows the creation to be overridden by sub-classes. <del> * @param args object array woth arguments <add> * @param args object array with arguments <ide> * @param argTypes int array of SQLTypes for arguments <ide> * @return the new PreparedStatementSetter <ide> */ <ide> public CloseSuppressingInvocationHandler(Connection target) { <ide> this.target = target; <ide> } <ide> <add> @SuppressWarnings("rawtypes") <ide> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { <ide> // Invocation on ConnectionProxy interface coming in... <ide>
1
Mixed
Javascript
handle build_id mismatch error
0bd250f4aaf773287754ba6f40156a1ce79cc8fb
<ide><path>lib/router/index.js <add>/* global window, location */ <ide> import _Router from './router' <ide> <ide> const SingletonRouter = { <ide> export const createRouter = function (...args) { <ide> <ide> // Export the actual Router class, which is usually used inside the server <ide> export const Router = _Router <add> <add>export function _notifyBuildIdMismatch (nextRoute) { <add> if (SingletonRouter.onAppUpdated) { <add> SingletonRouter.onAppUpdated(nextRoute) <add> } else { <add> location.href = nextRoute <add> } <add>} <ide><path>lib/router/router.js <ide> import evalScript from '../eval-script' <ide> import shallowEquals from '../shallow-equals' <ide> import PQueue from '../p-queue' <ide> import { loadGetInitialProps, getLocationOrigin } from '../utils' <add>import { _notifyBuildIdMismatch } from './' <ide> <ide> // Add "fetch" polyfill for older browsers <ide> if (typeof window !== 'undefined') { <ide> export default class Router extends EventEmitter { <ide> data, <ide> props, <ide> error <del> } = await this.getRouteInfo(route, pathname, query) <add> } = await this.getRouteInfo(route, pathname, query, as) <ide> <ide> if (error && error.cancelled) { <ide> this.emit('routeChangeError', error, as) <ide> export default class Router extends EventEmitter { <ide> data, <ide> props, <ide> error <del> } = await this.getRouteInfo(route, pathname, query) <add> } = await this.getRouteInfo(route, pathname, query, url) <ide> <ide> if (error && error.cancelled) { <ide> this.emit('routeChangeError', error, url) <ide> export default class Router extends EventEmitter { <ide> this.emit('routeChangeStart', as) <ide> const { <ide> data, props, error <del> } = await this.getRouteInfo(route, pathname, query) <add> } = await this.getRouteInfo(route, pathname, query, as) <ide> <ide> if (error && error.cancelled) { <ide> this.emit('routeChangeError', error, as) <ide> export default class Router extends EventEmitter { <ide> } <ide> } <ide> <del> async getRouteInfo (route, pathname, query) { <add> async getRouteInfo (route, pathname, query, as) { <ide> const routeInfo = {} <ide> <ide> try { <del> const { Component, err, jsonPageRes } = routeInfo.data = await this.fetchComponent(route) <add> routeInfo.data = await this.fetchComponent(route, as) <add> if (!routeInfo.data) { <add> return null <add> } <add> <add> const { Component, err, jsonPageRes } = routeInfo.data <ide> const ctx = { err, pathname, query, jsonPageRes } <ide> routeInfo.props = await this.getInitialProps(Component, ctx) <ide> } catch (err) { <ide> export default class Router extends EventEmitter { <ide> return this.prefetchQueue.add(() => this.fetchRoute(route)) <ide> } <ide> <del> async fetchComponent (route) { <add> async fetchComponent (route, as) { <ide> let data = this.components[route] <ide> if (data) return data <ide> <ide> export default class Router extends EventEmitter { <ide> <ide> const jsonPageRes = await this.fetchRoute(route) <ide> const jsonData = await jsonPageRes.json() <add> <add> if (jsonData.buildIdMismatch) { <add> _notifyBuildIdMismatch(as) <add> <add> const error = Error('Abort due to BUILD_ID mismatch') <add> error.cancelled = true <add> throw error <add> } <add> <ide> const newData = { <ide> ...loadComponent(jsonData), <ide> jsonPageRes <ide><path>readme.md <ide> Here's a list of supported events: <ide> - `routeChangeStart(url)` - Fires when a route starts to change <ide> - `routeChangeComplete(url)` - Fires when a route changed completely <ide> - `routeChangeError(err, url)` - Fires when there's an error when changing routes <add>- `appUpdated(nextRoute)` - Fires when switching pages and there's a new version of the app <ide> <ide> > Here `url` is the URL shown in the browser. If you call `Router.push(url, as)` (or similar), then the value of `url` will be `as`. <ide> <ide> Router.onRouteChangeError = (err, url) => { <ide> } <ide> ``` <ide> <add>If you change a route while in between a new deployment, we can't navigate the app via client side. We need to do a full browser navigation. We do it automatically for you. <add> <add>But you can customize that via `Route.onAppUpdated` event like this: <add> <add>```js <add>Router.onAppUpdated = (nextUrl) => { <add> // persist the local state <add> location.href = nextUrl <add>} <add>``` <add> <ide> ### Prefetching Pages <ide> <ide> <p><details> <ide><path>server/index.js <ide> export default class Server { <ide> }, <ide> <ide> '/_next/:buildId/main.js': async (req, res, params) => { <del> this.handleBuildId(params.buildId, res) <add> if (!this.handleBuildId(params.buildId, res)) { <add> throwBuildIdMismatchError() <add> } <add> <ide> const p = join(this.dir, '.next/main.js') <ide> await this.serveStatic(req, res, p) <ide> }, <ide> <ide> '/_next/:buildId/commons.js': async (req, res, params) => { <del> this.handleBuildId(params.buildId, res) <add> if (!this.handleBuildId(params.buildId, res)) { <add> throwBuildIdMismatchError() <add> } <add> <ide> const p = join(this.dir, '.next/commons.js') <ide> await this.serveStatic(req, res, p) <ide> }, <ide> <ide> '/_next/:buildId/pages/:path*': async (req, res, params) => { <del> this.handleBuildId(params.buildId, res) <add> if (!this.handleBuildId(params.buildId, res)) { <add> res.setHeader('Content-Type', 'application/json') <add> res.end(JSON.stringify({ buildIdMismatch: true })) <add> return <add> } <add> <ide> const paths = params.path || ['index'] <ide> const pathname = `/${paths.join('/')}` <ide> await this.renderJSON(req, res, pathname) <ide> export default class Server { <ide> } <ide> <ide> handleBuildId (buildId, res) { <del> if (this.dev) return <add> if (this.dev) return true <ide> if (buildId !== this.renderOpts.buildId) { <del> const errorMessage = 'Build id mismatch!' + <del> 'Seems like the server and the client version of files are not the same.' <del> throw new Error(errorMessage) <add> return false <ide> } <ide> <ide> res.setHeader('Cache-Control', 'max-age=365000000, immutable') <add> return true <ide> } <ide> <ide> getCompilationError (page) { <ide> export default class Server { <ide> if (p) return errors.get(p)[0] <ide> } <ide> } <add> <add>function throwBuildIdMismatchError () { <add> throw new Error('BUILD_ID Mismatched!') <add>} <ide><path>test/integration/basic/test/misc.js <ide> /* global describe, test, expect */ <ide> <del>export default function ({ app }) { <add>export default function (context) { <ide> describe('Misc', () => { <ide> test('finishes response', async () => { <ide> const res = { <ide> export default function ({ app }) { <ide> this.finished = true <ide> } <ide> } <del> const html = await app.renderToHTML({}, res, '/finish-response', {}) <add> const html = await context.app.renderToHTML({}, res, '/finish-response', {}) <ide> expect(html).toBeFalsy() <ide> }) <ide> })
5
Ruby
Ruby
fix the example code for `rails.groups` [ci skip]
bc76ecf6550375176e46f3ea296607744d12bbfe
<ide><path>railties/lib/rails.rb <ide> def env=(environment) <ide> # groups assets: [:development, :test] <ide> # <ide> # # Returns <del> # # => [:default, :development, :assets] for Rails.env == "development" <del> # # => [:default, :production] for Rails.env == "production" <add> # # => [:default, "development", :assets] for Rails.env == "development" <add> # # => [:default, "production"] for Rails.env == "production" <ide> def groups(*groups) <ide> hash = groups.extract_options! <ide> env = Rails.env
1
Javascript
Javascript
update variable validations
0b944ddfded8b7f44abf85ca1bd40ab0fd8c5c31
<ide><path>client/i18n/config.js <ide> import i18n from 'i18next'; <ide> import { initReactI18next } from 'react-i18next'; <ide> <del>const { environment, clientLocale } = require('../config/env'); <add>const { clientLocale } = require('../config/env'); <ide> const { i18nextCodes } = require('./allLangs'); <ide> <ide> const i18nextCode = i18nextCodes[clientLocale]; <ide> i18n.use(initReactI18next).init({ <ide> ns: ['translations', 'trending', 'intro'], <ide> defaultNS: 'translations', <ide> returnObjects: true, <del> debug: environment === 'development', <add> // Uncomment the next line for debug logging <add> // debug: true, <ide> interpolation: { <ide> escapeValue: false <ide> }, <ide><path>config/env.js <ide> const { <ide> <ide> const locations = { <ide> homeLocation, <add> chineseHome: !chineseHome ? 'https://chinese.freecodecamp.org' : chineseHome, <ide> apiLocation, <ide> forumLocation, <ide> newsLocation, <del> radioLocation, <del> chineseHome <add> radioLocation: !radioLocation <add> ? 'https://coderadio.freecodecamp.org' <add> : radioLocation <ide> }; <ide> <ide> module.exports = Object.assign(locations, { <ide><path>tools/scripts/build/ensure-env.js <ide> const { FREECODECAMP_NODE_ENV } = process.env; <ide> <ide> function checkClientLocale() { <ide> if (!availableLangs.client.includes(process.env.CLIENT_LOCALE)) { <del> throw Error( <del> `CLIENT_LOCALE, ${process.env.CLIENT_LOCALE}, is not an available language in client/i18n/allLangs.js` <del> ); <add> throw Error(` <add> <add> CLIENT_LOCALE, ${process.env.CLIENT_LOCALE}, is not an available language in client/i18n/allLangs.js <add> <add> `); <ide> } <ide> } <ide> <ide> function checkCurriculumLocale() { <ide> if (!availableLangs.curriculum.includes(process.env.CURRICULUM_LOCALE)) { <del> throw Error( <del> `CURRICULUM_LOCALE, ${process.env.CURRICULUM_LOCALE}, is not an available language in client/i18n/allLangs.js` <del> ); <add> throw Error(` <add> <add> CURRICULUM_LOCALE, ${process.env.CURRICULUM_LOCALE}, is not an available language in client/i18n/allLangs.js <add> <add> `); <ide> } <ide> } <ide> <ide> if (FREECODECAMP_NODE_ENV !== 'development') { <ide> const locationKeys = [ <ide> 'homeLocation', <add> 'chineseHome', <ide> 'apiLocation', <ide> 'forumLocation', <del> 'newsLocation' <add> 'newsLocation', <add> 'radioLocation' <ide> ]; <ide> const deploymentKeys = [ <ide> 'clientLocale', <ide> if (FREECODECAMP_NODE_ENV !== 'development') { <ide> searchKeys, <ide> donationKeys <ide> ); <del> const variables = Object.keys(env); <add> const receivedvariables = Object.keys(env); <ide> expectedVariables.sort(); <del> variables.sort(); <del> if (expectedVariables.length !== variables.length) { <del> throw Error(`Env. variable validation failed. Expected <del> ${expectedVariables} <del> but recieved <del> ${variables} <add> receivedvariables.sort(); <add> if (expectedVariables.length !== receivedvariables.length) { <add> throw Error(` <add> <add> Env. variable validation failed. Make sure these keys are used and configured. <add> <add> Mismatch: <add> ${expectedVariables <add> .filter(expected => !receivedvariables.includes(expected)) <add> .concat( <add> receivedvariables.filter( <add> received => !expectedVariables.includes(received) <add> ) <add> )} <add> <ide> `); <ide> } <ide> <ide> for (const key of expectedVariables) { <ide> if (typeof env[key] === 'undefined' || env[key] === null) { <del> throw Error(`Env. variable ${key} is missing, build cannot continue`); <add> throw Error(` <add> <add> Env. variable ${key} is missing, build cannot continue <add> <add> `); <ide> } <ide> } <ide> <ide> if (env['environment'] !== 'production') <del> throw Error("Production environment should be 'production' "); <add> throw Error(` <add> <add> Production environment should be 'production' <add> <add> `); <ide> <ide> if (env['showUpcomingChanges']) <del> throw Error("SHOW_UPCOMING_CHANGES should never be 'true' in production"); <add> throw Error(` <add> <add> SHOW_UPCOMING_CHANGES should never be 'true' in production <add> <add> `); <ide> <ide> checkClientLocale(); <ide> checkCurriculumLocale();
3
Ruby
Ruby
delete unused methods in joinassociation
1ddbb216eae155cd9347c7651b16a885867c542c
<ide><path>activerecord/lib/active_record/associations.rb <ide> def pluralize(table_name) <ide> ActiveRecord::Base.pluralize_table_names ? table_name.to_s.pluralize : table_name <ide> end <ide> <del> def table_alias_for(table_name, table_alias) <del> "#{table_name} #{table_alias if table_name != table_alias}".strip <del> end <del> <del> def table_name_and_alias <del> table_alias_for table_name, aliased_table_name <del> end <del> <ide> def interpolate_sql(sql) <ide> instance_eval("%@#{sql.gsub('@', '\@')}@", __FILE__, __LINE__) <ide> end
1
Text
Text
fix typos, grammar, and formatting [ci-skip]
cb0da4f817eee35089c1f12a4fa46a765611181f
<ide><path>guides/source/2_3_release_notes.md <ide> There are two major changes in the architecture of Rails applications: complete <ide> <ide> ### Rack Integration <ide> <del>Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test: <add>Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface). Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test: <ide> <ide> * Sessions <ide> * Cookies <ide> render 'other_controller/action' <ide> render 'show' <ide> render :show <ide> ``` <add> <ide> Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (`:inline`, `:text`, `:update`, `:nothing`, `:json`, `:xml`, `:js`) still require an explicit option. <ide> <ide> ### Application Controller Renamed <ide><path>guides/source/3_0_release_notes.md <ide> More information: - [Make Any Ruby Object Feel Like ActiveRecord](http://yehudak <ide> <ide> ### Controller Abstraction <ide> <del>Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views etc. This creation of `AbstractController` allowed `ActionController` and `ActionMailer` to be greatly simplified with common code removed from all these libraries and put into Abstract Controller. <add>Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views, etc. This creation of `AbstractController` allowed `ActionController` and `ActionMailer` to be greatly simplified with common code removed from all these libraries and put into Abstract Controller. <ide> <ide> More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/rails-edge-architecture/) <ide> <ide><path>guides/source/3_1_release_notes.md <ide> Railties <ide> <ide> * Added `Rack::Cache` to the default middleware stack. <ide> <del>* Engines received a major update - You can mount them at any path, enable assets, run generators etc. <add>* Engines received a major update - You can mount them at any path, enable assets, run generators, etc. <ide> <ide> Action Pack <ide> ----------- <ide> Active Record <ide> ```ruby <ide> class FooMigration < ActiveRecord::Migration <ide> def up # Not self.up <del> ... <add> # ... <ide> end <ide> end <ide> ``` <ide><path>guides/source/3_2_release_notes.md <ide> Active Record <ide> end <ide> <ide> Post.table_name # => "special_posts" <del> <ide> ``` <ide> <ide> Active Model <ide><path>guides/source/4_1_release_notes.md <ide> class Todo < ActiveRecord::Base <ide> end <ide> <ide> def latest_event <del> ... <add> # ... <ide> end <ide> <ide> private <ide> def some_internal_method <del> ... <add> # ... <ide> end <ide> end <ide> end <ide><path>guides/source/5_2_release_notes.md <ide> Please refer to the [Changelog][railties] for detailed changes. <ide> ([Pull Request](https://github.com/rails/rails/pull/29534)) <ide> <ide> * Skip unused components when running `bin/rails app:update`. <del> If the initial app generation skipped Action Cable, Active Record etc., <add> If the initial app generation skipped Action Cable, Active Record, etc., <ide> the update task honors those skips too. <ide> ([Pull Request](https://github.com/rails/rails/pull/29645)) <ide> <ide> Please refer to the [Changelog][railties] for detailed changes. <ide> ([Pull Request](https://github.com/rails/rails/pull/30633)) <ide> <ide> * `rails new` and `rails plugin new` get `Active Storage` by default. <del> Add ability to skip `Active Storage` with `--skip-active-storage` <del> and do so automatically when `--skip-active-record` is used. <add> Add ability to skip `Active Storage` with `--skip-active-storage` <add> and do so automatically when `--skip-active-record` is used. <ide> ([Pull Request](https://github.com/rails/rails/pull/30101)) <ide> <ide> Action Cable <ide><path>guides/source/action_cable_overview.md <ide> config.action_cable.worker_pool_size = 4 <ide> Also, note that your server must provide at least the same number of database <ide> connections as you have workers. The default worker pool size is set to 4, so <ide> that means you have to make at least 4 database connections available. <del> You can change that in `config/database.yml` through the `pool` attribute. <add>You can change that in `config/database.yml` through the `pool` attribute. <ide> <ide> ### Client side logging <ide> <ide> import * as ActionCable from '@rails/actioncable' <ide> ActionCable.logger.enabled = true <ide> ``` <ide> <del> <ide> ### Other Configurations <ide> <ide> The other common option to configure is the log tags applied to the <ide><path>guides/source/action_controller_overview.md <ide> Controller Naming Convention <ide> <ide> The naming convention of controllers in Rails favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. `ApplicationController`). For example, `ClientsController` is preferable to `ClientController`, `SiteAdminsController` is preferable to `SiteAdminController` or `SitesAdminsController`, and so on. <ide> <del>Following this convention will allow you to use the default route generators (e.g. `resources`, etc) without needing to qualify each `:path` or `:controller`, and will keep named route helpers' usage consistent throughout your application. See [Layouts & Rendering Guide](layouts_and_rendering.html) for more details. <add>Following this convention will allow you to use the default route generators (e.g. `resources`, etc) without needing to qualify each `:path` or `:controller`, and will keep named route helpers' usage consistent throughout your application. See [Layouts and Rendering Guide](layouts_and_rendering.html) for more details. <ide> <ide> NOTE: The controller naming convention differs from the naming convention of models, which are expected to be named in singular form. <ide> <ide> def new <ide> end <ide> ``` <ide> <del>The [Layouts & Rendering Guide](layouts_and_rendering.html) explains this in more detail. <add>The [Layouts and Rendering Guide](layouts_and_rendering.html) explains this in more detail. <ide> <ide> `ApplicationController` inherits from [`ActionController::Base`][], which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the [API documentation](https://api.rubyonrails.org/classes/ActionController.html) or in the source itself. <ide> <ide> These options will be used as a starting point when generating URLs, so it's pos <ide> <ide> If you define `default_url_options` in `ApplicationController`, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there. <ide> <del>In a given request, the method is not actually called for every single generated URL; for performance reasons, the returned hash is cached, there is at most one invocation per request. <add>In a given request, the method is not actually called for every single generated URL. For performance reasons, the returned hash is cached, and there is at most one invocation per request. <ide> <ide> ### Strong Parameters <ide> <ide> Your application has a session for each user in which you can store small amount <ide> <ide> * [`ActionDispatch::Session::CookieStore`][] - Stores everything on the client. <ide> * [`ActionDispatch::Session::CacheStore`][] - Stores the data in the Rails cache. <del>* `ActionDispatch::Session::ActiveRecordStore` - Stores the data in a database using Active Record. (require `activerecord-session_store` gem). <add>* `ActionDispatch::Session::ActiveRecordStore` - Stores the data in a database using Active Record (requires the `activerecord-session_store` gem). <ide> * [`ActionDispatch::Session::MemCacheStore`][] - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead). <ide> <ide> All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure). <ide> To reset the entire session, use [`reset_session`][]. <ide> <ide> ### The Flash <ide> <del>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc. <add>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages, etc. <ide> <ide> The flash is accessed via the [`flash`][] method. Like the session, the flash is represented as a hash. <ide> <ide> You can choose not to yield and build the response yourself, in which case the a <ide> <ide> ### Other Ways to Use Filters <ide> <del>While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing. <add>While the most common way to use filters is by creating private methods and using `before_action`, `after_action`, or `around_action` to add them, there are two other ways to do the same thing. <ide> <del>The first is to use a block directly with the *\_action methods. The block receives the controller as an argument. The `require_login` filter from above could be rewritten to use a block: <add>The first is to use a block directly with the `*_action` methods. The block receives the controller as an argument. The `require_login` filter from above could be rewritten to use a block: <ide> <ide> ```ruby <ide> class ApplicationController < ActionController::Base <ide> The Request and Response Objects <ide> <ide> In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The [`request`][] method contains an instance of [`ActionDispatch::Request`][] and the [`response`][] method returns a response object representing what is going to be sent back to the client. <ide> <del> [`ActionDispatch::Request`]: https://api.rubyonrails.org/classes/ActionDispatch/Request.html <del> [`request`]: https://api.rubyonrails.org/classes/ActionController/Base.html#method-i-request <del> [`response`]: https://api.rubyonrails.org/classes/ActionController/Base.html#method-i-response <add>[`ActionDispatch::Request`]: https://api.rubyonrails.org/classes/ActionDispatch/Request.html <add>[`request`]: https://api.rubyonrails.org/classes/ActionController/Base.html#method-i-request <add>[`response`]: https://api.rubyonrails.org/classes/ActionController/Base.html#method-i-response <ide> <ide> ### The `request` Object <ide> <ide> The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the [Rails API documentation](https://api.rubyonrails.org/classes/ActionDispatch/Request.html) and [Rack Documentation](https://www.rubydoc.info/github/rack/rack/Rack/Request). Among the properties that you can access on this object are: <ide> <ide> | Property of `request` | Purpose | <ide> | ----------------------------------------- | -------------------------------------------------------------------------------- | <del>| host | The hostname used for this request. | <del>| domain(n=2) | The hostname's first `n` segments, starting from the right (the TLD). | <del>| format | The content type requested by the client. | <del>| method | The HTTP method used for the request. | <del>| get?, post?, patch?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. | <del>| headers | Returns a hash containing the headers associated with the request. | <del>| port | The port number (integer) used for the request. | <del>| protocol | Returns a string containing the protocol used plus "://", for example "http://". | <del>| query_string | The query string part of the URL, i.e., everything after "?". | <del>| remote_ip | The IP address of the client. | <del>| url | The entire URL used for the request. | <add>| `host` | The hostname used for this request. | <add>| `domain(n=2)` | The hostname's first `n` segments, starting from the right (the TLD). | <add>| `format` | The content type requested by the client. | <add>| `method` | The HTTP method used for the request. | <add>| `get?`, `post?`, `patch?`, `put?`, `delete?`, `head?` | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. | <add>| `headers` | Returns a hash containing the headers associated with the request. | <add>| `port` | The port number (integer) used for the request. | <add>| `protocol` | Returns a string containing the protocol used plus "://", for example "http://". | <add>| `query_string` | The query string part of the URL, i.e., everything after "?". | <add>| `remote_ip` | The IP address of the client. | <add>| `url` | The entire URL used for the request. | <ide> <ide> #### `path_parameters`, `query_parameters`, and `request_parameters` <ide> <ide> The response object is not usually used directly, but is built up during the exe <ide> <ide> | Property of `response` | Purpose | <ide> | ---------------------- | --------------------------------------------------------------------------------------------------- | <del>| body | This is the string of data being sent back to the client. This is most often HTML. | <del>| status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. | <del>| location | The URL the client is being redirected to, if any. | <del>| content_type | The content type of the response. | <del>| charset | The character set being used for the response. Default is "utf-8". | <del>| headers | Headers used for the response. | <add>| `body` | This is the string of data being sent back to the client. This is most often HTML. | <add>| `status` | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. | <add>| `location` | The URL the client is being redirected to, if any. | <add>| `content_type` | The content type of the response. | <add>| `charset` | The character set being used for the response. Default is "utf-8". | <add>| `headers` | Headers used for the response. | <ide> <ide> #### Setting Custom Headers <ide> <ide><path>guides/source/action_mailer_basics.md <ide> message: <ide> * [`attachments`][] - Allows you to add attachments to your email. For example, <ide> `attachments['file-name.jpg'] = File.read('file-name.jpg')`. <ide> * [`mail`][] - Creates the actual email itself. You can pass in headers as a hash to <del> the mail method as a parameter, mail will then create an email, either plain <del> text, or multipart, depending on what email templates you have defined. <add> the `mail` method as a parameter. `mail` will create an email — either plain <add> text or multipart — depending on what email templates you have defined. <ide> <ide> [`attachments`]: https://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-attachments <ide> [`headers`]: https://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-headers <ide> Action Mailer makes it very easy to add attachments. <ide> <ide> * Pass the file name and content and Action Mailer and the <ide> [Mail gem](https://github.com/mikel/mail) will automatically guess the <del> mime_type, set the encoding, and create the attachment. <add> `mime_type`, set the `encoding`, and create the attachment. <ide> <ide> ```ruby <ide> attachments['filename.jpg'] = File.read('/path/to/filename.jpg') <ide> end <ide> This will render the template 'another_template.html.erb' for the HTML part and <ide> use the rendered text for the text part. The render command is the same one used <ide> inside of Action Controller, so you can use all the same options, such as <del>`:text`, `:inline` etc. <add>`:text`, `:inline`, etc. <ide> <ide> If you would like to render a template located outside of the default `app/views/mailer_name/` directory, you can apply the [`prepend_view_path`][], like so: <ide> <ide> If you did not configure the `:host` option globally make sure to pass it to <ide> #### Generating URLs with Named Routes <ide> <ide> Email clients have no web context and so paths have no base URL to form complete <del>web addresses. Thus, you should always use the "_url" variant of named route <add>web addresses. Thus, you should always use the `*_url` variant of named route <ide> helpers. <ide> <ide> If you did not configure the `:host` option globally make sure to pass it to the <ide> config.action_mailer.smtp_settings = { <ide> authentication: 'plain', <ide> enable_starttls_auto: true } <ide> ``` <add> <ide> NOTE: As of July 15, 2014, Google increased [its security measures](https://support.google.com/accounts/answer/6010255) and now blocks attempts from apps it deems less secure. <ide> You can change your Gmail settings [here](https://www.google.com/settings/security/lesssecureapps) to allow the attempts. If your Gmail account has 2-factor authentication enabled, <ide> then you will need to set an [app password](https://myaccount.google.com/apppasswords) and use that instead of your regular password. Alternatively, you can <ide> Action Mailer provides hooks into the Mail observer and interceptor methods. The <ide> <ide> ### Intercepting Emails <ide> <del>Interceptors allow you to make modifications to emails before they are handed off to the delivery agents. An interceptor class must implement the `:delivering_email(message)` method which will be called before the email is sent. <add>Interceptors allow you to make modifications to emails before they are handed off to the delivery agents. An interceptor class must implement the `::delivering_email(message)` method which will be called before the email is sent. <ide> <ide> ```ruby <ide> class SandboxEmailInterceptor <ide> end <ide> ``` <ide> <ide> Before the interceptor can do its job you need to register it using <del>[`register_interceptor`][]. You can do this in an initializer file <del>`config/initializers/sandbox_email_interceptor.rb` <add>[`register_interceptor`][]. You can do this in an initializer file like <add>`config/initializers/sandbox_email_interceptor.rb`: <ide> <ide> ```ruby <ide> if Rails.env.staging? <ide> end <ide> <ide> NOTE: The example above uses a custom environment called "staging" for a <ide> production like server but for testing purposes. You can read <del>[Creating Rails environments](configuring.html#creating-rails-environments) <add>[Creating Rails Environments](configuring.html#creating-rails-environments) <ide> for more information about custom Rails environments. <ide> <ide> [`register_interceptor`]: https://api.rubyonrails.org/classes/ActionMailer/Base.html#method-c-register_interceptor <ide> class EmailDeliveryObserver <ide> end <ide> end <ide> ``` <add> <ide> Similar to interceptors, you must register observers using [`register_observer`][]. You can do this in an initializer file <del>`config/initializers/email_delivery_observer.rb` <add>like `config/initializers/email_delivery_observer.rb`: <ide> <ide> ```ruby <ide> ActionMailer::Base.register_observer(EmailDeliveryObserver) <ide><path>guides/source/action_text_overview.md <ide> end <ide> <ide> ## Avoid N+1 queries <ide> <del>If you wish to preload the dependent `ActionText::RichText` model, assuming your rich text field is named 'content', you can use the named scope: <add>If you wish to preload the dependent `ActionText::RichText` model, assuming your rich text field is named `content`, you can use the named scope: <ide> <ide> ```ruby <ide> Message.all.with_rich_text_content # Preload the body without attachments. <ide><path>guides/source/active_job_basics.md <ide> After reading this guide, you will know: <ide> <ide> -------------------------------------------------------------------------------- <ide> <del> <ide> What is Active Job? <ide> ------------------- <ide> <ide> into small units of work and run in parallel, really. <ide> <ide> The Purpose of Active Job <ide> ----------------------------- <add> <ide> The main point is to ensure that all Rails apps will have a job infrastructure <ide> in place. We can then have framework features and other gems build on top of that, <ide> without having to worry about API differences between various job runners such as <ide> module YourApp <ide> end <ide> ``` <ide> <del>You can also configure your backend on a per job basis. <add>You can also configure your backend on a per job basis: <ide> <ide> ```ruby <ide> class GuestsCleanupJob < ApplicationJob <ide> self.queue_adapter = :resque <del> #.... <add> # ... <ide> end <ide> <del># Now your job will use `resque` as its backend queue adapter overriding what <add># Now your job will use `resque` as its backend queue adapter, overriding what <ide> # was configured in `config.active_job.queue_adapter`. <ide> ``` <ide> <ide> the job to run on a specific queue using [`queue_as`][]: <ide> ```ruby <ide> class GuestsCleanupJob < ApplicationJob <ide> queue_as :low_priority <del> #.... <add> # ... <ide> end <ide> ``` <ide> <ide> end <ide> # app/jobs/guests_cleanup_job.rb <ide> class GuestsCleanupJob < ApplicationJob <ide> queue_as :low_priority <del> #.... <add> # ... <ide> end <ide> <ide> # Now your job will run on queue production_low_priority on your <ide> You can also configure the prefix on a per job basis. <ide> class GuestsCleanupJob < ApplicationJob <ide> queue_as :low_priority <ide> self.queue_name_prefix = nil <del> #.... <add> # ... <ide> end <ide> <ide> # Now your job's queue won't be prefixed, overriding what <ide> end <ide> # app/jobs/guests_cleanup_job.rb <ide> class GuestsCleanupJob < ApplicationJob <ide> queue_as :low_priority <del> #.... <add> # ... <ide> end <ide> <ide> # Now your job will run on queue production.low_priority on your <ide> end <ide> ``` <ide> <ide> If you want more control on what queue a job will be run you can pass a `:queue` <del>option to `#set`: <add>option to `set`: <ide> <ide> ```ruby <ide> MyJob.set(queue: :another_queue).perform_later(record) <ide> ``` <ide> <del>To control the queue from the job level you can pass a block to `#queue_as`. The <del>block will be executed in the job context (so you can access `self.arguments`) <del>and you must return the queue name: <add>To control the queue from the job level you can pass a block to `queue_as`. The <add>block will be executed in the job context (so it can access `self.arguments`), <add>and it must return the queue name: <ide> <ide> ```ruby <ide> class ProcessVideoJob < ApplicationJob <ide> of the `.deliver_later` emails are processed. To avoid this problem, use <ide> Internationalization <ide> -------------------- <ide> <del>Each job uses the `I18n.locale` set when the job was created. Useful if you send <add>Each job uses the `I18n.locale` set when the job was created. This is useful if you send <ide> emails asynchronously: <ide> <ide> ```ruby <ide> class GuestsCleanupJob < ApplicationJob <ide> end <ide> ``` <ide> <del>If the exception is not rescued within the job, e.g. as shown above, then the job is referred to as "failed". <add>If an exception from a job is not rescued, then the job is referred to as "failed". <ide> <ide> [`rescue_from`]: https://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html#method-i-rescue_from <ide> <ide><path>guides/source/active_record_basics.md <ide> by underscores. Examples: <ide> | `Mouse` | `mice` | <ide> | `Person` | `people` | <ide> <del> <ide> ### Schema Conventions <ide> <ide> Active Record uses naming conventions for the columns in database tables, <ide> definition: <ide> class ProductTest < ActiveSupport::TestCase <ide> set_fixture_class my_products: Product <ide> fixtures :my_products <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> end <ide> ``` <ide> <ide> Rails keeps track of which files have been committed to the database and <del>provides rollback features. To actually create the table, you'd run `bin/rails db:migrate` <add>provides rollback features. To actually create the table, you'd run `bin/rails db:migrate`, <ide> and to roll it back, `bin/rails db:rollback`. <ide> <ide> Note that the above code is database-agnostic: it will run in MySQL, <ide><path>guides/source/active_record_migrations.md <ide> class AddPartNumberToProducts < ActiveRecord::Migration[6.0] <ide> end <ide> ``` <ide> <del> <ide> Similarly, you can generate a migration to remove a column from the command line: <ide> <ide> ```bash <ide> or remove from it as you see fit by editing the <ide> `db/migrate/YYYYMMDDHHMMSS_add_details_to_products.rb` file. <ide> <ide> Also, the generator accepts column type as `references` (also available as <del>`belongs_to`). For instance: <add>`belongs_to`). For example, <ide> <ide> ```bash <ide> $ bin/rails generate migration AddUserRefToProducts user:references <ide> definitions: <ide> * [`add_index`][] <ide> * [`add_reference`][] <ide> * [`add_timestamps`][] <del>* [`change_column_default`][] (must supply a :from and :to option) <add>* [`change_column_default`][] (must supply a `:from` and `:to` option) <ide> * [`change_column_null`][] <ide> * [`create_join_table`][] <ide> * [`create_table`][] <ide><path>guides/source/active_record_multiple_databases.md <ide> Note that there is no command for creating the users and you'll need to do that <ide> to support the readonly users for your replicas. If you want to create just the animals <ide> database you can run `bin/rails db:create:animals`. <ide> <del>## Generators & Migrations <add>## Generators and Migrations <ide> <ide> Migrations for multiple databases should live in their own folders prefixed with the <ide> name of the database key in the configuration. <ide><path>guides/source/active_record_querying.md <ide> The SQL that would be executed: <ide> ```sql <ide> SELECT * FROM books WHERE id > 100 LIMIT 20 <ide> <del># Original query without `unscope` <add>-- Original query without `unscope` <ide> SELECT * FROM books WHERE id > 100 ORDER BY id desc LIMIT 20 <del> <ide> ``` <ide> <ide> You can also unscope specific `where` clauses. For example, this will remove `id` condition from the where clause: <ide> The SQL that would be executed: <ide> ```sql <ide> SELECT * FROM books WHERE id > 10 ORDER BY id DESC <ide> <del># Original query without `only` <add>-- Original query without `only` <ide> SELECT * FROM books WHERE id > 10 ORDER BY id DESC LIMIT 20 <del> <ide> ``` <ide> <ide> [`only`]: https://api.rubyonrails.org/classes/ActiveRecord/SpawnMethods.html#method-i-only <ide> Book.first.highlighted_reviews.average(:rating) <ide> # => Returns average rating of a book <ide> <ide> class Book <del> # Returns reviews if there are atleast 5, <add> # Returns reviews if there are at least 5, <ide> # else consider this as non-reviewed book <ide> def highlighted_reviews <ide> if reviews.count > 5 <ide> SELECT books.* FROM books <ide> <ide> Or, in English: "return all books that have a review by a customer." <ide> <del> <ide> ##### Joining Nested Associations (Multiple Level) <ide> <ide> ```ruby <ide> INNER JOIN suppliers ON suppliers.id = books.supplier_id <ide> <ide> Or, in English: "return all authors that have books with reviews _and_ have been ordered by a customer, and the suppliers for those books." <ide> <del> <ide> #### Specifying Conditions on the Joined Tables <ide> <ide> You can specify conditions on the joined tables using the regular [Array](#array-conditions) and [String](#pure-string-conditions) conditions. [Hash conditions](#hash-conditions) provide a special syntax for specifying conditions for the joined tables: <ide> irb> order.complete? <ide> ``` <ide> <ide> These instance methods are created automatically and will first update the value of `status` to the named value <del> and then query whether or not the status has been successfully set to the value: <add>and then query whether or not the status has been successfully set to the value: <ide> <ide> ```irb <ide> irb> order = Order.first <ide> have to be at the end of the statement. <ide> <ide> There are some examples below. This guide won't cover all the possibilities, just a few as examples. <ide> When an Active Record method is called, the query is not immediately generated and sent to the database. <del> The query is sent only when the data is actually needed. So each example below generates a single query. <add>The query is sent only when the data is actually needed. So each example below generates a single query. <ide> <ide> ### Retrieving filtered data from multiple tables <ide> <ide> It's common that you need to find a record or create it if it doesn't exist. You <ide> <ide> The [`find_or_create_by`][] method checks whether a record with the specified attributes exists. If it doesn't, then `create` is called. Let's see an example. <ide> <del>Suppose you want to find a customer named 'Andy', and if there's none, create one. You can do so by running: <add>Suppose you want to find a customer named "Andy", and if there's none, create one. You can do so by running: <ide> <ide> ```irb <ide> irb> Customer.find_or_create_by(first_name: 'Andy') <ide> Customer.pluck(:id, :first_name) <ide> <ide> Unlike `select`, `pluck` directly converts a database result into a Ruby `Array`, <ide> without constructing `ActiveRecord` objects. This can mean better performance for <del>a large or often-running query. However, any model method overrides will <add>a large or frequently-run query. However, any model method overrides will <ide> not be available. For example: <ide> <ide> ```ruby <ide> irb> Customer.pluck(:first_name) <ide> You are not limited to querying fields from a single table, you can query multiple tables as well. <ide> <ide> ```irb <del>irb> Order.joins(:customer, :books).pluck("orders.created_at, customers.email, books.title") <add>irb> Order.joins(:customer, :books).pluck("orders.created_at, customers.email, books.title") <ide> ``` <ide> <ide> Furthermore, unlike `select` and other `Relation` scopes, `pluck` triggers an immediate <ide> SELECT COUNT(DISTINCT customers.id) FROM customers <ide> LEFT OUTER JOIN orders ON orders.customer_id = customers.id <ide> WHERE (customers.first_name = 'Ryan' AND orders.status = 0) <ide> ``` <del>assuming that Order has `enum status: [ :shipped, :being_packed, :cancelled ]` <add> <add>assuming that Order has `enum status: [ :shipped, :being_packed, :cancelled ]`. <ide> <ide> ### Count <ide> <ide><path>guides/source/active_record_validations.md <ide> controller-level validations. Here's a summary of the pros and cons: <ide> * Controller-level validations can be tempting to use, but often become <ide> unwieldy and difficult to test and maintain. Whenever possible, it's a good <ide> idea to keep your controllers skinny, as it will make your application a <del> pleasure to work within the long run. <add> pleasure to work with in the long run. <ide> <ide> Choose these in certain, specific cases. It's the opinion of the Rails team <ide> that model-level validations are the most appropriate in most circumstances. <ide> The possible length constraint options are: <ide> * `:is` - The attribute length must be equal to the given value. <ide> <ide> The default error messages depend on the type of length validation being <del>performed. You can personalize these messages using the `:wrong_length`, <add>performed. You can customize these messages using the `:wrong_length`, <ide> `:too_long`, and `:too_short` options and `%{count}` as a placeholder for the <ide> number corresponding to the length constraint being used. You can still use the <ide> `:message` option to specify an error message. <ide> end <ide> <ide> Note that the default error messages are plural (e.g., "is too short (minimum <ide> is %{count} characters)"). For this reason, when `:minimum` is 1 you should <del>provide a personalized message or use `presence: true` instead. When <add>provide a custom message or use `presence: true` instead. When <ide> `:in` or `:within` have a lower limit of 1, you should either provide a <del>personalized message or call `presence` prior to `length`. <add>custom message or call `presence` prior to `length`. <ide> <ide> ### `numericality` <ide> <ide> class Holiday < ApplicationRecord <ide> message: "should happen once per year" } <ide> end <ide> ``` <add> <ide> Should you wish to create a database constraint to prevent possible violations of a uniqueness validation using the `:scope` option, you must create a unique index on both columns in your database. See [the MySQL manual](https://dev.mysql.com/doc/refman/en/multiple-column-indexes.html) for more details about multiple column indexes or [the PostgreSQL manual](https://www.postgresql.org/docs/current/static/ddl-constraints.html) for examples of unique constraints that refer to a group of columns. <ide> <ide> There is also a `:case_sensitive` option that you can use to define whether the <ide><path>guides/source/active_storage_overview.md <ide> Generate a permanent URL for the blob that points to the application. Upon <ide> access, a redirect to the actual service endpoint is returned. This indirection <ide> decouples the service URL from the actual one, and allows, for example, mirroring <ide> attachments in different services for high-availability. The redirection has an <del>HTTP expiration of 5 min. <add>HTTP expiration of 5 minutes. <ide> <ide> ```ruby <ide> url_for(user.avatar) <ide> to "attachment" for some kind of files. To change this behaviour see the <ide> available configuration options in [Configuring Rails Applications](configuring.html#configuring-active-storage). <ide> <ide> If you need to create a link from outside of controller/view context (Background <del>jobs, Cronjobs, etc.), you can access the rails_blob_path like this: <add>jobs, Cronjobs, etc.), you can access the `rails_blob_path` like this: <ide> <ide> ```ruby <ide> Rails.application.routes.url_helpers.rails_blob_path(user.avatar, only_path: true) <ide> a link to a lazily-generated preview, use the attachment's [`preview`][] method: <ide> </ul> <ide> ``` <ide> <del>WARNING: Extracting previews requires third-party applications, FFmpeg v3.4+ for <add>WARNING: Extracting previews requires third-party applications: FFmpeg v3.4+ for <ide> video and muPDF for PDFs, and on macOS also XQuartz and Poppler. <ide> These libraries are not provided by Rails. You must install them yourself to <ide> use the built-in previewers. Before you install and use third-party software, <ide> directly from the client to the cloud. <ide> <ide> ```js <ide> //= require activestorage <del> <ide> ``` <ide> <ide> Using the npm package: <ide> directly from the client to the cloud. <ide> ActiveStorage.start() <ide> ``` <ide> <del>2. Add `direct_upload: true` to your [`file_field`](form_helpers.html#uploading-files). <add>2. Add `direct_upload: true` to your [file field](form_helpers.html#uploading-files): <ide> <ide> ```erb <ide> <%= form.file_field :attachments, multiple: true, direct_upload: true %> <ide> ``` <del> <del> If you aren't using a [FormBuilder](form_helpers.html#customizing-form-builders), add the data attribute directly: <add> <add> Or, if you aren't using a `FormBuilder`, add the data attribute directly: <ide> <ide> ```erb <ide> <input type=file data-direct-upload-url="<%= rails_direct_uploads_url %>" /> <ide><path>guides/source/active_support_core_extensions.md <ide> The method [`present?`][Object#present?] is equivalent to `!blank?`. This exampl <ide> ```ruby <ide> def set_conditional_cache_control! <ide> return if self["Cache-Control"].present? <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`. <ide> [Module#cattr_reader]: https://api.rubyonrails.org/classes/Module.html#method-i-cattr_reader <ide> [Module#cattr_writer]: https://api.rubyonrails.org/classes/Module.html#method-i-cattr_writer <ide> <del>### Subclasses & Descendants <add>### Subclasses and Descendants <ide> <ide> #### `subclasses` <ide> <ide> Rails class and module autoloading uses `underscore` to infer the relative path <ide> ```ruby <ide> # active_support/dependencies.rb <ide> def load_missing_constant(from_mod, const_name) <del> ... <add> # ... <ide> qualified_name = qualified_name_for from_mod, const_name <ide> path_suffix = qualified_name.underscore <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> Given a string with a qualified constant name, [`demodulize`][String#demodulize] <ide> "Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils" <ide> "::Inflections".demodulize # => "Inflections" <ide> "".demodulize # => "" <del> <ide> ``` <ide> <ide> Active Record for example uses this method to compute the name of a counter cache column: <ide> def full_messages <ide> end <ide> <ide> def full_message <del> ... <add> # ... <ide> attr_name = attribute.to_s.tr('.', '_').humanize <ide> attr_name = @base.class.human_attribute_name(attribute, default: attr_name) <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> NOTE: Defined in `active_support/core_ext/integer/time.rb`. <ide> <ide> Extensions to `BigDecimal` <ide> -------------------------- <add> <ide> ### `to_s` <ide> <ide> The method `to_s` provides a default specifier of "F". This means that a simple call to `to_s` will result in floating point representation instead of engineering notation: <ide> Let's see for example the definition of the `caches_action` controller macro: <ide> def caches_action(*actions) <ide> return unless cache_configured? <ide> options = actions.extract_options! <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> This method may be useful for example to easily accept both symbols and strings <ide> def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0") <ide> options = options.stringify_keys <ide> options["type"] = "checkbox" <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> In case of key collision, the value will be the one most recently inserted into <ide> <ide> ```ruby <ide> {"a" => 1, a: 2}.symbolize_keys <del># The result will be <ide> # => {:a=>2} <ide> ``` <ide> <ide> This method may be useful for example to easily accept both symbols and strings <ide> def rich_text_area_tag(name, value = nil, options = {}) <ide> options = options.symbolize_keys <ide> <del> options[:input] ||= "trix_input_#{ActionText::TagHelper.id += 1} <del> ... <add> options[:input] ||= "trix_input_#{ActionText::TagHelper.id += 1}" <add> # ... <ide> end <ide> ``` <ide> <ide> NOTE: Defined in `active_support/core_ext/hash/keys.rb`. <ide> <ide> #### `to_options` and `to_options!` <ide> <del>The methods [`to_options`][Hash#to_options] and [`to_options!`][Hash#to_options!] are respectively aliases of `symbolize_keys` and `symbolize_keys!`. <add>The methods [`to_options`][Hash#to_options] and [`to_options!`][Hash#to_options!] are aliases of `symbolize_keys` and `symbolize_keys!`, respectively. <ide> <ide> NOTE: Defined in `active_support/core_ext/hash/keys.rb`. <ide> <ide> Rails uses this method in a single place, also in the routing code. Multiline re <ide> <ide> ```ruby <ide> def verify_regexp_requirements(requirements) <del> ... <add> # ... <ide> if requirement.multiline? <ide> raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}" <ide> end <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide><path>guides/source/active_support_instrumentation.md <ide> INFO. Options passed to fetch will be merged with the payload when writing to th <ide> } <ide> ``` <ide> <del> <ide> ### cache_fetch_hit.active_support <ide> <ide> This event is only used when `#fetch` is called with a block. <ide><path>guides/source/api_documentation_guidelines.md <ide> Start comments in upper case. Follow regular punctuation rules: <ide> # Declares an attribute reader backed by an internally-named <ide> # instance variable. <ide> def attr_internal_reader(*attrs) <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide> When "true" and "false" are English words rather than Ruby keywords use a regula <ide> # matter the context. Validations with # some <tt>:on</tt> <ide> # option will only run in the specified context. <ide> def valid?(context = nil) <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide><path>guides/source/asset_pipeline.md <ide> config.assets.js_compressor = :uglifier <ide> NOTE: The `sass-rails` gem is automatically used for CSS compression if included <ide> in the `Gemfile` and no `config.assets.css_compressor` option is set. <ide> <del> <ide> ### Main Features <ide> <ide> The first feature of the pipeline is to concatenate assets, which can reduce the <ide> The query string strategy has several disadvantages: <ide> query parameters** <ide> <ide> [Steve Souders recommends](https://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/), <del> "...avoiding a querystring for cacheable resources". He found that in this <add>"...avoiding a querystring for cacheable resources". He found that in this <ide> case 5-20% of requests will not be cached. Query strings in particular do not <ide> work at all with some CDNs for cache invalidation. <ide> <ide> gem. <ide> ```ruby <ide> config.assets.css_compressor = :yui <ide> ``` <add> <ide> The other option for compressing CSS if you have the sass-rails gem installed is <ide> <ide> ```ruby <ide> NOTE: You will need an [ExecJS](https://github.com/rails/execjs#readme) <ide> supported runtime in order to use `uglifier`. If you are using macOS or <ide> Windows you have a JavaScript runtime installed in your operating system. <ide> <del> <del> <ide> ### GZipping your assets <ide> <ide> By default, gzipped version of compiled assets will be generated, along with <ide> To enable this, pass a new object to the config option in `application.rb`: <ide> config.assets.css_compressor = Transformer.new <ide> ``` <ide> <del> <ide> ### Changing the _assets_ Path <ide> <ide> The public path that Sprockets uses by default is `/assets`. <ide><path>guides/source/association_basics.md <ide> Here are a few things you should know to make efficient use of Active Record ass <ide> All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example: <ide> <ide> ```ruby <del>author.books.load # retrieves books from the database <del>author.books.size # uses the cached copy of books <del>author.books.empty? # uses the cached copy of books <add># retrieves books from the database <add>author.books.load <add> <add># uses the cached copy of books <add>author.books.size <add> <add># uses the cached copy of books <add>author.books.empty? <ide> ``` <ide> <ide> But what if you want to reload the cache, because data might have been changed by some other part of the application? Just call `reload` on the association: <ide> <ide> ```ruby <del>author.books.load # retrieves books from the database <del>author.books.size # uses the cached copy of books <del>author.books.reload.empty? # discards the cached copy of books <del> # and goes back to the database <add># retrieves books from the database <add>author.books.load <add> <add># uses the cached copy of books <add>author.books.size <add> <add># discards the cached copy of books and goes back to the database <add>author.books.reload.empty? <ide> ``` <ide> <ide> ### Avoiding Name Collisions <ide> In database terms, the `belongs_to` association says that this model's table con <ide> This can be used to set up one-to-one or one-to-many relations, depending on the setup. <ide> If the table of the other class contains the reference in a one-to-one relation, then you should use `has_one` instead. <ide> <del> <ide> #### Methods Added by `belongs_to` <ide> <ide> When you declare a `belongs_to` association, the declaring class automatically gains 6 methods related to the association: <ide> The `create_association` method returns a new object of the associated type. Thi <ide> <ide> Does the same as `create_association` above, but raises `ActiveRecord::RecordInvalid` if the record is invalid. <ide> <del> <ide> #### Options for `belongs_to` <ide> <ide> While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `belongs_to` association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options: <ide> The `:counter_cache` option can be used to make finding the number of belonging <ide> class Book < ApplicationRecord <ide> belongs_to :author <ide> end <add> <ide> class Author < ApplicationRecord <ide> has_many :books <ide> end <ide> With these declarations, asking for the value of `@author.books.size` requires m <ide> class Book < ApplicationRecord <ide> belongs_to :author, counter_cache: true <ide> end <add> <ide> class Author < ApplicationRecord <ide> has_many :books <ide> end <ide> the `counter_cache` declaration instead of `true`. For example, to use <ide> class Book < ApplicationRecord <ide> belongs_to :author, counter_cache: :count_of_books <ide> end <add> <ide> class Author < ApplicationRecord <ide> has_many :books <ide> end <ide> When you declare a `has_many` association, the declaring class automatically gai <ide> * [`collection.find(...)`][`collection.find`] <ide> * [`collection.where(...)`][`collection.where`] <ide> * [`collection.exists?(...)`][`collection.exists?`] <del>* [`collection.build(attributes = {}, ...)`][`collection.build`] <add>* [`collection.build(attributes = {})`][`collection.build`] <ide> * [`collection.create(attributes = {})`][`collection.create`] <ide> * [`collection.create!(attributes = {})`][`collection.create!`] <ide> * [`collection.reload`][] <ide> The [`collection.where`][] method finds objects within the collection based on t <ide> The [`collection.exists?`][] method checks whether an object meeting the supplied <ide> conditions exists in the collection's table. <ide> <del>##### `collection.build(attributes = {}, ...)` <add>##### `collection.build(attributes = {})` <ide> <ide> The [`collection.build`][] method returns a single or array of new objects of the associated type. The object(s) will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved. <ide> <ide> end <ide> Now if we execute `@todo = @user.todos.create` then the `@todo` <ide> record's `user_id` value will be the `guid` value of `@user`. <ide> <del> <ide> ##### `:source` <ide> <ide> The `:source` option specifies the source association name for a `has_many :through` association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name. <ide> The `has_and_belongs_to_many` association creates a many-to-many relationship wi <ide> <ide> #### Methods Added by `has_and_belongs_to_many` <ide> <del>When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains 17 methods related to the association: <add>When you declare a `has_and_belongs_to_many` association, the declaring class automatically gains several methods related to the association: <ide> <ide> * `collection` <ide> * [`collection<<(object, ...)`][`collection<<`] <ide> If the join table for a `has_and_belongs_to_many` association has additional col <ide> <ide> WARNING: The use of extra attributes on the join table in a `has_and_belongs_to_many` association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a `has_many :through` association instead of `has_and_belongs_to_many`. <ide> <del> <ide> ##### `collection` <ide> <ide> The `collection` method returns a Relation of all of the associated objects. If there are no associated objects, it returns an empty Relation. <ide> class Author < ApplicationRecord <ide> has_many :books, before_add: :check_credit_limit <ide> <ide> def check_credit_limit(book) <del> ... <add> # ... <ide> end <ide> end <ide> ``` <ide> class Author < ApplicationRecord <ide> before_add: [:check_credit_limit, :calculate_shipping_charges] <ide> <ide> def check_credit_limit(book) <del> ... <add> # ... <ide> end <ide> <ide> def calculate_shipping_charges(book) <del> ... <add> # ... <ide> end <ide> end <ide> ``` <ide><path>guides/source/autoloading_and_reloading_constants.md <ide> After reading this guide, you will know: <ide> <ide> -------------------------------------------------------------------------------- <ide> <del> <ide> Introduction <ide> ------------ <ide> <ide><path>guides/source/autoloading_and_reloading_constants_classic_mode.md <ide> After reading this guide, you will know: <ide> <ide> -------------------------------------------------------------------------------- <ide> <del> <ide> Introduction <ide> ------------ <ide> <ide> default it contains: <ide> <ide> How files are autoloaded depends on `eager_load` and `cache_classes` config settings which typically vary in development, production, and test modes: <ide> <del> * In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below). <del> * In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to be have thread-safety problems. <del> * In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour. <add>* In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below). <add>* In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to be have thread-safety problems. <add>* In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour. <ide> <ide> What is described above are the defaults with a newly generated Rails app. <ide> There are multiple ways this can be configured differently (see [Configuring <del>Rails Applications](configuring.html#rails-general-configuration).). Before <del>Rails 5 developers might configure `autoload_paths` to add in extra locations <add>Rails Applications](configuring.html#rails-general-configuration)). In the past, before <add>Rails 5, developers might configure `autoload_paths` to add in extra locations <ide> (e.g. `lib` which used to be an autoload path list years ago, but no longer <ide> is). However this is now discouraged for most purposes, as it is likely to <ide> lead to production-only errors. It is possible to add new locations to both <ide> Files defining constants to be autoloaded should never be `require`d: <ide> require "user" # DO NOT DO THIS <ide> <ide> class UsersController < ApplicationController <del> ... <add> # ... <ide> end <ide> ``` <ide> <ide><path>guides/source/caching_with_rails.md <ide> All cached templates from previous renders will be fetched at once with much <ide> greater speed. Additionally, the templates that haven't yet been cached will be <ide> written to cache and multi fetched on the next render. <ide> <del> <ide> ### Russian Doll Caching <ide> <ide> You may want to nest cached fragments inside other cached fragments. This is <ide> class ProductsController < ApplicationController <ide> # Run a find query <ide> @products = Product.all <ide> <del> ... <add> # ... <ide> <ide> # Run the same query again <ide> @products = Product.all <ide> connection library by additionally adding its ruby wrapper to your Gemfile: <ide> gem 'hiredis' <ide> ``` <ide> <del>Redis cache store will automatically require & use hiredis if available. No further <add>Redis cache store will automatically require and use hiredis if available. No further <ide> configuration is needed. <ide> <ide> Finally, add the configuration in the relevant `config/environments/*.rb` file: <ide><path>guides/source/configuring.md <ide> in controllers and views. This defaults to `false`. <ide> <ide> * `config.active_record.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling `logger` on either an Active Record model class or an Active Record model instance. Set to `nil` to disable logging. <ide> <del>* `config.active_record.primary_key_prefix_type` lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named `id` (and this configuration option doesn't need to be set.) There are two other choices: <add>* `config.active_record.primary_key_prefix_type` lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named `id` (and this configuration option doesn't need to be set). There are two other choices: <ide> * `:table_name` would make the primary key for the Customer class `customerid`. <ide> * `:table_name_with_underscore` would make the primary key for the Customer class `customer_id`. <ide> <ide> Defaults to `'signed cookie'`. <ide> <ide> * `config.action_mailbox.queues.routing` accepts a symbol indicating the Active Job queue to use for routing jobs. When this option is `nil`, routing jobs are sent to the default Active Job queue (see `config.active_job.default_queue_name`). It defaults to `:action_mailbox_routing`. <ide> <del> <ide> ### Configuring Action Mailer <ide> <ide> There are a number of settings available on `config.action_mailer`: <ide> There are a number of settings available on `config.action_mailer`: <ide> <ide> * `config.action_mailer.delivery_job` specifies delivery job for mail. <ide> <del> <ide> ### Configuring Active Support <ide> <ide> There are a few configuration options available in Active Support: <ide> normal Rails server. <ide> You can find more detailed configuration options in the <ide> [Action Cable Overview](action_cable_overview.html#configuration). <ide> <del> <ide> ### Configuring Active Storage <ide> <ide> `config.active_storage` provides the following configuration options: <ide> text/javascript image/svg+xml application/postscript application/x-shockwave-fla <ide> <ide> ### Results of `config.load_defaults` <ide> <del>`config.load_defaults` sets new defaults up to and including the version passed. Such that passing, say, '6.0' also gets the new defaults from every version before it. <add>`config.load_defaults` sets new defaults up to and including the version passed. Such that passing, say, `6.0` also gets the new defaults from every version before it. <ide> <ide> #### For '6.1', defaults from previous versions below and: <ide> <ide> The `config/database.yml` file can contain ERB tags `<%= %>`. Anything in the ta <ide> <ide> TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the `config/database.yml` file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below. <ide> <del> <ide> ### Connection Preference <ide> <ide> Since there are two ways to configure your connection (using `config/database.yml` or using an environment variable) it is important to understand how they can interact. <ide> Imagine you have a server which mirrors the production environment but is only u <ide> <ide> That environment is no different than the default ones, start a server with `bin/rails server -e staging`, a console with `bin/rails console -e staging`, `Rails.env.staging?` works, etc. <ide> <del> <ide> ### Deploy to a Subdirectory (relative URL root) <ide> <ide> By default Rails expects that your application is running at the root <ide> development: <ide> timeout: 5000 <ide> ``` <ide> <del>Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, Puma, Unicorn etc.) should behave the same. The database connection pool is initially empty. As demand for connections increases it will create them until it reaches the connection pool limit. <add>Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, Puma, Unicorn, etc.) should behave the same. The database connection pool is initially empty. As demand for connections increases it will create them until it reaches the connection pool limit. <ide> <ide> Any one request will check out a connection the first time it requires access to the database. At the end of the request it will check the connection back in. This means that the additional connection slot will be available again for the next request in the queue. <ide> <ide> development: <ide> qux: 2 <ide> ``` <ide> <del> <ide> ```ruby <ide> # development environment <ide> Rails.application.config_for(:example)[:foo][:bar] #=> { baz: 1, qux: 2 } <ide><path>guides/source/contributing_to_ruby_on_rails.md <ide> Or: <ide> $ cd activerecord <ide> $ bundle exec rake db:postgresql:build <ide> ``` <add> <ide> This is not necessary for SQLite3. <ide> <ide> This is how you run the Active Record test suite only for SQLite3: <ide><path>guides/source/engines.md <ide> After reading this guide, you will know: <ide> * How to build features for the engine. <ide> * How to hook the engine into an application. <ide> * How to override engine functionality in the application. <del>* Avoid loading Rails frameworks with Load and Configuration Hooks <add>* How to avoid loading Rails frameworks with Load and Configuration Hooks. <ide> <ide> -------------------------------------------------------------------------------- <ide> <ide> require_dependency "blorgh/application_controller" <ide> <ide> module Blorgh <ide> class ArticlesController < ApplicationController <del> ... <add> # ... <ide> end <ide> end <ide> ``` <ide> class is defined within the `Blorgh` module: <ide> ```ruby <ide> module Blorgh <ide> class ArticlesController < ApplicationController <del> ... <add> # ... <ide> end <ide> end <ide> ``` <ide> The helper inside `app/helpers/blorgh/articles_helper.rb` is also namespaced: <ide> ```ruby <ide> module Blorgh <ide> module ArticlesHelper <del> ... <add> # ... <ide> end <ide> end <ide> ``` <ide> module Blorgh <ide> <ide> def test_index <ide> get foos_url <del> ... <add> # ... <ide> end <ide> end <ide> end <ide> module Blorgh <ide> <ide> def test_index <ide> get foos_url <del> ... <add> # ... <ide> end <ide> end <ide> end <ide> In `zeitwerk` mode you'd do this: <ide> # config/application.rb <ide> module MyApp <ide> class Application < Rails::Application <del> ... <add> # ... <ide> <ide> overrides = "#{Rails.root}/app/overrides" <ide> Rails.autoloaders.main.ignore(overrides) <ide> and in `classic` mode this: <ide> # config/application.rb <ide> module MyApp <ide> class Application < Rails::Application <del> ... <add> # ... <ide> <ide> config.to_prepare do <ide> Dir.glob("#{Rails.root}/app/overrides/**/*_override.rb").each do |override| <ide> Pipeline require statements in processed files: <ide> INFO. Remember that in order to use languages like Sass or CoffeeScript, you <ide> should add the relevant library to your engine's `.gemspec`. <ide> <del>### Separate Assets & Precompiling <add>### Separate Assets and Precompiling <ide> <ide> There are some situations where your engine's assets are not required by the <ide> host application. For example, say that you've created an admin functionality <ide><path>guides/source/form_helpers.md <ide> Output: <ide> Uploading Files <ide> --------------- <ide> <del>A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. File upload fields can be rendered with the [`file_field`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-file_field) helper. The most important thing to remember with file uploads is that the rendered form's enctype attribute **must** be set to "multipart/form-data". If you use `form_with` with `:model`, this is done automatically: <add>A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. File upload fields can be rendered with the [`file_field`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-file_field) helper. The most important thing to remember with file uploads is that the rendered form's `enctype` attribute **must** be set to "multipart/form-data". If you use `form_with` with `:model`, this is done automatically: <ide> <ide> ```erb <ide> <%= form_with model: @person do |form| %> <ide> If you use `form_with` without `:model`, you must set it yourself: <ide> <% end %> <ide> ``` <ide> <del>Note that, in accordance with `form_with` conventions, the field names in two forms above will also differ. That is, the field name in the first form will be `person[picture]` (accessible via `params[:person][:picture]`), and the field name in the second form will be just `picture` (accessible via `params[:picture]`). <add>Note that, in accordance with `form_with` conventions, the field names in the two forms above will also differ. That is, the field name in the first form will be `person[picture]` (accessible via `params[:person][:picture]`), and the field name in the second form will be just `picture` (accessible via `params[:picture]`). <ide> <ide> ### What Gets Uploaded <ide> <ide> Once a file has been uploaded, there are a multitude of potential tasks, ranging <ide> Customizing Form Builders <ide> ------------------------- <ide> <del>The object yielded by `form_with` and `fields_for` is an instance of [`ActionView::Helpers::FormBuilder`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html). Form builders encapsulate the notion of displaying form elements for a single object. While you can write helpers for your forms in the usual way, you can also create subclass `ActionView::Helpers::FormBuilder` and add the helpers there. For example: <add>The object yielded by `form_with` and `fields_for` is an instance of [`ActionView::Helpers::FormBuilder`](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html). Form builders encapsulate the notion of displaying form elements for a single object. While you can write helpers for your forms in the usual way, you can also create a subclass of `ActionView::Helpers::FormBuilder`, and add the helpers there. For example, <ide> <ide> ```erb <ide> <%= form_with model: @person do |form| %> <ide> def labeled_form_with(model: nil, scope: nil, url: nil, format: nil, **options, <ide> end <ide> ``` <ide> <del>The form builder used also determines what happens when you do <add>The form builder used also determines what happens when you do: <ide> <ide> ```erb <ide> <%= render partial: f %> <ide> ``` <ide> <del>If `f` is an instance of `ActionView::Helpers::FormBuilder` then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class `LabellingFormBuilder` then the `labelling_form` partial would be rendered instead. <add>If `f` is an instance of `ActionView::Helpers::FormBuilder`, then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class `LabellingFormBuilder`, then the `labelling_form` partial would be rendered instead. <ide> <ide> Understanding Parameter Naming Conventions <ide> ------------------------------------------ <ide> We can mix and match these two concepts. One element of a hash might be an array <ide> <ide> This would result in `params[:person][:addresses]` being an array of hashes with keys `line1`, `line2`, and `city`. <ide> <del>There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can usually be replaced by hashes; for example, instead of having an array of model objects, one can have a hash of model objects keyed by their id, an array index, or some other parameter. <add>There's a restriction, however: while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can usually be replaced by hashes; for example, instead of having an array of model objects, one can have a hash of model objects keyed by their id, an array index, or some other parameter. <ide> <ide> WARNING: Array parameters do not play well with the `check_box` helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The `check_box` helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. <ide> <ide> As a convenience you can instead pass the symbol `:all_blank` which will create <ide> <ide> ### Adding Fields on the Fly <ide> <del>Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new address' button. Rails does not provide any built-in support for this. When generating new sets of fields you must ensure the key of the associated array is unique - the current JavaScript date (milliseconds since the [epoch](https://en.wikipedia.org/wiki/Unix_time)) is a common choice. <add>Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an "Add new address" button. Rails does not provide any built-in support for this. When generating new sets of fields you must ensure the key of the associated array is unique - the current JavaScript date (milliseconds since the [epoch](https://en.wikipedia.org/wiki/Unix_time)) is a common choice. <ide> <ide> Using Tag Helpers Without a Form Builder <ide> ---------------------------------------- <ide><path>guides/source/generators.md <ide> Whilst the final section of this guide doesn't cover how to generate the most aw <ide> <ide> Adding Command Line Arguments <ide> ----------------------------- <add> <ide> Rails generators can be easily modified to accept custom command line arguments. This functionality comes from [Thor](https://www.rubydoc.info/github/erikhuda/thor/master/Thor/Base/ClassMethods#class_option-instance_method): <ide> <ide> ```ruby <ide> Runs the specified generator where the first argument is the generator name and <ide> generate "scaffold", "forums title:string description:text" <ide> ``` <ide> <del> <ide> ### `rake` <ide> <ide> Runs the specified Rake task. <ide><path>guides/source/getting_started.md <ide> the `app/views/comments` directory. <ide> The `@article` object is available to any partials rendered in the view because <ide> we defined it as an instance variable. <ide> <del> <ide> ### Using Concerns <ide> <ide> Concerns are a way to make large controllers or models easier to understand and manage. This also has the advantage of reusability when multiple models (or controllers) share the same concerns. Concerns are implemented using modules that contain methods representing a well-defined slice of the functionality that a model or controller is responsible for. In other languages, modules are often known as mixins. <ide> The `destroy` action will find the article we are looking at, locate the comment <ide> within the `@article.comments` collection, and then remove it from the <ide> database and send us back to the show action for the article. <ide> <del> <ide> ### Deleting Associated Objects <ide> <ide> If you delete an article, its associated comments will also need to be <ide> authentication add-ons for Rails are the <ide> the [Authlogic](https://github.com/binarylogic/authlogic) gem, <ide> along with a number of others. <ide> <del> <ide> ### Other Security Considerations <ide> <ide> Security, especially in web applications, is a broad and detailed area. Security <ide><path>guides/source/i18n.md <ide> end <ide> ``` <ide> <ide> ```html+erb <del># app/views/home/index.html.erb <add><!-- app/views/home/index.html.erb --> <ide> <h1>Hello World</h1> <ide> <p><%= flash[:notice] %></p> <ide> ``` <ide> end <ide> ``` <ide> <ide> ```html+erb <del># app/views/home/index.html.erb <add><!-- app/views/home/index.html.erb --> <ide> <h1><%= t :hello_world %></h1> <ide> <p><%= flash[:notice] %></p> <ide> ``` <ide> made about the ordering of the different parts of the translation. Note that Rai <ide> provides a `number_to_currency` helper to handle the following case. <ide> <ide> ```erb <del># app/views/products/show.html.erb <add><!-- app/views/products/show.html.erb --> <ide> <%= "#{t('currency')}#{@product.price}" %> <ide> ``` <ide> <ide> pass the values for these variables to the translation method. <ide> Proper abstraction is shown in the following example: <ide> <ide> ```erb <del># app/views/products/show.html.erb <add><!-- app/views/products/show.html.erb --> <ide> <%= t('product_price', price: @product.price) %> <ide> ``` <ide> <ide> to `#translate`, an `I18n::MissingInterpolationArgument` exception is raised. <ide> OK! Now let's add a timestamp to the view, so we can demo the **date/time localization** feature as well. To localize the time format you pass the Time object to `I18n.l` or (preferably) use Rails' `#l` helper. You can pick a format by passing the `:format` option - by default the `:default` format is used. <ide> <ide> ```erb <del># app/views/home/index.html.erb <add><!-- app/views/home/index.html.erb --> <ide> <h1><%= t :hello_world %></h1> <ide> <p><%= flash[:notice] %></p> <ide> <p><%= l Time.now, format: :short %></p> <ide> I18n.t 'welcome', deep_interpolation: true, app_name: 'book store' <ide> # => {:title=>"Welcome!", :content=>"Welcome to the book store"} <ide> ``` <ide> <del> <ide> #### "Lazy" Lookup <ide> <ide> Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary: <ide> en: <ide> ``` <ide> <ide> ```html+erb <del># app/views/home/index.html.erb <add><!-- app/views/home/index.html.erb --> <ide> <div><%= t('welcome') %></div> <ide> <div><%= raw t('welcome') %></div> <ide> <div><%= t('hello_html') %></div> <ide> The I18n API will catch all of these exceptions when they are thrown in the back <ide> <ide> The reason for this is that during development you'd usually want your views to still render even though a translation is missing. <ide> <del>In other contexts you might want to change this behavior, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with `#call` method: <add>In other contexts you might want to change this behavior, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with a `call` method: <ide> <ide> ```ruby <ide> module I18n <ide><path>guides/source/initialization.md <ide> module Rails <ide> log_to_stdout if options[:log_stdout] <ide> <ide> super() <del> ... <add> # ... <ide> end <ide> <ide> private <ide> module Rack <ide> def app <ide> @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config <ide> end <del> ... <add> <add> # ... <ide> <ide> private <ide> def build_app_and_options_from_config <ide> The `Rack::Builder.parse_file` method here takes the content from this `config.r <ide> module Rack <ide> class Builder <ide> def self.load_file(path, opts = Server::Options.new) <del> ... <add> # ... <ide> app = new_from_string cfgfile, config <del> ... <add> # ... <ide> end <ide> <del> ... <add> # ... <ide> <ide> def self.new_from_string(builder_script, file="(rackup)") <ide> eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app", <ide> module Rack <ide> def app <ide> @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config <ide> end <del> ... <add> <add> # ... <ide> <ide> private <ide> def build_app_and_options_from_config <ide> the `run` method would look like: <ide> module Rack <ide> module Handler <ide> module Puma <del> ... <add> # ... <ide> def self.run(app, options = {}) <ide> conf = self.config(app, options) <ide> <ide> module Rack <ide> puts "* Goodbye!" <ide> end <ide> end <del> ... <add> # ... <ide> end <ide> end <ide> end <ide><path>guides/source/layouts_and_rendering.md <ide> You can supply a path to the audio file if you like: <ide> <%= audio_tag "music/first_song.mp3" %> <ide> ``` <ide> <del>You can also supply a hash of additional options, such as `:id`, `:class` etc. <add>You can also supply a hash of additional options, such as `:id`, `:class`, etc. <ide> <ide> Like the `video_tag`, the `audio_tag` has special options: <ide> <ide><path>guides/source/plugins.md <ide> different Rails applications using RubyGems and Bundler if desired. <ide> <ide> ### Generate a gemified plugin. <ide> <del> <ide> Rails ships with a `rails plugin new` command which creates a <ide> skeleton for developing any kind of Rails extension with the ability <ide> to run integration tests using a dummy Rails application. Create your <ide> Testing Your Newly Generated Plugin <ide> ----------------------------------- <ide> <ide> You can navigate to the directory that contains the plugin, run the `bundle install` command <del> and run the one generated test using the `bin/test` command. <add>and run the one generated test using the `bin/test` command. <ide> <ide> You should see: <ide> <ide><path>guides/source/rails_application_templates.md <ide> Rails Application Templates <ide> =========================== <ide> <del>Application templates are simple Ruby files containing DSL for adding gems/initializers etc. to your freshly created Rails project or an existing Rails project. <add>Application templates are simple Ruby files containing DSL for adding gems, initializers, etc. to your freshly created Rails project or an existing Rails project. <ide> <ide> After reading this guide, you will know: <ide> <ide><path>guides/source/rails_on_rack.md <ide> The `Rails::Server` inherits from `Rack::Server` and calls the `Rack::Server#sta <ide> ```ruby <ide> class Server < ::Rack::Server <ide> def start <del> ... <add> # ... <ide> super <ide> end <ide> end <ide><path>guides/source/routing.md <ide> NOTE: The `Rails.application.routes.draw do ... end` block that wraps your route <ide> Resource Routing: the Rails Default <ide> ----------------------------------- <ide> <del>Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. A single call to [`resources`][] can declare all of the necessary routes for your `index`, `show`, `new`, `edit`, `create`, `update` and `destroy` actions. <add>Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. A single call to [`resources`][] can declare all of the necessary routes for your `index`, `show`, `new`, `edit`, `create`, `update`, and `destroy` actions. <ide> <ide> [`resources`]: https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources <ide> <ide> This can also be done for a single route: <ide> resources :articles, path: '/admin/articles' <ide> ``` <ide> <del>In each of these cases, the named routes remain the same as if you did not use `scope`. In the last case, the following paths map to `ArticlesController`: <add>In both of these cases, the named route helpers remain the same as if you did not use `scope`. In the last case, the following paths map to `ArticlesController`: <ide> <ide> | HTTP Verb | Path | Controller#Action | Named Route Helper | <ide> | --------- | ------------------------ | -------------------- | ---------------------- | <ide> In each of these cases, the named routes remain the same as if you did not use ` <ide> | PATCH/PUT | /admin/articles/:id | articles#update | article_path(:id) | <ide> | DELETE | /admin/articles/:id | articles#destroy | article_path(:id) | <ide> <del>TIP: _If you need to use a different controller namespace inside a `namespace` block you can specify an absolute controller path, e.g: `get '/foo', to: '/foo#index'`._ <add>TIP: If you need to use a different controller namespace inside a `namespace` block you can specify an absolute controller path, e.g: `get '/foo', to: '/foo#index'`. <ide> <ide> [`namespace`]: https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-namespace <ide> [`scope`]: https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-scope <ide> Deeply-nested resources quickly become cumbersome. In this case, for example, th <ide> <ide> The corresponding route helper would be `publisher_magazine_photo_url`, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular [article](http://weblog.jamisbuck.org/2007/2/5/nesting-resources) by Jamis Buck proposes a rule of thumb for good Rails design: <ide> <del>TIP: _Resources should never be nested more than 1 level deep._ <add>TIP: Resources should never be nested more than 1 level deep. <ide> <ide> #### Shallow Nesting <ide> <ide> Both the `matches?` method and the lambda gets the `request` object as an argume <ide> <ide> #### Constraints in a block form <ide> <del>You can specify constraints in a block form. This is useful for when you need to apply the same rule to several routes. For example <add>You can specify constraints in a block form. This is useful for when you need to apply the same rule to several routes. For example: <ide> <ide> ```ruby <ide> class RestrictedListConstraint <ide> Rails.application.routes.draw do <ide> end <ide> ``` <ide> <del>You also use a `lambda`: <add>You can also use a `lambda`: <ide> <ide> ```ruby <ide> Rails.application.routes.draw do <ide> Rails.application.routes.draw do <ide> end <ide> ``` <ide> <del> <ide> ### Route Globbing and Wildcard Segments <ide> <ide> Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example: <ide> get '*pages', to: 'pages#show', format: true <ide> <ide> ### Redirection <ide> <del>You can redirect any path to another path using the [`redirect`][] helper in your router: <add>You can redirect any path to another path by using the [`redirect`][] helper in your router: <ide> <ide> ```ruby <ide> get '/stories', to: redirect('/articles') <ide> You can also reuse dynamic segments from the match in the path to redirect to: <ide> get '/stories/:name', to: redirect('/articles/%{name}') <ide> ``` <ide> <del>You can also provide a block to redirect, which receives the symbolized path parameters and the request object: <add>You can also provide a block to `redirect`, which receives the symbolized path parameters and the request object: <ide> <ide> ```ruby <ide> get '/stories/:name', to: redirect { |path_params, req| "/articles/#{path_params[:name].pluralize}" } <ide> This would cause the routing to recognize paths such as: <ide> <ide> NOTE: The actual action names aren't changed by this option. The two paths shown would still route to the `new` and `edit` actions. <ide> <del>TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope. <add>TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope, like below: <ide> <ide> ```ruby <ide> scope path_names: { new: 'make' } do <ide> Rails now creates routes to the `CategoriesController`. <ide> <ide> ### Overriding the Singular Form <ide> <del>If you want to define the singular form of a resource, you should add additional rules to the `Inflector` via [`inflections`][]: <add>If you want to override the singular form of a resource, you should add additional rules to the inflector via [`inflections`][]: <ide> <ide> ```ruby <ide> ActiveSupport::Inflector.inflections do |inflect| <ide> You can use the normal routing DSL inside the `admin.rb` routing file, **however <ide> <ide> ### When to use and not use this feature <ide> <del>Drawing routes from external files can be very useful to organise a large set of routes into multiple organised ones. You could have a `admin.rb` route that contains all the routes for the admin area, another `api.rb` file to route API related resources etc... <add>Drawing routes from external files can be very useful to organise a large set of routes into multiple organised ones. You could have a `admin.rb` route that contains all the routes for the admin area, another `api.rb` file to route API related resources, etc... <ide> <del>However, you shouldn't abuse this feature as having too many route files make discoverability and understandability more difficult. Depending on the application, it might be easier for developers to have a single routing file even if you have few hundreds routes. You shouldn't try to create a new routing file for each category (admin, api ...) at all cost; the Rails routing DSL already offers a way to break routes in a organised manner with `namespaces` and `scopes`. <add>However, you shouldn't abuse this feature as having too many route files make discoverability and understandability more difficult. Depending on the application, it might be easier for developers to have a single routing file even if you have few hundreds routes. You shouldn't try to create a new routing file for each category (e.g. admin, api, ...) at all cost; the Rails routing DSL already offers a way to break routes in a organised manner with `namespaces` and `scopes`. <ide> <ide> <ide> Inspecting and Testing Routes <ide> Rails offers facilities for inspecting and testing your routes. <ide> <ide> ### Listing Existing Routes <ide> <del>To get a complete list of the available routes in your application, visit `http://localhost:3000/rails/info/routes` in your browser while your server is running in the **development** environment. You can also execute the `bin/rails routes` command in your terminal to produce the same output. <add>To get a complete list of the available routes in your application, visit <http://localhost:3000/rails/info/routes> in your browser while your server is running in the **development** environment. You can also execute the `bin/rails routes` command in your terminal to produce the same output. <ide> <ide> Both methods will list all of your routes, in the same order that they appear in `config/routes.rb`. For each route, you'll see: <ide> <ide><path>guides/source/security.md <ide> Hence, the cookie serves as temporary authentication for the web application. An <ide> <ide> * Instead of stealing a cookie unknown to the attacker, they fix a user's session identifier (in the cookie) known to them. Read more about this so-called session fixation later. <ide> <del>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from 0.5%-10% of account balance, $0.5-$30 for credit card numbers ($20-$60 with full details), $0.1-$1.5 for identities (Name, SSN & DOB), $20-$50 for retailer accounts, and $6-$10 for cloud service provider accounts, according to the [Symantec Internet Security Threat Report (2017)](https://www.symantec.com/content/dam/symantec/docs/reports/istr-22-2017-en.pdf). <add>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from 0.5%-10% of account balance, $0.5-$30 for credit card numbers ($20-$60 with full details), $0.1-$1.5 for identities (Name, SSN, and DOB), $20-$50 for retailer accounts, and $6-$10 for cloud service provider accounts, according to the [Symantec Internet Security Threat Report (2017)](https://www.symantec.com/content/dam/symantec/docs/reports/istr-22-2017-en.pdf). <ide> <ide> ### Session Storage <ide> <ide> The problem with CAPTCHAs is that they have a negative impact on the user experi <ide> <ide> Most bots are really dumb. They crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript. <ide> <del>Note that negative CAPTCHAs are only effective against dumb bots and won't suffice to protect critical applications from targeted bots. Still, the negative and positive CAPTCHAs can be combined to increase the performance, e.g., if the "honeypot" field is not empty (bot detected), you won't need to verify the positive CAPTCHA, which would require an HTTPS request to Google ReCaptcha before computing the response. <add>Note that negative CAPTCHAs are only effective against dumb bots and won't suffice to protect critical applications from targeted bots. Still, the negative and positive CAPTCHAs can be combined to increase the performance, e.g., if the "honeypot" field is not empty (bot detected), you won't need to verify the positive CAPTCHA, which would require an HTTPS request to Google ReCaptcha before computing the response. <ide> <ide> Here are some ideas how to hide honeypot fields by JavaScript and/or CSS: <ide> <ide> system("/bin/echo","hello; rm *") <ide> # prints "hello; rm *" and does not delete files <ide> ``` <ide> <del> <ide> ### Header Injection <ide> <ide> WARNING: _HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS, or HTTP response splitting._ <ide><path>guides/source/testing.md <ide> The `test_helper.rb` file holds the default configuration for your tests. <ide> The `application_system_test_case.rb` holds the default configuration for your system <ide> tests. <ide> <del> <ide> ### The Test Environment <ide> <ide> By default, every Rails application has three environments: development, test, and production. <ide> end <ide> <ide> Although you can still use regular method definitions, using the `test` macro allows for a more readable test name. <ide> <del>NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. This may require use of `define_method` and `send` calls to function properly, but formally there's little restriction on the name. <add>NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though — the name may contain punctuation characters, etc. That's because in Ruby technically any string may be a method name. This may require use of `define_method` and `send` calls to function properly, but formally there's little restriction on the name. <ide> <ide> Next, let's look at our first assertion: <ide> <ide> rails test test/models/article_test.rb:6 <ide> Finished in 0.023918s, 41.8090 runs/s, 41.8090 assertions/s. <ide> <ide> 1 runs, 1 assertions, 1 failures, 0 errors, 0 skips <del> <ide> ``` <ide> <ide> In the output, `F` denotes a failure. You can see the corresponding trace shown under `Failure` along with the name of the failing test. The next few lines contain the stack trace followed by a message that mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable, every assertion provides an optional message parameter, as shown here: <ide> $ bin/rails test test/controllers # run all tests from specific directory <ide> ``` <ide> <ide> The test runner also provides a lot of other features like failing fast, deferring test output <del>at the end of test run and so on. Check the documentation of the test runner as follows: <add>at the end of the test run and so on. Check the documentation of the test runner as follows: <ide> <ide> ```bash <ide> $ bin/rails test -h <ide> By default, every Rails application has three environments: development, test, a <ide> <ide> A dedicated test database allows you to set up and interact with test data in isolation. This way your tests can mangle test data with confidence, without worrying about the data in the development or production databases. <ide> <del> <ide> ### Maintaining the test database schema <ide> <ide> In order to run your tests, your test database will need to have the current <ide> create test/models/article_test.rb <ide> create test/fixtures/articles.yml <ide> ``` <ide> <del>Model tests don't have their own superclass like `ActionMailer::TestCase` instead they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). <add>Model tests don't have their own superclass like `ActionMailer::TestCase`. Instead, they inherit from [`ActiveSupport::TestCase`](https://api.rubyonrails.org/classes/ActiveSupport/TestCase.html). <ide> <ide> System Testing <ide> -------------- <ide> class MobileSystemTestCase < ActionDispatch::SystemTestCase <ide> driven_by :selenium, using: :chrome, screen_size: [375, 667] <ide> end <ide> ``` <add> <ide> To use this configuration, create a test inside `test/system` that inherits from `MobileSystemTestCase`. <ide> Now you can test your app using multiple different configurations. <ide> <ide> publishing draft articles, etc. <ide> Integration Testing <ide> ------------------- <ide> <del>Integration tests are used to test how various parts of your application interact. They are generally used to test important workflows within our application. <add>Integration tests are used to test how various parts of our application interact. They are generally used to test important workflows within our application. <ide> <ide> For creating Rails integration tests, we use the `test/integration` directory for our application. Rails provides a generator to create an integration test skeleton for us. <ide> <ide> The goals of testing your mailer classes are to ensure that: <ide> <ide> #### From All Sides <ide> <del>There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture.) In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time. <add>There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture). In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time. <ide> <ide> ### Unit Testing <ide> <ide><path>guides/source/threading_and_code_execution.md <ide> Rails.application.executor.wrap do <ide> end <ide> ``` <ide> <del> <ide> ### ActionDispatch::DebugLocks <ide> <ide> If your application is deadlocking and you think the Load Interlock may be <ide><path>guides/source/upgrading_ruby_on_rails.md <ide> You can call `with_indifferent_access` on the return value of `config_for` if yo <ide> Rails.application.config_for(:example).with_indifferent_access.dig('options', 'key') <ide> ``` <ide> <del> <ide> ### Response's Content-Type when using `respond_to#any` <ide> <ide> The Content-Type header returned in the response can differ from what Rails 6.0 returned, <ide> gem 'rails-deprecated_sanitizer' <ide> <ide> The [`TagAssertions` module](https://api.rubyonrails.org/v4.1/classes/ActionDispatch/Assertions/TagAssertions.html) (containing methods such as `assert_tag`), [has been deprecated](https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb) in favor of the `assert_select` methods from the `SelectorAssertions` module, which has been extracted into the [rails-dom-testing gem](https://github.com/rails/rails-dom-testing). <ide> <del> <ide> ### Masked Authenticity Tokens <ide> <ide> In order to mitigate SSL attacks, `form_authenticity_token` is now masked so that it varies with each request. Thus, tokens are validated by unmasking and then decrypting. As a result, any strategies for verifying requests from non-rails forms that relied on a static session CSRF token have to take this into account. <ide> secrets, you need to: <ide> ``` <ide> <ide> 2. Use your existing `secret_key_base` from the `secret_token.rb` initializer to <del> set the SECRET_KEY_BASE environment variable for whichever users running the <add> set the `SECRET_KEY_BASE` environment variable for whichever users running the <ide> Rails application in production. Alternatively, you can simply copy the existing <ide> `secret_key_base` from the `secret_token.rb` initializer to `secrets.yml` <del> under the `production` section, replacing '<%= ENV["SECRET_KEY_BASE"] %>'. <add> under the `production` section, replacing `<%= ENV["SECRET_KEY_BASE"] %>`. <ide> <ide> 3. Remove the `secret_token.rb` initializer. <ide> <ide> module FixtureFileHelpers <ide> Digest::SHA2.hexdigest(File.read(Rails.root.join('test/fixtures', path))) <ide> end <ide> end <add> <ide> ActiveRecord::FixtureSet.context_class.include FixtureFileHelpers <ide> ``` <ide> <ide><path>guides/source/working_with_javascript_in_rails.md <ide> Here's the simplest way to write JavaScript. You may see it referred to as <ide> ```html <ide> <a href="#" onclick="this.style.backgroundColor='#990000';event.preventDefault();">Paint it red</a> <ide> ``` <add> <ide> When clicked, the link background will become red. Here's the problem: what <ide> happens when we have lots of JavaScript we want to execute on a click? <ide>
43
Javascript
Javascript
use a dictionary for the view registry
d78c0dd1415ed6b49ab97b966ef650e8d5be3b35
<ide><path>packages/ember-application/lib/system/application.js <ide> */ <ide> import { ENV } from 'ember-environment'; <ide> import { assert, debug } from 'ember-metal/debug'; <add>import dictionary from 'ember-metal/dictionary'; <ide> import libraries from 'ember-metal/libraries'; <ide> import { isTesting } from 'ember-metal/testing'; <ide> import { get } from 'ember-metal/property_get'; <ide> Application.reopenClass({ <ide> }); <ide> <ide> function commonSetupRegistry(registry) { <del> registry.register('-view-registry:main', { create() { return {}; } }); <add> registry.register('-view-registry:main', { create() { return dictionary(null); } }); <ide> <ide> registry.register('route:basic', Route); <ide> registry.register('event_dispatcher:main', EventDispatcher); <ide><path>packages/ember-glimmer/tests/utils/helpers.js <ide> export { DOMChanges } from 'glimmer-runtime'; <ide> export { InteractiveRenderer, InertRenderer } from 'ember-glimmer/renderer'; <ide> export { default as makeBoundHelper } from 'ember-glimmer/make-bound-helper'; <ide> export { htmlSafe, SafeString } from 'ember-glimmer/utils/string'; <add>import dictionary from 'ember-metal/dictionary'; <ide> <ide> export function buildOwner(options) { <ide> let owner = _buildOwner(options); <ide> export function buildOwner(options) { <ide> owner.inject('component', 'renderer', 'renderer:-dom'); <ide> owner.inject('template', 'env', 'service:-glimmer-environment'); <ide> <del> owner.register('-view-registry:main', { create() { return {}; } }); <add> owner.register('-view-registry:main', { create() { return dictionary(null); } }); <ide> owner.inject('renderer', '_viewRegistry', '-view-registry:main'); <ide> <ide> owner.register('template:-root', RootTemplate); <ide><path>packages/ember-htmlbars/tests/utils/helpers.js <ide> export { default as LinkTo } from 'ember-htmlbars/components/link-to'; <ide> export { InteractiveRenderer, InertRenderer } from 'ember-htmlbars/renderer'; <ide> export { default as makeBoundHelper } from 'ember-glimmer/make-bound-helper'; <ide> export { htmlSafe, SafeString } from 'ember-htmlbars/utils/string'; <add>import dictionary from 'ember-metal/dictionary'; <ide> <ide> export function buildOwner(options) { <ide> let owner = _buildOwner(options); <ide> export function buildOwner(options) { <ide> owner.inject('service:-htmlbars-environment', 'dom', 'service:-dom-helper'); <ide> <ide> owner.register('service:-document', document, { instantiate: false }); <del> owner.register('-view-registry:main', { create() { return {}; } }); <add> owner.register('-view-registry:main', { create() { return dictionary(null); } }); <ide> owner.inject('renderer', '_viewRegistry', '-view-registry:main'); <ide> owner.inject('renderer', 'dom', 'service:-dom-helper'); <ide> owner.inject('component', 'renderer', 'renderer:-dom');
3
Text
Text
update pos in tagging example
9aff317ca788cc996da5125e7d9c4783c8ab9f7e
<ide><path>website/docs/usage/101/_pos-deps.md <ide> for token in doc: <ide> | Text | Lemma | POS | Tag | Dep | Shape | alpha | stop | <ide> | ------- | ------- | ------- | ----- | ---------- | ------- | ------- | ------- | <ide> | Apple | apple | `PROPN` | `NNP` | `nsubj` | `Xxxxx` | `True` | `False` | <del>| is | be | `VERB` | `VBZ` | `aux` | `xx` | `True` | `True` | <add>| is | be | `AUX` | `VBZ` | `aux` | `xx` | `True` | `True` | <ide> | looking | look | `VERB` | `VBG` | `ROOT` | `xxxx` | `True` | `False` | <ide> | at | at | `ADP` | `IN` | `prep` | `xx` | `True` | `True` | <ide> | buying | buy | `VERB` | `VBG` | `pcomp` | `xxxx` | `True` | `False` |
1
Ruby
Ruby
add --skip-coffee generating option
ea2bf991a90a1c04ce867cfbbe7ac52b8456359f
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def self.add_shared_options_for(name) <ide> class_option :skip_listen, type: :boolean, default: false, <ide> desc: "Don't generate configuration that depends on the listen gem" <ide> <add> class_option :skip_coffee, type: :boolean, default: false, <add> desc: "Don't use CoffeeScript" <add> <ide> class_option :skip_javascript, type: :boolean, aliases: '-J', default: false, <ide> desc: 'Skip JavaScript files' <ide> <ide> def javascript_gemfile_entry <ide> if options[:skip_javascript] || options[:skip_sprockets] <ide> [] <ide> else <del> gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry] <add> gems = [javascript_runtime_gemfile_entry] <add> gems << coffee_gemfile_entry unless options[:skip_coffee] <add> <ide> gems << GemfileEntry.version("#{options[:javascript]}-rails", nil, <ide> "Use #{options[:javascript]} as the JavaScript library") <ide>
1
Python
Python
fix lemma in exceptions and morph rules
41a322c733808c2ccd6217cd69cb3309df40d2cd
<ide><path>spacy/de/tokenizer_exceptions.py <ide> from __future__ import unicode_literals <ide> <ide> from ..symbols import ORTH, LEMMA, TAG, NORM <del>from ..deprecated import PRON_LEMMA, DET_LEMMA <add>from ..deprecated import PRON_LEMMA <ide> <ide> <ide> _exc = { <ide> "auf'm": [ <ide> {ORTH: "auf", LEMMA: "auf"}, <del> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem" }], <add> {ORTH: "'m", LEMMA: "der", NORM: "dem" }], <ide> <ide> "du's": [ <ide> {ORTH: "du", LEMMA: PRON_LEMMA, TAG: "PPER"}, <ide> <ide> "hinter'm": [ <ide> {ORTH: "hinter", LEMMA: "hinter"}, <del> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"}], <add> {ORTH: "'m", LEMMA: "der", NORM: "dem"}], <ide> <ide> "ich's": [ <ide> {ORTH: "ich", LEMMA: PRON_LEMMA, TAG: "PPER"}, <ide> <ide> "unter'm": [ <ide> {ORTH: "unter", LEMMA: "unter"}, <del> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"}], <add> {ORTH: "'m", LEMMA: "der", NORM: "dem"}], <ide> <ide> "vor'm": [ <ide> {ORTH: "vor", LEMMA: "vor"}, <del> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"}], <add> {ORTH: "'m", LEMMA: "der", NORM: "dem"}], <ide> <ide> "wir's": [ <ide> {ORTH: "wir", LEMMA: PRON_LEMMA, TAG: "PPER"}, <ide> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER", NORM: "es"}], <ide> <ide> "über'm": [ <ide> {ORTH: "über", LEMMA: "über"}, <del> {ORTH: "'m", LEMMA: DET_LEMMA, NORM: "dem"}] <add> {ORTH: "'m", LEMMA: "der", NORM: "dem"}] <ide> } <ide> <ide> <ide> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER"}, <ide> {ORTH: "S'", LEMMA: PRON_LEMMA, TAG: "PPER"}, <ide> {ORTH: "s'", LEMMA: PRON_LEMMA, TAG: "PPER"}, <del> {ORTH: "'n", LEMMA: DET_LEMMA, NORM: "ein"}, <del> {ORTH: "'ne", LEMMA: DET_LEMMA, NORM: "eine"}, <del> {ORTH: "'nen", LEMMA: DET_LEMMA, NORM: "einen"}, <del> {ORTH: "'nem", LEMMA: DET_LEMMA, NORM: "einem"}, <del> {ORTH: "'s", LEMMA: PRON_LEMMA, TAG: "PPER"}, <del> <add> {ORTH: "'n", LEMMA: "ein", NORM: "ein"}, <add> {ORTH: "'ne", LEMMA: "eine", NORM: "eine"}, <add> {ORTH: "'nen", LEMMA: "ein", NORM: "einen"}, <add> {ORTH: "'nem", LEMMA: "ein", NORM: "einem"}, <ide> {ORTH: "Abb.", LEMMA: "Abbildung"}, <ide> {ORTH: "Abk.", LEMMA: "Abkürzung"}, <ide> {ORTH: "Abt.", LEMMA: "Abteilung"}, <ide><path>spacy/deprecated.py <ide> <ide> <ide> PRON_LEMMA = "-PRON-" <del>DET_LEMMA = "-DET-" <ide> <ide> <ide> def depr_model_download(lang): <ide><path>spacy/es/tokenizer_exceptions.py <ide> from __future__ import unicode_literals <ide> <ide> from ..symbols import ORTH, LEMMA, TAG, NORM, ADP, DET <del>from ..deprecated import PRON_LEMMA, DET_LEMMA <add>from ..deprecated import PRON_LEMMA <ide> <ide> <ide> _exc = { <ide> <ide> "pal": [ <ide> {ORTH: "pa", LEMMA: "para"}, <del> {ORTH: "l", LEMMA: DET_LEMMA, NORM: "el"}], <add> {ORTH: "l", LEMMA: "el"}], <ide> <ide> "pala": [ <ide> {ORTH: "pa", LEMMA: "para"}, <del> {ORTH: "la", LEMMA: DET_LEMMA}] <add> {ORTH: "la"}] <ide> } <ide> <ide> <ide><path>spacy/nb/morph_rules.py <ide> }, <ide> <ide> "VBZ": { <del> "er": {LEMMA: "be", "VerbForm": "Fin", "Person": "One", "Tense": "Pres", "Mood": "Ind"}, <del> "er": {LEMMA: "be", "VerbForm": "Fin", "Person": "Two", "Tense": "Pres", "Mood": "Ind"}, <del> "er": {LEMMA: "be", "VerbForm": "Fin", "Person": "Three", "Tense": "Pres", "Mood": "Ind"}, <add> "er": {"VerbForm": "Fin", "Person": "One", "Tense": "Pres", "Mood": "Ind"}, <add> "er": {"VerbForm": "Fin", "Person": "Two", "Tense": "Pres", "Mood": "Ind"}, <add> "er": {"VerbForm": "Fin", "Person": "Three", "Tense": "Pres", "Mood": "Ind"}, <ide> }, <ide> <ide> "VBP": { <del> "er": {LEMMA: "be", "VerbForm": "Fin", "Tense": "Pres", "Mood": "Ind"} <add> "er": {"VerbForm": "Fin", "Tense": "Pres", "Mood": "Ind"} <ide> }, <ide> <ide> "VBD": { <del> "var": {LEMMA: "be", "VerbForm": "Fin", "Tense": "Past", "Number": "Sing"}, <del> "vært": {LEMMA: "be", "VerbForm": "Fin", "Tense": "Past", "Number": "Plur"} <add> "var": {"VerbForm": "Fin", "Tense": "Past", "Number": "Sing"}, <add> "vært": {"VerbForm": "Fin", "Tense": "Past", "Number": "Plur"} <ide> } <ide> } <ide><path>spacy/sv/morph_rules.py <ide> }, <ide> <ide> "VBZ": { <del> "är": {LEMMA: "be", "VerbForm": "Fin", "Person": "One", "Tense": "Pres", "Mood": "Ind"}, <del> "är": {LEMMA: "be", "VerbForm": "Fin", "Person": "Two", "Tense": "Pres", "Mood": "Ind"}, <del> "är": {LEMMA: "be", "VerbForm": "Fin", "Person": "Three", "Tense": "Pres", "Mood": "Ind"}, <add> "är": {"VerbForm": "Fin", "Person": "One", "Tense": "Pres", "Mood": "Ind"}, <add> "är": {"VerbForm": "Fin", "Person": "Two", "Tense": "Pres", "Mood": "Ind"}, <add> "är": {"VerbForm": "Fin", "Person": "Three", "Tense": "Pres", "Mood": "Ind"}, <ide> }, <ide> <ide> "VBP": { <del> "är": {LEMMA: "be", "VerbForm": "Fin", "Tense": "Pres", "Mood": "Ind"} <add> "är": {"VerbForm": "Fin", "Tense": "Pres", "Mood": "Ind"} <ide> }, <ide> <ide> "VBD": { <del> "var": {LEMMA: "be", "VerbForm": "Fin", "Tense": "Past", "Number": "Sing"}, <del> "vart": {LEMMA: "be", "VerbForm": "Fin", "Tense": "Past", "Number": "Plur"} <add> "var": {"VerbForm": "Fin", "Tense": "Past", "Number": "Sing"}, <add> "vart": {"VerbForm": "Fin", "Tense": "Past", "Number": "Plur"} <ide> } <ide> }
5
Javascript
Javascript
handle multiple dom updates without interference
f9a8bdcafe2900902c9912eee8aeec2a0c1fb557
<ide><path>src/renderers/dom/client/utils/DOMChildrenOperations.js <ide> var DOMChildrenOperations = { <ide> update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { <ide> var updatedIndex = update.fromIndex; <ide> var updatedChild = update.parentNode.childNodes[updatedIndex]; <del> var parentID = update.parentID; <add> var parentID = update.parentInst._rootNodeID; <ide> <ide> invariant( <ide> updatedChild, <ide> var DOMChildrenOperations = { <ide> case ReactMultiChildUpdateTypes.MOVE_EXISTING: <ide> insertChildAt( <ide> update.parentNode, <del> initialChildren[update.parentID][update.fromIndex], <add> initialChildren[update.parentInst._rootNodeID][update.fromIndex], <ide> update.toIndex <ide> ); <ide> break; <ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js <ide> describe('ReactDOMComponent', function() { <ide> ReactDOM.render(<div dir="ltr" />, container); <ide> expect(setter.mock.calls.length).toBe(1); <ide> }); <add> <add> it('handles multiple child updates without interference', function() { <add> // This test might look like it's just testing ReactMultiChild but the <add> // last bug in this was actually in DOMChildrenOperations so this test <add> // needs to be in some DOM-specific test file. <add> var container = document.createElement('div'); <add> <add> // ABCD <add> ReactDOM.render( <add> <div> <add> <div key="one"> <add> <div key="A">A</div><div key="B">B</div> <add> </div> <add> <div key="two"> <add> <div key="C">C</div><div key="D">D</div> <add> </div> <add> </div>, <add> container <add> ); <add> // BADC <add> ReactDOM.render( <add> <div> <add> <div key="one"> <add> <div key="B">B</div><div key="A">A</div> <add> </div> <add> <div key="two"> <add> <div key="D">D</div><div key="C">C</div> <add> </div> <add> </div>, <add> container <add> ); <add> <add> expect(container.textContent).toBe('BADC'); <add> }); <ide> }); <ide> <ide> describe('createOpenTagMarkup', function() {
2
Ruby
Ruby
add append_lines tests
e00375e381c7bcd4f0db0d69944dbf831fc62672
<ide><path>Library/Homebrew/test/test_pathname.rb <ide> def test_write_does_not_overwrite <ide> assert_raises(RuntimeError) { @file.write("CONTENT") } <ide> end <ide> <add> def test_append_lines <add> touch @file <add> @file.append_lines("CONTENT") <add> assert_equal "CONTENT\n", File.read(@file) <add> @file.append_lines("CONTENTS") <add> assert_equal "CONTENT\nCONTENTS\n", File.read(@file) <add> end <add> <add> def test_append_lines_does_not_create <add> assert_raises(RuntimeError) { @file.append_lines("CONTENT") } <add> end <add> <ide> def test_atomic_write <ide> touch @file <ide> @file.atomic_write("CONTENT")
1
Ruby
Ruby
use set_server_option if possible
425449e98d0539e3fa4debb819283103cf27bce5
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def max_allowed_packet <ide> end <ide> <ide> def with_multi_statements <del> previous_flags = @config[:flags] <del> @config[:flags] = Mysql2::Client::MULTI_STATEMENTS <del> reconnect! <add> if supports_set_server_option? <add> @connection.set_server_option(Mysql2::Client::OPTION_MULTI_STATEMENTS_ON) <add> elsif !supports_multi_statements? <add> previous_flags = @config[:flags] <add> @config[:flags] = Mysql2::Client::MULTI_STATEMENTS <add> reconnect! <add> end <ide> <ide> yield <ide> ensure <del> @config[:flags] = previous_flags <del> reconnect! <add> unless supports_multi_statements? <add> if supports_set_server_option? <add> @connection.set_server_option(Mysql2::Client::OPTION_MULTI_STATEMENTS_OFF) <add> else <add> @config[:flags] = previous_flags <add> reconnect! <add> end <add> end <add> end <add> <add> def supports_multi_statements? <add> (@config[:flags] & Mysql2::Client::MULTI_STATEMENTS) != 0 <add> end <add> <add> def supports_set_server_option? <add> @connection.respond_to?(:set_server_option) <ide> end <ide> <ide> def initialize_type_map(m = type_map) <ide><path>activerecord/test/cases/fixtures_test.rb <ide> def test_bulk_insert_with_a_multi_statement_query_raises_an_exception_when_any_i <ide> end <ide> end <ide> end <add> <add> def test_bulk_insert_with_a_multi_statement_query_in_a_nested_transaction <add> fixtures = { <add> "traffic_lights" => [ <add> { "location" => "US", "state" => ["NY"], "long_state" => ["a"] }, <add> ] <add> } <add> <add> ActiveRecord::Base.transaction do <add> con = ActiveRecord::Base.connection <add> assert_equal 1, con.open_transactions <add> con.insert_fixtures_set(fixtures) <add> assert_equal 1, con.open_transactions <add> end <add> end <ide> end <ide> <ide> if current_adapter?(:Mysql2Adapter)
2
Mixed
Go
add pkg/parsers/architecture and pkg/platform
49779b674af09b46c165c8dfe2e76054336b0595
<ide><path>daemon/info.go <ide> import ( <ide> "github.com/docker/docker/pkg/fileutils" <ide> "github.com/docker/docker/pkg/parsers/kernel" <ide> "github.com/docker/docker/pkg/parsers/operatingsystem" <add> "github.com/docker/docker/pkg/platform" <ide> "github.com/docker/docker/pkg/sysinfo" <ide> "github.com/docker/docker/pkg/system" <ide> "github.com/docker/docker/registry" <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> KernelVersion: kernelVersion, <ide> OperatingSystem: operatingSystem, <ide> IndexServerAddress: registry.IndexServer, <del> OSType: runtime.GOOS, <del> Architecture: runtime.GOARCH, <add> OSType: platform.OSType, <add> Architecture: platform.Architecture, <ide> RegistryConfig: daemon.RegistryService.Config, <ide> InitSha1: dockerversion.InitSHA1, <ide> InitPath: initPath, <ide><path>docs/reference/api/docker_remote_api_v1.21.md <ide> Display system-wide information <ide> Content-Type: application/json <ide> <ide> { <del> "Architecture": "amd64", <add> "Architecture": "x86_64", <ide> "Containers": 11, <ide> "CpuCfsPeriod": true, <ide> "CpuCfsQuota": true, <ide><path>docs/reference/commandline/info.md <ide> For example: <ide> Logging Driver: json-file <ide> Kernel Version: 3.19.0-22-generic <ide> OSType: linux <del> Architecture: amd64 <add> Architecture: x86_64 <ide> Operating System: Ubuntu 15.04 <ide> CPUs: 24 <ide> Total Memory: 62.86 GiB <ide><path>man/docker-info.1.md <ide> Here is a sample output: <ide> Kernel Version: 3.13.0-24-generic <ide> Operating System: Ubuntu 14.04 LTS <ide> OSType: linux <del> Architecture: amd64 <add> Architecture: x86_64 <ide> CPUs: 1 <ide> Total Memory: 2 GiB <ide> <ide><path>pkg/platform/architecture_freebsd.go <add>package platform <add> <add>import ( <add> "os/exec" <add>) <add> <add>// GetRuntimeArchitecture get the name of the current architecture (x86, x86_64, …) <add>func GetRuntimeArchitecture() (string, error) { <add> cmd := exec.Command("uname", "-m") <add> machine, err := cmd.Output() <add> if err != nil { <add> return "", err <add> } <add> return string(machine), nil <add>} <ide><path>pkg/platform/architecture_linux.go <add>// Package platform provides helper function to get the runtime architecture <add>// for different platforms. <add>package platform <add> <add>import ( <add> "syscall" <add>) <add> <add>// GetRuntimeArchitecture get the name of the current architecture (x86, x86_64, …) <add>func GetRuntimeArchitecture() (string, error) { <add> utsname := &syscall.Utsname{} <add> if err := syscall.Uname(utsname); err != nil { <add> return "", err <add> } <add> return charsToString(utsname.Machine), nil <add>} <add> <add>func charsToString(ca [65]int8) string { <add> s := make([]byte, len(ca)) <add> var lens int <add> for ; lens < len(ca); lens++ { <add> if ca[lens] == 0 { <add> break <add> } <add> s[lens] = uint8(ca[lens]) <add> } <add> return string(s[0:lens]) <add>} <ide><path>pkg/platform/architecture_windows.go <add>package platform <add> <add>import ( <add> "fmt" <add> "syscall" <add> "unsafe" <add>) <add> <add>var ( <add> modkernel32 = syscall.NewLazyDLL("kernel32.dll") <add> procGetSystemInfo = modkernel32.NewProc("GetSystemInfo") <add>) <add> <add>// see http://msdn.microsoft.com/en-us/library/windows/desktop/ms724958(v=vs.85).aspx <add>type systeminfo struct { <add> wProcessorArchitecture uint16 <add> wReserved uint16 <add> dwPageSize uint32 <add> lpMinimumApplicationAddress uintptr <add> lpMaximumApplicationAddress uintptr <add> dwActiveProcessorMask uintptr <add> dwNumberOfProcessors uint32 <add> dwProcessorType uint32 <add> dwAllocationGranularity uint32 <add> wProcessorLevel uint16 <add> wProcessorRevision uint16 <add>} <add> <add>// Constants <add>const ( <add> ProcessorArchitecture64 = 9 // PROCESSOR_ARCHITECTURE_AMD64 <add> ProcessorArchitectureIA64 = 6 // PROCESSOR_ARCHITECTURE_IA64 <add> ProcessorArchitecture32 = 0 // PROCESSOR_ARCHITECTURE_INTEL <add> ProcessorArchitectureArm = 5 // PROCESSOR_ARCHITECTURE_ARM <add>) <add> <add>var sysinfo systeminfo <add> <add>// GetRuntimeArchitecture get the name of the current architecture (x86, x86_64, …) <add>func GetRuntimeArchitecture() (string, error) { <add> syscall.Syscall(procGetSystemInfo.Addr(), 1, uintptr(unsafe.Pointer(&sysinfo)), 0, 0) <add> switch sysinfo.wProcessorArchitecture { <add> case ProcessorArchitecture64, ProcessorArchitectureIA64: <add> return "x86_64", nil <add> case ProcessorArchitecture32: <add> return "i686", nil <add> case ProcessorArchitectureArm: <add> return "arm", nil <add> default: <add> return "", fmt.Errorf("Unknown processor architecture") <add> } <add>} <ide><path>pkg/platform/platform.go <add>package platform <add> <add>import ( <add> "runtime" <add> <add> "github.com/Sirupsen/logrus" <add>) <add> <add>var ( <add> // Architecture holds the runtime architecture of the process. <add> Architecture string <add> // OSType holds the runtime operating system type (Linux, …) of the process. <add> OSType string <add>) <add> <add>func init() { <add> var err error <add> Architecture, err = GetRuntimeArchitecture() <add> if err != nil { <add> logrus.Errorf("Could no read system architecture info: %v", err) <add> } <add> OSType = runtime.GOOS <add>}
8
PHP
PHP
apply fixes from styleci
9abdb287ba4a577c53fe8fccdf2305ce45fbdb81
<ide><path>src/Illuminate/Support/Collection.php <ide> public function intersect($items) <ide> } <ide> <ide> /** <del> * Intersect the collection with the given items by key <add> * Intersect the collection with the given items by key. <ide> * <ide> * @param mixed $items <ide> * @return static
1
Python
Python
prevent unnecessary copies (thx to eric firing)
673de279532eaf153ac97449b0c81a5c4b239ef3
<ide><path>numpy/ma/core.py <ide> def getdata(a, subok=True): <ide> Input ``MaskedArray``, alternatively a ndarray or a subclass thereof. <ide> subok : bool <ide> Whether to force the output to be a `pure` ndarray (False) or to <del> return a subclass of ndarray if approriate (True - default). <add> return a subclass of ndarray if approriate (True, default). <ide> <ide> See Also <ide> -------- <ide> def getdata(a, subok=True): <ide> [3, 4]]) <ide> <ide> """ <del> data = getattr(a, '_data', np.array(a, subok=subok)) <add> try: <add> data = a._data <add> except AttributeError: <add> data = np.array(a, copy=False, subok=subok) <ide> if not subok: <ide> return data.view(ndarray) <ide> return data <ide> def __call__ (self, x): <ide> "Execute the call behavior." <ide> return umath.logical_or(umath.greater (x, self.b), <ide> umath.less(x, self.a)) <del>#............................ <add> <add> <add> <ide> class _DomainTan: <ide> """Define a valid interval for the `tan` function, so that: <ide> <ide> class _DomainTan: <ide> def __init__(self, eps): <ide> "domain_tan(eps) = true where abs(cos(x)) < eps)" <ide> self.eps = eps <add> <ide> def __call__ (self, x): <ide> "Executes the call behavior." <ide> return umath.less(umath.absolute(umath.cos(x)), self.eps) <del>#............................ <add> <add> <add> <ide> class _DomainSafeDivide: <ide> """Define a domain for safe division.""" <ide> def __init__ (self, tolerance=None): <ide> self.tolerance = tolerance <add> <ide> def __call__ (self, a, b): <ide> # Delay the selection of the tolerance to here in order to reduce numpy <ide> # import times. The calculation of these parameters is a substantial <ide> # component of numpy's import time. <ide> if self.tolerance is None: <ide> self.tolerance = np.finfo(float).tiny <ide> return umath.absolute(a) * self.tolerance >= umath.absolute(b) <del>#............................ <add> <add> <add> <ide> class _DomainGreater: <ide> "DomainGreater(v)(x) = true where x <= v" <ide> def __init__(self, critical_value): <ide> def __init__(self, critical_value): <ide> def __call__ (self, x): <ide> "Executes the call behavior." <ide> return umath.less_equal(x, self.critical_value) <del>#............................ <add> <add> <add> <ide> class _DomainGreaterEqual: <ide> "DomainGreaterEqual(v)(x) = true where x < v" <ide> def __init__(self, critical_value): <ide> def __call__ (self, x): <ide> <ide> #.............................................................................. <ide> class _MaskedUnaryOperation: <del> """Defines masked version of unary operations, where invalid <del> values are pre-masked. <add> """ <add> Defines masked version of unary operations, where invalid values are <add> pre-masked. <ide> <ide> Parameters <ide> ---------- <ide> def __init__ (self, mufunc, fill=0, domain=None): <ide> # <ide> def __call__ (self, a, *args, **kwargs): <ide> "Execute the call behavior." <del> # <del> m = getmask(a) <del> d1 = getdata(a) <del> # <add> d = getdata(a) <add> # Case 1.1. : Domained function <ide> if self.domain is not None: <del> dm = np.array(self.domain(d1), copy=False) <del> m = np.logical_or(m, dm) <del> # The following two lines control the domain filling methods. <del> d1 = d1.copy() <del> # We could use smart indexing : d1[dm] = self.fill ... <del> # ... but np.putmask looks more efficient, despite the copy. <del> np.putmask(d1, dm, self.fill) <del> # Take care of the masked singletong first ... <del> if (not m.ndim) and m: <del> return masked <del> elif m is nomask: <del> result = self.f(d1, *args, **kwargs) <add> # Save the error status <add> err_status_ini = np.geterr() <add> np.seterr(divide='ignore', invalid='ignore') <add> # Get the result <add> result = self.f(d, *args, **kwargs) <add> # Reset the error status <add> np.seterr(**err_status_ini) <add> # Make a mask <add> m = ~umath.isfinite(result) <add> m |= getmask(a) <add> # Case 1.2. : Function without a domain <ide> else: <del> result = np.where(m, d1, self.f(d1, *args, **kwargs)) <del> # If result is not a scalar <del> if result.ndim: <del> # Get the result subclass: <del> if isinstance(a, MaskedArray): <del> subtype = type(a) <del> else: <del> subtype = MaskedArray <del> result = result.view(subtype) <del> result._mask = m <del> result._update_from(a) <add> # Get the result and the mask <add> result = self.f(d, *args, **kwargs) <add> m = getmask(a) <add> # Case 2.1. : The result is scalarscalar <add> if not result.ndim: <add> if m: <add> return masked <add> return result <add> # Case 2.2. The result is an array <add> # We need to fill the invalid data back w/ the input <add> # Now, that's plain silly: in C, we would just skip the element and keep <add> # the original, but we do have to do it that way in Python <add> if m is not nomask: <add> # In case result has a lower dtype than the inputs (as in equal) <add> try: <add> np.putmask(result, m, d) <add> except TypeError: <add> pass <add> # Transform to <add> if isinstance(a, MaskedArray): <add> subtype = type(a) <add> else: <add> subtype = MaskedArray <add> result = result.view(subtype) <add> result._mask = m <add> result._update_from(a) <ide> return result <ide> # <ide> def __str__ (self): <ide> return "Masked version of %s. [Invalid values are masked]" % str(self.f) <ide> <del>#.............................................................................. <add> <add> <ide> class _MaskedBinaryOperation: <ide> """Define masked version of binary operations, where invalid <ide> values are pre-masked. <ide> def __init__ (self, mbfunc, fillx=0, filly=0): <ide> <ide> def __call__ (self, a, b, *args, **kwargs): <ide> "Execute the call behavior." <del> m = mask_or(getmask(a), getmask(b), shrink=False) <del> (da, db) = (getdata(a), getdata(b)) <del> # Easy case: there's no mask... <del> if m is nomask: <del> result = self.f(da, db, *args, **kwargs) <del> # There are some masked elements: run only on the unmasked <add> # Get the data, as ndarray <add> (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) <add> # Get the mask <add> (ma, mb) = (getmask(a), getmask(b)) <add> if ma is nomask: <add> if mb is nomask: <add> m = nomask <add> else: <add> m = umath.logical_or(getmaskarray(a), mb) <add> elif mb is nomask: <add> m = umath.logical_or(ma, getmaskarray(b)) <ide> else: <del> result = np.where(m, da, self.f(da, db, *args, **kwargs)) <del> # Transforms to a (subclass of) MaskedArray if we don't have a scalar <del> if result.shape: <del> result = result.view(get_masked_subclass(a, b)) <del> # If we have a mask, make sure it's broadcasted properly <del> if m.any(): <del> result._mask = mask_or(getmaskarray(a), getmaskarray(b)) <del> # If some initial masks where not shrunk, don't shrink the result <del> elif m.shape: <del> result._mask = make_mask_none(result.shape, result.dtype) <add> m = umath.logical_or(ma, mb) <add> # Get the result <add> result = self.f(da, db, *args, **kwargs) <add> # Case 1. : scalar <add> if not result.ndim: <add> if m: <add> return masked <add> return result <add> # Case 2. : array <add> # Revert result to da where masked <add> if m.any(): <add> np.putmask(result, m, 0) <add> result += m*da <add> # Transforms to a (subclass of) MaskedArray <add> result = result.view(get_masked_subclass(a, b)) <add> result._mask = m <add> # Update the optional info from the inputs <add> if isinstance(b, MaskedArray): <ide> if isinstance(a, MaskedArray): <ide> result._update_from(a) <del> if isinstance(b, MaskedArray): <add> else: <ide> result._update_from(b) <del> # ... or return masked if we have a scalar and the common mask is True <del> elif m: <del> return masked <add> elif isinstance(a, MaskedArray): <add> result._update_from(a) <ide> return result <del># <del># result = self.f(d1, d2, *args, **kwargs).view(get_masked_subclass(a, b)) <del># if len(result.shape): <del># if m is not nomask: <del># result._mask = make_mask_none(result.shape) <del># result._mask.flat = m <del># #!!!!! <del># # Force m to be at least 1D <del># m.shape = m.shape or (1,) <del># print "Resetting data" <del># result.data[m].flat = d1.flat <del># #!!!!! <del># if isinstance(a, MaskedArray): <del># result._update_from(a) <del># if isinstance(b, MaskedArray): <del># result._update_from(b) <del># elif m: <del># return masked <del># return result <add> <ide> <ide> def reduce(self, target, axis=0, dtype=None): <ide> """Reduce `target` along the given `axis`.""" <ide> def outer (self, a, b): <ide> if (not m.ndim) and m: <ide> return masked <ide> (da, db) = (getdata(a), getdata(b)) <del> if m is nomask: <del> d = self.f.outer(da, db) <del> else: <del> d = np.where(m, da, self.f.outer(da, db)) <add> d = self.f.outer(da, db) <add> if m is not nomask: <add> np.putmask(d, m, da) <ide> if d.shape: <ide> d = d.view(get_masked_subclass(a, b)) <ide> d._mask = m <ide> def accumulate (self, target, axis=0): <ide> def __str__ (self): <ide> return "Masked version of " + str(self.f) <ide> <del>#.............................................................................. <add> <add> <ide> class _DomainedBinaryOperation: <ide> """ <ide> Define binary operations that have a domain, like divide. <ide> def __init__ (self, dbfunc, domain, fillx=0, filly=0): <ide> <ide> def __call__(self, a, b, *args, **kwargs): <ide> "Execute the call behavior." <del> ma = getmask(a) <del> mb = getmaskarray(b) <del> da = getdata(a) <del> db = getdata(b) <del> t = narray(self.domain(da, db), copy=False) <del> if t.any(None): <del> mb = mask_or(mb, t, shrink=False) <del> # The following line controls the domain filling <del> if t.size == db.size: <del> db = np.where(t, self.filly, db) <add> # Get the data and the mask <add> (da, db) = (getdata(a, subok=False), getdata(b, subok=False)) <add> (ma, mb) = (getmask(a), getmask(b)) <add> # Save the current error status <add> err_status_ini = np.geterr() <add> np.seterr(divide='ignore', invalid='ignore') <add> # Get the result <add> result = self.f(da, db, *args, **kwargs) <add> # Reset the error status <add> np.seterr(**err_status_ini) <add> # Get the mask as a combination of ma, mb and invalid <add> m = ~umath.isfinite(result) <add> m |= ma <add> m |= mb <add> # Take care of the scalar case first <add> if (not m.ndim): <add> if m: <add> return masked <ide> else: <del> db = np.where(np.resize(t, db.shape), self.filly, db) <del> # Shrink m if a.mask was nomask, otherwise don't. <del> m = mask_or(ma, mb, shrink=(getattr(a, '_mask', nomask) is nomask)) <del> if (not m.ndim) and m: <del> return masked <del> elif (m is nomask): <del> result = self.f(da, db, *args, **kwargs) <del> else: <del> result = np.where(m, da, self.f(da, db, *args, **kwargs)) <del> if result.shape: <del> result = result.view(get_masked_subclass(a, b)) <del> # If we have a mask, make sure it's broadcasted properly <del> if m.any(): <del> result._mask = mask_or(getmaskarray(a), mb) <del> # If some initial masks where not shrunk, don't shrink the result <del> elif m.shape: <del> result._mask = make_mask_none(result.shape, result.dtype) <add> return result <add> # When the mask is True, put back da <add> np.putmask(result, m, 0) <add> result += m*da <add> result = result.view(get_masked_subclass(a, b)) <add> result._mask = m <add> if isinstance(b, MaskedArray): <ide> if isinstance(a, MaskedArray): <ide> result._update_from(a) <del> if isinstance(b, MaskedArray): <add> else: <ide> result._update_from(b) <add> elif isinstance(a, MaskedArray): <add> result._update_from(a) <ide> return result <ide> <ide> def __str__ (self): <ide> def __setitem__(self, indx, value): <ide> #........................................ <ide> # ndgetattr = ndarray.__getattribute__ <ide> _data = self._data <del> _dtype = ndarray.__getattribute__(_data,'dtype') <del> _mask = ndarray.__getattribute__(self,'_mask') <add> _dtype = ndarray.__getattribute__(_data, 'dtype') <add> _mask = ndarray.__getattribute__(self, '_mask') <ide> nbfields = len(_dtype.names or ()) <ide> #........................................ <ide> if value is masked: <ide><path>numpy/ma/tests/test_subclassing.py <ide> def _get_series(self): <ide> class TestSubclassing(TestCase): <ide> """Test suite for masked subclasses of ndarray.""" <ide> <add> def setUp(self): <add> x = np.arange(5) <add> mx = mmatrix(x, mask=[0, 1, 0, 0, 0]) <add> self.data = (x, mx) <add> <ide> def test_data_subclassing(self): <ide> "Tests whether the subclass is kept." <ide> x = np.arange(5) <ide> def test_data_subclassing(self): <ide> <ide> def test_maskedarray_subclassing(self): <ide> "Tests subclassing MaskedArray" <del> x = np.arange(5) <del> mx = mmatrix(x,mask=[0,1,0,0,0]) <add> (x, mx) = self.data <ide> self.failUnless(isinstance(mx._data, np.matrix)) <add> <add> def test_masked_unary_operations(self): <ide> "Tests masked_unary_operation" <add> (x, mx) = self.data <add> self.failUnless(isinstance(log(mx), mmatrix)) <add> assert_equal(log(x), np.log(x)) <add> <add> def test_masked_binary_operations(self): <add> "Tests masked_binary_operation" <add> (x, mx) = self.data <add> # Result should be a mmatrix <ide> self.failUnless(isinstance(add(mx,mx), mmatrix)) <ide> self.failUnless(isinstance(add(mx,x), mmatrix)) <add> # Result should work <ide> assert_equal(add(mx,x), mx+x) <ide> self.failUnless(isinstance(add(mx,mx)._data, np.matrix)) <ide> self.failUnless(isinstance(add.outer(mx,mx), mmatrix)) <del> "Tests masked_binary_operation" <ide> self.failUnless(isinstance(hypot(mx,mx), mmatrix)) <ide> self.failUnless(isinstance(hypot(mx,x), mmatrix)) <ide> <add> def test_masked_binary_operations(self): <add> "Tests domained_masked_binary_operation" <add> (x, mx) = self.data <add> xmx = masked_array(mx.data.__array__(), mask=mx.mask) <add> self.failUnless(isinstance(divide(mx,mx), mmatrix)) <add> self.failUnless(isinstance(divide(mx,x), mmatrix)) <add> assert_equal(divide(mx, mx), divide(xmx, xmx)) <add> <ide> def test_attributepropagation(self): <ide> x = array(arange(5), mask=[0]+[1]*4) <ide> my = masked_array(subarray(x))
2
Javascript
Javascript
handle transitioning nans
d61745a31155843fd0583f3c6c0a08673e0d4a93
<ide><path>src/core/core.element.js <ide> <ide> // Init if doesn't exist <ide> else if (!this._view[key]) { <del> if (typeof value === 'number') { <add> if (typeof value === 'number' && isNaN(this._view[key]) === false) { <ide> this._view[key] = value * ease; <ide> } else { <ide> this._view[key] = value || null; <ide> } <ide> // Number transitions <ide> else if (typeof value === 'number') { <del> var startVal = this._start[key] !== undefined ? this._start[key] : 0; <add> var startVal = this._start[key] !== undefined && isNaN(this._start[key]) === false ? this._start[key] : 0; <ide> this._view[key] = ((this._model[key] - startVal) * ease) + startVal; <ide> } <ide> // Everything else <ide> else { <ide> this._view[key] = value; <ide> } <del> <ide> }, this); <ide> <ide> if (ease === 1) { <ide><path>src/scales/scale.radialLinear.js <ide> return index * angleMultiplier - (Math.PI / 2); <ide> }, <ide> getDistanceFromCenterForValue: function(value) { <del> if (value === null) return 0; // null always in center <add> if (value === null || value === undefined || isNaN(value)) { <add> return 0; // null always in center <add> } <add> <ide> // Take into account half font size + the yPadding of the top value <ide> var scalingFactor = this.drawingArea / (this.max - this.min); <ide> if (this.options.reverse) {
2
Javascript
Javascript
add arrayofstreams to pipeline
e0ecde973705402bd3ce3ec7d611d866e3e95daa
<ide><path>test/parallel/test-stream-pipeline.js <ide> const net = require('net'); <ide> d.write('test'); <ide> d.end(); <ide> } <add> <add>{ <add> const r = new Readable({ <add> read() {} <add> }); <add> r.push('hello'); <add> r.push('world'); <add> r.push(null); <add> let res = ''; <add> const w = new Writable({ <add> write(chunk, encoding, callback) { <add> res += chunk; <add> callback(); <add> } <add> }); <add> pipeline([r, w], common.mustCall((err) => { <add> assert.ok(!err); <add> assert.strictEqual(res, 'helloworld'); <add> })); <add>}
1
Go
Go
expand hostname before passing it to newregistry()
ea59aa8cb5c4cde39259112123c47b69ccd9b53d
<ide><path>registry/service.go <ide> func (s *Service) Search(job *engine.Job) engine.Status { <ide> if err != nil { <ide> return job.Error(err) <ide> } <add> hostname, err = ExpandAndVerifyRegistryUrl(hostname) <add> if err != nil { <add> return job.Error(err) <add> } <ide> r, err := NewRegistry(authConfig, HTTPRequestFactory(metaHeaders), hostname, true) <ide> if err != nil { <ide> return job.Error(err)
1
PHP
PHP
use postgres catalog to fetch column names
ef27fb4118796056068aea8bc72ca689be35d9f4
<ide><path>src/Database/Schema/PostgresSchema.php <ide> public function describeIndexSql($tableName, $config) <ide> { <ide> $sql = 'SELECT <ide> c2.relname, <add> a.attname, <ide> i.indisprimary, <ide> i.indisunique, <ide> i.indisvalid, <ide> pg_catalog.pg_get_indexdef(i.indexrelid, 0, true) AS statement <ide> FROM pg_catalog.pg_class AS c, <ide> pg_catalog.pg_class AS c2, <del> pg_catalog.pg_index AS i <add> pg_catalog.pg_index AS i, <add> pg_catalog.pg_attribute AS a <ide> WHERE c.oid = ( <ide> SELECT c.oid <ide> FROM pg_catalog.pg_class c <ide> public function describeIndexSql($tableName, $config) <ide> AND n.nspname = ? <ide> ) <ide> AND c.oid = i.indrelid <add> AND c.oid = a.attrelid <add> AND a.attnum = ANY(i.indkey) <ide> AND i.indexrelid = c2.oid <del> ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname'; <add> ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname, a.attnum'; <ide> <ide> $schema = 'public'; <ide> if (!empty($config['schema'])) { <ide> public function convertIndexDescription(Table $table, $row) <ide> if ($row['indisunique'] && $type === Table::INDEX_INDEX) { <ide> $type = Table::CONSTRAINT_UNIQUE; <ide> } <del> preg_match('/\(([^\)]+?)\s*(?:ASC|DESC)?(?:NULLS FIRST|LAST)?\)/', $row['statement'], $matches); <del> $columns = $this->_convertColumnList($matches[1]); <ide> if ($type === Table::CONSTRAINT_PRIMARY || $type === Table::CONSTRAINT_UNIQUE) { <del> $table->addConstraint($name, [ <del> 'type' => $type, <del> 'columns' => $columns <del> ]); <add> $constraint = $table->constraint($name); <add> if (!$constraint) { <add> $constraint = [ <add> 'type' => $type, <add> 'columns' => [] <add> ]; <add> } <add> $constraint['columns'][] = $row['attname']; <add> $table->addConstraint($name, $constraint); <ide> <ide> // If there is only one column in the primary key and it is integery, <ide> // make it autoincrement. <add> $columns = $constraint['columns']; <ide> $columnDef = $table->column($columns[0]); <ide> <ide> if ($type === Table::CONSTRAINT_PRIMARY && <ide> public function convertIndexDescription(Table $table, $row) <ide> } <ide> return; <ide> } <del> $table->addIndex($name, [ <del> 'type' => $type, <del> 'columns' => $columns <del> ]); <del> } <del> <del> /** <del> * Convert a column list into a clean array. <del> * <del> * @param string $columns comma separated column list. <del> * @return array <del> */ <del> protected function _convertColumnList($columns) <del> { <del> $columns = explode(', ', $columns); <del> foreach ($columns as &$column) { <del> $column = trim($column, '"'); <add> $index = $table->index($name); <add> if (!$index) { <add> $index = [ <add> 'type' => $type, <add> 'columns' => [] <add> ]; <ide> } <del> return $columns; <add> $index['columns'][] = $row['attname']; <add> $table->addIndex($name, $index); <ide> } <ide> <ide> /**
1
Javascript
Javascript
send early logs to metro too
4ed05ca241b791ad629fd154429a4a53c7731556
<ide><path>Libraries/Utilities/HMRClient.js <ide> let hmrClient = null; <ide> let hmrUnavailableReason: string | null = null; <ide> let currentCompileErrorMessage: string | null = null; <ide> let didConnect: boolean = false; <add>let pendingLogs: Array<[LogLevel, Array<mixed>]> = []; <ide> <ide> type LogLevel = <ide> | 'trace' <ide> const HMRClient: HMRClientNativeInterface = { <ide> }, <ide> <ide> log(level: LogLevel, data: Array<mixed>) { <add> if (!hmrClient) { <add> // Catch a reasonable number of early logs <add> // in case hmrClient gets initialized later. <add> pendingLogs.push([level, data]); <add> if (pendingLogs.length > 100) { <add> pendingLogs.shift(); <add> } <add> return; <add> } <ide> try { <del> if (hmrClient) { <del> let message; <del> if (global.Symbol) { <add> let message; <add> if (global.Symbol) { <add> message = JSON.stringify({ <add> type: 'log', <add> level, <add> data: data.map(item => <add> typeof item === 'string' <add> ? item <add> : require('pretty-format')(item, { <add> escapeString: true, <add> highlight: true, <add> maxDepth: 3, <add> min: true, <add> plugins: [require('pretty-format').plugins.ReactElement], <add> }), <add> ), <add> }); <add> } else { <add> try { <add> message = JSON.stringify({type: 'log', level, data}); <add> } catch (error) { <ide> message = JSON.stringify({ <ide> type: 'log', <ide> level, <del> data: data.map(item => <del> typeof item === 'string' <del> ? item <del> : require('pretty-format')(item, { <del> escapeString: true, <del> highlight: true, <del> maxDepth: 3, <del> min: true, <del> plugins: [require('pretty-format').plugins.ReactElement], <del> }), <del> ), <add> data: [error.message], <ide> }); <del> } else { <del> try { <del> message = JSON.stringify({type: 'log', level, data}); <del> } catch (error) { <del> message = JSON.stringify({ <del> type: 'log', <del> level, <del> data: [error.message], <del> }); <del> } <ide> } <del> <del> hmrClient.send(message); <ide> } <add> <add> hmrClient.send(message); <ide> } catch (error) { <ide> // If sending logs causes any failures we want to silently ignore them <ide> // to ensure we do not cause infinite-logging loops. <ide> Error: ${e.message}`; <ide> } <ide> <ide> registerBundleEntryPoints(hmrClient); <add> flushEarlyLogs(hmrClient); <ide> }, <ide> }; <ide> <ide> function registerBundleEntryPoints(client) { <ide> } <ide> } <ide> <add>function flushEarlyLogs(client) { <add> try { <add> pendingLogs.forEach(([level: LogLevel, data: Array<mixed>]) => { <add> HMRClient.log(level, data); <add> }); <add> } finally { <add> pendingLogs.length = 0; <add> } <add>} <add> <ide> function dismissRedbox() { <ide> if ( <ide> Platform.OS === 'ios' &&
1
Javascript
Javascript
provide backpressure for pipeline flood
b97c28f59ee898a81f0df988c249359c9b42701d
<ide><path>lib/http.js <ide> if (process.env.NODE_DEBUG && /http/.test(process.env.NODE_DEBUG)) { <ide> } <ide> <ide> function readStart(socket) { <del> if (!socket || !socket._handle || !socket._handle.readStart) return; <add> if (!socket || !socket._handle || !socket._handle.readStart || socket._paused) <add> return; <ide> socket._handle.readStart(); <ide> } <ide> <ide> function parserOnMessageComplete() { <ide> stream.push(null); <ide> } <ide> <del> if (parser.socket.readable) { <del> // force to read the next incoming message <del> readStart(parser.socket); <del> } <add> // force to read the next incoming message <add> readStart(parser.socket); <ide> } <ide> <ide> <ide> function connectionListener(socket) { <ide> }); <ide> <ide> socket.ondata = function(d, start, end) { <add> assert(!socket._paused); <ide> var ret = parser.execute(d, start, end - start); <ide> if (ret instanceof Error) { <ide> debug('parse error'); <ide> function connectionListener(socket) { <ide> socket.destroy(); <ide> } <ide> } <add> <add> if (socket._paused) { <add> // onIncoming paused the socket, we should pause the parser as well <add> debug('pause parser'); <add> socket.parser.pause(); <add> } <ide> }; <ide> <ide> socket.onend = function() { <ide> function connectionListener(socket) { <ide> // The following callback is issued after the headers have been read on a <ide> // new message. In this callback we setup the response object and pass it <ide> // to the user. <add> <add> socket._paused = false; <add> function socketOnDrain() { <add> // If we previously paused, then start reading again. <add> if (socket._paused) { <add> socket._paused = false; <add> socket.parser.resume(); <add> readStart(socket); <add> } <add> } <add> socket.on('drain', socketOnDrain); <add> <ide> parser.onIncoming = function(req, shouldKeepAlive) { <ide> incoming.push(req); <ide> <add> // If the writable end isn't consuming, then stop reading <add> // so that we don't become overwhelmed by a flood of <add> // pipelined requests that may never be resolved. <add> if (!socket._paused) { <add> var needPause = socket._writableState.needDrain; <add> if (needPause) { <add> socket._paused = true; <add> // We also need to pause the parser, but don't do that until after <add> // the call to execute, because we may still be processing the last <add> // chunk. <add> readStop(socket); <add> } <add> } <add> <ide> var res = new ServerResponse(req); <ide> <ide> res.shouldKeepAlive = shouldKeepAlive; <ide><path>test/simple/test-http-pipeline-flood.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>switch (process.argv[2]) { <add> case undefined: <add> return parent(); <add> case 'child': <add> return child(); <add> default: <add> throw new Error('wtf'); <add>} <add> <add>function parent() { <add> var http = require('http'); <add> var bigResponse = new Buffer(10240) <add> bigResponse.fill('x'); <add> var gotTimeout = false; <add> var childClosed = false; <add> var requests = 0; <add> var connections = 0; <add> <add> var server = http.createServer(function(req, res) { <add> requests++; <add> res.setHeader('content-length', bigResponse.length); <add> res.end(bigResponse); <add> }); <add> <add> server.on('connection', function(conn) { <add> connections++; <add> }); <add> <add> // kill the connection after a bit, verifying that the <add> // flood of requests was eventually halted. <add> server.setTimeout(200, function(conn) { <add> gotTimeout = true; <add> conn.destroy(); <add> }); <add> <add> server.listen(common.PORT, function() { <add> var spawn = require('child_process').spawn; <add> var args = [__filename, 'child']; <add> var child = spawn(process.execPath, args, { stdio: 'inherit' }); <add> child.on('close', function(code) { <add> assert(!code); <add> childClosed = true; <add> server.close(); <add> }); <add> }); <add> <add> process.on('exit', function() { <add> assert(gotTimeout); <add> assert(childClosed); <add> assert.equal(connections, 1); <add> // 1213 works out to be the number of requests we end up processing <add> // before the outgoing connection backs up and requires a drain. <add> // however, to avoid being unnecessarily tied to a specific magic number, <add> // and making the test brittle, just assert that it's "a lot", which we <add> // can safely assume is more than 500. <add> assert(requests >= 500); <add> console.log('ok'); <add> }); <add>} <add> <add>function child() { <add> var net = require('net'); <add> <add> var gotEpipe = false; <add> var conn = net.connect({ port: common.PORT }); <add> <add> var req = 'GET / HTTP/1.1\r\nHost: localhost:' + <add> common.PORT + '\r\nAccept: */*\r\n\r\n'; <add> <add> req = new Array(10241).join(req); <add> <add> conn.on('connect', function() { <add> write(); <add> }); <add> <add> conn.on('drain', write); <add> <add> conn.on('error', function(er) { <add> gotEpipe = true; <add> }); <add> <add> process.on('exit', function() { <add> assert(gotEpipe); <add> console.log('ok - child'); <add> }); <add> <add> function write() { <add> while (false !== conn.write(req, 'ascii')); <add> } <add>}
2
PHP
PHP
fix code style
0286e4120d5f6fc119cefec5692ce1b6cb7cf1cf
<ide><path>lib/Cake/Test/Case/Model/Datasource/Database/MysqlTest.php <ide> public function testSchemaUnsigned() { <ide> $types = $this->Dbo->fieldParameters['unsigned']['types']; <ide> $schema = $Model->schema(); <ide> foreach ($types as $type) { <del> $this->assertArrayHasKey('unsigned', $schema['u'.$type]); <del> $this->assertTrue($schema['u'.$type]['unsigned']); <add> $this->assertArrayHasKey('unsigned', $schema['u' . $type]); <add> $this->assertTrue($schema['u' . $type]['unsigned']); <ide> $this->assertArrayHasKey('unsigned', $schema[$type]); <ide> $this->assertFalse($schema[$type]['unsigned']); <ide> }
1
Javascript
Javascript
fix typo in common/index.js
fc68bf22a9525def6b10f2a03a59e80723f7ea85
<ide><path>test/common/index.js <ide> module.exports = { <ide> skipIfReportDisabled, <ide> skipIfWorker, <ide> <del> get enoughTestCPU() { <add> get enoughTestCpu() { <ide> const cpus = require('os').cpus(); <ide> return Array.isArray(cpus) && (cpus.length > 1 || cpus[0].speed > 999); <ide> },
1
Javascript
Javascript
change child reference to object reference
2f234a2ac8b2fbac49997050caf9adcd896ca35d
<ide><path>src/core/Object3D.js <ide> THREE.Object3D.prototype = { <ide> remove: function ( object ) { <ide> var scene = this; <ide> <del> var childIndex = this.children.indexOf( child ); <add> var childIndex = this.children.indexOf( object ); <ide> <ide> if ( childIndex !== - 1 ) { <ide> <del> child.parent = undefined; <add> object.parent = undefined; <ide> this.children.splice( childIndex, 1 ); <ide> <ide> // remove from scene <ide> THREE.Object3D.prototype = { <ide> <ide> if ( scene !== undefined && scene instanceof THREE.Scene ) { <ide> <del> scene.removeChildRecurse( child ); <add> scene.removeChildRecurse( object ); <ide> <ide> } <ide>
1
PHP
PHP
add "reverse" method to collection
03f4e92a55fbaf2968a8417c38be491a6f29b60d
<ide><path>src/Illuminate/Support/Collection.php <ide> public function sortBy(Closure $callback) <ide> return $this; <ide> } <ide> <add> /** <add> * Reverse items order. <add> * <add> * @return \Illuminate\Support\Collection <add> */ <add> public function reverse() <add> { <add> $this->items = array_reverse($this->items); <add> <add> return $this; <add> } <add> <ide> /** <ide> * Reset the keys on the underlying array. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testEmptyCollectionIsEmpty() <ide> $c = new Collection(); <ide> <ide> $this->assertTrue($c->isEmpty()); <del> } <add> } <ide> <ide> <ide> public function testToArrayCallsToArrayOnEachItemInCollection() <ide> public function testSort() <ide> { <ide> $data = new Collection(array(5, 3, 1, 2, 4)); <ide> $data->sort(function($a, $b) <del> { <add> { <ide> if ($a === $b) <ide> { <ide> return 0; <ide> public function testSortBy() <ide> $this->assertEquals(array('dayle', 'taylor'), array_values($data->all())); <ide> } <ide> <add> <add> public function testReverse() <add> { <add> $data = new Collection(array('zaeed', 'alan')); <add> $data->reverse(); <add> <add> $this->assertEquals(array('alan', 'zaeed'), array_values($data->all())); <add> } <add> <ide> }
2
PHP
PHP
add option to skip detach on sync
b6d0ab1823b67153f16f0f32e81d9e869abebc26
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function createMany(array $records, array $joinings = array()) <ide> * Sync the intermediate tables with a list of IDs. <ide> * <ide> * @param array $ids <add> * @param bool $detaching <ide> * @return void <ide> */ <del> public function sync(array $ids) <add> public function sync(array $ids, $detaching = true) <ide> { <ide> // First we need to attach any of the associated models that are not currently <ide> // in this joining table. We'll spin through the given IDs, checking to see <ide> public function sync(array $ids) <ide> // Next, we will take the differences of the currents and given IDs and detach <ide> // all of the entities that exist in the "current" array but are not in the <ide> // the array of the IDs given to the method which will complete the sync. <del> if (count($detach) > 0) <add> if ($detaching and count($detach) > 0) <ide> { <ide> $this->detach($detach); <ide> } <ide> protected function attachNew(array $records, array $current, $touch = true) <ide> { <ide> foreach ($records as $id => $attributes) <ide> { <add> // If the ID is not in the list of existing pivot IDs, we will insert a new pivot <add> // record, otherwise, we will just update this existing record on this joining <add> // table, so that the developers will easily update these records pain free. <ide> if ( ! in_array($id, $current)) <ide> { <ide> $this->attach($id, $attributes, $touch);
1
Ruby
Ruby
show homebrew_cc in superenv
afd2dde47495d04bc9aeafc32fe8b39515f6563e
<ide><path>Library/Homebrew/cmd/--env.rb <ide> def __env <ide> end <ide> <ide> def build_env_keys env <del> %w[ CC CXX LD CFLAGS CXXFLAGS CPPFLAGS LDFLAGS SDKROOT MAKEFLAGS <add> %w[ <add> CC CXX LD <add> HOMEBREW_CC <add> CFLAGS CXXFLAGS CPPFLAGS LDFLAGS SDKROOT MAKEFLAGS <ide> CMAKE_PREFIX_PATH CMAKE_INCLUDE_PATH CMAKE_LIBRARY_PATH CMAKE_FRAMEWORK_PATH <ide> MACOSX_DEPLOYMENT_TARGET PKG_CONFIG_PATH PKG_CONFIG_LIBDIR <ide> HOMEBREW_DEBUG HOMEBREW_MAKE_JOBS HOMEBREW_VERBOSE HOMEBREW_USE_CLANG <ide> def build_env_keys env <ide> <ide> def dump_build_env env <ide> build_env_keys(env).each do |key| <add> case key when 'CC', 'CXX' <add> next <add> end if superenv? <add> <ide> value = env[key] <ide> print "#{key}: #{value}" <ide> case key when 'CC', 'CXX', 'LD'
1
Javascript
Javascript
fix prepack warning in rn bridge code
7e97ed00bc5c7cd6a5b8bbc711ddf0e0730ccb8a
<ide><path>Libraries/Interaction/FrameRateLogger.js <ide> const FrameRateLogger = { <ide> 'Trying to debug FrameRateLogger without the native module!', <ide> ); <ide> } <del> NativeModules.FrameRateLogger && NativeModules.FrameRateLogger.setGlobalOptions(options); <add> if (NativeModules.FrameRateLogger) { <add> // Freeze the object to avoid the prepack warning (PP0017) about leaking <add> // unfrozen objects. <add> // Needs to clone the object first to avoid modifying the argument. <add> const optionsClone = { <add> debug: !!options.debug, <add> reportStackTraces: !!options.reportStackTraces, <add> }; <add> Object.freeze(optionsClone); <add> Object.seal(optionsClone); <add> NativeModules.FrameRateLogger.setGlobalOptions(optionsClone); <add> } <ide> }, <ide> <ide> /**
1
Python
Python
change crop and resize fn to fit multilevel ones
f7d74d68320fdcfcbd6f1de496dbee9b2fee61eb
<ide><path>research/object_detection/meta_architectures/context_rcnn_meta_arch.py <ide> def _compute_second_stage_input_feature_maps(self, features_to_crop, <ide> A float32 Tensor with shape [K, new_height, new_width, depth]. <ide> """ <ide> box_features = self._crop_and_resize_fn( <del> features_to_crop, proposal_boxes_normalized, <add> [features_to_crop], proposal_boxes_normalized, None, <ide> [self._initial_crop_size, self._initial_crop_size]) <ide> <ide> attention_features = self._context_feature_extract_fn( <ide><path>research/object_detection/meta_architectures/context_rcnn_meta_arch_tf1_test.py <ide> from object_detection.protos import hyperparams_pb2 <ide> from object_detection.protos import post_processing_pb2 <ide> from object_detection.utils import ops <add>from object_detection.utils import spatial_transform_ops as spatial_ops <ide> from object_detection.utils import test_case <ide> from object_detection.utils import test_utils <ide> from object_detection.utils import tf_version <ide> def image_resizer_fn(image, masks=None): <ide> max_negatives_per_positive=None) <ide> <ide> crop_and_resize_fn = ( <del> ops.matmul_crop_and_resize <del> if use_matmul_crop_and_resize else ops.native_crop_and_resize) <add> spatial_ops.multilevel_matmul_crop_and_resize <add> if use_matmul_crop_and_resize <add> else spatial_ops.multilevel_native_crop_and_resize) <ide> common_kwargs = { <ide> 'is_training': <ide> is_training,
2
PHP
PHP
fix cs error
ab06c18726630015ea9beccdf1311741eb9e7d84
<ide><path>src/View/Helper/HtmlHelper.php <ide> namespace Cake\View\Helper; <ide> <ide> use Cake\Core\Configure; <del>use Cake\Http\Response; <ide> use Cake\View\Helper; <ide> use Cake\View\StringTemplateTrait; <del>use Cake\View\View; <ide> <ide> /** <ide> * Html Helper class for easy use of HTML widgets.
1
Javascript
Javascript
add key to fragment in superblockintro
73f8377d681f0c52faf3ce8f4ba9745616b02605
<ide><path>client/src/templates/Introduction/SuperBlockIntro.js <del>import React, { Component } from 'react'; <add>import React, { Component, Fragment } from 'react'; <ide> import PropTypes from 'prop-types'; <ide> import Helmet from 'react-helmet'; <ide> import { graphql } from 'gatsby'; <ide> export class SuperBlockIntroductionPage extends Component { <ide> <Spacer /> <ide> <div className='block-ui'> <ide> {blockDashedNames.map(blockDashedName => ( <del> <> <add> <Fragment key={blockDashedName}> <ide> <Block <ide> blockDashedName={blockDashedName} <ide> challenges={nodesForSuperBlock.filter( <ide> export class SuperBlockIntroductionPage extends Component { <ide> superBlockDashedName={superBlockDashedName} <ide> /> <ide> {blockDashedName !== 'project-euler' ? <Spacer /> : null} <del> </> <add> </Fragment> <ide> ))} <ide> {superBlock !== 'Coding Interview Prep' && ( <ide> <div>
1
Javascript
Javascript
add parser to agent
e576d4ec79ad983853d989819c78328aba0bb6f9
<ide><path>lib/http.js <ide> OutgoingMessage.prototype.assignSocket = function(socket) { <ide> }; <ide> <ide> <add>OutgoingMessage.prototype.detachSocket = function(socket) { <add> assert(socket._httpMessage == this); <add> socket._httpMessage = null; <add> this.socket = this.connection = null; <add>}; <add> <add> <ide> OutgoingMessage.prototype.destroy = function(error) { <ide> this.socket.destroy(error); <ide> }; <ide> OutgoingMessage.prototype._send = function(data, encoding) { <ide> <ide> <ide> OutgoingMessage.prototype._writeRaw = function(data, encoding) { <del> if (this.connection._httpMessage === this && this.connection.writable) { <add> if (this.connection && <add> this.connection._httpMessage === this && <add> this.connection.writable) { <ide> // There might be pending data in the this.output buffer. <ide> while (this.output.length) { <ide> if (!this.connection.writable) { <ide> OutgoingMessage.prototype.end = function(data, encoding) { <ide> <ide> <ide> OutgoingMessage.prototype._finish = function() { <del> this.socket._httpMessage = null; <del> this.socket = this.connection = null; <ide> this.emit('finish'); <ide> }; <ide> <ide> function connectionListener(socket) { <ide> // When we're finished writing the response, check if this is the last <ide> // respose, if so destroy the socket. <ide> res.on('finish', function() { <add> res.detachSocket(socket); <add> <ide> if (res._last) { <ide> socket.destroySoon(); <ide> } else { <ide> Agent.prototype.appendMessage = function(options) { <ide> var req = new ClientRequest(options); <ide> this.queue.push(req); <ide> <add> /* <ide> req.on('finish', function () { <ide> self._cycle(); <ide> }); <add> */ <ide> <ide> this._cycle(); <add> <add> return req; <ide> }; <ide> <ide> <del>Agent.prototype._establishNewConnection = function(socket, message) { <add>Agent.prototype._establishNewConnection = function() { <ide> var self = this; <ide> assert(this.sockets.length < this.maxSockets); <ide> <ide> // Grab a new "socket". Depending on the implementation of _getConnection <ide> // this could either be a raw TCP socket or a TLS stream. <ide> var socket = this._getConnection(this.host, this.port, function () { <add> debug("Agent _getConnection callback"); <ide> self._cycle(); <ide> }); <ide> <ide> this.sockets.push(socket); <ide> <add> // Add a parser to the socket. <add> var parser = parsers.alloc(); <add> parser.reinitialize('response'); <add> parser.socket = socket; <add> <add> socket.ondata = function(d, start, end) { <add> var ret = parser.execute(d, start, end - start); <add> if (ret instanceof Error) { <add> debug('parse error'); <add> socket.destroy(ret); <add> } else if (parser.incoming && parser.incoming.upgrade) { <add> var bytesParsed = ret; <add> socket.ondata = null; <add> socket.onend = null; <add> <add> var res = parser.incoming; <add> <add> // This is start + byteParsed + 1 due to the error of getting \n <add> // in the upgradeHead from the closing lines of the headers <add> var upgradeHead = d.slice(start + bytesParsed + 1, end); <add> <add> if (self.listeners('upgrade').length) { <add> self.emit('upgrade', res, res.socket, upgradeHead); <add> } else { <add> // Got upgrade header, but have no handler. <add> socket.destroy(); <add> } <add> } <add> }; <add> <add> socket.onend = function() { <add> parser.finish(); <add> socket.destroy(); <add> }; <add> <ide> // When the socket closes remove it from the list of available sockets. <ide> socket.on('close', function() { <ide> var i = self.sockets.indexOf(socket); <ide> if (i >= 0) self.sockets.splice(i, 1); <add> // unref the parser for easy gc <add> parsers.free(parser); <ide> }); <add> <add> parser.onIncoming = function(res, shouldKeepAlive) { <add> debug('AGENT incoming response!'); <add> <add> var req = socket._httpMessage; <add> assert(req); <add> <add> // Responses to HEAD requests are AWFUL. Ask Ryan. <add> // A major oversight in HTTP. Hence this nastiness. <add> var isHeadResponse = req.method == 'HEAD'; <add> debug('AGENT isHeadResponse ' + isHeadResponse); <add> <add> if (res.statusCode == 100) { <add> // restart the parser, as this is a continue message. <add> req.emit('continue'); <add> return true; <add> } <add> <add> if (req.shouldKeepAlive && res.headers.connection === 'close') { <add> req.shouldKeepAlive = false; <add> } <add> <add> res.addListener('end', function() { <add> debug('AGENT request complete disconnecting.'); <add> // For the moment we reconnect for every request. FIXME! <add> // All that should be required for keep-alive is to not reconnect, <add> // but outgoingFlush instead. <add> if (!req.shouldKeepAlive) socket.end(); <add> <add> req.detachSocket(socket); <add> self._cycle(); <add> }); <add> <add> req.emit('response', res); <add> <add> return isHeadResponse; <add> }; <ide> }; <ide> <ide> <ide> // Sub-classes can overwrite this method with e.g. something that supplies <ide> // TLS streams. <ide> Agent.prototype._getConnection = function(host, port, cb) { <add> debug("Agent connected!"); <ide> var c = net.createConnection(port, host); <ide> c.on('connect', cb); <ide> return c; <ide> Agent.prototype._getConnection = function(host, port, cb) { <ide> // waiting sockets. If a waiting socket cannot be found, it will <ide> // start the process of establishing one. <ide> Agent.prototype._cycle = function() { <add> debug("Agent _cycle"); <add> <ide> var first = this.queue[0]; <ide> if (!first) return; <ide> <ide> Agent.prototype._cycle = function() { <ide> // If the socket doesn't already have a message it's sending out <ide> // and the socket is available for writing... <ide> if (!socket._httpMessage && (socket.writable && socket.readable)) { <add> debug("Agent found socket, shift"); <ide> // We found an available connection! <ide> this.queue.shift(); // remove first from queue. <ide> first.assignSocket(socket);
1
Javascript
Javascript
remove mixins from scrollview
221e2fe4095bc9ae15878725bdac4071d53e61f5
<ide><path>Libraries/Components/ScrollView/ScrollView.js <ide> const StyleSheet = require('StyleSheet'); <ide> const View = require('View'); <ide> const InternalScrollViewType = require('InternalScrollViewType'); <ide> <del>const createReactClass = require('create-react-class'); <ide> const dismissKeyboard = require('dismissKeyboard'); <ide> const flattenStyle = require('flattenStyle'); <ide> const invariant = require('invariant'); <ide> export type Props = $ReadOnly<{| <ide> children?: React.Node, <ide> |}>; <ide> <add>type State = {| <add> layoutHeight: ?number, <add>|}; <add> <ide> /** <ide> * Component that wraps platform ScrollView while providing <ide> * integration with touch locking "responder" system. <ide> export type Props = $ReadOnly<{| <ide> * multiple columns, infinite scroll loading, or any number of other features it <ide> * supports out of the box. <ide> */ <del>const ScrollView = createReactClass({ <del> displayName: 'ScrollView', <del> mixins: [ScrollResponder.Mixin], <del> <del> _scrollAnimatedValue: (new AnimatedImplementation.Value( <add>class ScrollView extends React.Component<Props, State> { <add> _createScrollResponder = () => { <add> const scrollResponder = {...ScrollResponder.Mixin}; <add> for (const key in ScrollResponder.Mixin) { <add> if (typeof scrollResponder[key] === 'function') { <add> scrollResponder[key] = scrollResponder[key].bind(this); <add> (this: any)[key] = scrollResponder[key].bind(this); <add> } <add> } <add> return scrollResponder; <add> }; <add> _scrollResponder = this._createScrollResponder(); <add> _scrollAnimatedValue: AnimatedImplementation.Value = new AnimatedImplementation.Value( <ide> 0, <del> ): AnimatedImplementation.Value), <del> _scrollAnimatedValueAttachment: (null: ?{detach: () => void}), <del> _stickyHeaderRefs: (new Map(): Map<number, ScrollViewStickyHeader>), <del> _headerLayoutYs: (new Map(): Map<string, number>), <del> getInitialState: function() { <del> return { <del> ...this.scrollResponderMixinGetInitialState(), <del> layoutHeight: null, <del> }; <del> }, <add> ); <add> _scrollAnimatedValueAttachment: ?{detach: () => void} = null; <add> _stickyHeaderRefs: Map<number, ScrollViewStickyHeader> = new Map(); <add> _headerLayoutYs: Map<string, number> = new Map(); <ide> <del> UNSAFE_componentWillMount: function() { <add> state = { <add> layoutHeight: null, <add> }; <add> <add> UNSAFE_componentWillMount() { <add> this._scrollResponder.UNSAFE_componentWillMount(); <ide> this._scrollAnimatedValue = new AnimatedImplementation.Value( <ide> this.props.contentOffset ? this.props.contentOffset.y : 0, <ide> ); <ide> const ScrollView = createReactClass({ <ide> ); <ide> this._stickyHeaderRefs = new Map(); <ide> this._headerLayoutYs = new Map(); <del> }, <add> } <ide> <del> componentDidMount: function() { <add> componentDidMount() { <ide> this._updateAnimatedNodeAttachment(); <del> }, <add> } <ide> <del> componentDidUpdate: function() { <add> componentDidUpdate() { <ide> this._updateAnimatedNodeAttachment(); <del> }, <add> } <ide> <del> componentWillUnmount: function() { <add> componentWillUnmount() { <add> this._scrollResponder.componentWillUnmount(); <ide> if (this._scrollAnimatedValueAttachment) { <ide> this._scrollAnimatedValueAttachment.detach(); <ide> } <del> }, <add> } <ide> <del> setNativeProps: function(props: Object) { <add> setNativeProps = (props: Object) => { <ide> this._scrollViewRef && this._scrollViewRef.setNativeProps(props); <del> }, <add> }; <ide> <ide> /** <ide> * Returns a reference to the underlying scroll responder, which supports <ide> * operations like `scrollTo`. All ScrollView-like components should <ide> * implement this method so that they can be composed while providing access <ide> * to the underlying scroll responder's methods. <ide> */ <del> getScrollResponder: function(): ScrollView { <add> getScrollResponder = (): ScrollView => { <ide> return this; <del> }, <add> }; <ide> <del> getScrollableNode: function(): any { <add> getScrollableNode = (): any => { <ide> return ReactNative.findNodeHandle(this._scrollViewRef); <del> }, <add> }; <ide> <del> getInnerViewNode: function(): any { <add> getInnerViewNode = (): any => { <ide> return ReactNative.findNodeHandle(this._innerViewRef); <del> }, <add> }; <ide> <ide> /** <ide> * Scrolls to a given x, y offset, either immediately or with a smooth animation. <ide> const ScrollView = createReactClass({ <ide> * the function also accepts separate arguments as an alternative to the options object. <ide> * This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED. <ide> */ <del> scrollTo: function( <add> scrollTo = ( <ide> y?: number | {x?: number, y?: number, animated?: boolean}, <ide> x?: number, <ide> animated?: boolean, <del> ) { <add> ) => { <ide> if (typeof y === 'number') { <ide> console.warn( <ide> '`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, ' + <ide> const ScrollView = createReactClass({ <ide> } else { <ide> ({x, y, animated} = y || {}); <ide> } <del> this.getScrollResponder().scrollResponderScrollTo({ <add> this._scrollResponder.scrollResponderScrollTo({ <ide> x: x || 0, <ide> y: y || 0, <ide> animated: animated !== false, <ide> }); <del> }, <add> }; <ide> <ide> /** <ide> * If this is a vertical ScrollView scrolls to the bottom. <ide> const ScrollView = createReactClass({ <ide> * `scrollToEnd({animated: false})` for immediate scrolling. <ide> * If no options are passed, `animated` defaults to true. <ide> */ <del> scrollToEnd: function(options?: {animated?: boolean}) { <add> scrollToEnd = (options?: {animated?: boolean}) => { <ide> // Default to true <ide> const animated = (options && options.animated) !== false; <del> this.getScrollResponder().scrollResponderScrollToEnd({ <add> this._scrollResponder.scrollResponderScrollToEnd({ <ide> animated: animated, <ide> }); <del> }, <add> }; <ide> <ide> /** <ide> * Deprecated, use `scrollTo` instead. <ide> */ <del> scrollWithoutAnimationTo: function(y: number = 0, x: number = 0) { <add> scrollWithoutAnimationTo = (y: number = 0, x: number = 0) => { <ide> console.warn( <ide> '`scrollWithoutAnimationTo` is deprecated. Use `scrollTo` instead', <ide> ); <ide> this.scrollTo({x, y, animated: false}); <del> }, <add> }; <ide> <ide> /** <ide> * Displays the scroll indicators momentarily. <ide> * <ide> * @platform ios <ide> */ <del> flashScrollIndicators: function() { <del> this.getScrollResponder().scrollResponderFlashScrollIndicators(); <del> }, <add> flashScrollIndicators = () => { <add> this._scrollResponder.scrollResponderFlashScrollIndicators(); <add> }; <ide> <del> _getKeyForIndex: function(index, childArray) { <add> _getKeyForIndex = (index, childArray) => { <ide> // $FlowFixMe Invalid prop usage <ide> const child = childArray[index]; <ide> return child && child.key; <del> }, <add> }; <ide> <del> _updateAnimatedNodeAttachment: function() { <add> _updateAnimatedNodeAttachment = () => { <ide> if (this._scrollAnimatedValueAttachment) { <ide> this._scrollAnimatedValueAttachment.detach(); <ide> } <ide> const ScrollView = createReactClass({ <ide> [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}], <ide> ); <ide> } <del> }, <add> }; <ide> <del> _setStickyHeaderRef: function(key, ref) { <add> _setStickyHeaderRef = (key, ref) => { <ide> if (ref) { <ide> this._stickyHeaderRefs.set(key, ref); <ide> } else { <ide> this._stickyHeaderRefs.delete(key); <ide> } <del> }, <add> }; <ide> <del> _onStickyHeaderLayout: function(index, event, key) { <add> _onStickyHeaderLayout = (index, event, key) => { <ide> if (!this.props.stickyHeaderIndices) { <ide> return; <ide> } <ide> const ScrollView = createReactClass({ <ide> const layoutY = event.nativeEvent.layout.y; <ide> this._headerLayoutYs.set(key, layoutY); <ide> <add> // $FlowFixMe <ide> const indexOfIndex = this.props.stickyHeaderIndices.indexOf(index); <ide> const previousHeaderIndex = this.props.stickyHeaderIndices[ <add> // $FlowFixMe <ide> indexOfIndex - 1 <ide> ]; <ide> if (previousHeaderIndex != null) { <ide> const ScrollView = createReactClass({ <ide> ); <ide> previousHeader && previousHeader.setNextHeaderY(layoutY); <ide> } <del> }, <add> }; <ide> <del> _handleScroll: function(e: Object) { <add> _handleScroll = (e: Object) => { <ide> if (__DEV__) { <ide> if ( <ide> this.props.onScroll && <ide> const ScrollView = createReactClass({ <ide> if (Platform.OS === 'android') { <ide> if ( <ide> this.props.keyboardDismissMode === 'on-drag' && <del> this.state.isTouching <add> this._scrollResponder.isTouching <ide> ) { <ide> dismissKeyboard(); <ide> } <ide> } <del> this.scrollResponderHandleScroll(e); <del> }, <add> this._scrollResponder.scrollResponderHandleScroll(e); <add> }; <ide> <del> _handleLayout: function(e: Object) { <add> _handleLayout = (e: Object) => { <ide> if (this.props.invertStickyHeaders) { <ide> this.setState({layoutHeight: e.nativeEvent.layout.height}); <ide> } <ide> if (this.props.onLayout) { <ide> this.props.onLayout(e); <ide> } <del> }, <add> }; <ide> <del> _handleContentOnLayout: function(e: Object) { <add> _handleContentOnLayout = (e: Object) => { <ide> const {width, height} = e.nativeEvent.layout; <ide> this.props.onContentSizeChange && <ide> this.props.onContentSizeChange(width, height); <del> }, <add> }; <ide> <del> _scrollViewRef: (null: ?ScrollView), <del> _setScrollViewRef: function(ref: ?ScrollView) { <add> _scrollViewRef: ?ScrollView = null; <add> _setScrollViewRef = (ref: ?ScrollView) => { <ide> this._scrollViewRef = ref; <del> }, <add> }; <ide> <del> _innerViewRef: (null: ?NativeMethodsMixinType), <del> _setInnerViewRef: function(ref: ?NativeMethodsMixinType) { <add> _innerViewRef: ?NativeMethodsMixinType = null; <add> _setInnerViewRef = (ref: ?NativeMethodsMixinType) => { <ide> this._innerViewRef = ref; <del> }, <add> }; <ide> <del> render: function() { <add> render() { <ide> let ScrollViewClass; <ide> let ScrollContentContainerViewClass; <ide> if (Platform.OS === 'android') { <ide> const ScrollView = createReactClass({ <ide> const children = hasStickyHeaders <ide> ? // $FlowFixMe Invalid prop usage <ide> childArray.map((child, index) => { <add> // $FlowFixMe <ide> const indexOfIndex = child ? stickyHeaderIndices.indexOf(index) : -1; <ide> if (indexOfIndex > -1) { <ide> const key = child.key; <add> // $FlowFixMe <ide> const nextIndex = stickyHeaderIndices[indexOfIndex + 1]; <ide> return ( <ide> <ScrollViewStickyHeader <ide> const ScrollView = createReactClass({ <ide> // bubble up from TextInputs <ide> onContentSizeChange: null, <ide> onLayout: this._handleLayout, <del> onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, <del> onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, <del> onResponderGrant: this.scrollResponderHandleResponderGrant, <del> onResponderReject: this.scrollResponderHandleResponderReject, <del> onResponderRelease: this.scrollResponderHandleResponderRelease, <add> onMomentumScrollBegin: this._scrollResponder <add> .scrollResponderHandleMomentumScrollBegin, <add> onMomentumScrollEnd: this._scrollResponder <add> .scrollResponderHandleMomentumScrollEnd, <add> onResponderGrant: this._scrollResponder <add> .scrollResponderHandleResponderGrant, <add> onResponderReject: this._scrollResponder <add> .scrollResponderHandleResponderReject, <add> onResponderRelease: this._scrollResponder <add> .scrollResponderHandleResponderRelease, <ide> // $FlowFixMe <del> onResponderTerminate: this.scrollResponderHandleTerminate, <del> onResponderTerminationRequest: this <add> onResponderTerminate: this._scrollResponder <add> .scrollResponderHandleTerminate, <add> onResponderTerminationRequest: this._scrollResponder <ide> .scrollResponderHandleTerminationRequest, <del> onScroll: this._handleScroll, <del> onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, <del> onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, <del> onScrollShouldSetResponder: this <add> onScrollBeginDrag: this._scrollResponder <add> .scrollResponderHandleScrollBeginDrag, <add> onScrollEndDrag: this._scrollResponder.scrollResponderHandleScrollEndDrag, <add> onScrollShouldSetResponder: this._scrollResponder <ide> .scrollResponderHandleScrollShouldSetResponder, <del> onStartShouldSetResponder: this <add> onStartShouldSetResponder: this._scrollResponder <ide> .scrollResponderHandleStartShouldSetResponder, <del> onStartShouldSetResponderCapture: this <add> onStartShouldSetResponderCapture: this._scrollResponder <ide> .scrollResponderHandleStartShouldSetResponderCapture, <del> onTouchEnd: this.scrollResponderHandleTouchEnd, <del> onTouchMove: this.scrollResponderHandleTouchMove, <del> onTouchStart: this.scrollResponderHandleTouchStart, <del> onTouchCancel: this.scrollResponderHandleTouchCancel, <add> onTouchEnd: this._scrollResponder.scrollResponderHandleTouchEnd, <add> onTouchMove: this._scrollResponder.scrollResponderHandleTouchMove, <add> onTouchStart: this._scrollResponder.scrollResponderHandleTouchStart, <add> onTouchCancel: this._scrollResponder.scrollResponderHandleTouchCancel, <add> onScroll: this._handleScroll, <ide> scrollBarThumbImage: resolveAssetSource(this.props.scrollBarThumbImage), <ide> scrollEventThrottle: hasStickyHeaders <ide> ? 1 <ide> const ScrollView = createReactClass({ <ide> // On iOS the RefreshControl is a child of the ScrollView. <ide> // tvOS lacks native support for RefreshControl, so don't include it in that case <ide> return ( <add> // $FlowFixMe <ide> <ScrollViewClass {...props} ref={this._setScrollViewRef}> <ide> {Platform.isTV ? null : refreshControl} <ide> {contentContainer} <ide> const ScrollView = createReactClass({ <ide> <ScrollViewClass <ide> {...props} <ide> style={baseStyle} <add> // $FlowFixMe <ide> ref={this._setScrollViewRef}> <ide> {contentContainer} <ide> </ScrollViewClass>, <ide> ); <ide> } <ide> } <ide> return ( <add> // $FlowFixMe <ide> <ScrollViewClass {...props} ref={this._setScrollViewRef}> <ide> {contentContainer} <ide> </ScrollViewClass> <ide> ); <del> }, <del>}); <add> } <add>} <ide> <ide> const TypedScrollView = ((ScrollView: any): Class< <ide> InternalScrollViewType<Props>,
1
Text
Text
update image in readme
b0e7abac60eb2a679291484cff851dd8fdd76e0b
<ide><path>README.md <ide> # Atom — Futuristic Text Editing <ide> <del>![atom](http://f.cl.ly/items/3h1L1O333p1d0W3D2K3r/atom-sketch.jpg) <add>![atom](https://f.cloud.github.com/assets/1300064/208230/4cefbca4-821a-11e2-8139-92c0328abf68.png) <ide> <ide> Check out our [documentation on the docs tab](https://github.com/github/atom/docs). <ide>
1
Javascript
Javascript
remove extra semicolon
b4f18fc295fe9cdbabf9e6e8d7587e5d76ff6878
<ide><path>src/Injector.js <ide> function createInjector(factoryScope, factories, instanceCache) { <ide> instanceCache[value] = invoke(factoryScope, factory); <ide> } <ide> return instanceCache[value]; <del> }; <add> } <ide> <ide> function invoke(self, fn, args){ <ide> args = args || [];
1
Javascript
Javascript
fix error reporting in release script
0bd2c2bb3d93adcfebdff6bbc3ad3d338b79c42a
<ide><path>scripts/release/publish-commands/publish-to-npm.js <ide> const push = async ({cwd, dry, version}) => { <ide> // To better handle the case of pre-release versions. <ide> if (remoteVersion !== packageVersion) { <ide> throw Error( <del> chalk`Publised version {yellow.bold ${packageVersion}} for ` + <del> `{bold ${project}} but NPM shows {yellow.bold ${remoteVersion}}` <add> chalk`Published version {yellow.bold ${packageVersion}} for ` + <add> chalk`{bold ${project}} but NPM shows {yellow.bold ${remoteVersion}}` <ide> ); <ide> } <ide>
1
Text
Text
add gatsby.js pwa guide
40504e30b2310242cebee5603153748ff00f2cdb
<ide><path>guide/english/gatsbyjs/gatsbyjs-pwa/index.md <add>--- <add>title: Gatsby.js Progressive Web Apps (PWA) <add>--- <add> <add>## Gatsby.js PWA <add> <add>Gatsby is designed to provide top-notch performance out of the box. It handles code splitting, code minification, and optimizations like pre-loading in the background, image processing, etc., so that the site you build is highly performant, without any kind of manual tuning. These performance features are a big part of supporting the progressive web app approach. <add> <add>Gatsby mets the three baseline criterias for it to quality as PWA. <add> <add>- It must run under HTTPS. <add>- It must include a Web App Manifest. <add>- It must implement a service worker. <add> <add>### More Information: <add>Check out the Gatsby.js official docs for Progressive Web Apps at [Gatsby PWA](https://www.gatsbyjs.org/docs/progressive-web-app/). For more information and learn more, visit: [Gatsby.js official site](https://www.gatsbyjs.org/tutorial/)
1
PHP
PHP
fix typo in docblock
df443765cd009145fbed6f4224bf0816243e84ee
<ide><path>src/Network/CorsBuilder.php <ide> public function __construct(Response $response, $origin, $isSsl = false) <ide> /** <ide> * Apply the queued headers to the response. <ide> * <del> * If the builer has no Origin, or if there are no allowed domains, <add> * If the builder has no Origin, or if there are no allowed domains, <ide> * or if the allowed domains do not match the Origin header no headers will be applied. <ide> * <ide> * @return \Cake\Network\Response
1
Ruby
Ruby
improve issue searching
a65f649cf54d90700d039854c1619027cda9e8f6
<ide><path>Library/Homebrew/exceptions.rb <ide> def dump <ide> puts <ide> unless RUBY_VERSION < "1.8.6" || issues.empty? <ide> puts "These open issues may also help:" <del> puts issues.map{ |s| " #{s}" }.join("\n") <add> puts issues.map{ |i| "#{i['title']} (#{i['html_url']})" }.join("\n") <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/utils.rb <ide> def open url, headers={}, &block <ide> raise Error, "Failed to connect to: #{url}\n#{e.message}" <ide> end <ide> <del> def each_issue_matching(query, &block) <add> def issues_matching(query) <ide> uri = ISSUES_URI + uri_escape(query) <del> open(uri) { |f| Utils::JSON.load(f.read)['issues'].each(&block) } <add> open(uri) { |f| Utils::JSON.load(f.read)['issues'] } <ide> end <ide> <ide> def uri_escape(query) <ide> def issues_for_formula name <ide> <ide> name = f.name if Formula === name <ide> <del> issues = [] <del> <del> each_issue_matching(name) do |issue| <del> # don't include issues that just refer to the tool in their body <del> issues << issue['html_url'] if issue['title'].include? name <del> end <del> <del> issues <add> # don't include issues that just refer to the tool in their body <add> issues_matching(name).select {|issue| issue['title'].include? name } <ide> end <ide> <ide> def find_pull_requests rx <ide> return if ENV['HOMEBREW_NO_GITHUB_API'] <del> puts "Searching open pull requests..." <add> puts "Searching pull requests..." <ide> <ide> query = rx.source.delete('.*').gsub('\\', '') <ide> <del> each_issue_matching(query) do |issue| <del> if rx === issue['title'] && issue.has_key?('pull_request_url') && issue['state'] != 'closed' <del> yield issue['pull_request_url'] <del> end <add> open_or_closed_prs = issues_matching(query).select do |issue| <add> rx === issue['title'] && issue.has_key?('pull_request_url') <ide> end <add> open_prs = open_or_closed_prs.select {|i| i['state'] != 'closed' } <add> if open_prs.any? <add> puts "Open pull requests:" <add> prs = open_prs <add> elsif open_or_closed_prs.any? <add> puts "Closed pull requests:" <add> prs = open_or_closed_prs <add> else <add> return <add> end <add> <add> prs.each {|i| yield "#{i['title']} (#{i['pull_request_url']})" } <ide> end <ide> end
2
Javascript
Javascript
reduce core.title.js size
4068836a42962c306a79f8baec099df0d0f4377f
<ide><path>src/core/core.title.js <ide> module.exports = function(Chart) { <ide> text: '' <ide> }; <ide> <add> var noop = helpers.noop; <ide> Chart.Title = Chart.Element.extend({ <ide> <ide> initialize: function(config) { <ide> module.exports = function(Chart) { <ide> <ide> // These methods are ordered by lifecyle. Utilities then follow. <ide> <del> beforeUpdate: helpers.noop, <add> beforeUpdate: noop, <ide> update: function(maxWidth, maxHeight, margins) { <ide> <ide> // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) <ide> module.exports = function(Chart) { <ide> return this.minSize; <ide> <ide> }, <del> afterUpdate: helpers.noop, <add> afterUpdate: noop, <ide> <ide> // <ide> <del> beforeSetDimensions: helpers.noop, <add> beforeSetDimensions: noop, <ide> setDimensions: function() { <ide> // Set the unconstrained dimension before label rotation <ide> if (this.isHorizontal()) { <ide> module.exports = function(Chart) { <ide> height: 0 <ide> }; <ide> }, <del> afterSetDimensions: helpers.noop, <add> afterSetDimensions: noop, <ide> <ide> // <ide> <del> beforeBuildLabels: helpers.noop, <del> buildLabels: helpers.noop, <del> afterBuildLabels: helpers.noop, <add> beforeBuildLabels: noop, <add> buildLabels: noop, <add> afterBuildLabels: noop, <ide> <ide> // <ide> <del> beforeFit: helpers.noop, <add> beforeFit: noop, <ide> fit: function() { <ide> <del> var ctx = this.ctx; <del> var fontSize = helpers.getValueOrDefault(this.options.fontSize, Chart.defaults.global.defaultFontSize); <del> var fontStyle = helpers.getValueOrDefault(this.options.fontStyle, Chart.defaults.global.defaultFontStyle); <del> var fontFamily = helpers.getValueOrDefault(this.options.fontFamily, Chart.defaults.global.defaultFontFamily); <del> var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); <add> var ctx = this.ctx, <add> valueOrDefault = helpers.getValueOrDefault, <add> opts = this.options, <add> globalDefaults = Chart.defaults.global, <add> display = opts.display, <add> fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize), <add> minSize = this.minSize; <ide> <del> // Width <ide> if (this.isHorizontal()) { <del> this.minSize.width = this.maxWidth; // fill all the width <add> minSize.width = this.maxWidth; // fill all the width <add> minSize.height = display ? fontSize + (opts.padding * 2) : 0; <ide> } else { <del> this.minSize.width = 0; <add> minSize.width = display ? fontSize + (opts.padding * 2) : 0; <add> minSize.height = this.maxHeight; // fill all the height <ide> } <ide> <del> // height <del> if (this.isHorizontal()) { <del> this.minSize.height = 0; <del> } else { <del> this.minSize.height = this.maxHeight; // fill all the height <del> } <del> <del> // Increase sizes here <del> if (this.isHorizontal()) { <del> <del> // Title <del> if (this.options.display) { <del> this.minSize.height += fontSize + (this.options.padding * 2); <del> } <del> } else { <del> if (this.options.display) { <del> this.minSize.width += fontSize + (this.options.padding * 2); <del> } <del> } <del> <del> this.width = this.minSize.width; <del> this.height = this.minSize.height; <add> this.width = minSize.width; <add> this.height = minSize.height; <ide> <ide> }, <del> afterFit: helpers.noop, <add> afterFit: noop, <ide> <ide> // Shared Methods <ide> isHorizontal: function() { <del> return this.options.position === "top" || this.options.position === "bottom"; <add> var pos = this.options.position; <add> return pos === "top" || pos === "bottom"; <ide> }, <ide> <ide> // Actualy draw the title block on the canvas <ide> draw: function() { <del> if (this.options.display) { <del> var ctx = this.ctx; <del> var titleX, titleY; <del> <del> var fontColor = helpers.getValueOrDefault(this.options.fontColor, Chart.defaults.global.defaultFontColor); <del> var fontSize = helpers.getValueOrDefault(this.options.fontSize, Chart.defaults.global.defaultFontSize); <del> var fontStyle = helpers.getValueOrDefault(this.options.fontStyle, Chart.defaults.global.defaultFontStyle); <del> var fontFamily = helpers.getValueOrDefault(this.options.fontFamily, Chart.defaults.global.defaultFontFamily); <del> var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); <del> <del> ctx.fillStyle = fontColor; // render in correct colour <add> var ctx = this.ctx, <add> valueOrDefault = helpers.getValueOrDefault, <add> opts = this.options, <add> globalDefaults = Chart.defaults.global; <add> <add> if (opts.display) { <add> var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize), <add> fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle), <add> fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily), <add> titleFont = helpers.fontString(fontSize, fontStyle, fontFamily), <add> rotation = 0, <add> titleX, <add> titleY; <add> <add> ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour <ide> ctx.font = titleFont; <ide> <ide> // Horizontal <ide> if (this.isHorizontal()) { <del> // Title <del> ctx.textAlign = "center"; <del> ctx.textBaseline = 'middle'; <del> <ide> titleX = this.left + ((this.right - this.left) / 2); // midpoint of the width <ide> titleY = this.top + ((this.bottom - this.top) / 2); // midpoint of the height <del> <del> ctx.fillText(this.options.text, titleX, titleY); <ide> } else { <del> <del> // Title <del> titleX = this.options.position === 'left' ? this.left + (fontSize / 2) : this.right - (fontSize / 2); <add> titleX = opts.position === 'left' ? this.left + (fontSize / 2) : this.right - (fontSize / 2); <ide> titleY = this.top + ((this.bottom - this.top) / 2); <del> var rotation = this.options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; <del> <del> ctx.save(); <del> ctx.translate(titleX, titleY); <del> ctx.rotate(rotation); <del> ctx.textAlign = "center"; <del> ctx.textBaseline = 'middle'; <del> ctx.fillText(this.options.text, 0, 0); <del> ctx.restore(); <add> rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5); <ide> } <add> <add> ctx.save(); <add> ctx.translate(titleX, titleY); <add> ctx.rotate(rotation); <add> ctx.textAlign = 'center'; <add> ctx.textBaseline = 'middle'; <add> ctx.fillText(opts.text, 0, 0); <add> ctx.restore(); <ide> } <ide> } <ide> }); <ide><path>test/core.title.tests.js <ide> describe('Title block tests', function() { <ide> expect(context.getCalls()).toEqual([{ <ide> name: 'setFillStyle', <ide> args: ['#666'] <add> }, { <add> name: 'save', <add> args: [] <add> }, { <add> name: 'translate', <add> args: [300, 66] <add> }, { <add> name: 'rotate', <add> args: [0] <ide> }, { <ide> name: 'fillText', <del> args: ['My title', 300, 66] <add> args: ['My title', 0, 0] <add> }, { <add> name: 'restore', <add> args: [] <ide> }]); <ide> }); <ide>
2
Python
Python
add test for gh17797
1ef11c93a52e18ee2c45d4173ec8e685ceb53e9a
<ide><path>numpy/f2py/auxfuncs.py <ide> def ismodule(rout): <ide> def isfunction(rout): <ide> return 'block' in rout and 'function' == rout['block'] <ide> <add> <ide> def isfunction_wrap(rout): <ide> if isintent_c(rout): <ide> return 0 <ide> def hasassumedshape(rout): <ide> return False <ide> <ide> <add>def requiresf90wrapper(rout): <add> return ismoduleroutine(rout) or hasassumedshape(rout) <add> <add> <ide> def isroutine(rout): <ide> return isfunction(rout) or issubroutine(rout) <ide> <ide><path>numpy/f2py/crackfortran.py <ide> def crack2fortrangen(block, tab='\n', as_interface=False): <ide> result = ' result (%s)' % block['result'] <ide> if block['result'] not in argsl: <ide> argsl.append(block['result']) <del> body = crack2fortrangen(block['body'], tab + tabchar) <add> body = crack2fortrangen(block['body'], tab + tabchar, as_interface=as_interface) <ide> vars = vars2fortran( <ide> block, block['vars'], argsl, tab + tabchar, as_interface=as_interface) <ide> mess = '' <ide> def vars2fortran(block, vars, args, tab='', as_interface=False): <ide> show(vars) <ide> outmess('vars2fortran: No definition for argument "%s".\n' % a) <ide> continue <del> if a == block['name'] and not block['block'] == 'function': <del> continue <add> if a == block['name']: <add> if block['block'] == 'function': <add> if block.get('result'): <add> # skip declaring function if its result is already declared <add> continue <add> else: <add> continue <ide> if 'typespec' not in vars[a]: <ide> if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']: <ide> if a in args: <ide><path>numpy/f2py/rules.py <ide> issubroutine, issubroutine_wrap, isthreadsafe, isunsigned, <ide> isunsigned_char, isunsigned_chararray, isunsigned_long_long, <ide> isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray, <del> l_and, l_not, l_or, outmess, replace, stripcomma, <add> l_and, l_not, l_or, outmess, replace, stripcomma, requiresf90wrapper <ide> ) <ide> <ide> from . import capi_maps <ide> def buildmodule(m, um): <ide> nb1['args'] = a <ide> nb_list.append(nb1) <ide> for nb in nb_list: <add> # requiresf90wrapper must be called before buildapi as it <add> # rewrites assumed shape arrays as automatic arrays. <add> isf90 = requiresf90wrapper(nb) <ide> api, wrap = buildapi(nb) <ide> if wrap: <del> if ismoduleroutine(nb) or issubroutine_wrap(nb): <add> if isf90: <ide> funcwrappers2.append(wrap) <ide> else: <ide> funcwrappers.append(wrap) <ide> def buildmodule(m, um): <ide> 'C It contains Fortran 77 wrappers to fortran functions.\n') <ide> lines = [] <ide> for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'): <del> if l and l[0] == ' ': <add> i = l.find('!') <add> if i >= 0 and i < 66: <add> # don't split comment lines <add> lines.append(l + '\n') <add> elif l and l[0] == ' ': <ide> while len(l) >= 66: <ide> lines.append(l[:66] + '\n &') <ide> l = l[66:] <ide><path>numpy/f2py/tests/test_callback.py <ide> class TestF77CallbackPythonTLS(TestF77Callback): <ide> compiler-provided <ide> """ <ide> options = ["-DF2PY_USE_PYTHON_TLS"] <add> <add> <add>class TestF90Callback(util.F2PyTest): <add> <add> suffix = '.f90' <add> <add> code = """ <add>function gh17797(f, y) result(r) <add> external f <add> integer(8) :: r, f <add> integer(8), dimension(:) :: y <add> r = f(0) <add> r = r + sum(y) <add>end function gh17797 <add> """ <add> <add> def test_gh17797(self): <add> <add> def incr(x): <add> return x + 123 <add> <add> y = np.array([1, 2, 3], dtype=np.int64) <add> r = self.module.gh17797(incr, y) <add> assert r == 123 + 1 + 2 + 3
4
Text
Text
fix some minor typos on dockerlinks guide
06d633e1f68d003f6183403b134142b12a24c9ca
<ide><path>docs/sources/userguide/dockerlinks.md <ide> recipient container in two ways: <ide> <ide> ### Environment Variables <ide> <del>When two containers are linked, Docker will set some envrionment variables <add>When two containers are linked, Docker will set some environment variables <ide> in the target container to enable programmatic discovery of information <ide> related to the source container. <ide> <del>First, Docker will set a `<alias>_NAME` environment variable specifying the <add>First, Docker will set an `<alias>_NAME` environment variable specifying the <ide> alias of each target container that was given in a `--link` parameter. So, <ide> for example, if a new container called `web` is being linked to a database <ide> container called `db` via `--link db:webdb` then in the `web` container
1
PHP
PHP
add array_search to support\collection
ce9b24fd47791d2b92233e236a82f61c96f78070
<ide><path>src/Illuminate/Support/Collection.php <ide> public function reverse() <ide> return new static(array_reverse($this->items)); <ide> } <ide> <add> /** <add> * Search the collection for a given item and returns the corresponding key if successful <add> * <add> * @param mixed $value <add> * @param bool $strict <add> * @return mixed <add> */ <add> public function search($value, $strict = false) <add> { <add> return array_search($value, $this->items, $strict); <add> } <add> <ide> /** <ide> * Get and remove the first item from the collection. <ide> *
1
Text
Text
fix mobile layout
2b7012ffb01dd96a6096e77408bf35e8b9b40d25
<ide><path>docs/docs/optimizing-performance.md <ide> By default, React includes many helpful warnings. These warnings are very useful <ide> <ide> If you aren't sure whether your build process is set up correctly, you can check it by installing [React Developer Tools for Chrome](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi). If you visit a site with React in production mode, the icon will have a dark background: <ide> <del><img src="/react/img/docs/devtools-prod.png" width="600" alt="React DevTools on a website with production version of React"> <add><img src="/react/img/docs/devtools-prod.png" style="max-width:100%" alt="React DevTools on a website with production version of React"> <ide> <ide> If you visit a site with React in development mode, the icon will have a red background: <ide> <del><img src="/react/img/docs/devtools-dev.png" width="600" alt="React DevTools on a website with development version of React"> <add><img src="/react/img/docs/devtools-dev.png" style="max-width:100%" alt="React DevTools on a website with development version of React"> <ide> <ide> It is expected that you use the development mode when working on your app, and the production mode when deploying your app to the users. <ide>
1
Javascript
Javascript
fix ie8 test bug
398c67fa8173defe7c987331c338cefd91fbdaf5
<ide><path>src/test/moment/now.js <ide> test('now - Date mocked', function (assert) { <ide> // We need to test mocking the global Date object, so disable 'Read Only' jshint check <ide> /* jshint -W020 */ <ide> var RealDate = Date, <del> customTimeStr = '2015-01-01T01:30:00.000Z'; <add> customTimeMs = moment('2015-01-01T01:30:00.000Z').valueOf(); <ide> <ide> function MockDate() { <del> return new RealDate(customTimeStr); <add> return new RealDate(customTimeMs); <ide> } <ide> <ide> MockDate.now = function () { <ide> test('now - Date mocked', function (assert) { <ide> Date = MockDate; <ide> <ide> try { <del> assert.ok(moment().toISOString() === customTimeStr, 'moment now() time should use the global Date object'); <add> assert.equal(moment().valueOf(), customTimeMs, 'moment now() time should use the global Date object'); <ide> } finally { <ide> Date = RealDate; <ide> }
1
Ruby
Ruby
alter the naming structure a bit
a6fbddb7be5095186e7d66aac0ef64e46b7284f9
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> module DatabaseStatements <ide> def initialize <ide> super <ide> @transaction_joinable = nil <del> @transaction = Transaction::Closed.new(self) <add> @transaction = ClosedTransaction.new(self) <ide> end <ide> <ide> # Converts an arel AST to SQL <ide> def transaction(options = {}) <ide> @transaction_joinable = last_transaction_joinable <ide> <ide> if outside_transaction? <del> @transaction = Transactions::Closed.new(self) <add> @transaction = ClosedTransaction.new(self) <ide> elsif @transaction.open? && transaction_open <ide> begin <ide> commit_transaction <ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb <ide> module ActiveRecord <ide> module ConnectionAdapters <del> module Transaction # :nodoc: <del> class State <del> attr_reader :connection <add> class Transaction #:nodoc: <add> attr_reader :connection <ide> <del> def initialize(connection) <del> @connection = connection <del> end <add> def initialize(connection) <add> @connection = connection <ide> end <add> end <ide> <del> class Closed < State <del> def number <del> 0 <del> end <add> class ClosedTransaction < Transaction #:nodoc: <add> def number <add> 0 <add> end <ide> <del> def begin <del> Real.new(connection, self) <del> end <add> def begin <add> RealTransaction.new(connection, self) <add> end <ide> <del> def closed? <del> true <del> end <add> def closed? <add> true <add> end <ide> <del> def open? <del> false <del> end <add> def open? <add> false <add> end <ide> <del> # This is a noop when there are no open transactions <del> def add_record(record) <del> end <add> # This is a noop when there are no open transactions <add> def add_record(record) <ide> end <add> end <ide> <del> class Open < State <del> attr_reader :parent, :records <add> class OpenTransaction < Transaction #:nodoc: <add> attr_reader :parent, :records <ide> <del> def initialize(connection, parent) <del> super connection <add> def initialize(connection, parent) <add> super connection <ide> <del> @parent = parent <del> @records = [] <del> @finishing = false <del> end <add> @parent = parent <add> @records = [] <add> @finishing = false <add> end <ide> <del> def number <del> if finishing? <del> parent.number <del> else <del> parent.number + 1 <del> end <add> def number <add> if finishing? <add> parent.number <add> else <add> parent.number + 1 <ide> end <add> end <ide> <del> # Database adapters expect that #open_transactions will be decremented <del> # before we've actually executed a COMMIT or ROLLBACK. This is kinda <del> # annoying, but for now we use this @finishing flag to toggle what value <del> # #number should return. <del> def finishing? <del> @finishing <del> end <add> # Database adapters expect that #open_transactions will be decremented <add> # before we've actually executed a COMMIT or ROLLBACK. This is kinda <add> # annoying, but for now we use this @finishing flag to toggle what value <add> # #number should return. <add> def finishing? <add> @finishing <add> end <ide> <del> def begin <del> Savepoint.new(connection, self) <del> end <add> def begin <add> SavepointTransaction.new(connection, self) <add> end <ide> <del> def rollback <del> @finishing = true <del> perform_rollback <del> parent <del> end <add> def rollback <add> @finishing = true <add> perform_rollback <add> parent <add> end <ide> <del> def commit <del> @finishing = true <del> perform_commit <del> parent <del> end <add> def commit <add> @finishing = true <add> perform_commit <add> parent <add> end <ide> <del> def add_record(record) <del> records << record <del> end <add> def add_record(record) <add> records << record <add> end <ide> <del> def rollback_records <del> records.uniq.each do |record| <del> begin <del> record.rolledback!(parent.closed?) <del> rescue => e <del> record.logger.error(e) if record.respond_to?(:logger) && record.logger <del> end <add> def rollback_records <add> records.uniq.each do |record| <add> begin <add> record.rolledback!(parent.closed?) <add> rescue => e <add> record.logger.error(e) if record.respond_to?(:logger) && record.logger <ide> end <ide> end <add> end <ide> <del> def commit_records <del> records.uniq.each do |record| <del> begin <del> record.committed! <del> rescue => e <del> record.logger.error(e) if record.respond_to?(:logger) && record.logger <del> end <add> def commit_records <add> records.uniq.each do |record| <add> begin <add> record.committed! <add> rescue => e <add> record.logger.error(e) if record.respond_to?(:logger) && record.logger <ide> end <ide> end <add> end <ide> <del> def closed? <del> false <del> end <add> def closed? <add> false <add> end <ide> <del> def open? <del> true <del> end <add> def open? <add> true <ide> end <add> end <ide> <del> class Real < Open <del> def initialize(connection, parent) <del> super <del> connection.begin_db_transaction <del> end <add> class RealTransaction < OpenTransaction #:nodoc: <add> def initialize(connection, parent) <add> super <add> connection.begin_db_transaction <add> end <ide> <del> def perform_rollback <del> connection.rollback_db_transaction <del> rollback_records <del> end <add> def perform_rollback <add> connection.rollback_db_transaction <add> rollback_records <add> end <ide> <del> def perform_commit <del> connection.commit_db_transaction <del> commit_records <del> end <add> def perform_commit <add> connection.commit_db_transaction <add> commit_records <ide> end <add> end <ide> <del> class Savepoint < Open <del> def initialize(connection, parent) <del> super <del> connection.create_savepoint <del> end <add> class SavepointTransaction < OpenTransaction #:nodoc: <add> def initialize(connection, parent) <add> super <add> connection.create_savepoint <add> end <ide> <del> def perform_rollback <del> connection.rollback_to_savepoint <del> rollback_records <del> end <add> def perform_rollback <add> connection.rollback_to_savepoint <add> rollback_records <add> end <ide> <del> def perform_commit <del> connection.release_savepoint <del> records.each { |r| parent.add_record(r) } <del> end <add> def perform_commit <add> connection.release_savepoint <add> records.each { |r| parent.add_record(r) } <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> module ConnectionAdapters # :nodoc: <ide> autoload :Quoting <ide> autoload :ConnectionPool <ide> autoload :QueryCache <del> autoload :Transaction <add> end <add> <add> autoload_at 'active_record/connection_adapters/abstract/transaction' do <add> autoload :ClosedTransaction <add> autoload :RealTransaction <add> autoload :SavepointTransaction <ide> end <ide> <ide> # Active Record supports multiple database systems. AbstractAdapter and
3
Python
Python
deprecate close method on memmap arrays
43cddec31f70e212a5a4b8f748895711bc18c0dc
<ide><path>numpy/core/memmap.py <ide> def __new__(subtype, name, dtype=uint8, mode='r+', offset=0, <ide> <ide> def __array_finalize__(self, obj): <ide> self._mmap = None <del> if obj is not None and hasattr(obj, '_mmap'): <add> if hasattr(obj, '_mmap'): <ide> self._mmap = obj._mmap <ide> <ide> def flush(self): <ide> def sync(self): <ide> warnings.warn("Use ``flush``.", DeprecationWarning) <ide> self.flush() <ide> <del> def close(self): <del> """Close the memmap file.""" <add> def _close(self): <add> """Close the memmap file. Only do this when deleting the object.""" <ide> if self.base is self._mmap: <ide> self._mmap.close() <ide> elif self._mmap is not None: <ide> raise ValueError, "Cannot close a memmap that is being used " \ <ide> "by another object." <ide> <add> def close(self): <add> """Close the memmap file. Does nothing.""" <add> warnings.warn("``close`` is deprecated on memmap arrays. Use del", <add> DeprecationWarning) <add> <ide> def __del__(self): <ide> self.flush() <ide> try: <del> self.close() <add> self._close() <ide> except ValueError: <ide> pass
1
Javascript
Javascript
remove history event handler when app is torn down
d996305b4470f80fbb1cbddf54b7d10ffbb6ab47
<ide><path>src/ng/browser.js <ide> function Browser(window, document, $log, $sniffer) { <ide> return callback; <ide> }; <ide> <add> /** <add> * @private <add> * Remove popstate and hashchange handler from window. <add> * <add> * NOTE: this api is intended for use only by $rootScope. <add> */ <add> self.$$applicationDestroyed = function() { <add> jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange); <add> }; <add> <ide> /** <ide> * Checks whether the url has changed outside of Angular. <ide> * Needs to be exported to be able to check for changes that have been done in sync, <ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider() { <ide> this.$broadcast('$destroy'); <ide> this.$$destroyed = true; <ide> <add> if (this === $rootScope) { <add> //Remove handlers attached to window when $rootScope is removed <add> $browser.$$applicationDestroyed(); <add> } <add> <ide> incrementWatchersCount(this, -this.$$watchersCount); <ide> for (var eventName in this.$$listenerCount) { <ide> decrementListenerCount(this, this.$$listenerCount[eventName], eventName); <ide><path>src/ngMock/angular-mocks.js <ide> angular.mock.$Browser = function() { <ide> return listener; <ide> }; <ide> <add> self.$$applicationDestroyed = angular.noop; <ide> self.$$checkUrlChange = angular.noop; <ide> <ide> self.deferredFns = []; <ide><path>test/ng/browserSpecs.js <ide> describe('browser', function() { <ide> }; <ide> } <ide> }); <add> <add> <add> it("should stop calling callbacks when application has been torn down", function() { <add> sniffer.history = true; <add> browser.onUrlChange(callback); <add> fakeWindow.location.href = 'http://server/new'; <add> <add> browser.$$applicationDestroyed(); <add> <add> fakeWindow.fire('popstate'); <add> expect(callback).not.toHaveBeenCalled(); <add> <add> fakeWindow.fire('hashchange'); <add> fakeWindow.setTimeout.flush(); <add> expect(callback).not.toHaveBeenCalled(); <add> }); <add> <ide> }); <ide> <ide> <ide><path>test/ng/rootScopeSpec.js <ide> describe('Scope', function() { <ide> })); <ide> <ide> <add> it('should call $browser.$$applicationDestroyed when destroying rootScope', inject(function($rootScope, $browser) { <add> spyOn($browser, '$$applicationDestroyed'); <add> $rootScope.$destroy(); <add> expect($browser.$$applicationDestroyed).toHaveBeenCalledOnce(); <add> })); <add> <add> <ide> it('should remove first', inject(function($rootScope) { <ide> first.$destroy(); <ide> $rootScope.$digest();
5
Ruby
Ruby
capitalize the first letter of sentence
396bb77199883773c8ce9ef53365a8fc0cac37f8
<ide><path>actionpack/lib/abstract_controller/base.rb <ide> def abstract! <ide> end <ide> <ide> def inherited(klass) # :nodoc: <del> # define the abstract ivar on subclasses so that we don't get <add> # Define the abstract ivar on subclasses so that we don't get <ide> # uninitialized ivar warnings <ide> unless klass.instance_variable_defined?(:@abstract) <ide> klass.instance_variable_set(:@abstract, false)
1
PHP
PHP
use set order for test that failed on travis
ce3aa692b50b4239e32a58a250d4a7c8f0afca21
<ide><path>lib/Cake/Test/Case/Model/ModelReadTest.php <ide> public function testBindUnbind() { <ide> $this->assertTrue($result); <ide> <ide> $result = $TestModel->find('all', array( <del> 'fields' => 'User.id, User.user' <add> 'fields' => 'User.id, User.user', <add> 'order' => array('User.id' => 'ASC'), <ide> )); <ide> $expected = array( <ide> array( <ide> public function testBindUnbind() { <ide> $this->assertTrue($result); <ide> <ide> $result = $TestModel->find('all', array( <del> 'fields' => 'User.id, User.user' <add> 'fields' => 'User.id, User.user', <add> 'order' => array('User.id' => 'ASC'), <ide> )); <ide> <ide> $expected = array( <ide> public function testBindUnbind() { <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = $TestModel->find('all', array( <del> 'fields' => 'User.id, User.user' <add> 'fields' => 'User.id, User.user', <add> 'order' => array('User.id' => 'ASC'), <ide> )); <ide> $expected = array( <ide> array('User' => array('id' => '1', 'user' => 'mariano')), <ide> public function testBindUnbind() { <ide> $this->assertEquals($expected, $result); <ide> <ide> $result = $TestModel->find('all', array( <del> 'fields' => 'User.id, User.user' <add> 'fields' => 'User.id, User.user', <add> 'order' => array('User.id' => 'ASC'), <ide> )); <ide> $expected = array( <ide> array( <ide> public function testBindUnbind() { <ide> $result = $TestModel->unbindModel(array('hasMany' => array('Comment')), false); <ide> $this->assertTrue($result); <ide> <del> $result = $TestModel->find('all', array('fields' => 'User.id, User.user')); <add> $result = $TestModel->find('all', array( <add> 'fields' => 'User.id, User.user', <add> 'order' => array('User.id' => 'ASC'), <add> )); <ide> $expected = array( <ide> array('User' => array('id' => '1', 'user' => 'mariano')), <ide> array('User' => array('id' => '2', 'user' => 'nate')), <ide> public function testBindUnbind() { <ide> ))); <ide> $this->assertTrue($result); <ide> <del> $result = $TestModel->find('all', array('fields' => 'User.id, User.user')); <add> $result = $TestModel->find('all', array( <add> 'fields' => 'User.id, User.user', <add> 'order' => array('User.id' => 'ASC'), <add> )); <ide> $expected = array( <ide> array( <ide> 'User' => array(
1
Text
Text
add translation of advanced node and express (4/4)
ab4a4a0697ba89a5c5ac1c3b5844cb6855aa1839
<ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/announce-new-users.chinese.md <ide> id: 589fc832f9fc0f352b528e78 <ide> title: Announce New Users <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301546 <ide> localeTitle: 宣布新用户 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socketio/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socketio/">GitHub</a>克隆的。许多聊天室能够在用户连接或断开连接时进行通知,然后将其显示给聊天中的所有连接用户。看起来您已经在连接和断开连接上发出事件,您只需修改此事件即可支持此功能。最合乎逻辑的方法是使用事件发送3个数据:连接/断开用户的名称,当前用户计数以及连接或断开连接的名称。 <hr>将事件名称更改为“user”,并且数据传递一个对象,包含字段&#39;name&#39;,&#39;currentUsers&#39;和boolean&#39;connected&#39;(如果是连接则为true,对于断开发送的用户,则为false)。确保对我们有&#39;用户计数&#39;事件的两个点进行更改,并将断开连接设置为对&#39;field&#39;字段发送false,而不是像在connect上发出的事件那样为true。 <code>io.emit(&#39;user&#39;, {name: socket.request.user.name, currentUsers, connected: true});</code>现在,您的客户端将拥有所有必要信息,以便在用户连接或断开连接时正确显示当前用户数和通知!要在客户端处理此事件,我们应该监听“用户”,然后使用jQuery将<code>#num-users</code>的文本更改为“{NUMBER}在线用户”,并附加<code>&lt;li&gt;</code> ,以更新当前用户数<code>&lt;li&gt;</code>使用ID为&#39;messages&#39;的无序列表,其中&#39;{NAME}已{加/左}聊天。&#39;。此实现可能如下所示: <pre> socket.on(&#39;user&#39;,function(data){ <del> $(&#39;#num-users&#39;)。text(data.currentUsers +&#39;users online&#39;); <del> var message = data.name; <del> if(data.connected){ <del> 消息+ =&#39;已加入聊天。&#39;; <del> } else { <del> 消息+ =&#39;离开了聊天。&#39;; <del> } <del> $(&#39;#messages&#39;)。append($(&#39;&lt;li&gt;&#39;)。html(&#39;&lt;b&gt;&#39;+ message +&#39;&lt;\ / b&gt;&#39;)); <del>}); </pre>当您认为自己已经做对时,请提交您的页面。 </section> <add> <add><section id='description'> <add> <add>许多聊天室都有这个功能:所有已连接到服务器的在线用户都会看到有人加入或退出的提醒。我们已经写好了处理连接和断开事件的代码,只要对这个方法稍作修改就可以实现这个功能。在事件中,我们需要发送这三条信息:连接或断开的用户名、当前用户数量、事件类型(即需要知道用户究竟是连接还是断开)。 <add>请将事件名称更改为 <code>'user'</code>,其中应包含如下字段:'name'、'currentUsers'、'connected'(布尔值,连接上即为 <code>true</code>,断开则是 <code>false</code>)。记得要修改之前我们写好的处理 'user count' 的那部分代码,现在我们应在用户连接时传入布尔值 <code>true</code>;在用户断开连接是传入布尔值 <code>false</code>。 <add> <add>```js <add>io.emit('user', { <add> name: socket.request.user.name, <add> currentUsers, <add> connected: true <add>}); <add>``` <add> <add>现在,我们的客户端已经有足够的信息显示现有用户数量和发送用户上下线通知。接下来我们需要在客户端监听 'user' 事件,然后使用 jQuery 把 <code>#num-users</code> 节点的文本内容更新为 '{NUMBER} users online'。同时,我们需要为 <code>&#60;ul&#62;</code> 添加一个 id 为 'messages' 且带有 '{NAME} has {joined/left} the chat.' 文本的<code>&#60;li&#62;</code>。 <add>一种实现方式如下: <add> <add>```js <add>socket.on('user', data => { <add> $('#num-users').text(data.currentUsers + ' users online'); <add> let message = <add> data.name + <add> (data.connected ? ' has joined the chat.' : ' has left the chat.'); <add> $('#messages').append($('<li>').html('<b>' + message + '</b>')); <add>}); <add>``` <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/bf95a0f74b756cf0771cd62c087b8286' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 使用name,currentUsers和connected发出事件“user” <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io.emit.*('|")user('|").*name.*currentUsers.*connected/gi, 'You should have an event emitted named user sending name, currentUsers, and connected'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 客户正确处理和显示事件'用户'中的新数据 <del> testString: "getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.on.*('|\")user('|\")[^]*num-users/gi, 'You should change the text of #num-users within on your client within the \"user\" even listener to show the current users connected'); assert.match(data, /socket.on.*('|\")user('|\")[^]*messages.*li/gi, 'You should append a list item to #messages on your client within the \"user\" event listener to announce a user came or went'); }, xhr => { throw new Error(xhr.statusText); })" <del> <add> - text: <code>'user'</code> 事件应发送包含 name、currentUsers、connected 字段的对象。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => { assert.match(data, /io.emit.*('|")user\1.*name.*currentUsers.*connected/gis, 'You should have an event emitted named user sending name, currentUsers, and connected'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 客户端应处理和显示 <code>'user'</code> 对象中的信息 <add> testString: getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.on.*('|")user\1[^]*num-users/gi, 'You should change the text of "#num-users" within on your client within the "user" event listener to show the current users connected'); assert.match(data, /socket.on.*('|")user\1[^]*messages.*li/gi, 'You should append a list item to "#messages" on your client within the "user" event listener to announce a user came or went'); }, xhr => { throw new Error(xhr.statusText); }) <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/authentication-strategies.chinese.md <ide> id: 5895f70df9fc0f352b528e68 <ide> title: Authentication Strategies <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 认证策略 <add>forumTopicId: 301547 <add>localeTitle: 身份验证策略 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。策略是一种验证用户的方法。您可以使用策略允许用户根据本地保存的信息(如果您首先注册)或从Google或Github等各种提供商进行身份验证。对于这个项目,我们将制定一个本地战略。要查看的策略100的列表,请访问网站护照<a href="http://passportjs.org/">这里</a> 。将<em>passport-local</em>添加为依赖项并将其添加到服务器,如下所示: <code>const LocalStrategy = require(&#39;passport-local&#39;);</code>现在,您必须告诉护照<b>使用</b>实例化的LocalStartegy对象,并定义一些设置。确保这一点以及此时的所有内容都封装在数据库连接中,因为它依赖于它! <pre> passport.use(新的LocalStrategy( <del> function(用户名,密码,已完成){ <del> db.collection(&#39;users&#39;)。findOne({username:username},function(err,user){ <del> console.log(&#39;用户&#39;+用户名+&#39;试图登录。&#39;); <del> if(err){return done(err); } <del> if(!user){return done(null,false); } <del> if(password!== user.password){return done(null,false); } <del> return done(null,user); <del> }); <add><section id='description'> <add> <add>现在,我们需要构建验证用户的策略,策略的选择有很多。比如,如果我们已经让用户在注册时填写了用户信息,那我们就可以基于这些信息验证;或者也可以引入第三方登录,如 Google 或者 Github。为此,你可以参考 <a href='http://passportjs.org/'>Passports 中提供的策略插件</a>。对于这个项目的验证策略,我们会采用自己搭建的方式完成。 <add> <add>首先,我们需要引入 <em>passport-local</em> 作为依赖,然后将它添加到服务器,就像这样:<code>const LocalStrategy = require('passport-local');</code> <add> <add>然后,我们需要让 passport 使用实例化的本地策略对象。请注意,接下来的所有代码都应写在连接数据库的回调中,因为它们的执行都依赖数据库。 <add> <add>```js <add>passport.use(new LocalStrategy( <add> function(username, password, done) { <add> myDataBase.findOne({ username: username }, function (err, user) { <add> console.log('User '+ username +' attempted to log in.'); <add> if (err) { return done(err); } <add> if (!user) { return done(null, false); } <add> if (password !== user.password) { return done(null, false); } <add> return done(null, user); <add> }); <ide> } <del>)); </pre>这是我们尝试在本地验证某人时要采取的过程。首先,它尝试使用输入的用户名在我们的数据库中查找用户,然后检查要匹配的密码,最后如果没有弹出我们检查过的错误,如错误的密码,则返回用户对象,它们是认证。许多策略都是使用不同的设置设置的,一般来说,根据该策略库中的README很容易设置它。一个很好的例子是Github策略,我们不需要担心用户名或密码,因为用户将被发送到Github的auth页面进行身份验证,只要他们登录并同意,然后Github返回他们的个人资料我们用。在下一步中,我们将设置如何实际调用身份验证策略以根据表单数据验证用户!如果您认为自己已经完成了这一点,请提交您的页面。 </section> <add>)); <add>``` <add> <add>这就是我们的用户验证逻辑:首先根据用户输入的用户名在数据库中寻找用户;然后检查密码是否匹配;最后如果没有发生错误,那么就会返回用户对象并通过验证。 <add>我们也可以采用上面链接中提供的验证策略,一般来说,根据该策略仓库中的 README 来进行配置就足够了。一个很好的例子是 Github 策略,在该策略中,我们不需要写用户名或密码的相关验证逻辑,因为用户将被引导到 Github 页面进行验证。只要他们登录并同意,Github 就会返回他们的个人信息供我们使用。 <add>以上就是本次挑战的内容。在下一个挑战中,我们会基于表单数据调用上面写好的验证策略。 <add>完成上述要求后,你可以在下方提交你的页面链接。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Passport-local是一种依赖 <add> - text: 你的项目需要使用 <code>passport-local</code> 作为依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'passport-local', 'Your project should list "passport-local " as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: Passport-local正确需要和设置 <add> - text: 应正确地引入和设置 <code>passport-local</code>。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')passport-local("|')/gi, 'You should have required passport-local'); assert.match(data, /new LocalStrategy/gi, 'You should have told passport to use a new strategy'); assert.match(data, /findOne/gi, 'Your new local strategy should use the findOne query to find a username based on the inputs'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/authentication-with-socket.io.chinese.md <ide> id: 589fc831f9fc0f352b528e77 <ide> title: Authentication with Socket.IO <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301548 <ide> localeTitle: 使用Socket.IO进行身份验证 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socketio/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socketio/">GitHub</a>克隆的。目前,您无法确定谁连接到您的Web套接字。虽然&#39;req.user&#39;对用户对象进行了容器处理,但只有当您的用户与Web服务器进行交互并且使用Web套接字时,您才没有req(请求),因此没有用户数据。解决知道谁连接到您的Web套接字的问题的一种方法是解析和解码包含护照会话的cookie,然后对其进行反序列化以获取用户对象。幸运的是,NPM上有一个包,只是为了将一次复杂的任务变成简单的事情! <hr>将“passport.socketio”添加为依赖项,并将其命名为“passportSocketIo”。现在我们只需要告诉Socket.IO使用它并设置选项。确保在现有套接字代码之前添加它,而不是在现有连接侦听器中添加。对于您的服务器,它应如下所示: <pre> io.use(passportSocketIo.authorize({ <del> cookieParser:cookieParser, <del> key:&#39;express.sid&#39;, <del> secret:process.env.SESSION_SECRET, <del> store:sessionStore <del>})); </pre>您还可以选择将“成功”和“失败”与在客户端尝试连接时身份验证过程完成后调用的函数一起传递。现在可以在套接字对象上以<code>socket.request.user</code>访问用户对象。例如,现在您可以添加以下内容: <code>console.log(&#39;user &#39; + socket.request.user.name + &#39; connected&#39;);</code>它将登录已连接的服务器控制台!当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/a9e69ff91337500d5171e29324e1ff35">在此处</a>查看项目。 </section> <add> <add><section id='description'> <add> <add>目前,我们还无法确定连接到服务器的用户身份。虽然 <code>req.user</code> 包含用户信息,但这个只在用户直接与服务器交互(即不通过 web socket 访问服务器资源)时产生。当我们的用户通过 web socket 与服务器连接时,由于不存在 <code>req</code> 对象,因此我们无法获取用户数据。解决这个问题的方法之一是通过读取和解析请求中包含 passport session 的 cookie,然后反序列化,进而获取用户信息对象。幸运的是,npm 上有可以让这个复杂的流程简单化的库。 <add> <add>添加 <code>passport.socketio</code>、<code>connect-mongo</code>、<code>cookie-parser</code> 作为依赖,把它们分别赋值给 <code>passportSocketIo</code>、<code>MongoStore</code>、<code>cookieParser</code>。同时,我们需要从之前引入的 <code>express-session</code> 中开辟新的内存空间,就像接下来这样: <add> <add>```js <add>const MongoStore = require('connect-mongo')(session); <add>const URI = process.env.MONGO_URI; <add>const store = new MongoStore({ url: URI }); <add>``` <add> <add>现在我们只需要让 Socket.IO 调用它并进行相应的配置即可。请注意,以上这些都必须放在现有的 socket 相关代码之前,而且不能放到连接的监听回调函数里。你的服务器代码应类似于这样: <add> <add>```js <add>io.use( <add> passportSocketIo.authorize({ <add> cookieParser: cookieParser, <add> key: 'express.sid', <add> secret: process.env.SESSION_SECRET, <add> store: store, <add> success: onAuthorizeSuccess, <add> fail: onAuthorizeFail <add> }) <add>); <add>``` <add> <add>记得要把 <code>key</code> 和 <code>store</code> 加到 app 的 <code>session</code> 中间件。这样,SocketIO 才知道该对哪个 session 执行此配置。 <add> <add><hr> <add> <add>接下来,我们可以定义 <code>success</code> 与 <code>fail</code> 的回调函数: <add> <add>```js <add>function onAuthorizeSuccess(data, accept) { <add> console.log('successful connection to socket.io'); <add> <add> accept(null, true); <add>} <add> <add>function onAuthorizeFail(data, message, error, accept) { <add> if (error) throw new Error(message); <add> console.log('failed connection to socket.io:', message); <add> accept(null, false); <add>} <add>``` <add> <add>现在,我们可以通过 socket 对象通过 <code>socket.request.user</code> 访问 <code>user</code> 对象。为此,你可以这样做: <add> <add>```js <add>console.log('user ' + socket.request.user.name + ' connected'); <add>``` <add> <add>这样,我们可以在 console 里看到谁连接到了我们的服务器。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。 <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/1414cc9433044e306dd7fd0caa1c6254' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: passportSocketIo是一个依赖项 <add> - text: 应添加 <code>passport.socketio</code> 作为依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'passport.socketio', 'Your project should list "passport.socketio" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: passportSocketIo是正确需要的 <add> - text: 应添加 <code>cookie-parser</code> 作为依赖。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'cookie-parser', 'Your project should list "cookie-parser" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应正确引入 passportSocketIo。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => { assert.match(data, /require\((['"])passport\.socketio\1\)/gi, 'You should correctly require and instantiate "passport.socketio"');}, xhr => { throw new Error(xhr.statusText); }) <del> - text: passportSocketIo已正确设置 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io\.use\(.+\.authorize\(/gi, 'You should register "passport.socketio" as socket.io middleware and provide it correct options'); }, xhr => { throw new Error(xhr.statusText); }) <del> <add> - text: 应正确配置 passportSocketIo。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io\.use\(\s*\w+\.authorize\(/, 'You should register "passport.socketio" as socket.io middleware and provide it correct options'); }, xhr => { throw new Error(xhr.statusText); }) <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/clean-up-your-project-with-modules.chinese.md <ide> id: 589690e6f9fc0f352b528e6e <ide> title: Clean Up Your Project with Modules <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301549 <ide> localeTitle: 使用模块清理项目 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。现在你拥有的一切都在你的server.js文件中。这可能导致难以管理不易扩展的代码。创建2个新文件:Routes.js和Auth.js两者都应该从以下代码开始: <pre> module.exports = function(app,db){ <del><p> } </p></pre>现在位于服务器文件的顶部,需要这样的文件: <code>const routes = require(&#39;./routes.js&#39;);</code>在您与数据库建立成功连接之后,实例化它们中的每一个如下: <code>routes(app, db)</code>最后,获取服务器中的所有路由并将它们粘贴到新文件中并从服务器文件中删除它们。也可以使用ensureAuthenticated,因为我们专门为路由创建了中间件功能。您现在必须正确添加所使用的依赖项,例如<code>const passport = require(&#39;passport&#39;);</code> ,在routes.js文件中导出行的最上方。继续添加它们直到不再存在错误,并且您的服务器文件不再有任何路由!现在在auth.js文件中执行相同的操作,其中包含与身份验证相关的所有内容,例如序列化和本地策略的设置,并从服务器文件中删除它们。确保添加依赖项并在同一位置调用服务器中的<code>auth(app,db)</code> 。确保<code>routes(app, db)</code> <code>auth(app, db)</code>之前有<code>auth(app, db)</code> <code>routes(app, db)</code>因为我们的注册路由取决于发起的护照!恭喜 - 您已经处于Advanced Node和Express的这一部分的末尾,并且有一些漂亮的代码可供展示!当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://glitch.com/#!/project/delicious-herring">在此处查看</a>已完成项目的示例。 <p></p></section> <add><section id='description'> <add> <add>目前,我们把所有的代码都放到了 server.js 文件里,这会导致代码难以维护,且扩展性差。 <add>现在让我们来创建两个新文件:<code>routes.js</code> 和 <code>auth.js</code> <add>在每个文件的开头,我们都需要写上这段代码: <add> <add>```js <add>module.exports = function (app, myDataBase) { <add> <add>} <add>``` <add> <add>然后,在 server.js 文件的开头,我们需要像这样引入文件:<code>const routes = require('./routes.js');</code> <add>在成功连接数据库之后,我们需要像这样进行实例化:<code>routes(app, myDataBase)</code>。 <add>最后,我们需要把所有路由相关的代码从 server.js 移动到新文件 routes.js。不要忘了,<code>ensureAuthenticated</code> 方法的定义也要移动到新文件中,这个是我们在之前的挑战中,为在路由中判断用户是否已登录创建的函数。然后,我们还需要在 routes.js 文件开头添加所需要的依赖,如:<code>const passport = require('passport');</code>。 <add> <add>如果在这些步骤后没有报错,那么恭喜你,你已成功地从 server.js 文件中分离出了路由文件(**尽管 catch 那部分还是包含了路由的逻辑**)。 <add> <add>现在,我们来把 server.js 中与验证相关的代码分离到 auth.js 中,例如序列化,设置验证策略等。请正确添加依赖,并在 server.js 中调用<code>auth(app,myDataBase)</code>。另外,由于我们的注册路由依赖 passport,所以我们需要先调用<code>auth(app, myDataBase)</code>,再调用<code>routes(app, myDataBase)</code>。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/2d06ac5c7d850d8cf073d2c2c794cc92' target='_blank'>这里</a> 的答案。 <add> <add>Submit your page when you think you've got it right. If you're running into errors, you can check out an example of the completed project <a href='https://gist.github.com/camperbot/2d06ac5c7d850d8cf073d2c2c794cc92' target='_blank'>here</a>. <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 存在的模块 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require\s*\(('|")\.\/routes(\.js)?\1\)/gi, 'You should have required your new files'); assert.match(data, /mongo.connect[^]*routes/gi, 'Your new modules should be called after your connection to the database'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应正确引入新文件。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require\s*\(('|")\.\/routes(\.js)?\1\)/gi, 'You should have required your new files'); assert.match(data, /client.db[^]*routes/gi, 'Your new modules should be called after your connection to the database'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/communicate-by-emitting.chinese.md <ide> id: 589fc831f9fc0f352b528e75 <ide> title: Communicate by Emitting <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 通过发射进行沟通 <add>forumTopicId: 301550 <add>localeTitle: 通过 Emitting 通信 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socketio/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socketio/">GitHub</a>克隆的。 <dfn>Emit</dfn>是您将使用的最常见的沟通方式。当您从服务器向&#39;io&#39;发送内容时,会将事件的名称和数据发送到所有连接的套接字。这个概念的一个很好的例子就是每次新用户连接时都会发出连接用户的当前数量! <hr>首先添加一个变量,以便在您当前正在侦听连接之前跟踪用户。 <code>var currentUsers = 0;</code>现在当有人连接时,你应该在发出计数之前递增计数,这样你就可以在连接监听器中添加增量器。 <code>++currentUsers;</code>最后,在递增计数后,您应该发出事件(仍在连接侦听器中)。该事件应命名为“用户计数”,数据应该只是&#39;currentUsers&#39;。 <code>io.emit(&#39;user count&#39;, currentUsers);</code> <hr>现在,您可以为客户实施一种方式来监听此事件!与在服务器上侦听连接类似,您将使用<em>on</em>关键字。 <pre> socket.on(&#39;user count&#39;,function(data){ <del> 的console.log(数据); <del>}); </pre>现在尝试加载您的应用并进行身份验证,您应该在客户端控制台中看到“1”代表当前用户数!尝试加载更多客户端并进行身份验证以查看数量是否上升。当您认为自己已经做对时,请提交您的页面。 </section> <add> <add><section id='description'> <add> <add><dfn>Emit</dfn> 是你会用到的,最常见的通信方式。如果我们从服务器发送信息给 'io',就相当于把事件的名称和数据发送给了所有处于连接状态的 socket。我们可以利用这个特性实现这样的功能:只要有新用户连接到服务器,我们就可以把目前连接的总用户数发给所有已连接的用户,这样所有用户随时都可以看到实时的在线人数。 <add> <add>首先,我们需要在监听连接的地方之前添加一个用于追踪用户数的变量: <add> <add>```js <add>let currentUsers = 0; <add>``` <add> <add>然后,只要有人连接到服务器,我们需要在发出用户数量之前先给这个变量加 1: <add> <add>```js <add>++currentUsers; <add>``` <add> <add>最后,在监听连接的地方发出(emit)该事件即可。这个事件应命名为 'user count',且数据应该为 <code>currentUsers</code>: <add> <add>```js <add>io.emit('user count', currentUsers); <add>``` <add> <add>接下来,我们还需要让客户端监听从服务端发出的事件。为此,我们还是需要用到 <em>on</em> 这个方法: <add> <add>```js <add>socket.on('user count', function(data) { <add> console.log(data); <add>}); <add>``` <add> <add>现在你可以尝试启动你的 app 并登录,你会看到在客户端的控制台打印出了 1,这就表示目前连接到服务器的用户数为 1。你可以试着通过打开多个 app 来验证数量是否会增加。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/28ef7f1078f56eb48c7b1aeea35ba1f5' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: currentUsers已定义 <add> - text: 应定义 currentUsers。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => {assert.match(data, /currentUsers/gi, 'You should have variable currentUsers defined');}, xhr => { throw new Error(xhr.statusText); }) <del> - text: 服务器在每个新连接上发出当前用户计数 <add> - text: 服务器应在有新的连接时 emit 当前用户数量。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io.emit.*('|")user count('|").*currentUsers/gi, 'You should emit "user count" with data currentUsers'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 您的客户正在侦听“用户计数”事件 <add> - text: 客户端应监听 'user count' 事件。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.on.*('|")user count('|")/gi, 'Your client should be connection to server with the connection defined as socket'); }, xhr => { throw new Error(xhr.statusText); }) <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/create-new-middleware.chinese.md <ide> id: 5895f70df9fc0f352b528e6a <ide> title: Create New Middleware <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301551 <ide> localeTitle: 创建新的中间件 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。同样,任何用户都可以通过输入网址来查看/配置他们是否通过身份验证。我们希望通过在呈现配置文件页面之前检查用户是否首先进行身份验证来防止这种情况。这是何时创建中间件的完美示例。这里的挑战是创建中间件功能<code>ensureAuthenticated(req, res, next)</code> ,它将检查用户是否通过调用护照进行身份验证isAuthenticated对<em>请求</em>进行检查,然后检查<em>req.user</em>是否定义。如果是,那么应该调用<em>next()</em> ,否则我们只需通过重定向到我们的主页来回复请求即可登录。该中间件的实现是: <pre> function ensureAuthenticated(req,res,next){ <del> if(req.isAuthenticated()){ <del> return next(); <add><section id='description'> <add> <add>无论是否登录,或者哪怕用户试图访问其他页面,目前都会跳转到 <code>/profile</code>。为了解决这个问题,我们需要在 profile 页面渲染之前进行用户验证,创建中间件就可以实现这个功能。 <add> <add>这个挑战的目标是创建<code>ensureAuthenticated(req, res, next)</code>中间件方法,通过在 <em>request</em> 上调用 passports 的<code>isAuthenticated</code> 方法,我们可以检查 <em>req.user</em> 是否定义,从而确定用户是否通过认证。如果用户已通过验证,就会调用 <em>next()</em>,否则我们应重定向到主页并让用户登录。该中间件的实现如下: <add> <add>```js <add>function ensureAuthenticated(req, res, next) { <add> if (req.isAuthenticated()) { <add> return next(); <ide> } <del> res.redirect( &#39;/&#39;); <del>}; </pre>现在,在包含呈现页面的函数的get请求的参数之前,将<em>ensureAuthenticated</em>作为中间件添加到配置文件页面的请求中。 <pre> app.route( &#39;/简档&#39;) <del> .get(ensureAuthenticated,(req,res)=&gt; { <del> res.render(process.cwd()+&#39;/ views / pug / profile&#39;); <del> }); </pre>当您认为自己已经做对时,请提交您的页面。 </section> <add> res.redirect('/'); <add>}; <add>``` <add> <add>然后,我们需要把 <em>ensureAuthenticated</em> 中间件添加到处理请求的回调之前: <add> <add>```js <add>app <add> .route('/profile') <add> .get(ensureAuthenticated, (req,res) => { <add> res.render(process.cwd() + '/views/pug/profile'); <add> }); <add>``` <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/ae49b8778cab87e93284a91343da0959' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 中间件确保应该在我们的/配置文件路由上实现 <add> - text: <code>ensureAuthenticated</code> 中间件应添加到 <code>/profile</code>路由中。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /ensureAuthenticated[^]*req.isAuthenticated/gi, 'Your ensureAuthenticated middleware should be defined and utilize the req.isAuthenticated function'); assert.match(data, /profile[^]*get[^]*ensureAuthenticated/gi, 'Your ensureAuthenticated middleware should be attached to the /profile route'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 正确的Get请求/配置文件重定向到/因为我们未经过身份验证 <add> - text: 如果没有通过验证,对 /profile 的 GET 请求应重定向到 / <ide> testString: getUserInput => $.get(getUserInput('url')+ '/profile') .then(data => { assert.match(data, /Home page/gi, 'An attempt to go to the profile at this point should redirect to the homepage since we are not logged in'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/handle-a-disconnect.chinese.md <ide> id: 589fc831f9fc0f352b528e76 <ide> title: Handle a Disconnect <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 处理断开连接 <add>forumTopicId: 301552 <add>localeTitle: 处理连接断开 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socketio/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socketio/">GitHub</a>克隆的。您可能会注意到,到目前为止,您只增加了用户数。处理用户断开连接就像处理初始连接一样简单,除了区别在于你必须在每个套接字上监听它而不是在整个服务器上监听它。 <hr>为此,请在现有的连接侦听器中添加一个侦听器,该侦听器在没有数据传递的情况下侦听套接字上的“disconnect”。您只需登录用户已断开连接的控制台即可测试此功能。 <code>socket.on(&#39;disconnect&#39;, () =&gt; { /*anything you want to do on disconnect*/ });</code>要确保客户端持续获得当前用户的更新计数,您应该在断开连接时将currentUsers减少1,然后使用更新的计数发出&#39;user count&#39;事件! <strong>注意</strong> <br>就像&#39;disconnect&#39;一样,套接字可以向服务器发出的所有其他事件应该在我们定义了&#39;socket&#39;的连接监听器中处理。当您认为自己已经做对时,请提交您的页面。 </section> <add> <add><section id='description'> <add> <add>你也许注意到,目前为止我们只处理用户数量的增加,没有处理减少。事实上,处理用户断开连接也很简单。区别在于,新连接的监听是发生在整个服务器上,但连接断开的监听是发生在每个 socket 上。 <add> <add>为此,我们需要在目前的监听回调里面监听 socket 断开连接的事件。在断开连接的回调函数中,我们可以不传任何参数,但你可以在这里添加连接断开的测试代码: <add> <add>```js <add>socket.on('disconnect', () => { <add> /*anything you want to do on disconnect*/ <add>}); <add>``` <add> <add>为确保客户端可以看到实时的用户数量,显然,我们应该在用户断开时让 currentUsers 减 1,然后发送 'user count' 事件,并使用修改后的用户数量。 <add> <add><strong>注意:</strong>和 <code>'disconnect'</code> 类似,所有 socket 可以发送到服务器的事件,我们都应该在有 'socket' 定义的连接监听器里处理。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 服务器处理与套接字的事件断开连接 <add> - text: 服务器应处理断开 socket 连接的事件。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /socket.on.*('|")disconnect('|")/gi, ''); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 您的客户正在侦听“用户计数”事件 <add> - text: 客户端应监听 'user count' 事件。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.on.*('|")user count('|")/gi, 'Your client should be connection to server with the connection defined as socket'); }, xhr => { throw new Error(xhr.statusText); }) <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/hashing-your-passwords.chinese.md <ide> id: 58a25c98f9fc0f352b528e7f <ide> title: Hashing Your Passwords <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301553 <ide> localeTitle: 哈希密码 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。回到信息安全部分,您​​可能还记得存储明文密码<em>永远不会</em>好。现在是时候实施BCrypt来解决这个问题了。 <hr>将BCrypt添加为依赖项并在服务器中将其需要。您需要在两个关键区域处理散列:您在哪里处理注册/保存新帐户以及在登录时检查密码是否正确。目前在我们的注册路线上,您将用户的密码插入数据库,如下所示: <code>password: req.body.password</code> 。实现保存哈希的一种简单方法是在数据库逻辑<code>var hash = bcrypt.hashSync(req.body.password, 12);</code>之前添加以下内容<code>var hash = bcrypt.hashSync(req.body.password, 12);</code>并使用<code>password: hash</code>替换数据库保存中的<code>req.body.password</code> 。最后在我们的身份验证策略中,我们在完成流程之前在代码中检查以下内容: <code>if (password !== user.password) { return done(null, false); }</code> 。完成之前的更改后,现在<code>user.password</code>是一个哈希。在更改现有代码之前,请注意语句如何检查密码是否不相等,然后返回未经过身份验证的密码。考虑到这一点,您的代码可能如下所示,以正确检查针对哈希输入的密码: <code>if (!bcrypt.compareSync(password, user.password)) { return done(null, false); }</code>这是所有需要实现的最重要的安全功能之一,当你有来存储密码!当您认为自己已经做对时,请提交您的页面。 </section> <add><section id='description'> <add> <add>回过头来看信息安全,你也许记得在数据库中存储明文密码是<em>绝对</em>禁止的。现在,我们需要引入 BCrypt 来解决这个问题。 <add> <add>添加 BCrypt 作为依赖,并通过<code>require</code>添加到服务器代码中。你需要在两个步骤中使用哈希运算:注册和保存新账户,以及登录时检查密码是否正确。 <add> <add>目前处理注册的路由中,我们是这样把密码添加到数据库的:<code>password: req.body.password</code>。我们可以通过这段代码创建哈希值:<code>var hash = bcrypt.hashSync(req.body.password, 12);</code>,然后就可以把<code>passsword: req.body.password</code>替换为<code>password: hash</code>。 <add> <add>最后,在验证逻辑中,我们已经有这样一段代码执行检查:<code>if (password !== user.password) { return done(null, false); }</code>。但我们现在存储的密码<code>user.password</code>已经是哈希值了。由于目前的检测机制是密码不匹配时就返回未认证,因此修改后,用于比对用户密码哈希值的代码应该是这样: <add> <add>```js <add>if (!bcrypt.compareSync(password, user.password)) { <add> return done(null, false); <add>} <add>``` <add> <add>当你需要存储密码时,这样做可以有效地提升网站的安全性。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/dc16cca09daea4d4151a9c36a1fab564' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: BCrypt是一种依赖 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'bcrypt', 'Your project should list "bcrypt" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: BCrypt正确需要并实施 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')bcrypt("|')/gi, 'You should have required bcrypt'); assert.match(data, /bcrypt.hashSync/gi, 'You should use hash the password in the registration'); assert.match(data, /bcrypt.compareSync/gi, 'You should compare the password to the hash in your strategy'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应存在 BCrypt 依赖。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'bcrypt', 'Your project should list "bcrypt" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: BCrypt 应正确地引入和调用。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')bcrypt\1/gi, 'You should have required bcrypt'); assert.match(data, /bcrypt.hashSync/gi, 'You should use hash the password in the registration'); assert.match(data, /bcrypt.compareSync/gi, 'You should compare the password to the hash in your strategy'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/how-to-put-a-profile-together.chinese.md <ide> id: 5895f70ef9fc0f352b528e6b <ide> title: How to Put a Profile Together <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 如何将配置文件放在一起 <add>forumTopicId: 301554 <add>localeTitle: 如何将 Profile 放在一起 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。现在我们可以确保访问<em>/ profile</em>的用户已经过身份验证,我们可以使用页面上“req.user”中包含的信息!继续将包含变量<em>username</em> equaling&#39;req.user.username&#39;的对象传递到配置文件视图的render方法中。然后转到你的&#39;profile.pug&#39;视图并添加第<code>h2.center#welcome Welcome, #{username}!</code>行<code>h2.center#welcome Welcome, #{username}!</code>使用“center”类创建h2元素,并使用包含文本“Welcome”和用户名的id“welcome”创建!同样在配置文件中,添加指向<em>/ logout</em>的链接。该路由将托管用于取消身份验证用户的逻辑。 <code>a(href=&#39;/logout&#39;) Logout</code>当您认为自己正确时,请提交您的页面。 </section> <add><section id='description'> <add> <add>现在,只有通过验证的用户才能进入 <em>/profile</em> 页面,这样我们就可以在页面上使用 'req.user' 里的信息了。 <add> <add>请在变量中包含 <em>username</em> 键,值为 'req.user.username',并通过 render 方法传给 profile 页面。然后在 'profile.pug' 页面,添加这行 <code>h2.center#welcome Welcome, #{username}!</code> 代码来创建 class 为 <code>center</code>、id 为 <code>welcome</code> 且文本内容为 'Welcome, ' 后加用户名的 h2 元素。 <add> <add>以及,请在 profile 里添加 <em>/logout</em> 链接,后续会用于处理用户退出登录的逻辑:<code>a(href='/logout') Logout</code> <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/136b3ad611cc80b41cab6f74bb460f6a' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 正确地将Pug渲染变量添加到/ profile <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /\/views\/pug\/profile[^]*username:( |)req.user.username/gi, 'You should be passing the variable username with req.user.username into the render function of the profile page'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应在 Pug render 中给 /profile 传一个变量。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /username:( |)req.user.username/gi, 'You should be passing the variable username with req.user.username into the render function of the profile page'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/how-to-use-passport-strategies.chinese.md <ide> id: 5895f70df9fc0f352b528e69 <ide> title: How to Use Passport Strategies <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 如何使用Passport策略 <add>forumTopicId: 301555 <add>localeTitle: 如何使用 Passport 策略 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。在提供的index.pug文件中,实际上有一个登录表单。它之前已被隐藏,因为内联javascript <code>if showLogin</code>的形式缩进后。在showLogin作为变量从未定义之前,它从未呈现包含该表单的代码块。继续在该页面的res.render上向对象<code>showLogin: true</code>添加一个新变量。刷新页面时,您应该看到表单!此表单设置为<b>POST</b> on <em>/ login,</em>因此我们应该设置此接受POST并验证用户身份。对于此挑战,您应添加路由/登录以接受POST请求。要在此路由上进行身份验证,您需要添加中间件才能发送响应。这是通过在您的<code>function(req,res)</code>之前使用中间件传递另一个参数来完成的!要使用的中间件是<code>passport.authenticate(&#39;local&#39;)</code> 。 <em>passport.authenticate</em>也可以将一些选项作为参数,例如: <code>{ failureRedirect: &#39;/&#39; }</code>这非常有用,所以一定要添加它。作为使用中间件后的响应(只有在身份验证中间件通过时才会调用)应该是将用户重定向到<em>/ profile,</em>并且该路由应该呈现视图&#39;profile.pug&#39;。如果身份验证成功,则用户对象将保存在<em>req.user中</em> 。现在,如果您在表单中输入用户名和密码,它应该重定向到主页<em>/</em>并且在服务器的控制台中应该是&#39;用户{USERNAME}尝试登录&#39;。因为我们目前无法登录未注册的用户。当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/8a335d1a68ed9170da02bb9d8f5b71d5">在这里查看</a>到目前为止完成的项目。 </section> <add><section id='description'> <add> <add>在提供的 index.pug 文件里有一个登录表单。因为这个表单中存在行内 JavaScript 代码 <code>if showLogin</code>,因此它是隐藏的。因为 showLogin 未定义,所以表单不会渲染。如果在该页面的 <code>res.render()</code> 里添加一个包含 <code>showLogin: true</code> 的对象,你就可以在刷新页面后看到表单。当你点击 login 时,表单会向服务器的 <em>/login</code> 发送 POST 请求,此时服务器端就可以接受 POST 请求信息并进行用户验证。 <add> <add>在这个挑战中,你需要为 POST 请求添加路由<code>/login</code>。为了用这个路由进行验证,你需要添加一个中间件,中间件应作为参数添加到用于处理请求的回调函数 <code>function(req,res)</code> 之前。对于 passport 的验证中间件,应这样调用:<code>passport.authenticate('local')</code>。 <add> <add><em>passport.authenticate</em> 也接收选项作为参数,这些选项用于设置验证,例如<code>{ failureRedirect: '/' }</code>就很有用,请记得添加到你的代码中。如果中间件验证通过,我们就应该提供相应的后续处理。在这个挑战中,我们需要让用户重定到 <em>/profile</em>,这样 <code>profile.pug</code> 页面就会渲染。 <add> <add>如果验证通过,用户对象将会储存到 <em>req.user</em> 中。 <add> <add>这时,如果你在表单里输入了用户名和密码,路由将会重定向到主页 <em>/</em>,在服务端将会打印 'User {USERNAME} attempted to log in.',由于现在我们还没有实现注册功能,因此所有登录尝试都会失败。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/7ad011ac54612ad53188b500c5e99cb9' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 所有步骤都在server.js中正确实现 <add> - text: server.js 中应正确执行所有步骤。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /showLogin:( |)true/gi, 'You should be passing the variable "showLogin" as true to your render function for the homepage'); assert.match(data, /failureRedirect:( |)('|")\/('|")/gi, 'Your code should include a failureRedirect to the "/" route'); assert.match(data, /login[^]*post[^]*local/gi, 'You should have a route for login which accepts a POST and passport.authenticates local'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 对/ login的POST请求正确重定向到/ <add> - text: 到 /login 的 POST 请求应重定向到 / <ide> testString: getUserInput => $.post(getUserInput('url')+ '/login') .then(data => { assert.match(data, /Looks like this page is being rendered from Pug into HTML!/gi, 'A login attempt at this point should redirect to the homepage since we do not have any registered users'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/implement-the-serialization-of-a-passport-user.chinese.md <ide> id: 5895f70cf9fc0f352b528e67 <ide> title: Implement the Serialization of a Passport User <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 实现Passport用户的序列化 <add>forumTopicId: 301556 <add>localeTitle: 实现 Passport 用户的序列化 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。现在我们没有加载实际的用户对象,因为我们还没有设置我们的数据库。这可以通过许多不同的方式完成,但是对于我们的项目,当我们启动服务器并在应用程序的整个生命周期中保持持久连接时,我们将连接到数据库。为此,请将MongoDB添加为依赖项,并在服务器中将其需要。 ( <code>const mongo = require(&#39;mongodb&#39;).MongoClient;</code> )现在我们想要连接到我们的数据库,然后开始侦听请求。这样做的目的是在连接数据库之前或者出现数据库错误时不允许请求。要实现此目的,您需要在以下内容中包含序列化和应用程序侦听器: <pre> mongo.connect(process.env.DATABASE,(err,db)=&gt; { <del> if(错误){ <del> console.log(&#39;数据库错误:&#39;+错误); <del> } else { <del> console.log(&#39;成功的数据库连接&#39;); <del><pre> <code> //serialization and app.listen</code> </pre> <del><p> }}); </p></pre>您现在可以在deserializeUser中取消注释该块并删除您的<code>done(null, null)</code> 。确保将.env文件中的<em>DATABASE</em>设置为数据库的连接字符串(例如: <code>DATABASE=mongodb://admin:pass@mlab.com:12345/my-project</code> )。您可以在<a href="https://mlab.com/welcome/">mLab</a>上设置免费数据库。恭喜 - 您已完成序列化设置!当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/e192e809a1d27cb80dc2c6d3467b7477">在这里查看</a>到目前为止完成的项目。 <p></p></section> <add> <add><section id='description'> <add> <add>截至目前,我们还没有配置完数据库,因此还无法加载用户数据。实现这个的方式很多,但对于我们的项目,一旦服务器启动,那么只要有 app 实例在运行,数据库就应一直处于连接状态。 <add> <add>为此,你需要在环境变量 <code>MONGO_URI</code> 中添加你的数据库地址(比如:<code>mongodb+srv://:@cluster0-jvwxi.mongodb.net/?retryWrites=true&w=majority</code>),我们会在 <em>connection.js</em> 中调用它。 <add> <add>_你可以在 <a href='https://www.mongodb.com/cloud/atlas' target='_blank'>MongoDB Atlas</a> 创建一个免费的数据库。_ <add> <add>在连接数据库之后,我们才能让服务器开始监听请求,这样做可以保证服务器在数据库连接前或数据库发生错误时不接受任何请求。为此,我们需要这样写: <add> <add>```js <add>myDB(async client => { <add> const myDataBase = await client.db('database').collection('users'); <add> <add> // Be sure to change the title <add> app.route('/').get((req, res) => { <add> //Change the response to render the Pug template <add> res.render('pug', { <add> title: 'Connected to Database', <add> message: 'Please login' <add> }); <add> }); <add> <add> // Serialization and deserialization here... <add> <add> // Be sure to add this... <add>}).catch(e => { <add> app.route('/').get((req, res) => { <add> res.render('pug', { title: e, message: 'Unable to login' }); <add> }); <add>}); <add>// app.listen out here... <add>``` <add> <add>记得要取消 deserializeUser 中 <code>myDataBase</code> 的注释,并把 <code>doc</code> 添加到 <code>done(null, null)</code>。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/175f2f585a2d8034044c7e8857d5add7' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 存在数据库连接 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /mongo.connect/gi, 'You should have created a connection to your database'); assert.match(data, /mongo.connect[^]*app.listen[^]*}[^]*}/gi, 'You should have your app.listen nested at within your database connection at the bottom'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 反序列化现在正确使用DB并且擦除了<code>done(null, null)</code> <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.notMatch(data, /null,( |)null/gi, 'The callback in deserializeUser of (null, null) should be completely removed for the db block uncommented out'); }, xhr => { throw new Error(xhr.statusText); }) <del> <add> - text: 应存在数据库连接。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/') .then(data => { assert.match(data, /Connected to Database/gi, 'You successfully connected to the database!'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 反序列化应正确使用,且应正确调用 <code>done(null, null)</code>。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /null,\s*doc/gi, 'The callback in deserializeUser of (null, null) should be altered to (null, doc)'); }, xhr => { throw new Error(xhr.statusText); }) <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/implementation-of-social-authentication-ii.chinese.md <ide> id: 589a69f5f9fc0f352b528e71 <ide> title: Implementation of Social Authentication II <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 社会认证的实施II <add>forumTopicId: 301557 <add>localeTitle: 实现社交账号登陆 (2) <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socialauth/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socialauth/">GitHub</a>克隆的。设置Github身份验证的最后一部分是创建策略本身。为此,您需要将&#39;passport-github&#39;的依赖项添加到项目中,并将其作为GithubStrategy,例如<code>const GitHubStrategy = require(&#39;passport-github&#39;).Strategy;</code> 。要设置Github策略,你必须告诉<b>护照</b> <b>使用</b>实例化的<b>GithubStrategy</b> ,它接受2个参数:一个对象(包含<em>clientID</em> , <em>clientSecret</em>和<em>callbackURL</em> )和一个在成功验证用户时要调用的函数,我们将确定如果用户是新用户以及最初要保存在用户数据库对象中的字段。这在许多策略中很常见,但有些可能需要更多信息,如特定策略的github README所述;例如,Google也需要一个<em>范围</em>来确定您的请求所返回的信息类型,并要求用户批准此类访问。我们正在实施的当前策略<a>在此处</a>列出<a>了</a>它的用法,但我们将在freeCodeCamp上完成所有这些工作!以下是您的新战略应该如何看待这一点: <pre> passport.use(new GitHubStrategy({ <del> clientID:process.env.GITHUB_CLIENT_ID, <del> clientSecret:process.env.GITHUB_CLIENT_SECRET, <del> callbackURL:/ * INSERT CALLBACK URL在这里输入GITHUB * / <del> }, <del> function(accessToken,refreshToken,profile,cb){ <del> 的console.log(配置文件); <del> //这里的数据库逻辑带有包含我们用户对象的回调 <add><section id='description'> <add> <add>设置 GitHub 验证的最后一步是创建策略本身。为此,你需要在 <code>auth.js</code> 中<code>require</code>'passport-github',且实例化为 GithubStrategy:<code>const GithubStrategy = require('passport-github').Strategy;</code>。别忘了在 <code>dotenv</code> 中修改环境变量。 <add> <add>为了设置 GitHub 策略,我们需要在 <b>passport</b> 中使用实例化的 <b>GithubStrategy</b>,它可以接收两个参数:一个对象(包括 <em>clientID</em>, <em>clientSecret</em> 和 <em>callbackURL</em>),以及一个回调函数。在这个回调函数中,我们要处理验证成功时,判断用户是否已经在数据库中存在的逻辑,还有如果数据库中不存在,把用户数据添加到数据库的代码。这种处理方式适用于绝大部分第三方验证策略,但有些策略会需要我们提供更多的信息,详情请参考相关策略的 README。例如,Google 的验证策略会要求你提供一个 <em>scope</em>,用于标示用户成功登录后,你需要从返回的对象中获取那些信息。以及,这也需要经过用户同意,你才可以获取到。你可以在 <a href='https://github.com/jaredhanson/passport-github/' target='_blank'>这里</a> 了解当前我们使用的验证策略的用法,不过我们也会在这里进行详细讲解。 <add> <add>你的新策略应该这样去实现: <add> <add>```js <add>passport.use(new GitHubStrategy({ <add> clientID: process.env.GITHUB_CLIENT_ID, <add> clientSecret: process.env.GITHUB_CLIENT_SECRET, <add> callbackURL: /*INSERT CALLBACK URL ENTERED INTO GITHUB HERE*/ <add>}, <add> function(accessToken, refreshToken, profile, cb) { <add> console.log(profile); <add> //Database logic here with callback containing our user object <ide> } <del>)); </pre>您的身份验证还不会成功,并且实际上会抛出错误,没有数据库逻辑和回调,但如果您尝试它,它应该将您的Github配置文件记录到您的控制台!当您认为自己已经做对时,请提交您的页面。 </section> <add>)); <add>``` <add> <add>目前,你的验证部分不会成功。由于没有数据库的逻辑和回调函数,你的代码目前还会报错。但如果你试一试,就可以在右边的控制台里看到输出了你的 GitHub 的个人信息。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/ff3a1166684c1b184709ac0bee30dee6' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 依赖性增加了 <add> - text: 应正确添加依赖 passport-github。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'passport-github', 'Your project should list "passport-github" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 需要依赖性 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')passport-github("|')/gi, 'You should have required passport-github'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 到目前为止,Github策略设置正确 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /passport.use.*new GitHubStrategy/gi, 'Passport should use a new GitHubStrategy'); assert.match(data, /callbackURL:( |)("|').*("|')/gi, 'You should have a callbackURL'); assert.match(data, /process.env.GITHUB_CLIENT_SECRET/g, 'You should use process.env.GITHUB_CLIENT_SECRET'); assert.match(data, /process.env.GITHUB_CLIENT_ID/g, 'You should use process.env.GITHUB_CLIENT_ID'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应正确引入依赖 passport-github。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/auth.js') .then(data => { assert.match(data, /require.*("|')passport-github("|')/gi, 'You should have required passport-github'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 到目前为止,Github 策略应正确设置。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/auth.js') .then(data => { assert.match(data, /passport\.use.*new GitHubStrategy/gi, 'Passport should use a new GitHubStrategy'); assert.match(data, /callbackURL:\s*("|').*("|')/gi, 'You should have a callbackURL'); assert.match(data, /process.env.GITHUB_CLIENT_SECRET/g, 'You should use process.env.GITHUB_CLIENT_SECRET'); assert.match(data, /process.env.GITHUB_CLIENT_ID/g, 'You should use process.env.GITHUB_CLIENT_ID'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/implementation-of-social-authentication-iii.chinese.md <ide> id: 589a8eb3f9fc0f352b528e72 <ide> title: Implementation of Social Authentication III <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 社会认证的实施III <add>forumTopicId: 301558 <add>localeTitle: 实现社交账号登陆 (3) <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socialauth/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socialauth/">GitHub</a>克隆的。策略的最后一部分是处理从Github返回的配置文件。我们需要加载用户数据库对象(如果存在)或创建一个(如果不存在)并填充配置文件中的字段,然后返回用户的对象。 Github在每个配置文件中为我们提供了一个唯一的<em>ID</em> ,我们可以使用它来搜索(已经实现)用户序列化。下面是您可以在项目中使用的示例实现 - 它位于作为新策略的第二个参数的函数内,就在<code>console.log(profile);</code>目前是: <pre> db.collection( &#39;socialusers&#39;)。findAndModify( <del> {id:profile.id}, <del> {}, <del> {$ setOnInsert:{ <del> id:profile.id, <del> name:profile.displayName || &#39;John Doe&#39;, <del> 照片:profile.photos [0] .value || ” <del> 电子邮件:profile.emails [0] .value || &#39;没有公开电子邮件&#39;, <del> created_on:new Date(), <del> provider:profile.provider || “ <del> } $设置:{ <del> last_login:新日期() <del> } $ INC { <del> login_count:1 <del> }}, <del> {upsert:true,new:true}, <del> (错误,doc)=&gt; { <del> return cb(null,doc.value); <del> } <del>); </pre>使用findAndModify,它允许您搜索对象并对其进行更新,如果对象不存在则将其置换,并在每次回调函数中接收新对象。在这个例子中,我们总是将last_login设置为now,我们总是将login_count增加1,并且只有当我们插入一个新对象(新用户)时,我们才会填充大部分字段。需要注意的是使用默认值。有时,返回的个人资料不会填写所有信息,或者用户会选择保留私密信息;所以在这种情况下我们必须处理它以防止错误。你现在应该可以登录你的应用了 - 试试吧!当您认为自己已经做对时,请提交您的页面。如果你正在运行到错误,您可以检查出的这个小项目的完成代码的例子<a href="https://glitch.com/#!/project/guttural-birch">在这里</a> 。 </section> <add><section id='description'> <add> <add>验证策略的最后一部分是处理从 GitHub 返回的个人信息。如果用户存在,我们就需要从数据库中读取用户数据并在 profile 页面加载;否则,我们需要把用户信息添加到数据库。GitHub 在用户信息中为我们提供了独一无二的 <em>id</em>,我们可以通过序列化的 id 在数据库中搜索用户(已实现)。以下是这个逻辑的实现示例,我们应该把它传到新策略的第二个参数,就是目前 <code>console.log(profile);</code> 的下方: <add> <add>```js <add>myDataBase.findAndModify( <add> {id: profile.id}, <add> {}, <add> {$setOnInsert:{ <add> id: profile.id, <add> name: profile.displayName || 'John Doe', <add> photo: profile.photos[0].value || '', <add> email: Array.isArray(profile.emails) ? profile.emails[0].value : 'No public email', <add> created_on: new Date(), <add> provider: profile.provider || '' <add> },$set:{ <add> last_login: new Date() <add> },$inc:{ <add> login_count: 1 <add> }}, <add> {upsert:true, new: true}, <add> (err, doc) => { <add> return cb(null, doc.value); <add> } <add>); <add>``` <add> <add><code>findAndModify</code> 的作用是在数据库中查询对象并更新,如果对象不存在,我们也可以 <code>upsert</code>(注,upsert 可以理解为 update + insert)它,然后我们可以在回调方法里获取到插入数据后的新对象。在这个例子中,我们会把 last_login 设置成为 now,而且总会为 login_count 加 1。只有在插入一个新对象(新用户)时,我们才会初始化这些字段。另外,还需要注意默认值的使用。有时返回的用户信息可能不全,可能是因为用户没有填写,也可能是因为用户选择不公开一部分信息。在这种情况下,我们需要进行相应的处理,以防我们的 app 报错。 <add> <add>你现在应该可以登录你的应用了,试试吧。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/183e968f0e01d81dde015d45ba9d2745' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Github策略设置完成 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /GitHubStrategy[^]*db.collection/gi, 'Strategy should use now use the database to search for the user'); assert.match(data, /GitHubStrategy[^]*socialusers/gi, 'Strategy should use "socialusers" as db collection'); assert.match(data, /GitHubStrategy[^]*return cb/gi, 'Strategy should return the callback function "cb"'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: GitHub 策略应配置完成。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/auth.js') .then(data => { assert.match(data, /GitHubStrategy[^]*myDataBase/gi, 'Strategy should use now use the database to search for the user'); assert.match(data, /GitHubStrategy[^]*return cb/gi, 'Strategy should return the callback function "cb"'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/implementation-of-social-authentication.chinese.md <ide> id: 589a69f5f9fc0f352b528e70 <ide> title: Implementation of Social Authentication <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 社会认证的实施 <add>forumTopicId: 301559 <add>localeTitle: 实现社交账号登陆 (1) <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socialauth/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socialauth/">GitHub</a>克隆的。此类身份验证在您的应用中遵循的基本路径是: <ol><li>用户单击按钮或链接将它们发送到我们使用特定策略进行身份验证的路由(EG.GitHub) </li><li>您的路由呼叫<code>passport.authenticate(&#39;github&#39;)</code> ,将其重定向到Github。 </li><li>用户登陆的页面,在Github上,允许他们登录,如果他们还没有。然后它要求他们批准从我们的应用程序访问他们的个人资料。 </li><li>然后,如果用户获得批准,则会使用他们的个人资料将该用户返回到我们的应用。 </li><li>它们现在已经过身份验证,您的应用应检查它是否为返回的配置文件,如果不是,则将其保存在数据库中。 </li></ol> OAuth策略要求您至少拥有<em>客户端ID</em>和<em>客户端密钥</em> ,以便他们验证身份验证请求的来源以及是否有效。这些是从您尝试使用Github实现身份验证的站点获得的,并且对您的应用程序是唯一的 - 它们不会被<b>共享</b> ,不应该上传到公共存储库或直接在您的代码中编写。通常的做法是将它们放在<em>.env</em>文件中并引用它们: <code>process.env.GITHUB_CLIENT_ID</code> 。对于这个挑战,我们将使用Github策略。 <em><em>从Github</em></em>获取您的<em>客户ID和密码<em>是在“开发者设置”下的帐户配置文件设置中完成的,然后是“ <a href="https://github.com/settings/developers">OAuth应用程序</a> ”。点击“注册一个新的应用程序”,为您的应用命名,将网址粘贴到您的故障主页( <b>不是项目代码的网址</b> ),最后为回调网址,粘贴到与主页相同的网址,但使用&#39;/ auth / github / callback&#39;已添加。这是用户将被重定向到我们在Github上进行身份验证后处理的地方。将返回的信息保存为.env文件中的“GITHUB_CLIENT_ID”和“GITHUB_CLIENT_SECRET”。在重新混合的项目中,创建2条接受GET请求的路由:/ auth / github和/ auth / github / callback。第一个应该只调用护照来验证&#39;github&#39;,第二个应该调用护照来验证&#39;github&#39;,失败重定向到&#39;/&#39;然后如果成功重定向到&#39;/ profile&#39;(类似于我们的上一个项目)。 &#39;/ auth / github / callback&#39;应该如何看待的示例与我们在上一个项目中处理正常登录的方式类似:</em></em> <pre> <em><em>app.route( &#39;/登录&#39;) <del> .post(passport.authenticate(&#39;local&#39;,{failureRedirect:&#39;/&#39;}),(req,res)=&gt; { <del> res.redirect( &#39;/简档&#39;); <del> });</em></em> </pre> <em><em>当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/28ea2cae7e1dc6a53d7f0c42d987313b">在此处</a>查看项目。</em></em> </section> <add><section id='description'> <add> <add>第三方用户验证的实现逻辑如下:<ol><li>在用户点击按钮或者链接后,进入验证页面,通过第三方平台(如 GitHub)来进行用户验证。</li><li>需要在路由中调用<code>passport.authenticate('github')</code>,跳转至 GitHub 验证页面。</li><li>页面跳转到 GitHub 上,如果用户未登录 GitHub,就需要在这里进行登录。登录成功后,会出现向用户申请访问权限的确认页。</li><li>如果用户同意访问,则用户会回到我们提供的回调地址,带着 GitHub 那边提供的用户信息回到我们的 app 中。</li><li>验证已完成。在我们的应用中,我们需要查询这个用户是否已经存在。如果是新用户,那我们需要把他的用户信息存储到数据库。</li></ol> <add> <add>在 OAuth 验证策略中,我们至少需要提供 <em>Client ID</em> 和 <em>Client Secret</em>,这样第三方平台就会获悉验证请求的来源,以及这个来源是否有效。为此,需要去我们使用的第三方验证平台(比如 GitHub)获取这两个字段的值。注意,我们获取到的这个值是唯一的,且仅对我们的当前 app 有效——<b>因此,千万不要分享给别人</b>,更不要上传到公共仓库或者直接写在代码里。通常,我们会在 <em>.env</em> 文件里配置,并在 Node.js 里通过:<code>process.env.GITHUB_CLIENT_ID</code>获取。对于这次挑战,我们将会使用 GitHub 作为验证平台。 <add> <add>首先,你需要进入账户设置里的 <a href='https://github.com/settings/developers'>Developer settings</a>板块,然后在 OAuth Apps 获取 <em>Client ID</em> 和 <em>Client Secret</em>。点击 'Register a new application',设置你的应用名称,然后把你的 glitch 主页地址(<b>注意,不是项目代码的地址</b>)粘贴到 Homepage URL。然后,回调 url 需要设置成上面 Homepage URL 里你粘贴的地址,但后面要加上 '/auth/github/callback'。这样在用户通过 Github 验证后才能跳转到我们指定的页面。别忘了,我们还需要在 .env 文件里配置好 'GITHUB_CLIENT_ID' 和 'GITHUB_CLIENT_SECRET'。 <add> <add>然后,请在你现在的项目里,为 /auth/github 和 /auth/github/callback 创建两个接收 GET 请求的路由。第一个只需要通过 passport 来调用 'github' 验证,第二个需要调用 passport 来验证 'github',但需要在失败时跳转回主页 '/',成功是跳转到用户页面 '/profile'。跳转的逻辑与上一个项目中的逻辑一样。 <add> <add>例如 '/auth/github/callback' 应该像我们处理在上一个项目中一般的登录一样: <add> <add>```js <add>app.route('/login') <add> .post(passport.authenticate('local', { failureRedirect: '/' }), (req,res) => { <add> res.redirect('/profile'); <add> }); <add>``` <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/1f7f6f76adb178680246989612bea21e' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Route / auth / github正确 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /('|")\/auth\/github('|")[^]*get.*passport.authenticate.*github/gi, 'Route auth/github should only call passport.authenticate with github'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: Route / auth / github /回调正确 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /('|")\/auth\/github\/callback('|")[^]*get.*passport.authenticate.*github.*failureRedirect:( |)("|')\/("|')/gi, 'Route auth/github/callback should accept a get request and call passport.authenticate for github with a failure redirect to home'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 路由 /auth/github 应正确配置。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/routes.js') .then(data => { assert.match(data, /('|")\/auth\/github('|")[^]*get.*passport.authenticate.*github/gi, 'Route auth/github should only call passport.authenticate with github'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 路由 /auth/github/callback 应正确配置。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/routes.js') .then(data => { assert.match(data, /('|")\/auth\/github\/callback('|")[^]*get.*passport.authenticate.*github.*failureRedirect:( |)("|')\/\2/gi, 'Route auth/github/callback should accept a get request and call passport.authenticate for github with a failure redirect to home'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/logging-a-user-out.chinese.md <ide> id: 58965611f9fc0f352b528e6c <ide> title: Logging a User Out <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 记录用户 <add>forumTopicId: 301560 <add>localeTitle: 用户退出登录 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。创建注销逻辑很容易。路径应该只是取消认证用户并重定向到主页而不是渲染任何视图。在护照中, <code>req.logout();</code>认证用户就像调用<code>req.logout();</code>一样简单<code>req.logout();</code>在重定向之前。 <pre> app.route( &#39;/注销&#39;) <del> .get((req,res)=&gt; { <del> req.logout(); <del> res.redirect( &#39;/&#39;); <del> }); </pre>您可能已经注意到我们也没有处理丢失的页面(404),在Node中处理此问题的常用方法是使用以下中间件。继续在所有其他路线之后添加: <pre> app.use((req,res,next)=&gt; { <del> res.status(404) <del> .TYPE( &#39;文本&#39;) <del> .send(&#39;未找到&#39;); <del>}); </pre>当您认为自己已经做对时,请提交您的页面。 </section> <add><section id='description'> <add> <add>创建退出登录的逻辑是比较简单的。只要用户尝试退出登录,路由就应重定向到主页,而不应该显示任何其他页面。 <add> <add>在 passport 里,只需要在重定向前调用 <code>req.logout();</code> 即可完成用户的退出登录。 <add> <add>```js <add>app.route('/logout') <add> .get((req, res) => { <add> req.logout(); <add> res.redirect('/'); <add>}); <add>``` <add> <add>你可能注意到我们还没有处理 404 错误,这个错误码代表页面无法找到。在 Node.js 中我们通常会用如下的中间件来处理,请在所有路由之后添加这段代码: <add> <add>```js <add>app.use((req, res, next) => { <add> res.status(404) <add> .type('text') <add> .send('Not Found'); <add>}); <add>``` <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/c3eeb8a3ebf855e021fd0c044095a23b' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 退出路线 <add> - text: <code>req.Logout</code> 应在 <code>/logout</code> 中调用。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /req.logout/gi, 'You should be calling req.logout() in your /logout route'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 注销应该重定向到主页/ <add> - text: 退出登录后应重定向到主页 / <ide> testString: getUserInput => $.get(getUserInput('url')+ '/logout') .then(data => { assert.match(data, /Home page/gi, 'When a user logs out they should be redirected to the homepage'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/registration-of-new-users.chinese.md <ide> id: 58966a17f9fc0f352b528e6d <ide> title: Registration of New Users <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 新用户注册 <add>forumTopicId: 301561 <add>localeTitle: 注册新用户 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。现在我们需要允许我们网站上的新用户注册一个帐户。在主页的res.render上,向传递的对象添加一个新变量 - <code>showRegistration: true</code> 。刷新页面时,您应该会看到已在index.pug文件中创建的注册表单!此表单设置为<b>POST</b> on <em>/ register,</em>因此我们应该设置此接受POST并在数据库中创建用户对象。注册路由的逻辑应如下所示:注册新用户&gt;验证新用户&gt;重定向到/配置文件步骤1的逻辑,注册新用户,应如下所示:使用findOne命令查询数据库&gt;如果用户返回然后它存在并重定向回到主页<em>或者</em>如果用户未定义且没有发生错误,则使用用户名和密码将“insertOne”输入数据库,只要没有错误发生,然后调用<em>next</em>转到步骤2,验证新的user,我们已经在POST / login路由中编写了逻辑。 <pre> app.route( &#39;/寄存器&#39;) <del> .post((req,res,next)=&gt; { <del> db.collection(&#39;users&#39;)。findOne({username:req.body.username},function(err,user){ <del> if(错误){ <del> 下一个(ERR); <del> } else if(user){ <del> res.redirect( &#39;/&#39;); <del> } else { <del> db.collection( &#39;用户&#39;)。insertOne( <del> {username:req.body.username, <del> 密码:req.body.password}, <del> (错误,doc)=&gt; { <del> if(错误){ <del> res.redirect( &#39;/&#39;); <del> } else { <del> next(null,user); <del> } <del> } <del> ) <add><section id='description'> <add> <add>现在我们需要为新用户添加注册帐号的功能,首先我们需要在主页的 res.render 接收的变量对象中添加 <code>showRegistration: true</code>。此时刷新页面,你会看到页面上已经显示了我们在 index.pug 文件中定义的注册表单。这个表单设置了请求路径 <em>/register</em>,并将请求方法设置成 <b>POST</b>,所以我们需要在服务器接受 <b>POST</b> 请求,且在数据库中创建用户对象。 <add> <add>用户注册的逻辑如下:注册新用户 > 认证新用户 > 重定向到 /profile。 <add> <add>对于步骤一的注册新用户,详细逻辑如下:用 findOne 命令查询数据库 > 如果返回了用户对象,则表示用户存在,然后返回主页;如果用户未定义且没有报错,则会将包含用户名和密码的用户对象通过 <code>insertOne</code> 添加到数据库,只要没有报错则会继续下一步:认证新用户——我们已经在 /login 路由的 POST 请求中写好了这部分逻辑。 <add> <add>```js <add>app.route('/register') <add> .post((req, res, next) => { <add> myDataBase.findOne({ username: req.body.username }, function(err, user) { <add> if (err) { <add> next(err); <add> } else if (user) { <add> res.redirect('/'); <add> } else { <add> myDataBase.insertOne({ <add> username: req.body.username, <add> password: req.body.password <add> }, <add> (err, doc) => { <add> if (err) { <add> res.redirect('/'); <add> } else { <add> // The inserted document is held within <add> // the ops property of the doc <add> next(null, doc.ops[0]); <add> } <ide> } <del> })}, <del> passport.authenticate(&#39;local&#39;,{failureRedirect:&#39;/&#39;}), <del> (req,res,next)=&gt; { <del> res.redirect( &#39;/简档&#39;); <add> ) <add> } <add> }) <add> }, <add> passport.authenticate('local', { failureRedirect: '/' }), <add> (req, res, next) => { <add> res.redirect('/profile'); <ide> } <del>); </pre>当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/6c47bee7df34df9f11820803608071ed">在这里查看</a>到目前为止完成的项目。 </section> <add> ); <add>``` <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e' target='_blank'>这里</a> 的答案。 <add> <add>**注意:**接下来的挑战可能会在运行 _picture-in-picture_(画中画)模式的浏览器中出现问题。如果你使用的线上 IDE 提供在 IDE 内预览 app 的功能,请考虑打开新的标签页预览。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 注册路线并在家中显示 <del> testString: 'getUserInput => $.get(getUserInput(''url'')+ ''/_api/server.js'') .then(data => { assert.match(data, /showRegistration:( |)true/gi, ''You should be passing the variable "showRegistration" as true to your render function for the homepage''); assert.match(data, /register[^]*post[^]*findOne[^]*username:( |)req.body.username/gi, ''You should have a route accepted a post request on register that querys the db with findone and the query being "username: req.body.username"''); }, xhr => { throw new Error(xhr.statusText); })' <del> - text: 注册应该工作 <del> testString: 'getUserInput => $.ajax({url: getUserInput(''url'')+ ''/register'',data: {username: ''freeCodeCampTester'', password: ''freeCodeCampTester''},crossDomain: true, type: ''POST'', xhrFields: { withCredentials: true }}) .then(data => { assert.match(data, /Profile/gi, ''I should be able to register and it direct me to my profile. CLEAR YOUR DATABASE if this test fails (each time until its right!)''); }, xhr => { throw new Error(xhr.statusText); })' <del> - text: 登录应该工作 <del> testString: 'getUserInput => $.ajax({url: getUserInput(''url'')+ ''/login'',data: {username: ''freeCodeCampTester'', password: ''freeCodeCampTester''}, type: ''POST'', xhrFields: { withCredentials: true }}) .then(data => { assert.match(data, /Profile/gi, ''Login should work if previous test was done successfully and redirect successfully to the profile. Check your work and clear your DB''); assert.match(data, /freeCodeCampTester/gi, ''The profile should properly display the welcome to the user logged in''); }, xhr => { throw new Error(xhr.statusText); })' <del> - text: 注销应该有效 <del> testString: 'getUserInput => $.ajax({url: getUserInput(''url'')+ ''/logout'', type: ''GET'', xhrFields: { withCredentials: true }}) .then(data => { assert.match(data, /Home/gi, ''Logout should redirect to home''); }, xhr => { throw new Error(xhr.statusText); })' <del> - text: 注销后配置文件不再有效 <del> testString: 'getUserInput => $.ajax({url: getUserInput(''url'')+ ''/profile'', type: ''GET'', crossDomain: true, xhrFields: { withCredentials: true }}) .then(data => { assert.match(data, /Home/gi, ''Profile should redirect to home when we are logged out now again''); }, xhr => { throw new Error(xhr.statusText); })' <add> - text: 注册路由和显示主页。 <add> testString: "getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /showRegistration:( |)true/gi, 'You should be passing the variable showRegistration as true to your render function for the homepage'); assert.match(data, /register[^]*post[^]*findOne[^]*username:( |)req.body.username/gi, 'You should have a route accepted a post request on register that querys the db with findone and the query being username: req.body.username'); }, xhr => { throw new Error(xhr.statusText); })" <add> - text: 注册功能应可以正常运行。 <add> testString: "async getUserInput => { <add> const url = getUserInput('url'); <add> const user = `freeCodeCampTester${Date.now()}`; <add> const xhttp=new XMLHttpRequest(); <add> xhttp.onreadystatechange = function() { <add> if (this.readyState == 4 && this.status == 200) { <add> test(this); <add> } else { <add> throw new Error(`${this.status} ${this.statusText}`); <add> } <add> }; <add> xhttp.open('POST', url+'/register', true); <add> xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); <add> xhttp.send(`username=${user}&password=${user}`); <add> <add> function test(xhttpRes) { <add> const data = xhttpRes.responseText; <add> assert.match(data, /Profile/gi, 'Register should work, and redirect successfully to the profile.'); <add> } <add> } <add> " <add> - text: 登录功能应可以正常运行。 <add> testString: "async getUserInput => { <add> const url = getUserInput('url'); <add> const user = `freeCodeCampTester${Date.now()}`; <add> const xhttpReg = new XMLHttpRequest(); <add> xhttpReg.onreadystatechange = function() { <add> if (this.readyState == 4 && this.status == 200) { <add> login(); <add> } else { <add> throw new Error(`${this.status} ${this.statusText}`); <add> } <add> }; <add> xhttpReg.open('POST', url+'/register', true); <add> xhttpReg.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); <add> xhttpReg.send(`username=${user}&password=${user}`); <add> <add> function login() { <add> const xhttp=new XMLHttpRequest(); <add> xhttp.onreadystatechange = function() { <add> if (this.readyState == 4 && this.status == 200) { <add> test(this); <add> } else { <add> throw new Error(`${this.status} ${this.statusText}`); <add> } <add> }; <add> xhttp.open('POST', url+'/login', true); <add> xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); <add> xhttp.send(`username=${user}&password=${user}`); <add> } <add> function test(xhttpRes) { <add> const data = xhttpRes.responseText; <add> assert.match(data, /Profile/gi, 'Login should work if previous test was done successfully and redirect successfully to the profile.'); <add> assert.match(data, new RegExp(user, 'g'), 'The profile should properly display the welcome to the user logged in'); <add> } <add> } <add> " <add> - text: 退出登录功能应可以正常运行。 <add> testString: "getUserInput => $.ajax({url: getUserInput('url')+ '/logout', type: 'GET', xhrFields: { withCredentials: true }}) .then(data => { assert.match(data, /Home/gi, 'Logout should redirect to home'); }, xhr => { throw new Error(xhr.statusText); })" <add> - text: 退出登录后,profile 页面应无法访问。 <add> testString: "getUserInput => $.ajax({url: getUserInput('url')+ '/profile', type: 'GET', crossDomain: true, xhrFields: { withCredentials: true }}) .then(data => { assert.match(data, /Home/gi, 'Profile should redirect to home when we are logged out now again'); }, xhr => { throw new Error(xhr.statusText); })" <ide> <ide> ``` <ide> <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/send-and-display-chat-messages.chinese.md <ide> id: 589fc832f9fc0f352b528e79 <ide> title: Send and Display Chat Messages <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301562 <ide> localeTitle: 发送和显示聊天消息 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socketio/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socketio/">GitHub</a>克隆的。是时候开始允许客户端向服务器发送聊天消息以向所有客户端发送消息!已经在您的client.js文件中,您应该看到在提交messgae表单时已经存在一段代码处理! ( <code>$(&#39;form&#39;).submit(function(){ /*logic*/ });</code> ) <hr>在您处理表单提交的代码中,您应该在定义“messageToSend”之后但在清除文本框<code>#m</code>之前发出事件。该事件应命名为“聊天消息”,数据应为“messageToSend”。 <code>socket.emit(&#39;chat message&#39;, messageToSend);</code>现在,在您的服务器上,您应该收听事件“聊天消息”的套接字,并将数据命名为“message”。一旦接收到事件,应该然后发射所述事件“聊天消息”到所有插座<code>io.emit</code>与数据为含“名称”和“报文”的对象。现在再次在您的客户端上,您现在应该监听事件“聊天消息”,并在收到时,将一个列表项追加到<code>#messages</code> ,其名称为冒号和消息!此时聊天功能齐全,并在所有客户端发送消息!当您认为自己已经做对时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/3e4b7750f6cd42feaa2768458d682136">在此处</a>检查项目到此时<a href="https://gist.github.com/JosephLivengood/3e4b7750f6cd42feaa2768458d682136">为服务器</a>和<a href="https://gist.github.com/JosephLivengood/41ba76348df3013b7870dc64861de744">客户端</a> 。 </section> <add> <add><section id='description'> <add> <add>现在,我们可以开始实现聊天室功能了。整体逻辑很简单,只需要获取用户发给服务端的消息,再通过服务端给所有客户端发送信息就可以了。在 client.js 文件里,你应该已经注意到了这段提交表单的代码: <add> <add>```js <add>$('form').submit(function() { <add> /*logic*/ <add>}); <add>``` <add> <add>现在我们需要处理事件的 emit,它应该发生在定义 <code>messageToSend</code> 之后,以及清除 <code>#m</code> 中的文本之前。我们称这个事件叫 <code>'chat message'</code>,需发送的数据叫 <code>messageToSend</code>: <add> <add>```js <add>socket.emit('chat message', messageToSend); <add>``` <add> <add>在服务端,我们需要监听包含 <code>message</code> 的 <code>'chat message'</code> 事件。一旦事件发生,我们就通过<code>io.emit</code> 把包含 <code>name</code> 和 <code>message</code> 的 <code>'chat message'</code> 事件发送给所有已连接的 socket。 <add> <add>回到客户端,我们需要监听 <code>'chat message'</code> 事件。只要接收到这个事件,就把包含名字和消息的内容(注意:需要在名字后添加冒号)通过 <code>&#60;li&#62;</code> 添加到 <code>#messages</code>。 <add> <add>至此,我们已经完成发送信息到所有客户端的功能。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/d7af9864375207e254f73262976d2016' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 服务器侦听“聊天消息”,然后正确发出 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /socket.on.*('|")chat message('|")[^]*io.emit.*('|")chat message('|").*name.*message/gi, 'Your server should listen to the socket for "chat message" then emit to all users "chat message" with name and message in the data object'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 客户端正确处理和显示事件“聊天消息”中的新数据 <del> testString: "getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.on.*('|\")chat message('|\")[^]*messages.*li/gi, 'You should append a list item to #messages on your client within the \"chat message\" event listener to display the new message'); }, xhr => { throw new Error(xhr.statusText); })" <del> <add> - text: 服务端应监听 <code>'chat message'</code>,且应在监听到后 emit。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /socket.on.*('|")chat message('|")[^]*io.emit.*('|")chat message('|").*name.*message/gis, 'Your server should listen to the socket for "chat message" then emit to all users "chat message" with name and message in the data object'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: '客户端应正确处理和展示从 <code>'chat message'</code> 事件发来的新数据。 <add> testString: 'getUserInput => $.get(getUserInput(''url'')+ ''/public/client.js'') .then(data => { assert.match(data, /socket.on.*(''|")chat message(''|")[^]*messages.*li/gis, ''You should append a list item to #messages on your client within the "chat message" event listener to display the new message''); }, xhr => { throw new Error(xhr.statusText); })' <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/serialization-of-a-user-object.chinese.md <ide> id: 5895f70cf9fc0f352b528e66 <ide> title: Serialization of a User Object <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301563 <ide> localeTitle: 用户对象的序列化 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。序列化和反序列化是身份验证方面的重要概念。序列化对象意味着将其内容转换为一个小<em>键,</em>基本上可以将其反序列化为原始对象。这使我们能够知道与服务器通信的人,而无需在每次请求新页面时发送用户名和密码等身份验证数据。要正确设置它,我们需要一个序列化函数和一个反序列化函数。在护照中,我们使用<code>passport.serializeUser( OURFUNCTION )</code>和<code>passport.deserializeUser( OURFUNCTION )</code>创建它们。使用2个参数调用serializeUser,完整的用户对象和护照使用的回调。在回调中返回应该是唯一的键来标识该用户 - 最容易使用的用户是对象中的用户_id,因为它应该是MongoDb生成的唯一用户。类似地,使用该密钥和护照的回调函数调用deserializeUser,但这次我们必须获取该密钥并将用户完整对象返回到回调。要进行查询搜索Mongo _id,您必须创建<code>const ObjectID = require(&#39;mongodb&#39;).ObjectID;</code> ,然后使用它调用<code>new ObjectID(THE_ID)</code> 。一定要将MongoDB添加为依赖项。您可以在以下示例中看到: <pre> passport.serializeUser((user,done)=&gt; { <del> done(null,user._id); <del> }); </pre><br><pre> passport.deserializeUser((id,done)=&gt; { <del> db.collection( &#39;用户&#39;)。findOne( <del> {_id:new ObjectID(id)}, <del> (错误,doc)=&gt; { <del> 完成(null,doc); <del> } <del> ); <del> }); </pre>注意:这个deserializeUser将抛出一个错误,直到我们在下一步中设置数据库,因此注释掉整个块并在函数deserializeUser中调用<code>done(null, null)</code> 。当您认为自己已经做对时,请提交您的页面。 </section> <add> <add><section id='description'> <add> <add>序列化和反序列化在身份认证中是很重要的概念。序列化一个对象就是将其内容转换成一个体积很小的 <em>key</em>,后续可以通过这个 <em>key</em> 反序列化为原始对象。这样,服务器就可以在用户未登录时识别用户,或者说给这个用户一个唯一标识,用户也不需要在每次访问不同页面时都给服务器发送用户名和密码。 <add> <add>我们需要用到序列化和反序列化的方法来进行配置。passport 为我们提供了 <code>passport.serializeUser( OURFUNCTION )</code> 和 <code>passport.deserializeUser( OURFUNCTION )</code> 两个方法。 <add> <add>code>serializeUser</code>方法接收两个参数,分别是表示用户的对象和一个回调函数。其中,回调函数的返回值应为这个用户的唯一标识符:最简单的写法就是让它返回用户的<code>_id</code>,这个<code>_id</code>属性是 MongoDB 为用户创建的唯一字段。类似地,反序列化也接收两个参数,分别是在序列化时生成的标识符以及一个回调函数。在回调函数里,我们需要根据根据传入的标识符(比如 _id)返回表示用户的对象。为了在 MongoDB 中通过 query(查询语句)获取 <code>_id</code> 字段,首先我们需要引入 MongoDB 的<code>ObjectID</code>方法:<code>const ObjectID = require('mongodb').ObjectID;</code>;然后调用它:<code>new ObjectID(THE_ID)</code>。当然,这一切的前提都是先引入 MongoDB 作为依赖。你可以在下面的例子中看到: <add> <add>```js <add>passport.serializeUser((user, done) => { <add> done(null, user._id); <add>}); <add> <add>passport.deserializeUser((id, done) => { <add> myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => { <add> done(null, null); <add> }); <add>}); <add>``` <add> <add>注意:在完全配置好 MongoDB 前,<code>deserializeUser</code> 会抛出错误。因此,现在请先注释掉上面的代码,在 <code>deserializeUser</code> 中仅调用 <code>done(null, null)</code> 即可。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 序列化用户功能正确 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /passport.serializeUser/gi, 'You should have created your passport.serializeUser function'); assert.match(data, /null, user._id/gi, 'There should be a callback in your serializeUser with (null, user._id)'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 反序列化用户功能正确 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /passport.deserializeUser/gi, 'You should have created your passport.deserializeUser function'); assert.match(data, /null,( |)null/gi, 'There should be a callback in your deserializeUser with (null, null) for now'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: MongoDB是一个依赖项 <add> - text: 应存在正确的 <code>serializeUser</code> 方法。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /passport.serializeUser/gi, 'You should have created your passport.serializeUser function'); assert.match(data, /null,\s*user._id/gi, 'There should be a callback in your serializeUser with (null, user._id)'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应存在正确的 <code>deserializeUser</code> 方法。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /passport.deserializeUser/gi, 'You should have created your passport.deserializeUser function'); assert.match(data, /null,\s*null/gi, 'There should be a callback in your deserializeUser with (null, null) for now'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: MongoDB 应作为项目的依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'mongodb', 'Your project should list "mongodb" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: Mongodb正确要求包括ObjectId <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')mongodb("|')/gi, 'You should have required mongodb'); assert.match(data, /new ObjectID.*id/gi, 'Even though the block is commented out, you should use new ObjectID(id) for when we add the database'); }, xhr => { throw new Error(xhr.statusText); }) <del> <add> - text: 注释掉的代码中应包含 <code>ObjectId</code>。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')mongodb\1/gi, 'You should have required mongodb'); assert.match(data, /new ObjectID.*id/gi, 'Even though the block is commented out, you should use new ObjectID(id) for when we add the database'); }, xhr => { throw new Error(xhr.statusText); }) <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/set-up-a-template-engine.chinese.md <ide> id: 5895f700f9fc0f352b528e63 <ide> title: Set up a Template Engine <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301564 <ide> localeTitle: 设置模板引擎 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。模板引擎使您可以在应用程序中使用静态模板文件(例如用<em>Pug</em>编写的文件)。在运行时,模板引擎将模板文件中的变量替换为可由服务器提供的实际值,并将模板转换为静态HTML文件,然后将其发送到客户端。这种方法可以更轻松地设计HTML页面,并允许在页面上显示变量,而无需从客户端进行API调用。要设置<em>Pug</em>以便在项目中使用,您需要先在package.json中将其作为依赖项添加。 <code>&quot;pug&quot;: &quot;^0.1.0&quot;</code>现在告诉Node / Express使用模板引擎,你必须告诉你的快递<b>应用程序</b> <b>将</b> &#39;pug&#39; <b>设置</b>为&#39;view-engine&#39;。 <code>app.set(&#39;view engine&#39;, &#39;pug&#39;)</code>最后,你应该改变请求您响应该指数路线<code>res.render</code>与路径视图<em>意见/哈巴狗/ index.pug。</em>如果一切按计划进行,您应该刷新应用程序主页并看到一条小消息,说您已成功从我们的Pug文件中删除Pug!当您认为自己已经做对时,请提交您的页面。 </section> <add> <add><section id='description'> <add> <add>请注意,本项目在 <a href="https://repl.it/github/freeCodeCamp/boilerplate-mochachai">这个 Repl.it 项目</a> 的基础上进行开发。你也可以从 <a href='https://repl.it/github/freeCodeCamp/boilerplate-mochachai'>GitHub</a> 上克隆。 <add> <add>你可以在应用的模版引擎中使用静态模板文件(如那些写在 <em>Pug</em> 里的)。在运行时,模版引擎会用服务端的真实数据替换掉模版文件中的变量,然后将模版转译成发送给客户端的 HTML 静态文件。这样可以轻松地构造 HTML 页面,允许在页面直接显示变量内容而不需要发送 API 请求。 <add> <add>为了在项目中使用 <em>Pug</em>,你需要在 package.json 中添加依赖 <code>"pug": "^0.1.0"</code>。注意,依赖的名称和版本号都要添加。 <add> <add>为了在 Express 中使用 pug 作为模版引擎,你需要在 express 中将 <b>app</b> 的 "view-engine" 设置为 "pug",就像这样:<code>app.set('view engine', 'pug')</code>。 <add> <add>如果没有正确的 <em>render</em> <em>'views/pug'</em> 路径下的 index 文件,页面将不会被加载。 <add> <add>最后, 你需要修改 <code>res.render()</code> 方法,设置 <code>/</code> 的响应。<code>res.render()</code> 方法接收一个文件路径作为参数,这个路径既可以是相对路径(相对于 views),也可以是绝对路径。而且,我们不需要给它添加文件扩展名(文件后缀名)。 <add> <add>如果一切顺利,刷新一下应用的主页就不会看到 "Pug template is not defined." 的报错了,而是会看到 Pug 成功加载的提示。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/3515cd676ea4dfceab4e322f59a37791' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 帕格是一个依赖 <add> - text: 项目中应使用 Pug 作为依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'pug', 'Your project should list "pug" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 查看引擎是帕格 <add> - text: 项目中应使用 Pug 作为模版引擎。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /('|")view engine('|"),( |)('|")pug('|")/gi, 'Your project should set Pug as a view engine'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 帕格正在工作 <add> - text: 在 Response 里使用正确的 ExpressJS 方法渲染主页面。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/') .then(data => { assert.match(data, /FCC Advanced Node and Express/gi, 'You successfully rendered the Pug template!'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: Pug 应该生效。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/') .then(data => { assert.match(data, /pug-success-message/gi, 'Your projects home page should now be rendered by pug with the projects .pug file unaltered'); }, xhr => { throw new Error(xhr.statusText); }) <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/set-up-passport.chinese.md <ide> id: 5895f70cf9fc0f352b528e65 <ide> title: Set up Passport <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 设置护照 <add>forumTopicId: 301565 <add>localeTitle: 设置 Passport <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。是时候设置<em>Passport,</em>这样我们终于可以开始允许用户注册或登录帐户了!除了Passport,我们还将使用Express-session来处理会话。使用此中间件将会话ID保存为客户端中的cookie,并允许我们使用服务器上的该ID访问会话数据。这样,我们将个人帐户信息保留在客户端使用的cookie之外,以验证我们的服务器是否经过身份验证,并保留<em>密钥</em>以访问存储在服务器上的数据。要设置Passport以便在项目中使用,您需要先在package.json中将其作为依赖项添加。 <code>&quot;passport&quot;: &quot;^0.3.2&quot;</code>此外,现在还要将Express-session添加为依赖项。 Express-session拥有大量可以使用的高级功能,但现在我们只是要使用基础知识! <code>&quot;express-session&quot;: &quot;^1.15.0&quot;</code>您需要立即设置会话设置并初始化Passport。一定要先创建变量&#39;session&#39;和&#39;passport&#39;,分别要求&#39;express-session&#39;和&#39;passport&#39;。要设置您要使用的快速应用程序使用会话,我们将仅定义几个基本选项。请务必将“SESSION_SECRET”添加到.env文件中,并为其提供随机值。这用于计算用于加密cookie的哈希值! <pre> app.use(会话({ <del> secret:process.env.SESSION_SECRET, <del> resave:是的, <del> saveUninitialized:true, <del>})); </pre>您也可以继续告诉您的快递应用程序<b>使用</b> &#39;passport.initialize()&#39;和&#39;passport.session()&#39;。 (例如, <code>app.use(passport.initialize());</code> )当您认为自己正确时,请提交您的页面。如果您遇到错误,可以<a href="https://gist.github.com/JosephLivengood/338a9c5a326923c3826a666d430e65c3">在这里查看</a>到目前为止完成的项目。 </section> <add><section id='description'> <add> <add>现在我们来创建 <em>Passport</em>,最终我们需要用它来实现用户注册和登录。除了 Passport,我们还会用 express-session 来处理 session(会话)。在客户端,我们可以用这个中间件把 session id 储存到 cookie。同时,我们可以在服务器上通过这个 id 访问 session 数据。通过这种方式,我们无需把用户的个人信息存到 cookie 来只完成用户的验证,只需要用这个 id 作为 <em>key</em> 来访问服务器上用户的数据即可。 <add> <add>为了在你的项目中使用 Passport,首先你需要在 package.json 文件中添加依赖:<code>"passport": "^0.3.2"</code> <add> <add>此外,还需要添加 express-session 作为依赖,就像这样:<code>"express-session": "^1.15.0"</code>。express-session 有许多高级特性,但我们暂时只需要了解其基础功能。 <add> <add>现在,我们需要配置 session 并初始化 Passport。请先创建变量 <code>session</code> 和 <code>passport</code> 来引入 express-session 和 passport。 <add> <add>为了让 express 应用可以使用 session,我们需要添加一些基础选项。请在 .env 文件中添加字段 'SESSION_SECRET',并给它赋一个随机值,便于加密 cookie、计算哈希。 <add> <add>```js <add>app.use(session({ <add> secret: process.env.SESSION_SECRET, <add> resave: true, <add> saveUninitialized: true, <add> cookie: { secure: false } <add>})); <add>``` <add> <add>还有,我们需要让 express 使用 <code>passport.initialize()</code> 和 <code>passport.session()</code>。为此,你可以这样写:<code>app.use(passport.initialize());</code>。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/4068a7662a2f9f5d5011074397d6788c' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Passort和Express-session是依赖项 <add> - text: 应添加 Passort 和 express-session 作为依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'passport', 'Your project should list "passport" as a dependency'); assert.property(packJson.dependencies, 'express-session', 'Your project should list "express-session" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 正确要求依赖性 <add> - text: 依赖应正确引入。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /require.*("|')passport("|')/gi, 'You should have required passport'); assert.match(data, /require.*("|')express-session("|')/gi, 'You should have required express-session'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: Express应用程序使用新的依赖项 <add> - text: express 应调用 passport 的方法。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /passport.initialize/gi, 'Your express app should use "passport.initialize()"'); assert.match(data, /passport.session/gi, 'Your express app should use "passport.session()"'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 正确设置会话和会话密钥 <add> - text: 应正确设置 session 和 session secret。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /secret:( |)process.env.SESSION_SECRET/gi, 'Your express app should have express-session set up with your secret as process.env.SESSION_SECRET'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/set-up-the-environment.chinese.md <ide> id: 589fc830f9fc0f352b528e74 <ide> title: Set up the Environment <ide> challengeType: 2 <del>videoUrl: '' <add>forumTopicId: 301566 <ide> localeTitle: 设置环境 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-socketio/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-socketio/">GitHub</a>克隆的。将Socket.IO添加为依赖项,并在服务器中要求/实例化它,定义为&#39;io&#39;,并将http服务器作为参数。 <code>const io = require(&#39;socket.io&#39;)(http);</code>需要处理的第一件事是从客户端侦听新连接。 <dfn>on</dfn>关键字就是这样 - 监听特定事件。它需要2个参数:一个包含所发出事件标题的字符串,以及一个用于传递数据的函数。在我们的连接侦听器的情况下,我们使用<em>socket</em>来定义第二个参数中的数据。套接字是连接的个人客户端。要在我们的服务器上侦听连接,请在项目中的注释之间添加以下内容: <pre> io.on(&#39;connection&#39;,socket =&gt; { <del> console.log(&#39;用户已连接&#39;); <del>}); </pre>现在,对于客户端进行连接,您只需要将以下内容添加到client.js中,该客户端经过身份验证后由页面加载: <pre> / * global io * / <del>var socket = io(); </pre>注释会抑制您通常会看到的错误,因为文件中未定义“io”。我们已经在chat.pug页面上的Socket.IO库中添加了一个可靠的CDN。现在尝试加载您的应用并进行身份验证,您应该在服务器控制台中看到“用户已连接”! <strong>注意</strong> <br> <code>io()</code>仅在连接到同一URL /服务器上托管的套接字时起作用。要连接到其他地方托管的外部套接字,您可以使用<code>io.connect(&#39;URL&#39;);</code> 。当您认为自己已经做对时,请提交您的页面。 </section> <add> <add><section id='description'> <add> <add>在接下来的挑战中,我们将会用到 <code>chat.pug</code> 文件。首先,你需要在你的 <code>routes.js</code> 文件中为 <code>/chat</code> 添加一个处理 GET 请求的路由,并给它传入 <code>ensureAuthenticated</code>。在回调函数中,我们需要让它 render <code>chat.pug</code> 文件,并在响应中包含 <code>{ user: req.user }</code> 信息。现在,请修改 <code>/auth/github/callback</code> 路由,让它可以像这样设置 user_id:<code>req.session.user_id = req.user.id</code>,并在设置完成后重定向至 <code>/chat</code>。 <add> <add>我们还需要添加 <code>html</code> 和 <code>socket.io</code> 两个依赖项,并且像这样引入: <add> <add>```javascript <add>const http = require('http').createServer(app); <add>const io = require('socket.io')(http); <add>``` <add> <add>现在我们的 _express_ 应用已经包含了 _http_ 服务,接下来我们需要监听 _http_ 服务的事件。为此,我们需要把 <code>app.listen</code> 更新为 <code>http.listen</code>。 <add> <add>我们需要处理的第一件事是监听从客户端发出的连接事件,我们可以调用 <dfn>on</dfn> 方法来监听具体的事件。它接收两个参数:一个是发出的事件的标题字符串,另一个是后续用来传递数据的回调函数。在这个回调函数中,我们用 <em>socket</em> 来代表它所包含的数据。简单来说,socket 就是指已连接到服务器的客户端。 <add> <add>为了可以监听服务器的连接事件,我们在数据库连接的部分加入如下代码: <add> <add>```javascript <add>io.on('connection', socket => { <add> console.log('A user has connected'); <add>}); <add>``` <add> <add>对于发出连接事件的客户端,只需要在 <code>client.js</code> 中添加以下内容: <add> <add>```js <add>/*global io*/ <add>let socket = io(); <add>``` <add> <add>注意,这个 <code>client.js</code> 文件是在用户通过验证后才加载到客户端的。在这个文件中,我们没有定义 io 变量,但第一行的注释会阻止运行时产生的报错。不过,我们在 chat.pug 的页面上已经为你添加好了 Socket.IO 库的 CDN。 <add> <add>现在你可以重启一下你的 app,尝试一下验证用户,然后你应该会看到服务器的 console 里输出了 'A user has connected'。 <add> <add><strong>注意:</strong>只有在连接到处于同一个 url/server 上的 socket 时,<code>io()</code>才可以正常执行。如果需要连接到外部的 socket,就需要这样调用:<code>io.connect('URL');</code>。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <add> <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Socket.IO是一个依赖项 <add> - text: 应添加 Socket.IO 作为依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'socket.io', 'Your project should list "socket.io" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: Socket.IO已得到适当的要求和实例化 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => {assert.match(data, /io.*=.*require.*('|")socket.io('|").*http/gi, 'You should correctly require and instantiate socket.io as io.');}, xhr => { throw new Error(xhr.statusText); }) <del> - text: Socket.IO应该正在监听连接 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io.on.*('|")connection('|").*socket/gi, 'io should listen for "connection" and socket should be the 2nd arguments variable'); }, xhr => { throw new Error(xhr.statusText); }) <del> - text: 您的客户端应该连接到您的服务器 <add> - text: 应正确引入 <code>http</code>,并示例化为 <code>http</code>。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /http.*=.*require.*('|")http\1/gi, 'Your project should list "html" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 应正确引入 <code>socket.io</code>,并示例化为 <code>io</code>。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => {assert.match(data, /io.*=.*require.*('|")socket.io\1.*http/gi, 'You should correctly require and instantiate socket.io as io.');}, xhr => { throw new Error(xhr.statusText); }) <add> - text: Socket.IO 应监听连接。 <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /io.on.*('|")connection\1.*socket/gi, 'io should listen for "connection" and socket should be the 2nd arguments variable'); }, xhr => { throw new Error(xhr.statusText); }) <add> - text: 客户端应连接到服务器。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/public/client.js') .then(data => { assert.match(data, /socket.*=.*io/gi, 'Your client should be connection to server with the connection defined as socket'); }, xhr => { throw new Error(xhr.statusText); }) <del> <ide> ``` <ide> <ide> </section> <ide> <ide> ## Challenge Seed <add> <ide> <section id='challengeSeed'> <ide> <ide> </section> <ide> <ide> ## Solution <add> <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section> <ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/use-a-template-engines-powers.chinese.md <ide> id: 5895f70bf9fc0f352b528e64 <ide> title: Use a Template Engine's Powers <ide> challengeType: 2 <del>videoUrl: '' <del>localeTitle: 使用模板引擎的权力 <add>forumTopicId: 301567 <add>localeTitle: 使用模板引擎 <ide> --- <ide> <ide> ## Description <del><section id="description">提醒一下,这个项目是基于<a href="https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-advancednode/">Glitch</a>的以下入门项目构建的,或者是从<a href="https://github.com/freeCodeCamp/boilerplate-advancednode/">GitHub</a>克隆的。使用模板引擎的最大特点之一是能够将变量从服务器传递到模板文件,然后再将其呈现为HTML。在您的Pug文件中,您将通过引用变量名称作为<code>#{variable_name}</code>与元素上的其他文本内联,或者在元素上使用相等的一侧而不使用空格(例如<code>p= variable_name</code>来设置该<code>p= variable_name</code> 。 p元素文本等于变量。我们强烈建议在他们的Githubs自述文件中<a href="https://github.com/pugjs/pug">查看</a> Pug的语法和结构。 Pug就是使用空格和制表符来显示嵌套元素,并减少制作漂亮网站所需的代码量。查看项目中包含的我们的pug文件&#39;index.pug&#39;,我们使用变量<em>title</em>和<em>message</em>要从我们的服务器单独传递它们,您需要将一个对象作为第二个参数添加到<em>res.render中</em> ,并带有变量和他们的价值。例如,传递此对象以设置索引视图的变量: <code>{title: &#39;Hello&#39;, message: &#39;Please login&#39;</code>它应该看起来像: <code>res.render(process.cwd() + &#39;/views/pug/index&#39;, {title: &#39;Hello&#39;, message: &#39;Please login&#39;});</code>现在刷新页面,您应该在视图中呈现的那些值在index.pug文件中列出的正确位置!当您认为自己已经做对时,请提交您的页面。 </section> <add><section id='description'> <add> <add>模版引擎最大的特点之一就是在 HTML 页面展示之前,可以从服务端传变量到模版文件。 <add> <add>在 Pug 文件中,你可以用变量名来调用变量,比如写成 <code>#{variable_name}</code> 来实现行内调用,或像 <code>p= variable_name</code> 把元素与变量直接写在一起,这表示 p 元素的内容等价于这个变量。 <add> <add>建议大家在 <a href='https://github.com/pugjs/pug' target='_blank'>Pug 的 README</a> 里看看它的语法和用法,这样你写出的代码会相对简练。另外要注意,Pug 使用缩进来表示嵌套的代码块。 <add> <add>在 pug 的 'index.pug' 文件中,我们使用了 <em>title</em> 和 <em>message</em> 两个变量。 <add> <add>为了从服务器传递这些信息,你需要给 <em>res.render</em> 的第二个参数传入一个对象,其中包含变量对应的值。比如,如果你想传递对象 <code>{title: 'Hello', message: 'Please login'</code> 到你的主页,那么应该这样写: <add> <add><code>res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});</code> <add> <add>刷新页面,如果页面中数据显示正确,你就可以提交你的页面了。 <add> <add>完成上述要求后,你可以在下方提交你的页面链接。如果你遇到了问题,可以参考 <a href='https://gist.github.com/camperbot/4af125119ed36e6e6a8bb920db0c0871' target='_blank'>这里</a> 的答案。 <add> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> <add><section id='instructions'> <add> <ide> </section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 帕格渲染变量正确 <add> - text: Pug 应正确地展示变量。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/') .then(data => { assert.match(data, /pug-variable("|')>Please login/gi, 'Your projects home page should now be rendered by pug with the projects .pug file unaltered'); }, xhr => { throw new Error(xhr.statusText); }) <ide> <ide> ``` <ide> tests: <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>/** <add> Backend challenges don't need solutions, <add> because they would need to be tested against a full working project. <add> Please check our contributing guidelines to learn more. <add>*/ <ide> ``` <ide> <del>/section> <add></section>
22
Text
Text
add note about dotenv package
d3e00ff05e54b3316059fb9ee5c5165bdd7b07a7
<ide><path>curriculum/challenges/english/05-back-end-development-and-apis/basic-node-and-express/use-the-.env-file.md <ide> Then, in the `/json` GET route handler you created in the last challenge, transf <ide> <ide> **Note:** If you are using Replit, you cannot create a `.env` file. Instead, use the built-in <dfn>SECRETS</dfn> tab to add the variable. <ide> <add>If you are working locally, you will need the `dotenv` package. It loads environment variables from your `.env` file into `process.env`. Install it with `npm install dotenv`. Then, at the top of your `myApp.js` file, import and load the variables with `require('dotenv').config()`. <add> <ide> # --hints-- <ide> <ide> The response of the endpoint `/json` should change according to the environment variable `MESSAGE_STYLE`
1
Javascript
Javascript
add tests for texteditorelement.setscrolltop/left
4c8fd0cb7596dc126ecd7dc2c4fe32ce98ff587a
<ide><path>spec/text-editor-element-spec.js <ide> describe('TextEditorElement', () => { <ide> }) <ide> ) <ide> <add> describe('::setScrollTop and ::setScrollLeft', () => { <add> it('changes the scroll position', async () => { <add> element = buildTextEditorElement() <add> element.getModel().update({autoHeight: false}) <add> element.getModel().setText('lorem\nipsum\ndolor\nsit\namet') <add> element.setHeight(20) <add> await element.getNextUpdatePromise() <add> element.setWidth(20) <add> await element.getNextUpdatePromise() <add> <add> element.setScrollTop(22) <add> await element.getNextUpdatePromise() <add> expect(element.getScrollTop()).toBe(22) <add> <add> element.setScrollLeft(32) <add> await element.getNextUpdatePromise() <add> expect(element.getScrollLeft()).toBe(32) <add> }) <add> }) <add> <ide> describe('on TextEditor::setMini', () => <ide> it("changes the element's 'mini' attribute", async () => { <ide> const element = buildTextEditorElement() <ide><path>src/text-editor-element.js <ide> class TextEditorElement extends HTMLElement { <ide> } <ide> <ide> setScrollTop (scrollTop) { <del> this.getComponent().setScrollTop(scrollTop) <add> const component = this.getComponent() <add> component.setScrollTop(scrollTop) <add> component.scheduleUpdate() <ide> } <ide> <ide> getScrollLeft () { <ide> return this.getComponent().getScrollLeft() <ide> } <ide> <ide> setScrollLeft (scrollLeft) { <del> this.getComponent().setScrollLeft(scrollLeft) <add> const component = this.getComponent() <add> component.setScrollLeft(scrollLeft) <add> component.scheduleUpdate() <ide> } <ide> <ide> hasFocus () {
2
Text
Text
update hosting providers
b8e17502a304b987268340611127907fe6e0a518
<ide><path>README.md <ide> Our Xserve ESXi boxes for CI are hosted by [MacStadium](https://www.macstadium.c <ide> <ide> [![Powered by MacStadium](https://cloud.githubusercontent.com/assets/125011/22776032/097557ac-eea6-11e6-8ba8-eff22dfd58f1.png)](https://www.macstadium.com) <ide> <del>Our Mac Minis for CI were paid for by [our Kickstarter supporters](http://docs.brew.sh/Kickstarter-Supporters.html). <del> <del>Our Mac Minis for CI are hosted by [The Positive Internet Company](http://www.positive-internet.com). <add>Our Jenkins CI installation is hosted by [DigitalOcean](https://m.do.co/c/7e39c35d5581). <ide> <ide> Our bottles (binary packages) are hosted by [Bintray](https://bintray.com/homebrew). <ide>
1
Ruby
Ruby
fix frozen string usage
261e2e79262337aaad504dfc5240cd2d2d77d71b
<ide><path>Library/Homebrew/utils/github.rb <ide> def pretty_ratelimit_reset(reset) <ide> class AuthenticationFailedError < Error <ide> def initialize(github_message) <ide> @github_message = github_message <del> message = "GitHub #{github_message}:" <add> message += "GitHub #{github_message}:" <ide> if ENV["HOMEBREW_GITHUB_API_TOKEN"] <ide> message << <<~EOS <ide> HOMEBREW_GITHUB_API_TOKEN may be invalid or expired; check: <ide> def initialize(github_message) <ide> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <ide> EOS <ide> end <del> super message <add> super message.freeze <ide> end <ide> end <ide>
1
Text
Text
add more documentation to context page
7d0ee245144a29d66acde6abc56a209baa4cc0c3
<ide><path>docs/docs/12-context.ko-KR.md <ide> var MessageList = React.createClass({ <ide> <ide> 원한다면 전체 React 컴포넌트를 프로퍼티로 전달할 수도 있습니다. <ide> <add>## Referencing context in lifecycle methods <add> <add>If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object: <add> <add>```javascript <add>void componentWillReceiveProps( <add> object nextProps, object nextContext <add>) <add> <add>boolean shouldComponentUpdate( <add> object nextProps, object nextState, object nextContext <add>) <add> <add>void componentWillUpdate( <add> object nextProps, object nextState, object nextContext <add>) <add> <add>void componentDidUpdate( <add> object prevProps, object prevState, object prevContext <add>) <add>``` <add> <add>## Referencing context in stateless functional components <add> <add>Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows the `Button` component above written as a stateless functional component. <add> <add>```javascript <add>function Button(props, context) { <add> return ( <add> <button style={{'{{'}}background: context.color}}> <add> {props.children} <add> </button> <add> ); <add>} <add>Button.contextTypes = {color: React.PropTypes.string}; <add>``` <add> <ide> ## 컨텍스트를 사용하지 말아야 하는 경우 <ide> <ide> 대부분의 경우, 깔끔한 코드를 위해 전역 변수를 피하는 것과 마찬가지로 컨텍스트의 사용을 피해야 합니다. 특히 "타이핑을 줄이거나" 명시적인 프로퍼티 전달 대신 이를 사용하려는 경우 다시 한번 생각해 보세요. <ide><path>docs/docs/12-context.md <ide> By passing down the relevant info in the `Menu` component, each `MenuItem` can c <ide> <ide> Recall that you can also pass entire React components in props if you'd like to. <ide> <add>## Referencing context in lifecycle methods <add> <add>If `contextTypes` is defined within a component, the following lifecycle methods will receive an additional parameter, the `context` object: <add> <add>```javascript <add>void componentWillReceiveProps( <add> object nextProps, object nextContext <add>) <add> <add>boolean shouldComponentUpdate( <add> object nextProps, object nextState, object nextContext <add>) <add> <add>void componentWillUpdate( <add> object nextProps, object nextState, object nextContext <add>) <add> <add>void componentDidUpdate( <add> object prevProps, object prevState, object prevContext <add>) <add>``` <add> <add>## Referencing context in stateless functional components <add> <add>Stateless functional components are also able to reference `context` if `contextTypes` is defined as a property of the function. The following code shows the `Button` component above written as a stateless functional component. <add> <add>```javascript <add>function Button(props, context) { <add> return ( <add> <button style={{'{{'}}background: context.color}}> <add> {props.children} <add> </button> <add> ); <add>} <add>Button.contextTypes = {color: React.PropTypes.string}; <add>``` <add> <ide> ## When not to use context <ide> <ide> Just as global variables are best avoided when writing clear code, you should avoid using context in most cases. In particular, think twice before using it to "save typing" and using it instead of passing explicit props.
2
Python
Python
add hamming distance
89fc7bf0b024e4c9508db80f575efd5b5616f932
<ide><path>strings/hamming_distance.py <add>def hamming_distance(string1: str, string2: str) -> int: <add> """Calculate the Hamming distance between two equal length strings <add> In information theory, the Hamming distance between two strings of equal <add> length is the number of positions at which the corresponding symbols are <add> different. https://en.wikipedia.org/wiki/Hamming_distance <add> <add> Args: <add> string1 (str): Sequence 1 <add> string2 (str): Sequence 2 <add> <add> Returns: <add> int: Hamming distance <add> <add> >>> hamming_distance("python", "python") <add> 0 <add> >>> hamming_distance("karolin", "kathrin") <add> 3 <add> >>> hamming_distance("00000", "11111") <add> 5 <add> >>> hamming_distance("karolin", "kath") <add> ValueError: String lengths must match! <add> """ <add> if len(string1) != len(string2): <add> raise ValueError("String lengths must match!") <add> <add> count = 0 <add> <add> for char1, char2 in zip(string1, string2): <add> if char1 != char2: <add> count += 1 <add> <add> return count <add> <add> <add>if __name__ == "__main__": <add> <add> import doctest <add> <add> doctest.testmod()
1
Python
Python
add start date to ``trigger_dagrun`` operator
6609e9a50f0ab593e347bfa92f56194334f5a94d
<ide><path>airflow/api/common/experimental/trigger_dag.py <ide> def _trigger_dag( <ide> trigger = _dag.create_dagrun( <ide> run_id=run_id, <ide> execution_date=execution_date, <del> state=State.RUNNING, <add> state=State.QUEUED, <ide> conf=run_conf, <ide> external_trigger=True, <ide> dag_hash=dag_bag.dags_hash.get(dag_id), <ide><path>tests/api/client/test_local_client.py <ide> def test_trigger_dag(self, mock): <ide> mock.assert_called_once_with( <ide> run_id=run_id, <ide> execution_date=EXECDATE_NOFRACTIONS, <del> state=State.RUNNING, <add> state=State.QUEUED, <ide> conf=None, <ide> external_trigger=True, <ide> dag_hash=ANY, <ide> def test_trigger_dag(self, mock): <ide> mock.assert_called_once_with( <ide> run_id=run_id, <ide> execution_date=EXECDATE_NOFRACTIONS, <del> state=State.RUNNING, <add> state=State.QUEUED, <ide> conf=None, <ide> external_trigger=True, <ide> dag_hash=ANY, <ide> def test_trigger_dag(self, mock): <ide> mock.assert_called_once_with( <ide> run_id=custom_run_id, <ide> execution_date=EXECDATE_NOFRACTIONS, <del> state=State.RUNNING, <add> state=State.QUEUED, <ide> conf=None, <ide> external_trigger=True, <ide> dag_hash=ANY, <ide> def test_trigger_dag(self, mock): <ide> mock.assert_called_once_with( <ide> run_id=run_id, <ide> execution_date=EXECDATE_NOFRACTIONS, <del> state=State.RUNNING, <add> state=State.QUEUED, <ide> conf=json.loads(conf), <ide> external_trigger=True, <ide> dag_hash=ANY, <ide><path>tests/operators/test_trigger_dagrun.py <ide> def test_trigger_dagrun_with_wait_for_completion_true(self): <ide> execution_date=execution_date, <ide> wait_for_completion=True, <ide> poke_interval=10, <del> allowed_states=[State.RUNNING], <add> allowed_states=[State.QUEUED], <ide> dag=self.dag, <ide> ) <ide> task.run(start_date=execution_date, end_date=execution_date) <ide> def test_trigger_dagrun_with_wait_for_completion_true_fail(self): <ide> execution_date=execution_date, <ide> wait_for_completion=True, <ide> poke_interval=10, <del> failed_states=[State.RUNNING], <add> failed_states=[State.QUEUED], <ide> dag=self.dag, <ide> ) <ide> with pytest.raises(AirflowException): <ide> task.run(start_date=execution_date, end_date=execution_date) <add> <add> def test_trigger_dagrun_triggering_itself(self): <add> """Test TriggerDagRunOperator that triggers itself""" <add> execution_date = DEFAULT_DATE <add> task = TriggerDagRunOperator( <add> task_id="test_task", <add> trigger_dag_id=self.dag.dag_id, <add> dag=self.dag, <add> ) <add> task.run(start_date=execution_date, end_date=execution_date) <add> <add> with create_session() as session: <add> dagruns = ( <add> session.query(DagRun) <add> .filter(DagRun.dag_id == self.dag.dag_id) <add> .order_by(DagRun.execution_date) <add> .all() <add> ) <add> assert len(dagruns) == 2 <add> assert dagruns[1].state == State.QUEUED <add> <add> def test_trigger_dagrun_triggering_itself_with_execution_date(self): <add> """Test TriggerDagRunOperator that triggers itself with execution date, <add> fails with DagRunAlreadyExists""" <add> execution_date = DEFAULT_DATE <add> task = TriggerDagRunOperator( <add> task_id="test_task", <add> trigger_dag_id=self.dag.dag_id, <add> execution_date=execution_date, <add> dag=self.dag, <add> ) <add> with pytest.raises(DagRunAlreadyExists): <add> task.run(start_date=execution_date, end_date=execution_date) <ide><path>tests/www/api/experimental/test_dag_runs_endpoint.py <ide> def test_get_dag_runs_success(self): <ide> assert data[0]['id'] == dag_run.id <ide> <ide> def test_get_dag_runs_success_with_state_parameter(self): <del> url_template = '/api/experimental/dags/{}/dag_runs?state=running' <add> url_template = '/api/experimental/dags/{}/dag_runs?state=queued' <ide> dag_id = 'example_bash_operator' <ide> # Create DagRun <ide> dag_run = trigger_dag(dag_id=dag_id, run_id='test_get_dag_runs_success') <ide> def test_get_dag_runs_success_with_state_parameter(self): <ide> assert data[0]['id'] == dag_run.id <ide> <ide> def test_get_dag_runs_success_with_capital_state_parameter(self): <del> url_template = '/api/experimental/dags/{}/dag_runs?state=RUNNING' <add> url_template = '/api/experimental/dags/{}/dag_runs?state=QUEUED' <ide> dag_id = 'example_bash_operator' <ide> # Create DagRun <ide> dag_run = trigger_dag(dag_id=dag_id, run_id='test_get_dag_runs_success')
4
Text
Text
update version install commands in upgrade guide
cff07455e783a3b53a7765113bf231032fca0cbc
<ide><path>docs/upgrading.md <ide> description: Learn how to upgrade Next.js. <ide> To update to Next.js version 13, run the following command using your preferred package manager: <ide> <ide> ```bash <del>npm install next react@latest react-dom@latest eslint-config-next <add>npm i next@latest react@latest react-dom@latest eslint-config-next@latest <ide> # or <del>yarn add next react@latest react-dom@latest eslint-config-next <add>yarn upgrade next react react-dom eslint-config-next --latest <ide> # or <del>pnpm update next react@latest react-dom@latest eslint-config-next <add>pnpm up next react react-dom eslint-config-next --latest <ide> ``` <ide> <ide> ### v13 Summary
1
Go
Go
allow add of empty name
4dec36d1ee8cfd8b396210daa5367d146bbb34bc
<ide><path>pkg/netlink/netlink_linux.go <ide> func NetworkLinkAdd(name string, linkType string) error { <ide> msg := newIfInfomsg(syscall.AF_UNSPEC) <ide> wb.AddData(msg) <ide> <del> nameData := newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(name)) <del> wb.AddData(nameData) <add> if name != "" { <add> nameData := newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(name)) <add> wb.AddData(nameData) <add> } <ide> <ide> kindData := newRtAttr(IFLA_INFO_KIND, nonZeroTerminated(linkType)) <ide>
1
Text
Text
fix distribution strategy
bca18d0b0290418b13f3da10dbdb8edc127131f2
<ide><path>official/nlp/bert/README.md <ide> python run_classifier.py \ <ide> --learning_rate=2e-5 \ <ide> --num_train_epochs=3 \ <ide> --model_dir=${MODEL_DIR} \ <del> --distribution_strategy=mirror <add> --distribution_strategy=mirrored <ide> ``` <ide> <ide> To use TPU, you only need to switch distribution strategy type to `tpu` with TPU <ide> python run_squad.py \ <ide> --learning_rate=8e-5 \ <ide> --num_train_epochs=2 \ <ide> --model_dir=${MODEL_DIR} \ <del> --distribution_strategy=mirror <add> --distribution_strategy=mirrored <ide> ``` <ide> <ide> To use TPU, you need switch distribution strategy type to `tpu` with TPU
1
Python
Python
standardize aws kinesis/firehose naming
f6a41a036d450020917d5862f627e606d0d36ac0
<ide><path>airflow/providers/amazon/aws/hooks/kinesis.py <ide> # under the License. <ide> <ide> """This module contains AWS Firehose hook""" <add>import warnings <ide> from typing import Iterable <ide> <ide> from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook <ide> <ide> <del>class AwsFirehoseHook(AwsBaseHook): <add>class FirehoseHook(AwsBaseHook): <ide> """ <ide> Interact with AWS Kinesis Firehose. <ide> <ide> def put_records(self, records: Iterable): <ide> response = self.get_conn().put_record_batch(DeliveryStreamName=self.delivery_stream, Records=records) <ide> <ide> return response <add> <add> <add>class AwsFirehoseHook(FirehoseHook): <add> """ <add> This hook is deprecated. <add> Please use :class:`airflow.providers.amazon.aws.hooks.kinesis.FirehoseHook`. <add> """ <add> <add> def __init__(self, *args, **kwargs): <add> warnings.warn( <add> "This hook is deprecated. " <add> "Please use :class:`airflow.providers.amazon.aws.hooks.kinesis.FirehoseHook`.", <add> DeprecationWarning, <add> stacklevel=2, <add> ) <add> super().__init__(*args, **kwargs) <ide><path>tests/providers/amazon/aws/hooks/test_kinesis.py <ide> import boto3 <ide> import pytest <ide> <del>from airflow.providers.amazon.aws.hooks.kinesis import AwsFirehoseHook <add>from airflow.providers.amazon.aws.hooks.kinesis import FirehoseHook <ide> <ide> try: <ide> from moto import mock_firehose, mock_s3 <ide> <ide> <ide> @pytest.mark.skipif(mock_firehose is None, reason='moto package not present') <del>class TestAwsFirehoseHook: <add>class TestFirehoseHook: <ide> @mock_firehose <ide> def test_get_conn_returns_a_boto3_connection(self): <del> hook = AwsFirehoseHook( <add> hook = FirehoseHook( <ide> aws_conn_id='aws_default', delivery_stream="test_airflow", region_name="us-east-1" <ide> ) <ide> assert hook.get_conn() is not None <ide> def test_get_conn_returns_a_boto3_connection(self): <ide> @mock_s3 <ide> def test_insert_batch_records_kinesis_firehose(self): <ide> boto3.client('s3').create_bucket(Bucket='kinesis-test') <del> hook = AwsFirehoseHook( <add> hook = FirehoseHook( <ide> aws_conn_id='aws_default', delivery_stream="test_airflow", region_name="us-east-1" <ide> ) <ide>
2
Javascript
Javascript
add an additional hook
1f651d6fcb1c85581833eb68061e8fb3d478b9e1
<ide><path>lib/Compilation.js <ide> Compilation.prototype.seal = function seal(callback) { <ide> this.applyPlugins("optimize-chunks", this.chunks); <ide> this.applyPlugins("after-optimize-chunks", this.chunks); <ide> <del> this.applyPluginsAsyncSeries("optimize-tree", this.chunks, this.modules, function(err) { <add> this.applyPluginsAsync("optimize-tree", this.chunks, this.modules, function(err) { <ide> if(err) return callback(err); <ide> <ide> this.applyPlugins("revive-modules", this.modules, this.records); <ide> Compilation.prototype.seal = function seal(callback) { <ide> this.summarizeDependencies(); <ide> this.applyPlugins("record", this, this.records); <ide> <del> this.applyPluginsAsync("optimize-chunk-assets", this.chunks, function(err) { <add> this.applyPluginsAsync("additional-assets", function(err) { <ide> if(err) return callback(err); <del> this.applyPlugins("after-optimize-chunk-assets", this.chunks); <del> this.applyPluginsAsync("optimize-assets", this.assets, function(err) { <add> this.applyPluginsAsync("optimize-chunk-assets", this.chunks, function(err) { <ide> if(err) return callback(err); <del> this.applyPlugins("after-optimize-assets", this.assets); <del> return callback(); <add> this.applyPlugins("after-optimize-chunk-assets", this.chunks); <add> this.applyPluginsAsync("optimize-assets", this.assets, function(err) { <add> if(err) return callback(err); <add> this.applyPlugins("after-optimize-assets", this.assets); <add> return callback(); <add> }.bind(this)); <ide> }.bind(this)); <ide> }.bind(this)); <ide> }.bind(this));
1
Python
Python
fix wrong reference name/filename in docstring
adfe6ace8839031a4bfe1a9ae12347da3c73c0b4
<ide><path>src/transformers/data/processors/squad.py <ide> def get_dev_examples(self, data_dir, filename=None): <ide> Args: <ide> data_dir: Directory containing the data files used for training and evaluating. <ide> filename: None by default, specify this if the evaluation file has a different name than the original one <del> which is `train-v1.1.json` and `train-v2.0.json` for squad versions 1.1 and 2.0 respectively. <add> which is `dev-v1.1.json` and `dev-v2.0.json` for squad versions 1.1 and 2.0 respectively. <ide> """ <ide> if data_dir is None: <ide> data_dir = ""
1
Python
Python
add load and memswap
dad4d2846d43489d6b0f8fb29afe923384a06170
<ide><path>glances/outputs/glances_stdout_fields.py <ide> def update(self, <ide> """ <ide> print('.. _apidoc:') <ide> print('') <del> print('API documentation') <del> print('=================') <add> print('Restfull/API plugins documentation') <add> print('==================================') <add> print('') <add> print('The Glanes Restfull/API server could be ran using the following command line:') <add> print('') <add> print('.. code-block:: bash') <add> print('') <add> print(' # glances -w --disable-webui') <ide> print('') <ide> for plugin in sorted(stats._plugins): <del> print('{}'.format(plugin)) <del> print('-' * len(plugin)) <ide> if stats._plugins[plugin].fields_description: <add> print('{}'.format(plugin)) <add> print('-' * len(plugin)) <ide> print('') <ide> for field, description in iteritems(stats._plugins[plugin].fields_description): <ide> print('* **{}**: {} (unit is *{}*)'.format(field, <ide> description['description'][:-1] if description['description'].endswith('.') else description['description'], <ide> description['unit'])) <ide> print('') <del> print('Output example:') <add> print('GET {} plugin stats:'.format(plugin)) <ide> print('') <ide> print('.. code-block:: json') <ide> print('') <ide><path>glances/plugins/glances_cpu.py <ide> 0 on Windows and SunOS.', <ide> 'unit': 'percent'}, <ide> 'cpucore': {'description': 'Total number of CPU core.', <del> 'unit': 'count'}, <add> 'unit': 'number'}, <ide> 'time_since_update': {'description': 'Number of seconds since last update.', <ide> 'unit': 'seconds'}, <ide> } <ide><path>glances/plugins/glances_load.py <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> from glances.logger import logger <ide> <add># Fields description <add>fields_description = { <add> 'min1': {'description': 'Average sum of the number of processes \ <add>waiting in the run-queue plus the number currently executing \ <add>over 1 minute.', <add> 'unit': 'number'}, <add> 'min5': {'description': 'Average sum of the number of processes \ <add>waiting in the run-queue plus the number currently executing \ <add>over 5 minutes.', <add> 'unit': 'number'}, <add> 'min15': {'description': 'Average sum of the number of processes \ <add>waiting in the run-queue plus the number currently executing \ <add>over 15 minutes.', <add> 'unit': 'number'}, <add> 'cpucore': {'description': 'Total number of CPU core.', <add> 'unit': 'number'}, <add>} <add> <ide> # SNMP OID <ide> # 1 minute Load: .1.3.6.1.4.1.2021.10.1.3.1 <ide> # 5 minute Load: .1.3.6.1.4.1.2021.10.1.3.2 <ide> def __init__(self, args=None, config=None): <ide> """Init the plugin.""" <ide> super(Plugin, self).__init__(args=args, <ide> config=config, <del> items_history_list=items_history_list) <add> items_history_list=items_history_list, <add> fields_description=fields_description) <ide> <ide> # We want to display the stat in the curse interface <ide> self.display_curse = True <ide><path>glances/plugins/glances_memswap.py <ide> """Swap memory plugin.""" <ide> <ide> from glances.compat import iterkeys <add>from glances.timer import getTimeSinceLastUpdate <ide> from glances.plugins.glances_plugin import GlancesPlugin <ide> <ide> import psutil <ide> <add># Fields description <add> # total: total swap memory in bytes <add> # used: used swap memory in bytes <add> # free: free swap memory in bytes <add> # percent: the percentage usage <add> # sin: the number of bytes the system has swapped in from disk (cumulative) <add> # sout: the number of bytes the system has swapped out from disk (cumulative) <add>fields_description = { <add> 'total': {'description': 'Total swap memory.', <add> 'unit': 'bytes'}, <add> 'used': {'description': 'Used swap memory.', <add> 'unit': 'bytes'}, <add> 'free': {'description': 'Free swap memory.', <add> 'unit': 'bytes'}, <add> 'percent': {'description': 'Used swap memory in percentage.', <add> 'unit': 'percent'}, <add> 'sin': {'description': 'The number of bytes the system has swapped in from disk (cumulative).', <add> 'unit': 'bytes'}, <add> 'sout': {'description': 'The number of bytes the system has swapped out from disk (cumulative).', <add> 'unit': 'bytes'}, <add> 'time_since_update': {'description': 'Number of seconds since last update.', <add> 'unit': 'seconds'}, <add>} <add> <ide> # SNMP OID <ide> # Total Swap Size: .1.3.6.1.4.1.2021.4.3.0 <ide> # Available Swap Space: .1.3.6.1.4.1.2021.4.4.0 <ide> def __init__(self, args=None, config=None): <ide> """Init the plugin.""" <ide> super(Plugin, self).__init__(args=args, <ide> config=config, <del> items_history_list=items_history_list) <add> items_history_list=items_history_list, <add> fields_description=fields_description) <ide> <ide> # We want to display the stat in the curse interface <ide> self.display_curse = True <ide> def update(self): <ide> # free: free swap memory in bytes <ide> # percent: the percentage usage <ide> # sin: the number of bytes the system has swapped in from disk (cumulative) <del> # sout: the number of bytes the system has swapped out from disk <del> # (cumulative) <add> # sout: the number of bytes the system has swapped out from disk (cumulative) <ide> for swap in ['total', 'used', 'free', 'percent', <ide> 'sin', 'sout']: <ide> if hasattr(sm_stats, swap): <ide> stats[swap] = getattr(sm_stats, swap) <add> <add> # By storing time data we enable sin/s and sout/s calculations in the <add> # XML/RPC API, which would otherwise be overly difficult work <add> # for users of the API <add> stats['time_since_update'] = getTimeSinceLastUpdate('memswap') <ide> elif self.input_method == 'snmp': <ide> # Update stats using SNMP <ide> if self.short_system_name == 'windows':
4
Text
Text
release notes for 3.0.1
0188ca730674e41717ba914d38c8bf9582abdb0c
<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>### 3.0.1 <add> <add>**Date**: [December 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%223.0.1+Release%22) <add> <add>* Documentation improvements <add>* More helpful error message when the default `.create` fails (#2013) <add>* Raise error when attempting to save serializer if data is not valid. (#2098) <add>* Fix `FileUploadParser` breaks with empty file names and multiple upload handlers (#2109) <add>* Imporve BindingDict to support standard dict-functions (#2135, #2163) <add>* Add `validate` to `ListSerializer` (#2168, #2225, #2232) <add>* Fix JSONP renderer failing to escape some characters (#2169, #2195) <add>* Add missing default style for FileField (#2172) <add>* Actions are required when calling viewset.as_view() (#2175) <add>* Add allow_blank to ChoiceField (#2184, #2239) <add>* Cosmetic fixes in the HTML renderer (#2187) <add>* Raise error if `fields` on serializer is not a list of strings. (#2193, #2213) <add>* Improve checks for nested creates and updates. (#2194, #2196) <add>* `validated_attrs` argument renamed to `validated_data` in Serializer's `create`/`update` (#2197) <add>* Remove deprecated code to reflect the droped Django versions (#2200) <add>* Better serializer errors for nested writes. (#2202, #2215) <add>* Fix Pagination and custom permissions incompatibility (#2205) <add>* Raise error if `fields` on serializer is not a list of strings. (#2213) <add>* Add missing translation markers for relational fields. (#2231) <add>* Improve field lookup behavior for dicts/mappings. (#2244, #2243) <add>* Optimized hyperlinked PK (#2242) <add> <ide> ### 3.0.0 <ide> <ide> **Date**: 1st December 2014
1
Python
Python
add ignore_index crossentropy and iou
b7f02816b5320855ae528971766fdcaad7134a9b
<ide><path>keras/backend.py <ide> def softsign(x): <ide> return tf.math.softsign(x) <ide> <ide> <add>def _get_logits(output, from_logits, op_type, fn_name): <add> output_ = output <add> from_logits_ = from_logits <add> <add> has_keras_logits = hasattr(output, "_keras_logits") <add> if has_keras_logits: <add> output_ = output._keras_logits <add> from_logits_ = True <add> <add> from_expected_op_type = ( <add> not isinstance(output, (tf.__internal__.EagerTensor, tf.Variable)) <add> and output.op.type == op_type <add> ) and not has_keras_logits <add> <add> if from_expected_op_type: <add> # When softmax activation function is used for output operation, we <add> # use logits from the softmax function directly to compute loss in order <add> # to prevent collapsing zero when training. <add> # See b/117284466 <add> assert len(output.op.inputs) == 1 <add> output_ = output.op.inputs[0] <add> from_logits_ = True <add> <add> if from_logits and (has_keras_logits or from_expected_op_type): <add> warnings.warn( <add> f'"`{fn_name}` received `from_logits=True`, but ' <add> f"the `output` argument was produced by a {op_type} " <add> "activation and thus does not represent logits. " <add> "Was this intended?", <add> stacklevel=2, <add> ) <add> <add> return output_, from_logits_ <add> <add> <ide> @keras_export("keras.backend.categorical_crossentropy") <ide> @tf.__internal__.dispatch.add_dispatch_support <ide> @doc_controls.do_not_generate_docs <ide> def categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> output = tf.convert_to_tensor(output) <ide> target.shape.assert_is_compatible_with(output.shape) <ide> <del> # Use logits whenever they are available. `softmax` and `sigmoid` <del> # activations cache logits on the `output` Tensor. <del> if hasattr(output, "_keras_logits"): <del> output = output._keras_logits <del> if from_logits: <del> warnings.warn( <del> '"`categorical_crossentropy` received `from_logits=True`, but ' <del> "the `output` argument was produced by a sigmoid or softmax " <del> "activation and thus does not represent logits. " <del> "Was this intended?", <del> stacklevel=2, <del> ) <del> from_logits = True <del> <add> output, from_logits = _get_logits( <add> output, from_logits, "Softmax", "categorical_crossentropy" <add> ) <ide> if from_logits: <ide> return tf.nn.softmax_cross_entropy_with_logits( <ide> labels=target, logits=output, axis=axis <ide> ) <ide> <del> if ( <del> not isinstance(output, (tf.__internal__.EagerTensor, tf.Variable)) <del> and output.op.type == "Softmax" <del> ) and not hasattr(output, "_keras_history"): <del> # When softmax activation function is used for output operation, we <del> # use logits from the softmax function directly to compute loss in order <del> # to prevent collapsing zero when training. <del> # See b/117284466 <del> assert len(output.op.inputs) == 1 <del> output = output.op.inputs[0] <del> return tf.nn.softmax_cross_entropy_with_logits( <del> labels=target, logits=output, axis=axis <del> ) <del> <ide> # scale preds so that the class probas of each sample sum to 1 <ide> output = output / tf.reduce_sum(output, axis, True) <ide> # Compute cross entropy from probabilities. <ide> def categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> @keras_export("keras.backend.sparse_categorical_crossentropy") <ide> @tf.__internal__.dispatch.add_dispatch_support <ide> @doc_controls.do_not_generate_docs <del>def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): <add>def sparse_categorical_crossentropy( <add> target, output, from_logits=False, axis=-1, ignore_index=None <add>): <ide> """Categorical crossentropy with integer targets. <ide> <ide> Args: <ide> def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> axis: Int specifying the channels axis. `axis=-1` corresponds to data <ide> format `channels_last`, and `axis=1` corresponds to data format <ide> `channels_first`. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the entropy equation nor in gradient computation. This <add> is useful in segmentation problems containing the *void* label <add> (commonly -1 or 255) in its annotated segmentation maps. <add> By default, all label ids are considered. If `ignore_index` is not <add> `None` and the output is a tensor with `rank>=3`, then the valid <add> entries will be averaged over the axes `range(1, output_rank-1)`, <add> resulting in an output of shape `[batch]`. <ide> <ide> Returns: <ide> Output tensor. <ide> def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> target = tf.convert_to_tensor(target) <ide> output = tf.convert_to_tensor(output) <ide> <del> # Use logits whenever they are available. `softmax` and `sigmoid` <del> # activations cache logits on the `output` Tensor. <del> if hasattr(output, "_keras_logits"): <del> output = output._keras_logits <del> if from_logits: <del> warnings.warn( <del> '"`sparse_categorical_crossentropy` received ' <del> "`from_logits=True`, but the `output` argument " <del> "was produced by a sigmoid or softmax activation " <del> 'and thus does not represent logits. Was this intended?"', <del> stacklevel=2, <del> ) <del> from_logits = True <del> elif ( <del> not from_logits <del> and not isinstance(output, (tf.__internal__.EagerTensor, tf.Variable)) <del> and output.op.type == "Softmax" <del> ) and not hasattr(output, "_keras_history"): <del> # When softmax activation function is used for output operation, we <del> # use logits from the softmax function directly to compute loss in order <del> # to prevent collapsing zero when training. <del> # See b/117284466 <del> assert len(output.op.inputs) == 1 <del> output = output.op.inputs[0] <del> from_logits = True <del> elif not from_logits: <add> target = cast(target, "int64") <add> <add> output, from_logits = _get_logits( <add> output, from_logits, "Softmax", "sparse_categorical_crossentropy" <add> ) <add> if not from_logits: <ide> epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype) <ide> output = tf.clip_by_value(output, epsilon_, 1 - epsilon_) <ide> output = tf.math.log(output) <ide> <add> # Permute output so that the last axis contains the logits/probabilities. <ide> if isinstance(output.shape, (tuple, list)): <ide> output_rank = len(output.shape) <ide> else: <ide> def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> "on an output tensor with unknown rank".format(axis) <ide> ) <ide> <del> target = cast(target, "int64") <del> <ide> # Try to adjust the shape so that rank of labels = rank of logits - 1. <ide> output_shape = tf.shape(output) <ide> target_rank = target.shape.ndims <ide> def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> target = flatten(target) <ide> output = tf.reshape(output, [-1, output_shape[-1]]) <ide> <add> if ignore_index is not None: <add> valid_mask = tf.not_equal(target, ignore_index) <add> target = target[valid_mask] <add> output = output[valid_mask] <add> <ide> if py_any(_is_symbolic_tensor(v) for v in [target, output]): <ide> with get_graph().as_default(): <ide> res = tf.nn.sparse_softmax_cross_entropy_with_logits( <ide> def sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1): <ide> labels=target, logits=output <ide> ) <ide> <del> if update_shape and output_rank >= 3: <del> # If our output includes timesteps or spatial dimensions we need to <del> # reshape <del> return tf.reshape(res, output_shape[:-1]) <del> else: <add> if ignore_index is not None: <add> res_shape = cast(output_shape[:-1], "int64") <add> valid_mask = tf.reshape(valid_mask, res_shape) <add> <add> res = tf.scatter_nd(tf.where(valid_mask), res, res_shape) <add> <add> if output_rank is not None and output_rank >= 3: <add> # The output is a 2-dimensional (or higher) label map, <add> # and some pixels might be zero. We reduce the loss among the <add> # valid entries to prevent an artificial decrease of the loss <add> # value when many of them are invalid. <add> reduce_axis = list(range(1, output_rank - 1)) <add> res = tf.math.divide_no_nan( <add> tf.reduce_sum(res, axis=reduce_axis), <add> tf.reduce_sum(cast(valid_mask, res.dtype), axis=reduce_axis), <add> ) <add> <ide> return res <ide> <add> if update_shape and output_rank >= 3: <add> # If our output includes timesteps or <add> # spatial dimensions we need to reshape <add> res = tf.reshape(res, output_shape[:-1]) <add> <add> return res <add> <ide> <ide> @keras_export("keras.backend.binary_crossentropy") <ide> @tf.__internal__.dispatch.add_dispatch_support <ide> def binary_crossentropy(target, output, from_logits=False): <ide> target = tf.convert_to_tensor(target) <ide> output = tf.convert_to_tensor(output) <ide> <del> # Use logits whenever they are available. `softmax` and `sigmoid` <del> # activations cache logits on the `output` Tensor. <del> if hasattr(output, "_keras_logits"): <del> output = output._keras_logits <del> if from_logits: <del> warnings.warn( <del> '"`binary_crossentropy` received `from_logits=True`, ' <del> "but the `output` argument was produced by a sigmoid " <del> "or softmax activation and thus " <del> 'does not represent logits. Was this intended?"', <del> stacklevel=2, <del> ) <del> from_logits = True <del> <add> output, from_logits = _get_logits( <add> output, from_logits, "Sigmoid", "binary_crossentropy" <add> ) <ide> if from_logits: <ide> return tf.nn.sigmoid_cross_entropy_with_logits( <ide> labels=target, logits=output <ide> ) <ide> <del> if ( <del> not isinstance(output, (tf.__internal__.EagerTensor, tf.Variable)) <del> and output.op.type == "Sigmoid" <del> ) and not hasattr(output, "_keras_history"): <del> # When sigmoid activation function is used for output operation, we <del> # use logits from the sigmoid function directly to compute loss in order <del> # to prevent collapsing zero when training. <del> assert len(output.op.inputs) == 1 <del> output = output.op.inputs[0] <del> return tf.nn.sigmoid_cross_entropy_with_logits( <del> labels=target, logits=output <del> ) <del> <ide> epsilon_ = _constant_to_tensor(epsilon(), output.dtype.base_dtype) <ide> output = tf.clip_by_value(output, epsilon_, 1.0 - epsilon_) <ide> <ide><path>keras/backend_test.py <ide> def test_sparse_categorical_crossentropy_loss(self): <ide> ) <ide> self.assertArrayNear(self.evaluate(result)[0], [0.002, 0, 0.17], 1e-3) <ide> <add> @test_combinations.generate( <add> test_combinations.combine(mode=["graph", "eager"]) <add> ) <add> def test_sparse_categorical_crossentropy_loss_with_ignore_index(self): <add> t = backend.constant([255, 1, 2, 2]) <add> p = backend.softmax( <add> backend.constant( <add> [ <add> [1.8, 1.2, 0.5], <add> [0.2, 3.8, 0.8], <add> [1.1, 0.4, 3.4], <add> [1.3, 0.7, 3.8], <add> ] <add> ) <add> ) <add> result = backend.sparse_categorical_crossentropy(t, p, ignore_index=255) <add> self.assertArrayNear( <add> self.evaluate(result), <add> [0.0, 0.07428224, 0.13980183, 0.11967831], <add> 1e-3, <add> ) <add> <add> t = backend.constant([-1, 1, 2, 2]) <add> p = backend.constant( <add> [ <add> [1.8, 1.2, 0.5], <add> [0.2, 3.8, 0.8], <add> [1.1, 0.4, 3.4], <add> [1.3, 0.7, 3.8], <add> ] <add> ) <add> result = backend.sparse_categorical_crossentropy( <add> t, p, ignore_index=-1, from_logits=True <add> ) <add> self.assertArrayNear( <add> self.evaluate(result), <add> [0.0, 0.07428224, 0.13980183, 0.11967831], <add> 1e-3, <add> ) <add> <add> @test_combinations.generate( <add> test_combinations.combine(mode=["graph", "eager"]) <add> ) <add> def test_sparse_cce_loss_with_ignore_index_for_segmentation(self): <add> t = backend.constant( <add> [ <add> [[0, 2], [-1, -1]], <add> [[0, 2], [-1, -1]], <add> ] <add> ) <add> p = backend.constant( <add> [ <add> [ <add> [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], <add> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]], <add> ], <add> [ <add> [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]], <add> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]], <add> ], <add> ] <add> ) <add> <add> result = backend.sparse_categorical_crossentropy(t, p, ignore_index=-1) <add> self.assertArrayNear( <add> self.evaluate(result), [2.3841855e-07, 3.4657377e-01], 1e-3 <add> ) <add> <ide> @test_combinations.generate(test_combinations.combine(mode=["graph"])) <ide> def test_sparse_categorical_crossentropy_loss_with_unknown_rank_tensor( <ide> self, <ide><path>keras/losses.py <ide> def _ragged_tensor_categorical_crossentropy( <ide> "keras.losses.sparse_categorical_crossentropy", <ide> ) <ide> @tf.__internal__.dispatch.add_dispatch_support <del>def sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1): <add>def sparse_categorical_crossentropy( <add> y_true, y_pred, from_logits=False, axis=-1, ignore_index=None <add>): <ide> """Computes the sparse categorical crossentropy loss. <ide> <ide> Standalone usage: <ide> def sparse_categorical_crossentropy(y_true, y_pred, from_logits=False, axis=-1): <ide> >>> loss.numpy() <ide> array([0.0513, 2.303], dtype=float32) <ide> <add> >>> y_true = [[[ 0, 2], <add> ... [-1, -1]], <add> ... [[ 0, 2], <add> ... [-1, -1]]] <add> >>> y_pred = [[[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], <add> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]]], <add> [[[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]], <add> [[0.2, 0.5, 0.3], [0.0, 1.0, 0.0]]]] <add> >>> loss = tf.keras.losses.sparse_categorical_crossentropy( <add> ... y_true, y_pred, ignore_index=-1) <add> >>> assert loss.shape == (2,) <add> >>> loss.numpy() <add> array([2.3841855e-07, 3.4657377e-01], dtype=float32) <add> <ide> Args: <ide> y_true: Ground truth values. <ide> y_pred: The predicted values. <ide> from_logits: Whether `y_pred` is expected to be a logits tensor. By <ide> default, we assume that `y_pred` encodes a probability distribution. <ide> axis: Defaults to -1. The dimension along which the entropy is <ide> computed. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the entropy equation nor in gradient computation. This <add> is useful in segmentation problems containing the *void* label <add> (commonly -1 or 255) in its annotated segmentation maps. <add> By default, all label ids are considered. If `ignore_index` is not <add> `None` and the output is a tensor with `rank>=3`, then the valid <add> entries will be averaged over the axes `range(1, output_rank-1)`, <add> resulting in an output of shape `[batch]`. <ide> <ide> Returns: <ide> Sparse categorical crossentropy loss value. <ide> """ <ide> y_pred = tf.convert_to_tensor(y_pred) <ide> <ide> return backend.sparse_categorical_crossentropy( <del> y_true, y_pred, from_logits=from_logits, axis=axis <add> y_true, <add> y_pred, <add> from_logits=from_logits, <add> ignore_index=ignore_index, <add> axis=axis, <ide> ) <ide> <ide> <ide> @dispatch.dispatch_for_types(sparse_categorical_crossentropy, tf.RaggedTensor) <ide> def _ragged_tensor_sparse_categorical_crossentropy( <del> y_true, y_pred, from_logits=False, axis=-1 <add> y_true, y_pred, from_logits=False, axis=-1, ignore_index=None <ide> ): <ide> """Implements support for handling RaggedTensors. <ide> <ide> def _ragged_tensor_sparse_categorical_crossentropy( <ide> the sum of the individual loss values divided by 3. <ide> """ <ide> fn = functools.partial( <del> sparse_categorical_crossentropy, from_logits=from_logits, axis=axis <add> sparse_categorical_crossentropy, <add> from_logits=from_logits, <add> ignore_index=ignore_index, <add> axis=axis, <ide> ) <ide> return _ragged_tensor_apply_loss(fn, y_true, y_pred, y_pred_extra_dim=True) <ide> <ide><path>keras/losses_test.py <ide> def test_sparse_categorical_crossentropy_loss(self): <ide> atol=1e-5, <ide> ) <ide> <add> @test_combinations.generate( <add> test_combinations.combine(mode=["graph", "eager"]) <add> ) <add> def test_sparse_categorical_crossentropy_loss_with_ignore_index(self): <add> ignore_index = 255 <add> target = backend.variable(np.random.randint(0, 1, (5, 1))) <add> logits = backend.variable(np.random.random((5, 1))) <add> softmax_output = backend.softmax(logits) <add> <add> valid_entries = tf.reshape( <add> tf.constant([0, 1, 0, 1, 1], target.dtype), (5, 1) <add> ) <add> target.assign( <add> target * valid_entries + (1 - valid_entries) * ignore_index <add> ) <add> <add> output_from_logit = losses.sparse_categorical_crossentropy( <add> target, logits, ignore_index=ignore_index, from_logits=True <add> ) <add> output_from_softmax = losses.sparse_categorical_crossentropy( <add> target, softmax_output, ignore_index=ignore_index <add> ) <add> np.testing.assert_allclose( <add> backend.eval(output_from_logit), <add> backend.eval(output_from_softmax), <add> atol=1e-5, <add> ) <add> <ide> @test_combinations.generate(test_combinations.combine(mode=["graph"])) <ide> def test_sparse_categorical_crossentropy_loss_with_unknown_rank_tensor( <ide> self, <ide><path>keras/metrics/metrics.py <ide> <ide> import abc <ide> from typing import List <add>from typing import Optional <ide> from typing import Tuple <ide> from typing import Union <ide> <ide> class _IoUBase(base_metric.Metric): <ide> `(num_classes, num_classes)` will be allocated. <ide> name: (Optional) string name of the metric instance. <ide> dtype: (Optional) data type of the metric result. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the metric computation. This is useful in segmentation <add> problems containing the *void* label (commonly -1 or 255) in its <add> annotated segmentation maps. By default, all label ids are considered. <add> sparse_labels: Wether labels are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> sparse_preds: Wether predictions are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> axis: (Optional) Defaults to -1. The dimension containing the logits. <add> <ide> """ <ide> <del> def __init__(self, num_classes, name=None, dtype=None): <add> def __init__( <add> self, <add> num_classes: int, <add> name: Optional[str] = None, <add> dtype: Optional[Union[str, tf.dtypes.DType]] = None, <add> ignore_index: Optional[int] = None, <add> sparse_labels: bool = True, <add> sparse_preds: bool = True, <add> axis: int = -1, <add> ): <ide> super().__init__(name=name, dtype=dtype) <ide> self.num_classes = num_classes <add> self.ignore_index = ignore_index <add> self.sparse_labels = sparse_labels <add> self.sparse_preds = sparse_preds <add> self.axis = axis <ide> <ide> # Variable to accumulate the predictions in the confusion matrix. <ide> self.total_cm = self.add_weight( <ide> def update_state(self, y_true, y_pred, sample_weight=None): <ide> Update op. <ide> """ <ide> <add> if not self.sparse_labels: <add> y_true = tf.argmax(y_true, axis=self.axis) <add> if not self.sparse_preds: <add> y_pred = tf.argmax(y_pred, axis=self.axis) <add> <ide> y_true = tf.cast(y_true, self._dtype) <ide> y_pred = tf.cast(y_pred, self._dtype) <ide> <ide> def update_state(self, y_true, y_pred, sample_weight=None): <ide> if y_true.shape.ndims > 1: <ide> y_true = tf.reshape(y_true, [-1]) <ide> <add> if self.ignore_index is not None: <add> valid_mask = tf.not_equal(y_true, self.ignore_index) <add> y_true = y_true[valid_mask] <add> y_pred = y_pred[valid_mask] <add> <ide> if sample_weight is not None: <ide> sample_weight = tf.cast(sample_weight, self._dtype) <ide> if sample_weight.shape.ndims > 1: <ide> class IoU(_IoUBase): <ide> single id value should be provided. <ide> name: (Optional) string name of the metric instance. <ide> dtype: (Optional) data type of the metric result. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the metric computation. This is useful in segmentation <add> problems containing the *void* label (commonly -1 or 255) in its <add> annotated segmentation maps. By default, all label ids are considered. <add> sparse_labels: Wether labels are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> sparse_preds: Wether predictions are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> axis: (Optional) Defaults to -1. The dimension containing the logits. <ide> <ide> Standalone usage: <ide> <ide> def __init__( <ide> self, <ide> num_classes: int, <ide> target_class_ids: Union[List[int], Tuple[int, ...]], <del> name=None, <del> dtype=None, <add> name: Optional[str] = None, <add> dtype: Optional[Union[str, tf.dtypes.DType]] = None, <add> ignore_index: Optional[int] = None, <add> sparse_labels: bool = True, <add> sparse_preds: bool = True, <add> axis: int = -1, <ide> ): <ide> super().__init__( <ide> name=name, <ide> num_classes=num_classes, <add> ignore_index=ignore_index, <add> sparse_labels=sparse_labels, <add> sparse_preds=sparse_preds, <add> axis=axis, <ide> dtype=dtype, <ide> ) <ide> if max(target_class_ids) >= num_classes: <ide> def get_config(self): <ide> config = { <ide> "num_classes": self.num_classes, <ide> "target_class_ids": self.target_class_ids, <add> "ignore_index": self.ignore_index, <add> "sparse_labels": self.sparse_labels, <add> "sparse_preds": self.sparse_preds, <add> "axis": self.axis, <ide> } <ide> base_config = super().get_config() <ide> return dict(list(base_config.items()) + list(config.items())) <ide> class MeanIoU(IoU): <ide> [num_classes, num_classes] will be allocated. <ide> name: (Optional) string name of the metric instance. <ide> dtype: (Optional) data type of the metric result. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the metric computation. This is useful in segmentation <add> problems containing the *void* label (commonly -1 or 255) in its <add> annotated segmentation maps. By default, all label ids are considered. <add> sparse_labels: Wether labels are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> sparse_preds: Wether predictions are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> axis: (Optional) Defaults to -1. The dimension containing the logits. <ide> <ide> Standalone usage: <ide> <ide> class MeanIoU(IoU): <ide> """ <ide> <ide> @dtensor_utils.inject_mesh <del> def __init__(self, num_classes, name=None, dtype=None): <add> def __init__( <add> self, <add> num_classes: int, <add> name: Optional[str] = None, <add> dtype: Optional[Union[str, tf.dtypes.DType]] = None, <add> ignore_index: Optional[int] = None, <add> sparse_labels: bool = True, <add> sparse_preds: bool = True, <add> axis: int = -1, <add> ): <ide> target_class_ids = list(range(num_classes)) <ide> super().__init__( <ide> name=name, <ide> num_classes=num_classes, <ide> target_class_ids=target_class_ids, <add> axis=axis, <ide> dtype=dtype, <add> ignore_index=ignore_index, <add> sparse_labels=sparse_labels, <add> sparse_preds=sparse_preds, <ide> ) <ide> <ide> def get_config(self): <ide> return { <ide> "num_classes": self.num_classes, <ide> "name": self.name, <ide> "dtype": self._dtype, <add> "ignore_index": self.ignore_index, <add> "sparse_labels": self.sparse_labels, <add> "sparse_preds": self.sparse_preds, <add> "axis": self.axis, <ide> } <ide> <ide> <ide> class OneHotIoU(IoU): <ide> single id value should be provided. <ide> name: (Optional) string name of the metric instance. <ide> dtype: (Optional) data type of the metric result. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the metric computation. This is useful in segmentation <add> problems containing the *void* label (commonly -1 or 255) in its <add> annotated segmentation maps. By default, all label ids are considered. <add> sparse_preds: Wether predictions are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> axis: (Optional) Defaults to -1. The dimension containing the logits. <ide> <ide> Standalone usage: <ide> <ide> def __init__( <ide> target_class_ids: Union[List[int], Tuple[int, ...]], <ide> name=None, <ide> dtype=None, <add> ignore_index: Optional[int] = None, <add> sparse_preds: bool = False, <add> axis: int = -1, <ide> ): <ide> super().__init__( <ide> num_classes=num_classes, <ide> target_class_ids=target_class_ids, <ide> name=name, <ide> dtype=dtype, <add> ignore_index=ignore_index, <add> sparse_labels=False, <add> sparse_preds=sparse_preds, <add> axis=axis, <ide> ) <ide> <del> def update_state(self, y_true, y_pred, sample_weight=None): <del> """Accumulates the confusion matrix statistics. <del> <del> Args: <del> y_true: The ground truth values. <del> y_pred: The predicted values. <del> sample_weight: Optional weighting of each example. Defaults to 1. Can <del> be a `Tensor` whose rank is either 0, or the same rank as `y_true`, <del> and must be broadcastable to `y_true`. <del> <del> Returns: <del> Update op. <del> """ <del> # Select max hot-encoding channels to convert into all-class format <del> y_true = tf.argmax(y_true, axis=-1, output_type=tf.int32) <del> y_pred = tf.argmax(y_pred, axis=-1, output_type=tf.int32) <del> <del> return super().update_state(y_true, y_pred, sample_weight) <add> def get_config(self): <add> return { <add> "num_classes": self.num_classes, <add> "target_class_ids": self.target_class_ids, <add> "name": self.name, <add> "dtype": self._dtype, <add> "ignore_index": self.ignore_index, <add> "sparse_preds": self.sparse_preds, <add> "axis": self.axis, <add> } <ide> <ide> <ide> @keras_export("keras.metrics.OneHotMeanIoU") <ide> class apply. <ide> allocated to accumulate predictions from which the metric is calculated. <ide> name: (Optional) string name of the metric instance. <ide> dtype: (Optional) data type of the metric result. <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the metric computation. This is useful in segmentation <add> problems containing the *void* label (commonly -1 or 255) in its <add> annotated segmentation maps. By default, all label ids are considered. <add> sparse_preds: Wether predictions are encoded using natural numbers or <add> probability distribution vectors. If `False`, the `tf.argmax` function <add> will be used to determine each sample's most likely associated label. <add> axis: (Optional) Defaults to -1. The dimension containing the logits. <ide> <ide> Standalone usage: <ide> <ide> class apply. <ide> def __init__( <ide> self, <ide> num_classes: int, <del> name=None, <del> dtype=None, <add> name: str = None, <add> dtype: Optional[Union[str, tf.dtypes.DType]] = None, <add> ignore_index: Optional[int] = None, <add> sparse_preds: bool = False, <add> axis: int = -1, <ide> ): <ide> super().__init__( <ide> num_classes=num_classes, <add> axis=axis, <ide> name=name, <ide> dtype=dtype, <add> ignore_index=ignore_index, <add> sparse_labels=False, <add> sparse_preds=sparse_preds, <ide> ) <ide> <del> def update_state(self, y_true, y_pred, sample_weight=None): <del> """Accumulates the confusion matrix statistics. <del> <del> Args: <del> y_true: The ground truth values. <del> y_pred: The predicted values. <del> sample_weight: Optional weighting of each example. Defaults to 1. Can <del> be a `Tensor` whose rank is either 0, or the same rank as `y_true`, <del> and must be broadcastable to `y_true`. <del> <del> Returns: <del> Update op. <del> """ <del> # Select max hot-encoding channels to convert into all-class format <del> y_true = tf.argmax(y_true, axis=-1, output_type=tf.int32) <del> y_pred = tf.argmax(y_pred, axis=-1, output_type=tf.int32) <del> <del> return super().update_state(y_true, y_pred, sample_weight) <add> def get_config(self): <add> return { <add> "num_classes": self.num_classes, <add> "name": self.name, <add> "dtype": self._dtype, <add> "ignore_index": self.ignore_index, <add> "sparse_preds": self.sparse_preds, <add> "axis": self.axis, <add> } <ide> <ide> <ide> @keras_export("keras.metrics.BinaryCrossentropy") <ide> class CategoricalCrossentropy(base_metric.MeanMetricWrapper): <ide> smoothed, meaning the confidence on label values are relaxed. e.g. <ide> `label_smoothing=0.2` means that we will use a value of `0.1` for label <ide> `0` and `0.9` for label `1`" <add> axis: (Optional) Defaults to -1. The dimension along which entropy is <add> computed. <ide> <ide> Standalone usage: <ide> <ide> def __init__( <ide> dtype=None, <ide> from_logits=False, <ide> label_smoothing=0, <add> axis=-1, <ide> ): <ide> super().__init__( <ide> categorical_crossentropy, <ide> name, <ide> dtype=dtype, <ide> from_logits=from_logits, <ide> label_smoothing=label_smoothing, <add> axis=axis, <ide> ) <ide> <ide> <ide> class SparseCategoricalCrossentropy(base_metric.MeanMetricWrapper): <ide> dtype: (Optional) data type of the metric result. <ide> from_logits: (Optional) Whether output is expected to be a logits tensor. <ide> By default, we consider that output encodes a probability distribution. <del> axis: (Optional) Defaults to -1. The dimension along which the metric is <add> ignore_index: Optional integer, the id of a label that will not be <add> included in the metric computation. This is useful in segmentation <add> problems containing the *void* label (commonly -1 or 255) in its <add> annotated segmentation maps. By default, all label ids are considered. <add> axis: (Optional) Defaults to -1. The dimension along which entropy is <ide> computed. <ide> <ide> Standalone usage: <ide> class SparseCategoricalCrossentropy(base_metric.MeanMetricWrapper): <ide> @dtensor_utils.inject_mesh <ide> def __init__( <ide> self, <del> name="sparse_categorical_crossentropy", <del> dtype=None, <del> from_logits=False, <del> axis=-1, <add> name: str = "sparse_categorical_crossentropy", <add> dtype: Optional[Union[str, tf.dtypes.DType]] = None, <add> from_logits: bool = False, <add> ignore_index: Optional[int] = None, <add> axis: int = -1, <ide> ): <ide> super().__init__( <ide> sparse_categorical_crossentropy, <ide> name, <ide> dtype=dtype, <ide> from_logits=from_logits, <add> ignore_index=ignore_index, <ide> axis=axis, <ide> ) <ide> <ide><path>keras/metrics/metrics_test.py <ide> def test_unweighted(self): <ide> expected_result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2 <ide> self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3) <ide> <add> def test_unweighted_ignore_index_255(self): <add> y_pred = [0, 1, 1, 1] <add> y_true = [0, 1, 2, 255] <add> <add> m_obj = metrics.MeanIoU(num_classes=3, ignore_index=255) <add> self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables)) <add> <add> result = m_obj(y_true, y_pred) <add> <add> # cm = [[1, 0, 0], <add> # [0, 1, 0], <add> # [0, 1, 0]] <add> # sum_row = [1, 1, 1], sum_col = [1, 2, 0], true_positives = [1, 1, 0] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = ( <add> 1 / (1 + 1 - 1) + 1 / (2 + 1 - 1) + 0 / (0 + 1 - 0) <add> ) / 3 <add> self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3) <add> <add> def test_unweighted_ignore_index_1(self): <add> y_pred = [0, 1, 1, 1] <add> y_true = [0, 1, 2, -1] <add> <add> m_obj = metrics.MeanIoU(num_classes=3, ignore_index=-1) <add> self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables)) <add> <add> result = m_obj(y_true, y_pred) <add> <add> # cm = [[1, 0, 0], <add> # [0, 1, 0], <add> # [0, 1, 0]] <add> # sum_row = [1, 1, 1], sum_col = [1, 2, 0], true_positives = [1, 1, 0] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = ( <add> 1 / (1 + 1 - 1) + 1 / (2 + 1 - 1) + 0 / (0 + 1 - 0) <add> ) / 3 <add> self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3) <add> <ide> def test_weighted(self): <ide> y_pred = tf.constant([0, 1, 0, 1], dtype=tf.float32) <ide> y_true = tf.constant([0, 0, 1, 1]) <ide> def test_weighted(self): <ide> ) / 2 <ide> self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3) <ide> <add> def test_weighted_ignore_index_1(self): <add> y_pred = tf.constant([0, 1, 0, 1], dtype=tf.float32) <add> y_true = tf.constant([0, 0, 1, -1]) <add> sample_weight = tf.constant([0.2, 0.3, 0.4, 0.1]) <add> <add> m_obj = metrics.MeanIoU(num_classes=2, ignore_index=-1) <add> self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables)) <add> <add> result = m_obj(y_true, y_pred, sample_weight=sample_weight) <add> <add> # cm = [[0.2, 0.3], <add> # [0.4, 0.0]] <add> # sum_row = [0.6, 0.3], sum_col = [0.5, 0.4], true_positives = [0.2, <add> # 0.0] <add> # iou = true_positives / (sum_row + sum_col - true_positives)) <add> expected_result = ( <add> 0.2 / (0.6 + 0.5 - 0.2) + 0.0 / (0.3 + 0.4 - 0.0) <add> ) / 2 <add> self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3) <add> <ide> def test_multi_dim_input(self): <ide> y_pred = tf.constant([[0, 1], [0, 1]], dtype=tf.float32) <ide> y_true = tf.constant([[0, 0], [1, 1]])
6
Javascript
Javascript
remove unneeded type
9f596f63571450a3a30c50c124ca46705ecb2ab2
<ide><path>lib/Compilation.js <ide> const iterationBlockVariable = (variables, fn) => { <ide> indexVariable < variables.length; <ide> indexVariable++ <ide> ) { <del> // TODO: Remove when Dependency + DependenciesBlockVariable is typed <del> /** @type {Dependency[]} */ <ide> const varDep = variables[indexVariable].dependencies; <ide> for (let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { <ide> fn(varDep[indexVDep]);
1
Javascript
Javascript
remove picker from android permissions example
c780366eeed3d40066ad9ab3859005eda3c6d052
<ide><path>packages/rn-tester/js/examples/PermissionsAndroid/PermissionsExample.js <ide> <ide> 'use strict'; <ide> <del>const React = require('react'); <add>import * as React from 'react'; <ide> <del>const { <del> PermissionsAndroid, <del> Picker, <del> StyleSheet, <del> Text, <del> TouchableWithoutFeedback, <del> View, <del>} = require('react-native'); <add>import {PermissionsAndroid, StyleSheet, Text, View} from 'react-native'; <add>import RNTOption from '../../components/RNTOption'; <add>import RNTesterButton from '../../components/RNTesterButton'; <ide> <del>const Item = Picker.Item; <add>function PermissionsExample() { <add> const [permission, setPermission] = React.useState( <add> PermissionsAndroid.PERMISSIONS.CAMERA, <add> ); <add> const [hasPermission, setHasPermission] = React.useState('Not Checked'); <ide> <del>class PermissionsExample extends React.Component<{...}, $FlowFixMeState> { <del> state = { <del> permission: PermissionsAndroid.PERMISSIONS.CAMERA, <del> hasPermission: 'Not Checked', <add> const requestPermission = async () => { <add> let result; <add> try { <add> result = await PermissionsAndroid.request(permission, { <add> title: 'Permission Explanation', <add> message: <add> 'The app needs the following permission ' + <add> permission + <add> ' because of reasons. Please approve.', <add> }); <add> setHasPermission(result + ' for ' + permission); <add> } catch (e) { <add> throw e; <add> } <ide> }; <ide> <del> render() { <del> return ( <del> <View style={styles.container}> <del> <Text style={styles.text}>Permission Name:</Text> <del> <Picker <del> style={styles.picker} <del> selectedValue={this.state.permission} <del> onValueChange={this._onSelectPermission.bind(this)}> <del> <Item <add> const checkPermission = async () => { <add> let result; <add> try { <add> result = await PermissionsAndroid.check(permission); <add> } catch (e) { <add> throw e; <add> } <add> setHasPermission(`${result ? 'Granted' : 'Revoked'} for ${permission}`); <add> }; <add> <add> return ( <add> <View style={styles.container}> <add> <View style={styles.block}> <add> <Text style={styles.title}>Select Permission</Text> <add> <View style={styles.row}> <add> <RNTOption <ide> label={PermissionsAndroid.PERMISSIONS.CAMERA} <del> value={PermissionsAndroid.PERMISSIONS.CAMERA} <add> key={PermissionsAndroid.PERMISSIONS.CAMERA} <add> onPress={() => setPermission(PermissionsAndroid.PERMISSIONS.CAMERA)} <add> selected={permission === PermissionsAndroid.PERMISSIONS.CAMERA} <add> style={styles.option} <ide> /> <del> <Item <add> <RNTOption <ide> label={PermissionsAndroid.PERMISSIONS.READ_CALENDAR} <del> value={PermissionsAndroid.PERMISSIONS.READ_CALENDAR} <add> key={PermissionsAndroid.PERMISSIONS.READ_CALENDAR} <add> onPress={() => <add> setPermission(PermissionsAndroid.PERMISSIONS.READ_CALENDAR) <add> } <add> selected={ <add> permission === PermissionsAndroid.PERMISSIONS.READ_CALENDAR <add> } <add> style={styles.option} <ide> /> <del> <Item <add> <RNTOption <ide> label={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION} <del> value={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION} <add> key={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION} <add> onPress={() => <add> setPermission(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) <add> } <add> selected={ <add> permission === PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION <add> } <add> style={styles.option} <ide> /> <del> </Picker> <del> <TouchableWithoutFeedback onPress={this._checkPermission}> <del> <View> <del> <Text style={[styles.touchable, styles.text]}> <del> Check Permission <del> </Text> <del> </View> <del> </TouchableWithoutFeedback> <del> <Text style={styles.text}> <del> Permission Status: {this.state.hasPermission} <del> </Text> <del> <TouchableWithoutFeedback onPress={this._requestPermission}> <del> <View> <del> <Text style={[styles.touchable, styles.text]}> <del> Request Permission <del> </Text> <del> </View> <del> </TouchableWithoutFeedback> <add> </View> <ide> </View> <del> ); <del> } <del> <del> _onSelectPermission = (permission: string | number) => { <del> this.setState({ <del> permission: permission, <del> }); <del> }; <del> <del> _checkPermission = async () => { <del> let result = await PermissionsAndroid.check(this.state.permission); <del> this.setState({ <del> hasPermission: <del> (result ? 'Granted' : 'Revoked') + ' for ' + this.state.permission, <del> }); <del> }; <del> <del> _requestPermission = async () => { <del> let result = await PermissionsAndroid.request(this.state.permission, { <del> title: 'Permission Explanation', <del> message: <del> 'The app needs the following permission ' + <del> this.state.permission + <del> ' because of reasons. Please approve.', <del> }); <del> <del> this.setState({ <del> hasPermission: result + ' for ' + this.state.permission, <del> }); <del> }; <add> <RNTesterButton onPress={checkPermission}> <add> <View> <add> <Text style={[styles.touchable, styles.text]}>Check Permission</Text> <add> </View> <add> </RNTesterButton> <add> <RNTesterButton onPress={requestPermission}> <add> <View> <add> <Text style={[styles.touchable, styles.text]}> <add> Request Permission <add> </Text> <add> </View> <add> </RNTesterButton> <add> <Text style={styles.text}>Permission Status: {hasPermission}</Text> <add> </View> <add> ); <ide> } <ide> <add>const styles = StyleSheet.create({ <add> container: { <add> flex: 1, <add> backgroundColor: 'white', <add> }, <add> block: { <add> borderColor: 'rgba(0,0,0, 0.1)', <add> borderBottomWidth: 1, <add> padding: 6, <add> }, <add> row: { <add> flexDirection: 'row', <add> flexWrap: 'wrap', <add> }, <add> title: { <add> fontWeight: 'bold', <add> }, <add> text: { <add> fontSize: 20, <add> }, <add> touchable: { <add> color: '#007AFF', <add> }, <add> option: { <add> margin: 6, <add> }, <add>}); <add> <ide> exports.displayName = (undefined: ?string); <ide> exports.framework = 'React'; <ide> exports.title = 'PermissionsAndroid'; <ide> exports.examples = [ <ide> render: (): React.Node => <PermissionsExample />, <ide> }, <ide> ]; <del> <del>const styles = StyleSheet.create({ <del> container: { <del> flex: 1, <del> backgroundColor: 'white', <del> }, <del> text: { <del> margin: 10, <del> }, <del> touchable: { <del> color: '#007AFF', <del> }, <del> picker: { <del> flex: 1, <del> }, <del>});
1
Ruby
Ruby
get update_attributes working with schemamigration
57155064d135d67e0624d561c2badfe018b27a3a
<ide><path>activerecord/lib/active_record/schema_migration.rb <ide> module ActiveRecord <ide> class SchemaMigration < ActiveRecord::Base # :nodoc: <ide> class << self <ide> def primary_key <del> nil <add> "version" <ide> end <ide> <ide> def table_name <ide><path>activerecord/test/cases/ar_schema_test.rb <ide> class ActiveRecordSchemaTest < ActiveRecord::TestCase <ide> ActiveRecord::Migration.verbose = @original_verbose <ide> end <ide> <del> def test_has_no_primary_key <add> def test_has_has_primary_key <ide> old_primary_key_prefix_type = ActiveRecord::Base.primary_key_prefix_type <ide> ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore <del> assert_nil ActiveRecord::SchemaMigration.primary_key <add> assert_equal "version", ActiveRecord::SchemaMigration.primary_key <ide> <ide> ActiveRecord::SchemaMigration.create_table <ide> assert_difference "ActiveRecord::SchemaMigration.count", 1 do
2
Javascript
Javascript
log error stacktrace only when available
009d6a8863fae350c8b95f1a6f0936f7b3fbf12d
<ide><path>pdf.js <ide> function warn(msg) { <ide> } <ide> <ide> function backtrace() { <del> var stackStr; <ide> try { <ide> throw new Error(); <ide> } catch (e) { <del> stackStr = e.stack; <add> return e.stack ? e.stack.split('\n').slice(2).join('\n') : ""; <ide> } <del> return stackStr.split('\n').slice(1).join('\n'); <ide> } <ide> <ide> function error(msg) { <add> log("Error: " + msg); <ide> log(backtrace()); <ide> throw new Error(msg); <ide> }
1
Javascript
Javascript
reset state upon load if showpreviousviewonload
6a16d7dd44fb32dac6280a80554e2317e84b9cb9
<ide><path>web/viewer.js <ide> var PDFViewerApplication = { <ide> mouseScrollDelta: 0, <ide> preferenceSidebarViewOnLoad: SidebarView.NONE, <ide> preferencePdfBugEnabled: false, <add> preferenceShowPreviousViewOnLoad: true, <ide> isViewerEmbedded: (window.parent !== window), <ide> url: '', <ide> <ide> var PDFViewerApplication = { <ide> Preferences.get('pdfBugEnabled').then(function resolved(value) { <ide> self.preferencePdfBugEnabled = value; <ide> }), <add> Preferences.get('showPreviousViewOnLoad').then(function resolved(value) { <add> self.preferenceShowPreviousViewOnLoad = value; <add> if (!value && window.history.state) { <add> window.history.replaceState(null, ''); <add> } <add> }), <ide> Preferences.get('disableTextLayer').then(function resolved(value) { <ide> if (PDFJS.disableTextLayer === true) { <ide> return; <ide> var PDFViewerApplication = { <ide> Preferences.get('useOnlyCssZoom').then(function resolved(value) { <ide> PDFJS.useOnlyCssZoom = value; <ide> }) <add> <ide> // TODO move more preferences and other async stuff here <ide> ]).catch(function (reason) { }); <ide> <ide> var PDFViewerApplication = { <ide> }); <ide> <ide> // Fetch the necessary preference values. <del> var showPreviousViewOnLoad; <del> var showPreviousViewOnLoadPromise = <del> Preferences.get('showPreviousViewOnLoad').then(function (prefValue) { <del> showPreviousViewOnLoad = prefValue; <del> }); <ide> var defaultZoomValue; <ide> var defaultZoomValuePromise = <ide> Preferences.get('defaultZoomValue').then(function (prefValue) { <ide> defaultZoomValue = prefValue; <ide> }); <ide> <ide> var storePromise = store.initializedPromise; <del> Promise.all([firstPagePromise, storePromise, showPreviousViewOnLoadPromise, <del> defaultZoomValuePromise]).then(function resolved() { <add> Promise.all([firstPagePromise, storePromise, defaultZoomValuePromise]).then( <add> function resolved() { <ide> var storedHash = null; <del> if (showPreviousViewOnLoad && store.get('exists', false)) { <add> if (PDFViewerApplication.preferenceShowPreviousViewOnLoad && <add> store.get('exists', false)) { <ide> var pageNum = store.get('page', '1'); <ide> var zoom = defaultZoomValue || <ide> store.get('zoom', self.pdfViewer.currentScale);
1
Javascript
Javascript
improve port validation
5f7730e2f2689a6af0530d7de16370f9fcce1227
<ide><path>lib/url.js <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> <ide> // validate a little. <ide> if (!ipv6Hostname) { <del> rest = getHostname(this, rest, hostname); <add> rest = getHostname(this, rest, hostname, url); <ide> } <ide> <ide> if (this.hostname.length > hostnameMaxLen) { <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> return this; <ide> }; <ide> <del>function getHostname(self, rest, hostname) { <add>function getHostname(self, rest, hostname, url) { <ide> for (let i = 0; i < hostname.length; ++i) { <ide> const code = hostname.charCodeAt(i); <ide> const isValid = (code !== CHAR_FORWARD_SLASH && <ide> function getHostname(self, rest, hostname) { <ide> code !== CHAR_COLON); <ide> <ide> if (!isValid) { <add> // If leftover starts with :, then it represents an invalid port. <add> if (hostname.charCodeAt(i) === 58) { <add> throw new ERR_INVALID_URL(url); <add> } <ide> self.hostname = hostname.slice(0, i); <ide> return `/${hostname.slice(i)}${rest}`; <ide> } <ide><path>test/parallel/test-url-parse-format.js <ide> const parseTests = { <ide> href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f' <ide> }, <ide> <del> // Git urls used by npm <del> 'git+ssh://git@github.com:npm/npm': { <del> protocol: 'git+ssh:', <del> slashes: true, <del> auth: 'git', <del> host: 'github.com', <del> port: null, <del> hostname: 'github.com', <del> hash: null, <del> search: null, <del> query: null, <del> pathname: '/:npm/npm', <del> path: '/:npm/npm', <del> href: 'git+ssh://git@github.com/:npm/npm' <del> }, <del> <ide> 'https://*': { <ide> protocol: 'https:', <ide> slashes: true, <ide><path>test/parallel/test-url-parse-invalid-input.js <ide> if (common.hasIntl) { <ide> (e) => e.code === 'ERR_INVALID_URL', <ide> 'parsing http://\u00AD/bad.com/'); <ide> } <add> <add>{ <add> const badURLs = [ <add> 'https://evil.com:.example.com', <add> 'git+ssh://git@github.com:npm/npm', <add> ]; <add> badURLs.forEach((badURL) => { <add> assert.throws(() => { url.parse(badURL); }, <add> (e) => e.code === 'ERR_INVALID_URL', <add> `parsing ${badURL}`); <add> }); <add>}
3
Text
Text
add documentroot location
aa2adb933833c7fb7b67b3d0413cfe377b7cb61c
<ide><path>guide/english/apache/index.md <ide> sudo yum install httpd <ide> ``` <ide> pacman -S apache <ide> ``` <add> <add>### Getting Started <add>Once you have Apache installed you need to know where to put your HTML documents. This location is generally referred to as the `DocumentRoot`. This location is usually `/var/www/html` on most Linux systems. Follow the instructions below to find the configuration file for Apache and the `DocumentRoot`. <add> <add>#### Command <add>``` <add>~$ sudo grep "DocumentRoot" -R /etc/ <add>``` <add> <add>The `-R` flag will cause grep to search recursively through the `/etc` directory and print out the full path of the file that it finds the `DocumentRoot` keyword in. <add> <add>#### Ubuntu output <add>``` <add>/etc/apache2/sites-available/000-default.conf: DocumentRoot /var/www/html <add>/etc/apache2/sites-available/default-ssl.conf: DocumentRoot /var/www/html <add>/etc/apache2/sites-enabled/000-default.conf: DocumentRoot /var/www/html <add>``` <add> <add>#### Centos output <add>``` <add>/etc/httpd/conf/httpd.conf DocumentRoot /var/www/html <add>``` <add> <add>#### References <add>- Installation and Configurations guides <add> - [Ubuntu](https://tutorials.ubuntu.com/tutorial/install-and-configure-apache#2) <add> - [CentOS](https://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-apache-config-ui.html) <add> - [Arch Linux](https://wiki.archlinux.org/index.php/Apache_HTTP_Server)
1
Javascript
Javascript
create a wrapper to manage async callbacks
62761428eff3a53e69367449eb81869e59e75e39
<ide><path>angularFiles.js <ide> angularFiles = { <ide> <ide> 'src/ng/anchorScroll.js', <ide> 'src/ng/animate.js', <add> 'src/ng/asyncCallback.js', <ide> 'src/ng/browser.js', <ide> 'src/ng/cacheFactory.js', <ide> 'src/ng/compile.js', <ide><path>src/AngularPublic.js <ide> $TemplateCacheProvider, <ide> $TimeoutProvider, <ide> $$RAFProvider, <del> $AsyncCallbackProvider, <add> $$AsyncCallbackProvider, <ide> $WindowProvider <ide> */ <ide> <ide> function publishExternalAPI(angular){ <ide> $templateCache: $TemplateCacheProvider, <ide> $timeout: $TimeoutProvider, <ide> $window: $WindowProvider, <del> $$rAF: $$RAFProvider <add> $$rAF: $$RAFProvider, <add> $$asyncCallback : $$AsyncCallbackProvider <ide> }); <ide> } <ide> ]); <ide><path>src/ng/asyncCallback.js <add>'use strict'; <add> <add>function $$AsyncCallbackProvider(){ <add> this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { <add> return $$rAF.supported <add> ? function(fn) { return $$rAF(fn); } <add> : function(fn) { <add> return $timeout(fn, 0, false); <add> }; <add> }]; <add>} <ide><path>src/ngMock/angular-mocks.js <ide> angular.mock.$RAFDecorator = function($delegate) { <ide> return rafFn; <ide> }; <ide> <add>angular.mock.$AsyncCallbackDecorator = function($delegate) { <add> var callbacks = []; <add> var addFn = function(fn) { <add> callbacks.push(fn); <add> }; <add> addFn.flush = function() { <add> angular.forEach(callbacks, function(fn) { <add> fn(); <add> }); <add> callbacks = []; <add> }; <add> return addFn; <add>}; <add> <ide> /** <ide> * <ide> */ <ide> angular.module('ngMock', ['ng']).provider({ <ide> }).config(['$provide', function($provide) { <ide> $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); <ide> $provide.decorator('$$rAF', angular.mock.$RAFDecorator); <add> $provide.decorator('$$asyncCallback', angular.mock.$AsyncCallbackDecorator); <ide> }]); <ide> <ide> /** <ide><path>test/ng/asyncCallbackSpec.js <add>'use strict'; <add>describe('$$asyncCallback', function() { <add> it('should perform a callback asynchronously', inject(function($$asyncCallback) { <add> var message = 'hello there '; <add> $$asyncCallback(function() { <add> message += 'Angular'; <add> }); <add> <add> expect(message).toBe('hello there '); <add> $$asyncCallback.flush(); <add> expect(message).toBe('hello there Angular'); <add> })); <add> <add> describe('mocks', function() { <add> it('should queue up all async callbacks', inject(function($$asyncCallback) { <add> var callback = jasmine.createSpy('callback'); <add> $$asyncCallback(callback); <add> $$asyncCallback(callback); <add> $$asyncCallback(callback); <add> expect(callback.callCount).toBe(0); <add> <add> $$asyncCallback.flush(); <add> expect(callback.callCount).toBe(3); <add> <add> $$asyncCallback(callback); <add> $$asyncCallback(callback); <add> expect(callback.callCount).toBe(3); <add> <add> $$asyncCallback.flush(); <add> expect(callback.callCount).toBe(5); <add> })); <add> }); <add>});
5
Go
Go
use lookup path for init
a352ecb01a788eff3446fe12191ca0434fce1eed
<ide><path>pkg/libcontainer/nsinit/exec.go <ide> func createCommand(container *libcontainer.Container, console, logFile string, p <ide> command.SysProcAttr = &syscall.SysProcAttr{ <ide> Cloneflags: uintptr(getNamespaceFlags(container.Namespaces)), <ide> } <add> command.Env = container.Env <ide> return command <ide> } <ide><path>pkg/libcontainer/nsinit/init.go <ide> import ( <ide> "io/ioutil" <ide> "log" <ide> "os" <add> "os/exec" <ide> "path/filepath" <ide> "syscall" <ide> ) <ide> func Init(container *libcontainer.Container, uncleanRootfs, console string, pipe <ide> return fmt.Errorf("chdir to %s %s", container.WorkingDir, err) <ide> } <ide> } <del> log.Printf("execing %s goodbye", args[0]) <del> if err := system.Exec(args[0], args[0:], container.Env); err != nil { <add> name, err := exec.LookPath(args[0]) <add> if err != nil { <add> return err <add> } <add> <add> log.Printf("execing %s goodbye", name) <add> if err := system.Exec(name, args[0:], container.Env); err != nil { <ide> return fmt.Errorf("exec %s", err) <ide> } <ide> panic("unreachable")
2
Python
Python
return original exe name when not found
468a2f286f3a86c984ebfe8d6b81c7ac26de5135
<ide><path>scipy_distutils/exec_command.py <ide> def find_executable(exe, path=None): <ide> """ Return full path of a executable. <ide> """ <ide> log.debug('find_executable(%r)' % exe) <add> orig_exe = exe <ide> if path is None: <ide> path = os.environ.get('PATH',os.defpath) <ide> if os.name=='posix': <ide> def find_executable(exe, path=None): <ide> return f_ext <ide> exe = realpath(exe) <ide> if not os.path.isfile(exe) or os.access(exe,os.X_OK): <del> log.warn('Could not locate executable %s' % exe) <add> log.warn('Could not locate executable %s' % orig_exe) <add> return orig_exe <ide> return exe <ide> <ide> ############################################################
1
Python
Python
fix missing bool8
12d22f9337b3e24cccab694cd9caa73d73d1a92f
<ide><path>numpy/core/numerictypes.py <ide> def bitname(obj): <ide> base = '' <ide> char = '' <ide> try: <del> info = typeinfo[name.upper()] <add> if name[-1] == '_': <add> newname = name[:-1] <add> else: <add> newname = name <add> info = typeinfo[newname.upper()] <ide> assert(info[-1] == obj) # sanity check <ide> bits = info[2] <ide> <ide> except KeyError: # bit-width name <ide> base, bits = _evalname(name) <ide> char = base[0] <ide> <del> if name == 'bool': <add> if name == 'bool_': <ide> char = 'b' <ide> base = 'bool' <del> elif name=='string': <add> elif name=='string_': <ide> char = 'S' <ide> base = 'string' <del> elif name=='unicode': <add> elif name=='unicode_': <ide> char = 'U' <ide> base = 'unicode' <ide> elif name=='void': <ide> char = 'V' <ide> base = 'void' <del> elif name=='object': <add> elif name=='object_': <ide> char = 'O' <ide> base = 'object' <ide> bits = 0
1
Text
Text
fix usage of pluralized word
9826b24242ba4712ecbb71e19fe56982506ee17f
<ide><path>guides/source/getting_started.md <ide> The Rails philosophy includes two major guiding principles: <ide> again, our code is more maintainable, more extensible, and less buggy. <ide> * **Convention Over Configuration:** Rails has opinions about the best way to do many <ide> things in a web application, and defaults to this set of conventions, rather than <del> require that you specify every minutiae through endless configuration files. <add> require that you specify minutiae through endless configuration files. <ide> <ide> Creating a New Rails Project <ide> ----------------------------
1
Go
Go
reimplement iteration over fileinfos in getorphan
ebf12dbda08633375ab12387255d3f617ee9be38
<ide><path>layer/filestore.go <ide> import ( <ide> <ide> "github.com/docker/distribution" <ide> "github.com/docker/docker/pkg/ioutils" <del> "github.com/opencontainers/go-digest" <add> digest "github.com/opencontainers/go-digest" <ide> "github.com/pkg/errors" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> func (fms *fileMetadataStore) getOrphan() ([]roLayer, error) { <ide> } <ide> <ide> for _, fi := range fileInfos { <del> if fi.IsDir() && strings.Contains(fi.Name(), "-removing") { <del> nameSplit := strings.Split(fi.Name(), "-") <del> dgst := digest.NewDigestFromEncoded(algorithm, nameSplit[0]) <del> if err := dgst.Validate(); err != nil { <del> logrus.Debugf("Ignoring invalid digest %s:%s", algorithm, nameSplit[0]) <del> } else { <del> chainID := ChainID(dgst) <del> chainFile := filepath.Join(fms.root, string(algorithm), fi.Name(), "cache-id") <del> contentBytes, err := ioutil.ReadFile(chainFile) <del> if err != nil { <del> logrus.WithError(err).WithField("digest", dgst).Error("cannot get cache ID") <del> } <del> cacheID := strings.TrimSpace(string(contentBytes)) <del> if cacheID == "" { <del> logrus.Errorf("invalid cache id value") <del> } <del> <del> l := &roLayer{ <del> chainID: chainID, <del> cacheID: cacheID, <del> } <del> orphanLayers = append(orphanLayers, *l) <add> if !fi.IsDir() || !strings.HasSuffix(fi.Name(), "-removing") { <add> continue <add> } <add> // At this stage, fi.Name value looks like <digest>-<random>-removing <add> // Split on '-' to get the digest value. <add> nameSplit := strings.Split(fi.Name(), "-") <add> dgst := digest.NewDigestFromEncoded(algorithm, nameSplit[0]) <add> if err := dgst.Validate(); err != nil { <add> logrus.WithError(err).WithField("digest", string(algorithm)+":"+nameSplit[0]).Debug("ignoring invalid digest") <add> continue <add> } <add> <add> chainFile := filepath.Join(fms.root, string(algorithm), fi.Name(), "cache-id") <add> contentBytes, err := ioutil.ReadFile(chainFile) <add> if err != nil { <add> if !os.IsNotExist(err) { <add> logrus.WithError(err).WithField("digest", dgst).Error("failed to read cache ID") <ide> } <add> continue <add> } <add> cacheID := strings.TrimSpace(string(contentBytes)) <add> if cacheID == "" { <add> logrus.Error("invalid cache ID") <add> continue <ide> } <add> <add> l := &roLayer{ <add> chainID: ChainID(dgst), <add> cacheID: cacheID, <add> } <add> orphanLayers = append(orphanLayers, *l) <ide> } <ide> } <add> <ide> return orphanLayers, nil <ide> } <ide>
1
PHP
PHP
move remindabletrait into reminders namespace
8e96ccd6c78ca68c1d8e44f48fbab9ac0537229c
<add><path>src/Illuminate/Auth/Reminders/RemindableTrait.php <del><path>src/Illuminate/Auth/RemindableTrait.php <del><?php namespace Illuminate\Auth; <add><?php namespace Illuminate\Auth\Reminders; <ide> <ide> trait RemindableTrait { <ide>
1
PHP
PHP
expand test coverage in viewtask
e9282755a19389340f31579879a0ecf29793b8df
<ide><path>src/Console/Command/Task/ViewTask.php <ide> public function all() { <ide> * @return array Returns an variables to be made available to a view template <ide> */ <ide> protected function _loadController() { <del> $plugin = null; <del> if ($this->plugin) { <del> $plugin = $this->plugin . '.'; <del> } <del> <ide> $modelObj = TableRegistry::get($this->tableName); <ide> <ide> $singularVar = Inflector::variable(Inflector::singularize($this->controllerName)); <ide><path>tests/TestCase/Console/Command/Task/ViewTaskTest.php <ide> public function testCustomAction() { <ide> $this->Task->customAction(); <ide> } <ide> <add>/** <add> * Test execute no args. <add> * <add> * @return void <add> */ <add> public function testExecuteNoArgs() { <add> $this->_setupTask(['in', 'err', 'bake', 'createFile', '_stop']); <add> <add> $this->Task->Model->expects($this->once()) <add> ->method('listAll') <add> ->will($this->returnValue(['comments', 'articles'])); <add> <add> $this->Task->expects($this->never()) <add> ->method('bake'); <add> <add> $this->Task->execute(); <add> } <add> <ide> /** <ide> * Test all() <ide> * <ide> public function testExecuteIntoAll() { <ide> $this->Task->execute(); <ide> } <ide> <add>/** <add> * Test all() calls execute <add> * <add> * @return void <add> */ <add> public function testAllCallsExecute() { <add> $this->_setupTask(['in', 'err', 'createFile', 'execute', '_stop']); <add> <add> $this->Task->Model->expects($this->once()) <add> ->method('listAll') <add> ->will($this->returnValue(['comments', 'articles'])); <add> <add> $this->Task->expects($this->exactly(2)) <add> ->method('execute'); <add> <add> $this->Task->all(); <add> $this->assertEquals('articles', $this->Task->args[0]); <add> } <add> <ide> /** <ide> * test `cake bake view $controller view` <ide> *
2
Javascript
Javascript
remove `undefined` check
19b44854773623b684a172cc972b6c3e2e7981b6
<ide><path>lib/_stream_writable.js <ide> function validChunk(stream, state, chunk, cb) { <ide> <ide> if (chunk === null) { <ide> er = new errors.TypeError('ERR_STREAM_NULL_VALUES'); <del> } else if (typeof chunk !== 'string' && <del> chunk !== undefined && <del> !state.objectMode) { <add> } else if (typeof chunk !== 'string' && !state.objectMode) { <ide> er = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'chunk', <ide> ['string', 'Buffer']); <ide> }
1
Javascript
Javascript
fix build to remove all comments other than header
27b6791e7376420df7690699f856dbd2110f06bc
<ide><path>gulpfile.js <ide> function buildTask() { <ide> .pipe(insert.prepend(header)) <ide> .pipe(streamify(replace('{{ version }}', package.version))) <ide> .pipe(gulp.dest(outDir)) <del> .pipe(streamify(uglify({ <del> preserveComments: 'some' <del> }))) <add> .pipe(streamify(uglify())) <add> .pipe(insert.prepend(header)) <add> .pipe(streamify(replace('{{ version }}', package.version))) <ide> .pipe(streamify(concat('Chart.bundle.min.js'))) <ide> .pipe(gulp.dest(outDir)); <ide> <ide> function buildTask() { <ide> .pipe(insert.prepend(header)) <ide> .pipe(streamify(replace('{{ version }}', package.version))) <ide> .pipe(gulp.dest(outDir)) <del> .pipe(streamify(uglify({ <del> preserveComments: 'some' <del> }))) <add> .pipe(streamify(uglify())) <add> .pipe(insert.prepend(header)) <add> .pipe(streamify(replace('{{ version }}', package.version))) <ide> .pipe(streamify(concat('Chart.min.js'))) <ide> .pipe(gulp.dest(outDir)); <ide>
1
Ruby
Ruby
fix code syntax
f9f52435e7da8cce1b57e24035bdceacc61cab36
<ide><path>activemodel/lib/active_model/serialization.rb <ide> module ActiveModel <ide> # When called, serializable hash will use <ide> # instance methods that match the name of the attributes hash's keys. <ide> # In order to override this behavior, take a look at the private <del> # method ++read_attribute_for_serialization++. <add> # method +read_attribute_for_serialization+. <ide> # <ide> # Most of the time though, you will want to include the JSON or XML <ide> # serializations. Both of these modules automatically include the <del> # ++ActiveModel::Serialization++ module, so there is no need to explicitly <add> # +ActiveModel::Serialization+ module, so there is no need to explicitly <ide> # include it. <ide> # <ide> # A minimal implementation including XML and JSON would be:
1
Javascript
Javascript
replace fixturesdir with fixtures module
2bf182dc46f9da7c9ed98d9f98898f815da0d2f6
<ide><path>test/parallel/test-https-eof-for-eom.js <ide> if (!common.hasCrypto) <ide> const assert = require('assert'); <ide> const https = require('https'); <ide> const tls = require('tls'); <del>const fs = require('fs'); <add>const fixtures = require('../common/fixtures'); <ide> <ide> const options = { <del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`) <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem') <ide> }; <ide> <ide>
1
Ruby
Ruby
add test for ghc version style
d3ba9723b244fc52b0b20b1cffa88d71700e6b92
<ide><path>Library/Homebrew/test/test_versions.rb <ide> def test_dash_version_dash_style <ide> check 'http://www.antlr.org/download/antlr-3.4-complete.jar', '3.4' <ide> end <ide> <add> def check_ghc_style <add> check 'http://www.haskell.org/ghc/dist/7.0.4/ghc-7.0.4-x86_64-apple-darwin.tar.bz2', '7.0.4' <add> check 'http://www.haskell.org/ghc/dist/7.0.4/ghc-7.0.4-i386-apple-darwin.tar.bz2', '7.0.4' <add> end <add> <ide> def test_more_versions <ide> check 'http://pypy.org/download/pypy-1.4.1-osx.tar.bz2', '1.4.1' <ide> check 'http://www.openssl.org/source/openssl-0.9.8s.tar.gz', '0.9.8s'
1