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 | extract active donors from selectors | 66d628ff2fecac43186d4da177d3a2e69e5e706d | <ide><path>client/src/components/Donation/components/DonateText.js
<del>import React, { Component } from 'react';
<add>import React from 'react';
<add>import PropTypes from 'prop-types';
<add>import { connect } from 'react-redux';
<add>import { createSelector } from 'reselect';
<ide>
<del>class DonateText extends Component {
<del> render() {
<del> return (
<del> <div className='text-center'>
<del> <p>
<del> freeCodeCamp.org is a tiny nonprofit that's helping millions of
<del> people learn to code for free.
<del> </p>
<del> <p>
<del> Join <strong>4,180</strong> supporters.
<del> </p>
<del> <p>
<del> Your $5 / month donation will help keep tech education free and
<del> open.
<del> </p>
<del> </div>
<del> );
<del> }
<del>}
<add>import { activeDonationsSelector } from '../../../redux';
<ide>
<del>export default DonateText;
<add>const propTypes = {
<add> activeDonations: PropTypes.number
<add>};
<add>
<add>const mapStateToProps = createSelector(
<add> activeDonationsSelector,
<add> activeDonations => ({ activeDonations })
<add>);
<add>
<add>const DonateText = ({ activeDonations }) => {
<add> const donationsLocale = activeDonations.toLocaleString();
<add> return (
<add> <div className='text-center'>
<add> <p>
<add> freeCodeCamp.org is a tiny nonprofit that's helping millions of
<add> people learn to code for free.
<add> </p>
<add> <p>
<add> Join <strong>{donationsLocale}</strong> supporters.
<add> </p>
<add> <p>
<add> Your $5 / month donation will help keep tech education free and
<add> open.
<add> </p>
<add> </div>
<add> );
<add>};
<add>
<add>DonateText.displayName = 'DonateText';
<add>DonateText.propTypes = propTypes;
<add>
<add>export default connect(mapStateToProps)(DonateText);
<ide><path>client/src/components/Supporters.js
<ide> function Supporters({ isDonating, activeDonations }) {
<ide> them to join the community.
<ide> </Fragment>
<ide> ) : (
<del> `Join ${donationsLocale} supporters. Your $5 / month donation will help ` +
<del> 'keep tech education free and open.'
<add> `Join ${donationsLocale} supporters. Your $5 / month` +
<add> 'donation will help keep tech education free and open.'
<ide> )}
<ide> </p>
<ide> </b> | 2 |
Python | Python | reuse channel when sending remote control commands | 8a3ed48a5be062715b836a04e5f1f5d4eb87ae90 | <ide><path>celery/task/control.py
<ide> def broadcast(self, command, arguments=None, destination=None,
<ide>
<ide> """
<ide> with self.app.default_connection(connection, connect_timeout) as conn:
<add> if channel is None:
<add> if not getattr(conn, "_publisher_chan", None):
<add> conn._publisher_chan = conn.channel()
<add> channel = conn._publisher_chan
<ide> return self.mailbox(conn)._broadcast(command, arguments,
<ide> destination, reply, timeout,
<ide> limit, callback, | 1 |
Javascript | Javascript | add regression test for async iteration completion | 24e81d7c5ae785a015ac56ad75fe83120a998a3a | <ide><path>test/parallel/test-stream-readable-async-iterators.js
<ide> async function tests() {
<ide> p.then(common.mustCall()).catch(common.mustNotCall());
<ide> }
<ide>
<add>{
<add> // AsyncIterator should finish correctly if destroyed.
<add>
<add> const r = new Readable({
<add> objectMode: true,
<add> read() {
<add> }
<add> });
<add>
<add> r.destroy();
<add> r.on('close', () => {
<add> const it = r[Symbol.asyncIterator]();
<add> const next = it.next();
<add> next
<add> .then(common.mustCall(({ done }) => assert.strictEqual(done, true)))
<add> .catch(common.mustNotCall());
<add> });
<add>}
<add>
<ide> // To avoid missing some tests if a promise does not resolve
<ide> tests().then(common.mustCall()); | 1 |
Ruby | Ruby | add missing nodocs to mysql adapter | 89357455eb65603fc6627088ed6b79ecbc52b5f3 | <ide><path>activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
<ide> def last_inserted_id(result)
<ide> @connection.insert_id
<ide> end
<ide>
<del> module Fields
<add> module Fields # :nodoc:
<ide> class DateTime < Type::DateTime
<ide> def cast_value(value)
<ide> if Mysql::Time === value
<ide> def exec_without_stmt(sql, name = 'SQL') # :nodoc:
<ide> end
<ide> end
<ide>
<del> def execute_and_free(sql, name = nil)
<add> def execute_and_free(sql, name = nil) # :nodoc:
<ide> result = execute(sql, name)
<ide> ret = yield result
<ide> result.free
<ide> def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #
<ide> end
<ide> alias :create :insert_sql
<ide>
<del> def exec_delete(sql, name, binds)
<add> def exec_delete(sql, name, binds) # :nodoc:
<ide> affected_rows = 0
<ide>
<ide> exec_query(sql, name, binds) do |n| | 1 |
Ruby | Ruby | check target writable for move_back | 8bf948482325bdc10ab7d0eff75ce0da4d5daf1c | <ide><path>Library/Homebrew/cask/lib/hbc/artifact/moved.rb
<ide> def move_back(skip: false, force: false, command: nil, **options)
<ide> ohai "Moving #{self.class.english_name} '#{target.basename}' back to '#{source}'."
<ide> source.dirname.mkpath
<ide>
<del> if source.parent.writable?
<add> if target.parent.writable?
<ide> FileUtils.move(target, source)
<ide> else
<ide> command.run("/bin/mv", args: [target, source], sudo: true) | 1 |
Go | Go | add progress bar to docker load | fae09e25698006a190d14fe64f1576f68431fabf | <ide><path>api/client/load.go
<ide> import (
<ide> func (cli *DockerCli) CmdLoad(args ...string) error {
<ide> cmd := Cli.Subcmd("load", nil, Cli.DockerCommands["load"].Description, true)
<ide> infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN")
<add> quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the load output")
<ide> cmd.Require(flag.Exact, 0)
<ide> cmd.ParseFlags(args, true)
<ide>
<ide> func (cli *DockerCli) CmdLoad(args ...string) error {
<ide> defer file.Close()
<ide> input = file
<ide> }
<del>
<del> response, err := cli.client.ImageLoad(context.Background(), input, true)
<add> if !cli.isTerminalOut {
<add> *quiet = true
<add> }
<add> response, err := cli.client.ImageLoad(context.Background(), input, *quiet)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>api/server/router/local/image.go
<ide> func (s *router) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
<ide> }
<ide>
<ide> func (s *router) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> return s.daemon.LoadImage(r.Body, w)
<add> if err := httputils.ParseForm(r); err != nil {
<add> return err
<add> }
<add> quiet := httputils.BoolValueOrDefault(r, "quiet", true)
<add> w.Header().Set("Content-Type", "application/json")
<add> return s.daemon.LoadImage(r.Body, w, quiet)
<ide> }
<ide>
<ide> func (s *router) deleteImages(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) LookupImage(name string) (*types.ImageInspect, error) {
<ide> // LoadImage uploads a set of images into the repository. This is the
<ide> // complement of ImageExport. The input stream is an uncompressed tar
<ide> // ball containing images and metadata.
<del>func (daemon *Daemon) LoadImage(inTar io.ReadCloser, outStream io.Writer) error {
<add>func (daemon *Daemon) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
<ide> imageExporter := tarexport.NewTarExporter(daemon.imageStore, daemon.layerStore, daemon.referenceStore)
<del> return imageExporter.Load(inTar, outStream)
<add> return imageExporter.Load(inTar, outStream, quiet)
<ide> }
<ide>
<ide> // ImageHistory returns a slice of ImageHistory structures for the specified image
<ide><path>image/image.go
<ide> type History struct {
<ide>
<ide> // Exporter provides interface for exporting and importing images
<ide> type Exporter interface {
<del> Load(io.ReadCloser, io.Writer) error
<add> Load(io.ReadCloser, io.Writer, bool) error
<ide> // TODO: Load(net.Context, io.ReadCloser, <- chan StatusMessage) error
<ide> Save([]string, io.Writer) error
<ide> }
<ide><path>image/tarexport/load.go
<ide> import (
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/chrootarchive"
<add> "github.com/docker/docker/pkg/progress"
<add> "github.com/docker/docker/pkg/streamformatter"
<add> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/reference"
<ide> )
<ide>
<del>func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer) error {
<add>func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
<add> var (
<add> sf = streamformatter.NewJSONStreamFormatter()
<add> progressOutput progress.Output
<add> )
<add> if !quiet {
<add> progressOutput = sf.NewProgressOutput(outStream, false)
<add> } else {
<add> progressOutput = nil
<add> }
<add>
<ide> tmpDir, err := ioutil.TempDir("", "docker-import-")
<ide> if err != nil {
<ide> return err
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer) error {
<ide> manifestFile, err := os.Open(manifestPath)
<ide> if err != nil {
<ide> if os.IsNotExist(err) {
<del> return l.legacyLoad(tmpDir, outStream)
<add> return l.legacyLoad(tmpDir, outStream, progressOutput)
<ide> }
<ide> return manifestFile.Close()
<ide> }
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer) error {
<ide> r.Append(diffID)
<ide> newLayer, err := l.ls.Get(r.ChainID())
<ide> if err != nil {
<del> newLayer, err = l.loadLayer(layerPath, rootFS)
<add> newLayer, err = l.loadLayer(layerPath, rootFS, diffID.String(), progressOutput)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer) error {
<ide> return nil
<ide> }
<ide>
<del>func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS) (layer.Layer, error) {
<add>func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS, id string, progressOutput progress.Output) (layer.Layer, error) {
<ide> rawTar, err := os.Open(filename)
<ide> if err != nil {
<ide> logrus.Debugf("Error reading embedded tar: %v", err)
<ide> func (l *tarexporter) loadLayer(filename string, rootFS image.RootFS) (layer.Lay
<ide> }
<ide> defer inflatedLayerData.Close()
<ide>
<add> if progressOutput != nil {
<add> fileInfo, err := os.Stat(filename)
<add> if err != nil {
<add> logrus.Debugf("Error statting file: %v", err)
<add> return nil, err
<add> }
<add>
<add> progressReader := progress.NewProgressReader(inflatedLayerData, progressOutput, fileInfo.Size(), stringid.TruncateID(id), "Loading layer")
<add>
<add> return l.ls.Register(progressReader, rootFS.ChainID())
<add> }
<ide> return l.ls.Register(inflatedLayerData, rootFS.ChainID())
<ide> }
<ide>
<ide> func (l *tarexporter) setLoadedTag(ref reference.NamedTagged, imgID image.ID, ou
<ide> return nil
<ide> }
<ide>
<del>func (l *tarexporter) legacyLoad(tmpDir string, outStream io.Writer) error {
<add>func (l *tarexporter) legacyLoad(tmpDir string, outStream io.Writer, progressOutput progress.Output) error {
<ide> legacyLoadedMap := make(map[string]image.ID)
<ide>
<ide> dirs, err := ioutil.ReadDir(tmpDir)
<ide> func (l *tarexporter) legacyLoad(tmpDir string, outStream io.Writer) error {
<ide> // every dir represents an image
<ide> for _, d := range dirs {
<ide> if d.IsDir() {
<del> if err := l.legacyLoadImage(d.Name(), tmpDir, legacyLoadedMap); err != nil {
<add> if err := l.legacyLoadImage(d.Name(), tmpDir, legacyLoadedMap, progressOutput); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func (l *tarexporter) legacyLoad(tmpDir string, outStream io.Writer) error {
<ide> return nil
<ide> }
<ide>
<del>func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[string]image.ID) error {
<add>func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[string]image.ID, progressOutput progress.Output) error {
<ide> if _, loaded := loadedMap[oldID]; loaded {
<ide> return nil
<ide> }
<ide> func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[str
<ide> for {
<ide> var loaded bool
<ide> if parentID, loaded = loadedMap[img.Parent]; !loaded {
<del> if err := l.legacyLoadImage(img.Parent, sourceDir, loadedMap); err != nil {
<add> if err := l.legacyLoadImage(img.Parent, sourceDir, loadedMap, progressOutput); err != nil {
<ide> return err
<ide> }
<ide> } else {
<ide> func (l *tarexporter) legacyLoadImage(oldID, sourceDir string, loadedMap map[str
<ide> if err != nil {
<ide> return err
<ide> }
<del> newLayer, err := l.loadLayer(layerPath, *rootFS)
<add> newLayer, err := l.loadLayer(layerPath, *rootFS, oldID, progressOutput)
<ide> if err != nil {
<ide> return err
<ide> } | 5 |
Python | Python | add warning when left padding should be used | a357ed50e7144d6910dd924cb334518e90e59392 | <ide><path>src/transformers/generation_flax_utils.py
<ide> def generate(
<ide> if decoder_start_token_id is None and self.config.is_encoder_decoder:
<ide> raise ValueError("`decoder_start_token_id` has to be defined for encoder-decoder generation.")
<ide>
<add> # decoder-only models should use left-padding for generation (can't be checked with `trace=True`)
<add> if not self.config.is_encoder_decoder and not trace:
<add> if pad_token_id is not None and jnp.sum(input_ids[:, -1] == pad_token_id) > 0:
<add> logger.warning(
<add> "A decoder-only architecture is being used, but right-padding was detected! For correct "
<add> "generation results, please set `padding_side='left'` when initializing the tokenizer."
<add> )
<add>
<ide> if self.config.is_encoder_decoder:
<ide> # add encoder_outputs to model_kwargs
<ide> if model_kwargs.get("encoder_outputs") is None:
<ide><path>src/transformers/generation_tf_utils.py
<ide> def _generate(
<ide> input_ids, pad_token_id, eos_token_id
<ide> )
<ide>
<add> # decoder-only models should use left-padding for generation
<add> if not self.config.is_encoder_decoder:
<add> if pad_token_id is not None and tf.math.reduce_any(input_ids[:, -1] == pad_token_id):
<add> logger.warning(
<add> "A decoder-only architecture is being used, but right-padding was detected! For correct "
<add> "generation results, please set `padding_side='left'` when initializing the tokenizer."
<add> )
<add>
<ide> # 4. Prepare model inputs which will be used for auto-regressive generation
<ide> if self.config.is_encoder_decoder:
<ide> # if encoder-decoder, we create encoder_outputs and add to `model_kwargs`
<ide><path>src/transformers/generation_utils.py
<ide> def generate(
<ide> inputs_tensor, pad_token_id, eos_token_id
<ide> )
<ide>
<add> # decoder-only models should use left-padding for generation
<add> if not self.config.is_encoder_decoder:
<add> if pad_token_id is not None and torch.sum(inputs_tensor[:, -1] == pad_token_id) > 0:
<add> logger.warning(
<add> "A decoder-only architecture is being used, but right-padding was detected! For correct "
<add> "generation results, please set `padding_side='left'` when initializing the tokenizer."
<add> )
<add>
<ide> if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
<ide> # if model is encoder decoder encoder_outputs are created
<ide> # and added to `model_kwargs` | 3 |
Python | Python | expose skip output to test runner | 3cbb5870e5c8ce6a9da718c7fff6f50709545ed5 | <ide><path>tools/test.py
<ide> from Queue import Queue, Empty
<ide>
<ide> logger = logging.getLogger('testrunner')
<add>skip_regex = re.compile(r'# SKIP\S*\s+(.*)', re.IGNORECASE)
<ide>
<ide> VERBOSE = False
<ide>
<ide> def HasRun(self, output):
<ide> for l in output.output.stdout.splitlines():
<ide> logger.info('#' + l)
<ide> else:
<del> logger.info('ok %i - %s' % (self._done, command))
<add> skip = skip_regex.search(output.output.stdout)
<add> if skip:
<add> logger.info(
<add> 'ok %i - %s # skip %s' % (self._done, command, skip.group(1)))
<add> else:
<add> logger.info('ok %i - %s' % (self._done, command))
<ide>
<ide> duration = output.test.duration
<ide>
<ide> def BuildOptions():
<ide> result.add_option("--no-suppress-dialogs", help="Display Windows dialogs for crashing tests",
<ide> dest="suppress_dialogs", action="store_false")
<ide> result.add_option("--shell", help="Path to V8 shell", default="shell")
<del> result.add_option("--store-unexpected-output",
<add> result.add_option("--store-unexpected-output",
<ide> help="Store the temporary JS files from tests that fails",
<ide> dest="store_unexpected_output", default=True, action="store_true")
<del> result.add_option("--no-store-unexpected-output",
<add> result.add_option("--no-store-unexpected-output",
<ide> help="Deletes the temporary JS files from tests that fails",
<ide> dest="store_unexpected_output", action="store_false")
<ide> return result | 1 |
Javascript | Javascript | port the fixes too | a87aac00e4d1efd8afe5e5631e8ab98585ac8cc3 | <ide><path>src/git-repository-async.js
<ide> export default class GitRepositoryAsync {
<ide> // information.
<ide> getDirectoryStatus (directoryPath) {
<ide> return this.relativizeToWorkingDirectory(directoryPath)
<del> .then(relativePath => this._getStatus([relativePath]))
<add> .then(relativePath => {
<add> const pathspec = relativePath + '/**'
<add> return this._getStatus([pathspec])
<add> })
<ide> .then(statuses => {
<ide> return Promise.all(statuses.map(s => s.statusBit())).then(bits => {
<ide> return bits
<ide> export default class GitRepositoryAsync {
<ide> }
<ide>
<ide> return Promise.all(projectPathsPromises)
<del> .then(paths => paths.filter(p => p.length > 0))
<add> .then(paths => paths.map(p => p.length > 0 ? p + '/**' : '*'))
<ide> .then(projectPaths => {
<ide> return this._getStatus(projectPaths.length > 0 ? projectPaths : null)
<ide> })
<ide> export default class GitRepositoryAsync {
<ide> return this.getRepo()
<ide> .then(repo => {
<ide> const opts = {
<del> flags: Git.Status.OPT.INCLUDE_UNTRACKED | Git.Status.OPT.RECURSE_UNTRACKED_DIRS | Git.Status.OPT.DISABLE_PATHSPEC_MATCH
<add> flags: Git.Status.OPT.INCLUDE_UNTRACKED | Git.Status.OPT.RECURSE_UNTRACKED_DIRS
<ide> }
<ide>
<ide> if (paths) { | 1 |
PHP | PHP | add comments for possibly confusing code | f19916bccf627535e77e496c95fd4e0e20e8ea46 | <ide><path>lib/Cake/Error/ExceptionRenderer.php
<ide> protected function _getController($exception) {
<ide> } catch (Exception $e) {
<ide> $startup = false;
<ide> }
<del> if ($startup === false && !empty($controller) && $controller->Components->enabled('RequestHandler')) {
<add> // Retry RequestHandler, as another aspect of startupProcess()
<add> // could have failed. Ignore any exceptions out of startup, as
<add> // there could be userland input data parsers.
<add> if ($startup === false &&
<add> !empty($controller) &&
<add> $controller->Components->enabled('RequestHandler')
<add> ) {
<ide> try {
<ide> $controller->RequestHandler->startup($controller);
<ide> } catch (Exception $e) { | 1 |
Python | Python | fix occurences of "e.g"/"i.e" -> "e.g."/"i.e." | bd3149fe4837034116287a0b2e27627b72be4f73 | <ide><path>celery/conf.py
<ide>
<ide> The type of exchange. If the exchange type is ``direct``, all messages
<ide> receives all tasks. However, if the exchange type is ``topic``, you can
<del>route e.g some tasks to one server, and others to the rest.
<add>route e.g. some tasks to one server, and others to the rest.
<ide> See `Exchange types and the effect of bindings`_.
<ide>
<ide> .. _`Exchange types and the effect of bindings:
<ide><path>celery/task.py
<ide> def get_publisher(self):
<ide> :rtype: :class:`celery.messaging.TaskPublisher`.
<ide>
<ide> Please be sure to close the AMQP connection when you're done
<del> with this object, i.e:
<add> with this object, i.e.:
<ide>
<ide> >>> publisher = self.get_publisher()
<ide> >>> # do something with publisher
<ide> def get_consumer(self):
<ide> :rtype: :class:`celery.messaging.TaskConsumer`.
<ide>
<ide> Please be sure to close the AMQP connection when you're done
<del> with this object. i.e:
<add> with this object. i.e.:
<ide>
<ide> >>> consumer = self.get_consumer()
<ide> >>> # do something with consumer | 2 |
Ruby | Ruby | remove reference to full_clone in coretap | 6f6cbc592ac32a760aeb02772420732b9238db59 | <ide><path>Library/Homebrew/tap.rb
<ide> def self.ensure_installed!
<ide>
<ide> # CoreTap never allows shallow clones (on request from GitHub).
<ide> def install(quiet: false, clone_target: nil, force_auto_update: nil)
<del> raise "Shallow clones are not supported for homebrew-core!" unless full_clone
<del>
<ide> remote = Homebrew::EnvConfig.core_git_remote
<ide> if remote != default_remote
<ide> $stderr.puts "HOMEBREW_CORE_GIT_REMOTE set: using #{remote} for Homebrew/core Git remote URL." | 1 |
Javascript | Javascript | use prettyformat for metro logging | abd7faf3547e165abfc52383d3709b9d4d2e9006 | <ide><path>Libraries/Utilities/HMRClient.js
<ide>
<ide> const Platform = require('./Platform');
<ide> const invariant = require('invariant');
<add>const prettyFormat = require('pretty-format');
<ide>
<ide> const MetroHMRClient = require('metro/src/lib/bundle-modules/HMRClient');
<ide>
<ide> const HMRClient: HMRClientNativeInterface = {
<ide> },
<ide>
<ide> log(level: LogLevel, data: Array<mixed>) {
<del> let message;
<del> try {
<del> message = JSON.stringify({type: 'log', level, data});
<del> } catch (error) {
<del> message = JSON.stringify({type: 'log', level, data: [error.message]});
<del> }
<del>
<ide> try {
<ide> if (hmrClient) {
<del> hmrClient.send(message);
<add> hmrClient.send(
<add> JSON.stringify({
<add> type: 'log',
<add> level,
<add> data: data.map(message =>
<add> typeof message === 'string'
<add> ? message
<add> : prettyFormat(message, {
<add> escapeString: true,
<add> highlight: true,
<add> maxDepth: 3,
<add> min: true,
<add> plugins: [prettyFormat.plugins.ReactElement],
<add> }),
<add> ),
<add> }),
<add> );
<ide> }
<ide> } catch (error) {
<ide> // If sending logs causes any failures we want to silently ignore them | 1 |
Text | Text | indicate the format of process.version | 0dae5d93809450a7dce1f9370473a1ffc480657d | <ide><path>doc/api/process.md
<ide> added: v0.1.3
<ide>
<ide> * {string}
<ide>
<del>The `process.version` property returns the Node.js version string.
<add>The `process.version` property returns the Node.js version string in the form of
<add>`v<major>.<minor>.<patch>`.
<ide>
<ide> ```js
<ide> console.log(`Version: ${process.version}`); | 1 |
Text | Text | fix code example in ecdh.setpublickey() | aed17e963ae6c4fb8b745116823863450761d33d | <ide><path>doc/api/crypto.md
<ide> Example (obtaining a shared secret):
<ide> const {
<ide> createECDH,
<ide> createHash,
<del>} = await crypto('crypto');
<add>} = await import('crypto');
<ide>
<ide> const alice = createECDH('secp256k1');
<ide> const bob = createECDH('secp256k1'); | 1 |
Java | Java | fix marbles of first(t) | 72f24e2d1603a4b210d3331911b242ce84c5b0a7 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java
<ide> public final Maybe<T> firstElement() {
<ide> * Returns a {@link Single} that emits only the very first item emitted by this {@code Flowable}, or a default
<ide> * item if this {@code Flowable} completes without emitting anything.
<ide> * <p>
<del> * <img width="640" height="285" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/first.s.png" alt="">
<add> * <img width="640" height="298" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.first.s.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The operator honors backpressure from downstream and consumes the current {@code Flowable} in a bounded manner.</dd>
<ide><path>src/main/java/io/reactivex/rxjava3/core/Observable.java
<ide> public final Maybe<T> firstElement() {
<ide> * Returns a {@link Single} that emits only the very first item emitted by the current {@code Observable}, or a default item
<ide> * if the current {@code Observable} completes without emitting any items.
<ide> * <p>
<del> * <img width="640" height="285" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/first.s.png" alt="">
<add> * <img width="640" height="283" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/first.s.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code first} does not operate by default on a particular {@link Scheduler}.</dd> | 2 |
Ruby | Ruby | add missing require | 687db9f86d23c21decddc4ec981f36e1c5fc8447 | <ide><path>actionpack/test/abstract/abstract_controller_test.rb
<ide> require 'abstract_unit'
<add>require 'set'
<ide>
<ide> module AbstractController
<ide> module Testing | 1 |
PHP | PHP | fix docblock of database component | 618114204c2be4e1e305cb1ed502d16e0ec1f0c7 | <ide><path>src/Illuminate/Database/Connection.php
<ide> class Connection implements ConnectionInterface
<ide> /**
<ide> * All of the callbacks that should be invoked before a query is executed.
<ide> *
<del> * @var array
<add> * @var \Closure[]
<ide> */
<ide> protected $beforeExecutingCallbacks = [];
<ide>
<ide> class Connection implements ConnectionInterface
<ide> /**
<ide> * Type mappings that should be registered with new Doctrine connections.
<ide> *
<del> * @var array
<add> * @var array<string, string>
<ide> */
<ide> protected $doctrineTypeMappings = [];
<ide>
<ide> /**
<ide> * The connection resolvers.
<ide> *
<del> * @var array
<add> * @var \Closure[]
<ide> */
<ide> protected static $resolvers = [];
<ide>
<ide><path>src/Illuminate/Database/ConnectionResolver.php
<ide> class ConnectionResolver implements ConnectionResolverInterface
<ide> /**
<ide> * All of the registered connections.
<ide> *
<del> * @var array
<add> * @var \Illuminate\Database\ConnectionInterface[]
<ide> */
<ide> protected $connections = [];
<ide>
<ide> class ConnectionResolver implements ConnectionResolverInterface
<ide> /**
<ide> * Create a new connection resolver instance.
<ide> *
<del> * @param array $connections
<add> * @param array<string, \Illuminate\Database\ConnectionInterface> $connections
<ide> * @return void
<ide> */
<ide> public function __construct(array $connections = [])
<ide><path>src/Illuminate/Database/DatabaseManager.php
<ide> class DatabaseManager implements ConnectionResolverInterface
<ide> /**
<ide> * The active connection instances.
<ide> *
<del> * @var array
<add> * @var array<string, \Illuminate\Database\Connection>
<ide> */
<ide> protected $connections = [];
<ide>
<ide> /**
<ide> * The custom connection resolvers.
<ide> *
<del> * @var array
<add> * @var array<string, callable>
<ide> */
<ide> protected $extensions = [];
<ide>
<ide> class DatabaseManager implements ConnectionResolverInterface
<ide> /**
<ide> * The custom Doctrine column types.
<ide> *
<del> * @var array
<add> * @var array<string, array>
<ide> */
<ide> protected $doctrineTypes = [];
<ide>
<ide> public function setDefaultConnection($name)
<ide> /**
<ide> * Get all of the support drivers.
<ide> *
<del> * @return array
<add> * @return string[]
<ide> */
<ide> public function supportedDrivers()
<ide> {
<ide> public function supportedDrivers()
<ide> /**
<ide> * Get all of the drivers that are actually available.
<ide> *
<del> * @return array
<add> * @return string[]
<ide> */
<ide> public function availableDrivers()
<ide> {
<ide> public function forgetExtension($name)
<ide> /**
<ide> * Return all of the created connections.
<ide> *
<del> * @return array
<add> * @return array<string, \Illuminate\Database\Connection>
<ide> */
<ide> public function getConnections()
<ide> { | 3 |
Javascript | Javascript | fix jshint errors | 05a32f07339b4b0c61e36ee87db079d143567631 | <ide><path>Gruntfile.js
<ide> var fs = require('fs'),
<ide> module.exports = function (grunt) {
<ide>
<ide> var minifiedFiles = {
<del> 'min/langs.min.js' : ['min/langs.js'],
<del> 'min/moment.min.js' : ['moment.js']
<del> };
<del>
<del> var minLangs = {
<del> langs: {
<del> src: ['min/langs.js'],
<del> dest: 'min/langs.min.js'
<del> }
<del> };
<add> 'min/langs.min.js' : ['min/langs.js'],
<add> 'min/moment.min.js' : ['moment.js']
<add> },
<add> minLangs = {
<add> langs: {
<add> src: ['min/langs.js'],
<add> dest: 'min/langs.min.js'
<add> }
<add> };
<ide>
<ide> // all the lang files need to be added manually
<ide> fs.readdirSync('./lang').forEach(function (path) {
<ide> module.exports = function (grunt) {
<ide> src = ['lang/' + path];
<ide>
<ide> minifiedFiles[dest] = src;
<del> minLangs[path] = {src:src, dest:dest};
<add> minLangs[path] = {src: src, dest: dest};
<ide> }
<ide> });
<ide> | 1 |
Python | Python | remove unused variable in configure.py | 32d58d72710e262a94693488b57c60fa66a6653e | <ide><path>configure.py
<ide> def icu_download(path):
<ide> 'variables': {}
<ide> }
<ide> icu_config_name = 'icu_config.gypi'
<del> def write_config(data, name):
<del> return
<ide>
<ide> # write an empty file to start with
<ide> write(icu_config_name, do_not_edit + | 1 |
PHP | PHP | try a larger value for the fractional tests | 75792dc8ed71b032bcc906af41f1cb3557a02512 | <ide><path>tests/Fixture/DatatypesFixture.php
<ide> class DatatypesFixture extends TestFixture
<ide> public $fields = [
<ide> 'id' => ['type' => 'biginteger'],
<ide> 'cost' => ['type' => 'decimal', 'length' => 20, 'precision' => 1, 'null' => true],
<del> 'fraction' => ['type' => 'decimal', 'length' => 20, 'precision' => 19, 'null' => true],
<add> 'fraction' => ['type' => 'decimal', 'length' => 15, 'precision' => 14, 'null' => true],
<ide> 'floaty' => ['type' => 'float', 'null' => true],
<ide> 'small' => ['type' => 'smallinteger', 'null' => true],
<ide> 'tiny' => ['type' => 'tinyinteger', 'null' => true],
<ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testSelectLargeNumbers()
<ide> $this->assertNotEmpty($out, 'Should get a record');
<ide> $this->assertSame($big, $out->cost);
<ide>
<del> $small = '0.123456789012345';
<add> $small = '0.12345678901234';
<ide> $entity = $table->newEntity(['fraction' => $small]);
<ide>
<ide> $table->saveOrFail($entity);
<ide> public function testSelectLargeNumbers()
<ide> ])
<ide> ->first();
<ide> $this->assertNotEmpty($out, 'Should get a record');
<del> $this->assertRegExp('/^0?\.123456789012345/', $out->fraction);
<add> $this->assertRegExp('/^0?\.12345678901234/', $out->fraction);
<ide>
<del> $small = 0.123456789012345;
<add> $small = 0.12345678901234;
<ide> $entity = $table->newEntity(['fraction' => $small]);
<ide>
<ide> $table->saveOrFail($entity); | 2 |
Python | Python | append planid to extra field | 27921de49eafd43765ff87e1860c5885495628f5 | <ide><path>libcloud/compute/drivers/linode.py
<ide> def _to_nodes(self, objs):
<ide> state=self.LINODE_STATES[o["STATUS"]],
<ide> driver=self.connection.driver)
<ide> n.extra = copy(o)
<add> n.extra["PLANID"] = self._linode_plan_ids.get(o.get("TOTALRAM"))
<ide> batch.append({"api_action": "linode.ip.list", "LinodeID": lid})
<ide>
<ide> # Avoid batch limitation | 1 |
Text | Text | remove wrong lxc support | 0e8d41272c7e5979d8a3f8676c94320f6c2ff691 | <ide><path>docs/introduction/understanding-docker.md
<ide> including: AUFS, btrfs, vfs, and DeviceMapper.
<ide>
<ide> ### Container format
<ide> Docker combines these components into a wrapper we call a container format. The
<del>default container format is called `libcontainer`. Docker also supports
<del>traditional Linux containers using [LXC](https://linuxcontainers.org/). In the
<del>future, Docker may support other container formats, for example, by integrating with
<del>BSD Jails or Solaris Zones.
<add>default container format is called `libcontainer`. In the future, Docker may
<add>support other container formats, for example, by integrating with BSD Jails
<add>or Solaris Zones.
<ide>
<ide> ## Next steps
<ide> ### Installing Docker | 1 |
Text | Text | unify link formatting in buffer.md | 7aa7971eec258ce1f8895ff66c5de78c6a59710f | <ide><path>doc/api/buffer.md
<ide>
<ide> > Stability: 2 - Stable
<ide>
<del>Prior to the introduction of [`TypedArray`], the JavaScript language had no
<add>Prior to the introduction of [`TypedArray`][], the JavaScript language had no
<ide> mechanism for reading or manipulating streams of binary data. The `Buffer` class
<ide> was introduced as part of the Node.js API to enable interaction with octet
<ide> streams in TCP streams, file system operations, and other contexts.
<ide>
<del>With [`TypedArray`] now available, the `Buffer` class implements the
<del>[`Uint8Array`] API in a manner that is more optimized and suitable for Node.js.
<add>With [`TypedArray`][] now available, the `Buffer` class implements the
<add>[`Uint8Array`][] API in a manner that is more optimized and suitable for
<add>Node.js.
<ide>
<ide> Instances of the `Buffer` class are similar to arrays of integers from `0` to
<ide> `255` (other integers are coerced to this range by `& 255` operation) but
<ide> differently based on what arguments are provided:
<ide> `new Buffer(num)` will return a `Buffer` with initialized memory.
<ide> * Passing a string, array, or `Buffer` as the first argument copies the
<ide> passed object's data into the `Buffer`.
<del>* Passing an [`ArrayBuffer`] or a [`SharedArrayBuffer`] returns a `Buffer` that
<del> shares allocated memory with the given array buffer.
<add>* Passing an [`ArrayBuffer`][] or a [`SharedArrayBuffer`][] returns a `Buffer`
<add> that shares allocated memory with the given array buffer.
<ide>
<ide> Because the behavior of `new Buffer()` is different depending on the type of the
<ide> first argument, security and reliability issues can be inadvertently introduced
<ide> performed.
<ide>
<ide> To make the creation of `Buffer` instances more reliable and less error-prone,
<ide> the various forms of the `new Buffer()` constructor have been **deprecated**
<del>and replaced by separate `Buffer.from()`, [`Buffer.alloc()`], and
<del>[`Buffer.allocUnsafe()`] methods.
<add>and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and
<add>[`Buffer.allocUnsafe()`][] methods.
<ide>
<ide> *Developers should migrate all existing uses of the `new Buffer()` constructors
<ide> to one of these new APIs.*
<ide>
<del>* [`Buffer.from(array)`] returns a new `Buffer` that *contains a copy* of the
<add>* [`Buffer.from(array)`][] returns a new `Buffer` that *contains a copy* of the
<ide> provided octets.
<ide> * [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
<ide> returns a new `Buffer` that *shares the same allocated memory* as the given
<del> [`ArrayBuffer`].
<del>* [`Buffer.from(buffer)`] returns a new `Buffer` that *contains a copy* of the
<add> [`ArrayBuffer`][].
<add>* [`Buffer.from(buffer)`][] returns a new `Buffer` that *contains a copy* of the
<ide> contents of the given `Buffer`.
<ide> * [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
<ide> `Buffer` that *contains a copy* of the provided string.
<ide> to one of these new APIs.*
<ide> uninitialized, the allocated segment of memory might contain old data that is
<ide> potentially sensitive.
<ide>
<del>`Buffer` instances returned by [`Buffer.allocUnsafe()`] *may* be allocated off
<add>`Buffer` instances returned by [`Buffer.allocUnsafe()`][] *may* be allocated off
<ide> a shared internal memory pool if `size` is less than or equal to half
<del>[`Buffer.poolSize`]. Instances returned by [`Buffer.allocUnsafeSlow()`] *never*
<del>use the shared internal memory pool.
<add>[`Buffer.poolSize`][]. Instances returned by [`Buffer.allocUnsafeSlow()`][]
<add>*never* use the shared internal memory pool.
<ide>
<ide> ### The `--zero-fill-buffers` command line option
<ide> <!-- YAML
<ide> added: v5.10.0
<ide> Node.js can be started using the `--zero-fill-buffers` command line option to
<ide> cause all newly allocated `Buffer` instances to be zero-filled upon creation by
<ide> default, including buffers returned by `new Buffer(size)`,
<del>[`Buffer.allocUnsafe()`], [`Buffer.allocUnsafeSlow()`], and `new
<add>[`Buffer.allocUnsafe()`][], [`Buffer.allocUnsafeSlow()`][], and `new
<ide> SlowBuffer(size)`. Use of this flag can have a significant negative impact on
<ide> performance. Use of the `--zero-fill-buffers` option is recommended only when
<ide> necessary to enforce that newly allocated `Buffer` instances cannot contain old
<ide> $ node --zero-fill-buffers
<ide>
<ide> ### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"?
<ide>
<del>When calling [`Buffer.allocUnsafe()`] and [`Buffer.allocUnsafeSlow()`], the
<add>When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the
<ide> segment of allocated memory is *uninitialized* (it is not zeroed-out). While
<ide> this design makes the allocation of memory quite fast, the allocated segment of
<ide> memory might contain old data that is potentially sensitive. Using a `Buffer`
<del>created by [`Buffer.allocUnsafe()`] without *completely* overwriting the memory
<del>can allow this old data to be leaked when the `Buffer` memory is read.
<add>created by [`Buffer.allocUnsafe()`][] without *completely* overwriting the
<add>memory can allow this old data to be leaked when the `Buffer` memory is read.
<ide>
<del>While there are clear performance advantages to using [`Buffer.allocUnsafe()`],
<del>extra care *must* be taken in order to avoid introducing security
<del>vulnerabilities into an application.
<add>While there are clear performance advantages to using
<add>[`Buffer.allocUnsafe()`][], extra care *must* be taken in order to avoid
<add>introducing security vulnerabilities into an application.
<ide>
<ide> ## Buffers and Character Encodings
<ide> <!-- YAML
<ide> The character encodings currently supported by Node.js include:
<ide>
<ide> * `'base64'` - Base64 encoding. When creating a `Buffer` from a string,
<ide> this encoding will also correctly accept "URL and Filename Safe Alphabet" as
<del> specified in [RFC 4648, Section 5].
<add> specified in [RFC 4648, Section 5][].
<ide>
<ide> * `'latin1'` - A way of encoding the `Buffer` into a one-byte encoded string
<del> (as defined by the IANA in [RFC 1345],
<add> (as defined by the IANA in [RFC 1345][],
<ide> page 63, to be the Latin-1 supplement block and C0/C1 control codes).
<ide>
<ide> * `'binary'` - Alias for `'latin1'`.
<ide> changes:
<ide> description: The `Buffer`s class now inherits from `Uint8Array`.
<ide> -->
<ide>
<del>`Buffer` instances are also [`Uint8Array`] instances. However, there are subtle
<del>incompatibilities with [`TypedArray`]. For example, while
<del>[`ArrayBuffer#slice()`] creates a copy of the slice, the implementation of
<add>`Buffer` instances are also [`Uint8Array`][] instances. However, there are
<add>subtle incompatibilities with [`TypedArray`][]. For example, while
<add>[`ArrayBuffer#slice()`][] creates a copy of the slice, the implementation of
<ide> [`Buffer#slice()`][`buf.slice()`] creates a view over the existing `Buffer`
<ide> without copying, making [`Buffer#slice()`][`buf.slice()`] far more efficient.
<ide>
<del>It is also possible to create new [`TypedArray`] instances from a `Buffer` with
<del>the following caveats:
<add>It is also possible to create new [`TypedArray`][] instances from a `Buffer`
<add>with the following caveats:
<ide>
<del>1. The `Buffer` object's memory is copied to the [`TypedArray`], not shared.
<add>1. The `Buffer` object's memory is copied to the [`TypedArray`][], not shared.
<ide>
<ide> 2. The `Buffer` object's memory is interpreted as an array of distinct
<ide> elements, and not as a byte array of the target type. That is,
<del>`new Uint32Array(Buffer.from([1, 2, 3, 4]))` creates a 4-element [`Uint32Array`]
<del> with elements `[1, 2, 3, 4]`, not a [`Uint32Array`] with a single element
<del> `[0x1020304]` or `[0x4030201]`.
<add>`new Uint32Array(Buffer.from([1, 2, 3, 4]))` creates a 4-element
<add>[`Uint32Array`][] with elements `[1, 2, 3, 4]`, not a [`Uint32Array`][] with a
<add>single element `[0x1020304]` or `[0x4030201]`.
<ide>
<ide> It is possible to create a new `Buffer` that shares the same allocated memory as
<del>a [`TypedArray`] instance by using the `TypedArray` object's `.buffer` property.
<add>a [`TypedArray`][] instance by using the `TypedArray` object's `.buffer`
<add>property.
<ide>
<ide> ```js
<ide> const arr = new Uint16Array(2);
<ide> console.log(buf2);
<ide> // Prints: <Buffer 88 13 70 17>
<ide> ```
<ide>
<del>Note that when creating a `Buffer` using a [`TypedArray`]'s `.buffer`, it is
<del>possible to use only a portion of the underlying [`ArrayBuffer`] by passing in
<add>Note that when creating a `Buffer` using a [`TypedArray`][]'s `.buffer`, it is
<add>possible to use only a portion of the underlying [`ArrayBuffer`][] by passing in
<ide> `byteOffset` and `length` parameters.
<ide>
<ide> ```js
<ide> console.log(buf.length);
<ide> // Prints: 16
<ide> ```
<ide>
<del>The `Buffer.from()` and [`TypedArray.from()`] have different signatures and
<del>implementations. Specifically, the [`TypedArray`] variants accept a second
<add>The `Buffer.from()` and [`TypedArray.from()`][] have different signatures and
<add>implementations. Specifically, the [`TypedArray`][] variants accept a second
<ide> argument that is a mapping function that is invoked on every element of the
<ide> typed array:
<ide>
<ide> typed array:
<ide> The `Buffer.from()` method, however, does not support the use of a mapping
<ide> function:
<ide>
<del>* [`Buffer.from(array)`]
<del>* [`Buffer.from(buffer)`]
<add>* [`Buffer.from(array)`][]
<add>* [`Buffer.from(buffer)`][]
<ide> * [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
<ide> * [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]
<ide>
<ide> for (const b of buf) {
<ide> // 3
<ide> ```
<ide>
<del>Additionally, the [`buf.values()`], [`buf.keys()`], and
<del>[`buf.entries()`] methods can be used to create iterators.
<add>Additionally, the [`buf.values()`][], [`buf.keys()`][], and
<add>[`buf.entries()`][] methods can be used to create iterators.
<ide>
<ide> ## Class: Buffer
<ide>
<ide> changes:
<ide> description: Calling this constructor emits a deprecation warning now.
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated: Use [`Buffer.from(array)`] instead.
<add>> Stability: 0 - Deprecated: Use [`Buffer.from(array)`][] instead.
<ide>
<ide> * `array` {integer[]} An array of bytes to copy from.
<ide>
<ide> changes:
<ide> > [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
<ide> > instead.
<ide>
<del>* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`],
<del> [`SharedArrayBuffer`] or the `.buffer` property of a [`TypedArray`].
<add>* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
<add> [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].
<ide> * `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
<ide> * `length` {integer} Number of bytes to expose.
<ide> **Default:** `arrayBuffer.length - byteOffset`.
<ide>
<del>This creates a view of the [`ArrayBuffer`] or [`SharedArrayBuffer`] without
<add>This creates a view of the [`ArrayBuffer`][] or [`SharedArrayBuffer`][] without
<ide> copying the underlying memory. For example, when passed a reference to the
<del>`.buffer` property of a [`TypedArray`] instance, the newly created `Buffer` will
<del>share the same allocated memory as the [`TypedArray`].
<add>`.buffer` property of a [`TypedArray`][] instance, the newly created `Buffer`
<add>will share the same allocated memory as the [`TypedArray`][].
<ide>
<ide> The optional `byteOffset` and `length` arguments specify a memory range within
<ide> the `arrayBuffer` that will be shared by the `Buffer`.
<ide> changes:
<ide> description: Calling this constructor emits a deprecation warning now.
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`] instead.
<add>> Stability: 0 - Deprecated: Use [`Buffer.from(buffer)`][] instead.
<ide>
<del>* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`] from which
<del> to copy data.
<add>* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
<add> which to copy data.
<ide>
<ide> Copies the passed `buffer` data onto a new `Buffer` instance.
<ide>
<ide> changes:
<ide> description: Calling this constructor emits a deprecation warning now.
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated: Use [`Buffer.alloc()`] instead (also see
<del>> [`Buffer.allocUnsafe()`]).
<add>> Stability: 0 - Deprecated: Use [`Buffer.alloc()`][] instead (also see
<add>> [`Buffer.allocUnsafe()`][]).
<ide>
<ide> * `size` {integer} The desired length of the new `Buffer`.
<ide>
<ide> Allocates a new `Buffer` of `size` bytes. If `size` is larger than
<del>[`buffer.constants.MAX_LENGTH`] or smaller than 0, [`ERR_INVALID_OPT_VALUE`] is
<del>thrown. A zero-length `Buffer` is created if `size` is 0.
<add>[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
<add>is thrown. A zero-length `Buffer` is created if `size` is 0.
<ide>
<ide> Prior to Node.js 8.0.0, the underlying memory for `Buffer` instances
<ide> created in this way is *not initialized*. The contents of a newly created
<ide> console.log(buf);
<ide> ```
<ide>
<ide> If `size` is larger than
<del>[`buffer.constants.MAX_LENGTH`] or smaller than 0, [`ERR_INVALID_OPT_VALUE`] is
<del>thrown. A zero-length `Buffer` is created if `size` is 0.
<add>[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
<add>is thrown. A zero-length `Buffer` is created if `size` is 0.
<ide>
<ide> If `fill` is specified, the allocated `Buffer` will be initialized by calling
<ide> [`buf.fill(fill)`][`buf.fill()`].
<ide> console.log(buf);
<ide> // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
<ide> ```
<ide>
<del>Calling [`Buffer.alloc()`] can be significantly slower than the alternative
<del>[`Buffer.allocUnsafe()`] but ensures that the newly created `Buffer` instance
<add>Calling [`Buffer.alloc()`][] can be significantly slower than the alternative
<add>[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
<ide> contents will *never contain sensitive data*.
<ide>
<ide> A `TypeError` will be thrown if `size` is not a number.
<ide> changes:
<ide> * `size` {integer} The desired length of the new `Buffer`.
<ide>
<ide> Allocates a new `Buffer` of `size` bytes. If `size` is larger than
<del>[`buffer.constants.MAX_LENGTH`] or smaller than 0, [`ERR_INVALID_OPT_VALUE`] is
<del>thrown. A zero-length `Buffer` is created if `size` is 0.
<add>[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
<add>is thrown. A zero-length `Buffer` is created if `size` is 0.
<ide>
<ide> The underlying memory for `Buffer` instances created in this way is *not
<ide> initialized*. The contents of the newly created `Buffer` are unknown and
<del>*may contain sensitive data*. Use [`Buffer.alloc()`] instead to initialize
<add>*may contain sensitive data*. Use [`Buffer.alloc()`][] instead to initialize
<ide> `Buffer` instances with zeroes.
<ide>
<ide> ```js
<ide> console.log(buf);
<ide> A `TypeError` will be thrown if `size` is not a number.
<ide>
<ide> Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
<del>size [`Buffer.poolSize`] that is used as a pool for the fast allocation of new
<del>`Buffer` instances created using [`Buffer.allocUnsafe()`] and the deprecated
<add>size [`Buffer.poolSize`][] that is used as a pool for the fast allocation of new
<add>`Buffer` instances created using [`Buffer.allocUnsafe()`][] and the deprecated
<ide> `new Buffer(size)` constructor only when `size` is less than or equal to
<del>`Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`] divided by two).
<add>`Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`][] divided by two).
<ide>
<ide> Use of this pre-allocated internal memory pool is a key difference between
<ide> calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
<ide> Specifically, `Buffer.alloc(size, fill)` will *never* use the internal `Buffer`
<ide> pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
<del>`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`]. The
<add>`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`][]. The
<ide> difference is subtle but can be important when an application requires the
<del>additional performance that [`Buffer.allocUnsafe()`] provides.
<add>additional performance that [`Buffer.allocUnsafe()`][] provides.
<ide>
<ide> ### Class Method: Buffer.allocUnsafeSlow(size)
<ide> <!-- YAML
<ide> added: v5.12.0
<ide> * `size` {integer} The desired length of the new `Buffer`.
<ide>
<ide> Allocates a new `Buffer` of `size` bytes. If `size` is larger than
<del>[`buffer.constants.MAX_LENGTH`] or smaller than 0, [`ERR_INVALID_OPT_VALUE`] is
<del>thrown. A zero-length `Buffer` is created if `size` is 0.
<add>[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
<add>is thrown. A zero-length `Buffer` is created if `size` is 0.
<ide>
<ide> The underlying memory for `Buffer` instances created in this way is *not
<ide> initialized*. The contents of the newly created `Buffer` are unknown and
<ide> *may contain sensitive data*. Use [`buf.fill(0)`][`buf.fill()`] to initialize
<ide> such `Buffer` instances with zeroes.
<ide>
<del>When using [`Buffer.allocUnsafe()`] to allocate new `Buffer` instances,
<add>When using [`Buffer.allocUnsafe()`][] to allocate new `Buffer` instances,
<ide> allocations under 4KB are sliced from a single pre-allocated `Buffer`. This
<ide> allows applications to avoid the garbage collection overhead of creating many
<ide> individually allocated `Buffer` instances. This approach improves both
<ide> changes:
<ide> * Returns: {integer} The number of bytes contained within `string`.
<ide>
<ide> Returns the actual byte length of a string. This is not the same as
<del>[`String.prototype.length`] since that returns the number of *characters* in
<add>[`String.prototype.length`][] since that returns the number of *characters* in
<ide> a string.
<ide>
<ide> For `'base64'` and `'hex'`, this function assumes valid input. For strings that
<ide> console.log(`${str}: ${str.length} characters, ` +
<ide> // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
<ide> ```
<ide>
<del>When `string` is a `Buffer`/[`DataView`]/[`TypedArray`]/[`ArrayBuffer`]/
<del>[`SharedArrayBuffer`], the actual byte length is returned.
<add>When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
<add>[`SharedArrayBuffer`][], the actual byte length is returned.
<ide>
<ide> ### Class Method: Buffer.compare(buf1, buf2)
<ide> <!-- YAML
<ide> changes:
<ide> description: The elements of `list` can now be `Uint8Array`s.
<ide> -->
<ide>
<del>* `list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`] instances
<del> to concat.
<add>* `list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`][]
<add> instances to concat.
<ide> * `totalLength` {integer} Total length of the `Buffer` instances in `list`
<ide> when concatenated.
<ide> * Returns: {Buffer}
<ide> appropriate for `Buffer.from()` variants.
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`],
<del> [`SharedArrayBuffer`], or the `.buffer` property of a [`TypedArray`].
<add>* `arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][],
<add> [`SharedArrayBuffer`][], or the `.buffer` property of a [`TypedArray`][].
<ide> * `byteOffset` {integer} Index of first byte to expose. **Default:** `0`.
<ide> * `length` {integer} Number of bytes to expose.
<ide> **Default:** `arrayBuffer.length - byteOffset`.
<ide>
<del>This creates a view of the [`ArrayBuffer`] without copying the underlying
<add>This creates a view of the [`ArrayBuffer`][] without copying the underlying
<ide> memory. For example, when passed a reference to the `.buffer` property of a
<del>[`TypedArray`] instance, the newly created `Buffer` will share the same
<del>allocated memory as the [`TypedArray`].
<add>[`TypedArray`][] instance, the newly created `Buffer` will share the same
<add>allocated memory as the [`TypedArray`][].
<ide>
<ide> ```js
<ide> const arr = new Uint16Array(2);
<ide> console.log(buf.length);
<ide> // Prints: 2
<ide> ```
<ide>
<del>A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`] or a
<del>[`SharedArrayBuffer`] or other type appropriate for `Buffer.from()` variants.
<add>A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`][] or a
<add>[`SharedArrayBuffer`][] or other type appropriate for `Buffer.from()` variants.
<ide>
<ide> ### Class Method: Buffer.from(buffer)
<ide> <!-- YAML
<ide> added: v5.10.0
<ide> -->
<ide>
<del>* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`] from which
<del> to copy data.
<add>* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
<add> which to copy data.
<ide>
<ide> Copies the passed `buffer` data onto a new `Buffer` instance.
<ide>
<ide> changes:
<ide> description: Additional parameters for specifying offsets are supported now.
<ide> -->
<ide>
<del>* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`] with which to
<add>* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to
<ide> compare `buf`.
<ide> * `targetStart` {integer} The offset within `target` at which to begin
<ide> comparison. **Default:** `0`.
<ide> changes:
<ide> * `sourceStart` {integer} The offset within `buf` at which to begin comparison.
<ide> **Default:** `0`.
<ide> * `sourceEnd` {integer} The offset within `buf` at which to end comparison
<del> (not inclusive). **Default:** [`buf.length`].
<add> (not inclusive). **Default:** [`buf.length`][].
<ide> * Returns: {integer}
<ide>
<ide> Compares `buf` with `target` and returns a number indicating whether `buf`
<ide> console.log(buf1.compare(buf2, 5, 6, 5));
<ide> // Prints: 1
<ide> ```
<ide>
<del>[`ERR_OUT_OF_RANGE`] is thrown if `targetStart < 0`, `sourceStart < 0`,
<add>[`ERR_OUT_OF_RANGE`][] is thrown if `targetStart < 0`, `sourceStart < 0`,
<ide> `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
<ide>
<ide> ### buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide>
<del>* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`] to copy into.
<add>* `target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] to copy into.
<ide> * `targetStart` {integer} The offset within `target` at which to begin
<ide> writing. **Default:** `0`.
<ide> * `sourceStart` {integer} The offset within `buf` from which to begin copying.
<ide> **Default:** `0`.
<ide> * `sourceEnd` {integer} The offset within `buf` at which to stop copying (not
<del> inclusive). **Default:** [`buf.length`].
<add> inclusive). **Default:** [`buf.length`][].
<ide> * Returns: {integer} The number of bytes copied.
<ide>
<ide> Copies data from a region of `buf` to a region in `target` even if the `target`
<ide> added: v1.1.0
<ide>
<ide> * Returns: {Iterator}
<ide>
<del>Creates and returns an [iterator] of `[index, byte]` pairs from the contents of
<del>`buf`.
<add>Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
<add>of `buf`.
<ide>
<ide> ```js
<ide> // Log the entire contents of a `Buffer`.
<ide> changes:
<ide> description: The arguments can now be `Uint8Array`s.
<ide> -->
<ide>
<del>* `otherBuffer` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`] with which to
<add>* `otherBuffer` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to
<ide> compare `buf`.
<ide> * Returns: {boolean}
<ide>
<ide> changes:
<ide> * `offset` {integer} Number of bytes to skip before starting to fill `buf`.
<ide> **Default:** `0`.
<ide> * `end` {integer} Where to stop filling `buf` (not inclusive). **Default:**
<del> [`buf.length`].
<add> [`buf.length`][].
<ide> * `encoding` {string} The encoding for `value` if `value` is a string.
<ide> **Default:** `'utf8'`.
<ide> * Returns: {Buffer} A reference to `buf`.
<ide> If `value` is:
<ide>
<ide> * a string, `value` is interpreted according to the character encoding in
<ide> `encoding`.
<del> * a `Buffer` or [`Uint8Array`], `value` will be used in its entirety.
<del> To compare a partial `Buffer`, use [`buf.slice()`].
<add> * a `Buffer` or [`Uint8Array`][], `value` will be used in its entirety.
<add> To compare a partial `Buffer`, use [`buf.slice()`][].
<ide> * a number, `value` will be interpreted as an unsigned 8-bit integer
<ide> value between `0` and `255`.
<ide>
<ide> an integer between 0 and 255.
<ide>
<ide> If `byteOffset` is not a number, it will be coerced to a number. If the result
<ide> of coercion is `NaN` or `0`, then the entire buffer will be searched. This
<del>behavior matches [`String#indexOf()`].
<add>behavior matches [`String#indexOf()`][].
<ide>
<ide> ```js
<ide> const b = Buffer.from('abcdef');
<ide> added: v1.1.0
<ide>
<ide> * Returns: {Iterator}
<ide>
<del>Creates and returns an [iterator] of `buf` keys (indices).
<add>Creates and returns an [iterator][] of `buf` keys (indices).
<ide>
<ide> ```js
<ide> const buf = Buffer.from('buffer');
<ide> changes:
<ide> * `value` {string|Buffer|Uint8Array|integer} What to search for.
<ide> * `byteOffset` {integer} Where to begin searching in `buf`. If negative, then
<ide> offset is calculated from the end of `buf`. **Default:**
<del> [`buf.length`]` - 1`.
<add> [`buf.length`][]` - 1`.
<ide> * `encoding` {string} If `value` is a string, this is the encoding used to
<ide> determine the binary representation of the string that will be searched for in
<ide> `buf`. **Default:** `'utf8'`.
<ide> * Returns: {integer} The index of the last occurrence of `value` in `buf`, or
<ide> `-1` if `buf` does not contain `value`.
<ide>
<del>Identical to [`buf.indexOf()`], except the last occurrence of `value` is found
<add>Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
<ide> rather than the first occurrence.
<ide>
<ide> ```js
<ide> an integer between 0 and 255.
<ide>
<ide> If `byteOffset` is not a number, it will be coerced to a number. Any arguments
<ide> that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer.
<del>This behavior matches [`String#lastIndexOf()`].
<add>This behavior matches [`String#lastIndexOf()`][].
<ide>
<ide> ```js
<ide> const b = Buffer.from('abcdef');
<ide> console.log(buf.length);
<ide> While the `length` property is not immutable, changing the value of `length`
<ide> can result in undefined and inconsistent behavior. Applications that wish to
<ide> modify the length of a `Buffer` should therefore treat `length` as read-only and
<del>use [`buf.slice()`] to create a new `Buffer`.
<add>use [`buf.slice()`][] to create a new `Buffer`.
<ide>
<ide> ```js
<ide> let buf = Buffer.allocUnsafe(10);
<ide> console.log(buf.length);
<ide> deprecated: v8.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated: Use [`buf.buffer`] instead.
<add>> Stability: 0 - Deprecated: Use [`buf.buffer`][] instead.
<ide>
<ide> The `buf.parent` property is a deprecated alias for `buf.buffer`.
<ide>
<ide> changes:
<ide>
<ide> * `start` {integer} Where the new `Buffer` will start. **Default:** `0`.
<ide> * `end` {integer} Where the new `Buffer` will end (not inclusive).
<del> **Default:** [`buf.length`].
<add> **Default:** [`buf.length`][].
<ide> * Returns: {Buffer}
<ide>
<ide> Returns a new `Buffer` that references the same memory as the original, but
<ide> offset and cropped by the `start` and `end` indices.
<ide>
<del>Specifying `end` greater than [`buf.length`] will return the same result as
<del>that of `end` equal to [`buf.length`].
<add>Specifying `end` greater than [`buf.length`][] will return the same result as
<add>that of `end` equal to [`buf.length`][].
<ide>
<ide> Modifying the new `Buffer` slice will modify the memory in the original `Buffer`
<ide> because the allocated memory of the two objects overlap.
<ide> added: v5.10.0
<ide> * Returns: {Buffer} A reference to `buf`.
<ide>
<ide> Interprets `buf` as an array of unsigned 16-bit integers and swaps the
<del>byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`] if [`buf.length`] is
<del>not a multiple of 2.
<add>byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
<add>is not a multiple of 2.
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
<ide> added: v5.10.0
<ide> * Returns: {Buffer} A reference to `buf`.
<ide>
<ide> Interprets `buf` as an array of unsigned 32-bit integers and swaps the
<del>byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`] if [`buf.length`] is
<del>not a multiple of 4.
<add>byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
<add>is not a multiple of 4.
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
<ide> added: v6.3.0
<ide> * Returns: {Buffer} A reference to `buf`.
<ide>
<ide> Interprets `buf` as an array of 64-bit numbers and swaps byte order *in-place*.
<del>Throws [`ERR_INVALID_BUFFER_SIZE`] if [`buf.length`] is not a multiple of 8.
<add>Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8.
<ide>
<ide> ```js
<ide> const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
<ide> added: v0.9.2
<ide>
<ide> * Returns: {Object}
<ide>
<del>Returns a JSON representation of `buf`. [`JSON.stringify()`] implicitly calls
<add>Returns a JSON representation of `buf`. [`JSON.stringify()`][] implicitly calls
<ide> this function when stringifying a `Buffer` instance.
<ide>
<ide> ```js
<ide> added: v0.1.90
<ide> * `encoding` {string} The character encoding to use. **Default:** `'utf8'`.
<ide> * `start` {integer} The byte offset to start decoding at. **Default:** `0`.
<ide> * `end` {integer} The byte offset to stop decoding at (not inclusive).
<del> **Default:** [`buf.length`].
<add> **Default:** [`buf.length`][].
<ide> * Returns: {string}
<ide>
<ide> Decodes `buf` to a string according to the specified character encoding in
<ide> added: v1.1.0
<ide>
<ide> * Returns: {Iterator}
<ide>
<del>Creates and returns an [iterator] for `buf` values (bytes). This function is
<add>Creates and returns an [iterator][] for `buf` values (bytes). This function is
<ide> called automatically when a `Buffer` is used in a `for..of` statement.
<ide>
<ide> ```js
<ide> added: v0.5.4
<ide>
<ide> Returns the maximum number of bytes that will be returned when
<ide> `buf.inspect()` is called. This can be overridden by user modules. See
<del>[`util.inspect()`] for more details on `buf.inspect()` behavior.
<add>[`util.inspect()`][] for more details on `buf.inspect()` behavior.
<ide>
<ide> Note that this is a property on the `buffer` module returned by
<ide> `require('buffer')`, not on the `Buffer` global or a `Buffer` instance.
<ide> Note that this is a property on the `buffer` module returned by
<ide> deprecated: v6.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`] instead.
<add>> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
<ide>
<ide> Returns an un-pooled `Buffer`.
<ide>
<ide> has observed undue memory retention in their applications.
<ide> deprecated: v6.0.0
<ide> -->
<ide>
<del>> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`] instead.
<add>> Stability: 0 - Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
<ide>
<ide> * `size` {integer} The desired length of the new `SlowBuffer`.
<ide>
<ide> Allocates a new `Buffer` of `size` bytes. If `size` is larger than
<del>[`buffer.constants.MAX_LENGTH`] or smaller than 0, [`ERR_INVALID_OPT_VALUE`] is
<del>thrown. A zero-length `Buffer` is created if `size` is 0.
<add>[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_OPT_VALUE`][]
<add>is thrown. A zero-length `Buffer` is created if `size` is 0.
<ide>
<ide> The underlying memory for `SlowBuffer` instances is *not initialized*. The
<ide> contents of a newly created `SlowBuffer` are unknown and may contain sensitive | 1 |
Javascript | Javascript | fix helpers, layoutservice and logarithmic tests | a93b3f45ac0e25bdda01d558acbffbe1d1e36e24 | <ide><path>test/core.helpers.tests.js
<ide> describe('Core helper tests', function() {
<ide> helpers = window.Chart.helpers;
<ide> });
<ide>
<del> it('Should iterate over an array and pass the extra data to that function', function() {
<add> it('should iterate over an array and pass the extra data to that function', function() {
<ide> var testData = [0, 9, "abc"];
<ide> var scope = {}; // fake out the scope and ensure that 'this' is the correct thing
<ide>
<ide> describe('Core helper tests', function() {
<ide> expect(iterated.slice().reverse()).toEqual(testData);
<ide> });
<ide>
<del> it('Should iterate over properties in an object', function() {
<add> it('should iterate over properties in an object', function() {
<ide> var testData = {
<ide> myProp1: 'abc',
<ide> myProp2: 276,
<ide> describe('Core helper tests', function() {
<ide> }).not.toThrow();
<ide> });
<ide>
<del> it('Should clone an object', function() {
<add> it('should clone an object', function() {
<ide> var testData = {
<ide> myProp1: 'abc',
<ide> myProp2: ['a', 'b'],
<ide> describe('Core helper tests', function() {
<ide> });
<ide> });
<ide>
<del> it('Should merge a normal config without scales', function() {
<add> it('should merge a normal config without scales', function() {
<ide> var baseConfig = {
<ide> valueProp: 5,
<ide> arrayProp: [1, 2, 3, 4, 5, 6],
<ide> describe('Core helper tests', function() {
<ide> });
<ide> });
<ide>
<del> it('Should merge scale configs', function() {
<add> it('should merge scale configs', function() {
<ide> var baseConfig = {
<ide> scales: {
<ide> prop1: {
<ide> describe('Core helper tests', function() {
<ide> expect(helpers.findPreviousWhere(data, callback, 0)).toBe(undefined);
<ide> });
<ide>
<del> it('Should get the correct sign', function() {
<add> it('should get the correct sign', function() {
<ide> expect(helpers.sign(0)).toBe(0);
<ide> expect(helpers.sign(10)).toBe(1);
<ide> expect(helpers.sign(-5)).toBe(-1);
<ide> describe('Core helper tests', function() {
<ide> expect(helpers.almostEquals(1e30, 1e30 + Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
<ide> });
<ide>
<del> it('Should generate ids', function() {
<del> expect(helpers.uid()).toBe('chart-0');
<del> expect(helpers.uid()).toBe('chart-1');
<del> expect(helpers.uid()).toBe('chart-2');
<del> expect(helpers.uid()).toBe('chart-3');
<add> it('should generate integer ids', function() {
<add> var uid = helpers.uid();
<add> expect(uid).toEqual(jasmine.any(Number));
<add> expect(helpers.uid()).toBe(uid + 1);
<add> expect(helpers.uid()).toBe(uid + 2);
<add> expect(helpers.uid()).toBe(uid + 3);
<ide> });
<ide>
<ide> it('should detect a number', function() {
<ide><path>test/core.layoutService.tests.js
<ide> // Tests of the scale service
<ide> describe('Test the layout service', function() {
<del> it('should fit a simple chart with 2 scales', function() {
<del> var chartInstance = {
<del> boxes: [],
<del> };
<del>
<del> var xScaleID = 'xScale';
<del> var yScaleID = 'yScale';
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: yScaleID,
<del> data: [10, 5, 0, 25, 78, -10]
<del> }],
<del> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
<del> };
<del> var mockContext = window.createMockContext();
<add> beforeEach(function() {
<add> window.addDefaultMatchers(jasmine);
<add> });
<ide>
<del> var xScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
<del> var XConstructor = Chart.scaleService.getScaleConstructor('category');
<del> var xScale = new XConstructor({
<del> ctx: mockContext,
<del> options: xScaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: xScaleID
<del> });
<add> afterEach(function() {
<add> window.releaseAllCharts();
<add> });
<ide>
<del> var yScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear'));
<del> var YConstructor = Chart.scaleService.getScaleConstructor('linear');
<del> var yScale = new YConstructor({
<del> ctx: mockContext,
<del> options: yScaleConfig,
<del> chart: {
<del> data: mockData
<add> it('should fit a simple chart with 2 scales', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [
<add> { data: [10, 5, 0, 25, 78, -10] }
<add> ],
<add> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> },
<del> id: yScaleID
<del> });
<del>
<del> chartInstance.boxes.push(xScale);
<del> chartInstance.boxes.push(yScale);
<del>
<del> var canvasWidth = 250;
<del> var canvasHeight = 150;
<del> Chart.layoutService.update(chartInstance, canvasWidth, canvasHeight);
<del>
<del> expect(chartInstance.chartArea).toEqual({
<del> left: 50,
<del> right: 250,
<del> top: 0,
<del> bottom: 83.6977778440511,
<del> });
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'xScale',
<add> type: 'category'
<add> }],
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'linear'
<add> }]
<add> }
<add> }
<add> }, {
<add> height: '150px',
<add> width: '250px'
<add> });
<add>
<add> expect(chart.chartArea.bottom).toBeCloseToPixel(112);
<add> expect(chart.chartArea.left).toBeCloseToPixel(41);
<add> expect(chart.chartArea.right).toBeCloseToPixel(250);
<add> expect(chart.chartArea.top).toBeCloseToPixel(32);
<ide>
<ide> // Is xScale at the right spot
<del> expect(xScale.left).toBe(50);
<del> expect(xScale.right).toBe(250);
<del> expect(xScale.top).toBe(83.6977778440511);
<del> expect(xScale.bottom).toBe(150);
<del> expect(xScale.labelRotation).toBe(50);
<add> expect(chart.scales.xScale.bottom).toBeCloseToPixel(150);
<add> expect(chart.scales.xScale.left).toBeCloseToPixel(41);
<add> expect(chart.scales.xScale.right).toBeCloseToPixel(250);
<add> expect(chart.scales.xScale.top).toBeCloseToPixel(112);
<add> expect(chart.scales.xScale.labelRotation).toBeCloseTo(25);
<ide>
<ide> // Is yScale at the right spot
<del> expect(yScale.left).toBe(0);
<del> expect(yScale.right).toBe(50);
<del> expect(yScale.top).toBe(0);
<del> expect(yScale.bottom).toBe(83.6977778440511);
<add> expect(chart.scales.yScale.bottom).toBeCloseToPixel(112);
<add> expect(chart.scales.yScale.left).toBeCloseToPixel(0);
<add> expect(chart.scales.yScale.right).toBeCloseToPixel(41);
<add> expect(chart.scales.yScale.top).toBeCloseToPixel(32);
<add> expect(chart.scales.yScale.labelRotation).toBeCloseTo(0);
<ide> });
<ide>
<ide> it('should fit scales that are in the top and right positions', function() {
<del> var chartInstance = {
<del> boxes: [],
<del> };
<del>
<del> var xScaleID = 'xScale';
<del> var yScaleID = 'yScale';
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: yScaleID,
<del> data: [10, 5, 0, 25, 78, -10]
<del> }],
<del> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
<del> };
<del> var mockContext = window.createMockContext();
<del>
<del> var xScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
<del> xScaleConfig.position = 'top';
<del> var XConstructor = Chart.scaleService.getScaleConstructor('category');
<del> var xScale = new XConstructor({
<del> ctx: mockContext,
<del> options: xScaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: xScaleID
<del> });
<del>
<del> var yScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear'));
<del> yScaleConfig.position = 'right';
<del> var YConstructor = Chart.scaleService.getScaleConstructor('linear');
<del> var yScale = new YConstructor({
<del> ctx: mockContext,
<del> options: yScaleConfig,
<del> chart: {
<del> data: mockData
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [
<add> { data: [10, 5, 0, 25, 78, -10] }
<add> ],
<add> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> },
<del> id: yScaleID
<del> });
<del>
<del> chartInstance.boxes.push(xScale);
<del> chartInstance.boxes.push(yScale);
<del>
<del> var canvasWidth = 250;
<del> var canvasHeight = 150;
<del> Chart.layoutService.update(chartInstance, canvasWidth, canvasHeight);
<del>
<del> expect(chartInstance.chartArea).toEqual({
<del> left: 0,
<del> right: 200,
<del> top: 66.3022221559489,
<del> bottom: 150,
<del> });
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'xScale',
<add> type: 'category',
<add> position: 'top'
<add> }],
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'linear',
<add> position: 'right'
<add> }]
<add> }
<add> }
<add> }, {
<add> height: '150px',
<add> width: '250px'
<add> });
<add>
<add> expect(chart.chartArea.bottom).toBeCloseToPixel(150);
<add> expect(chart.chartArea.left).toBeCloseToPixel(0);
<add> expect(chart.chartArea.right).toBeCloseToPixel(209);
<add> expect(chart.chartArea.top).toBeCloseToPixel(71);
<ide>
<ide> // Is xScale at the right spot
<del> expect(xScale.left).toBe(0);
<del> expect(xScale.right).toBe(200);
<del> expect(xScale.top).toBe(0);
<del> expect(xScale.bottom).toBe(66.3022221559489);
<del> expect(xScale.labelRotation).toBe(50);
<add> expect(chart.scales.xScale.bottom).toBeCloseToPixel(71);
<add> expect(chart.scales.xScale.left).toBeCloseToPixel(0);
<add> expect(chart.scales.xScale.right).toBeCloseToPixel(209);
<add> expect(chart.scales.xScale.top).toBeCloseToPixel(32);
<add> expect(chart.scales.xScale.labelRotation).toBeCloseTo(25);
<ide>
<ide> // Is yScale at the right spot
<del> expect(yScale.left).toBe(200);
<del> expect(yScale.right).toBe(250);
<del> expect(yScale.top).toBe(66.3022221559489);
<del> expect(yScale.bottom).toBe(150);
<add> expect(chart.scales.yScale.bottom).toBeCloseToPixel(150);
<add> expect(chart.scales.yScale.left).toBeCloseToPixel(209);
<add> expect(chart.scales.yScale.right).toBeCloseToPixel(250);
<add> expect(chart.scales.yScale.top).toBeCloseToPixel(71);
<add> expect(chart.scales.yScale.labelRotation).toBeCloseTo(0);
<ide> });
<ide>
<del> it('should fit multiple axes in the same position', function() {
<del> var chartInstance = {
<del> boxes: [],
<del> };
<del>
<del> var xScaleID = 'xScale';
<del> var yScaleID1 = 'yScale1';
<del> var yScaleID2 = 'yScale2';
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: yScaleID1,
<del> data: [10, 5, 0, 25, 78, -10]
<del> }, {
<del> yAxisID: yScaleID2,
<del> data: [-19, -20, 0, -99, -50, 0]
<del> }],
<del> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
<del> };
<del> var mockContext = window.createMockContext();
<add> it('should fit scales that overlap the chart area', function() {
<add> var chart = window.acquireChart({
<add> type: 'radar',
<add> data: {
<add> datasets: [{
<add> data: [10, 5, 0, 25, 78, -10]
<add> }, {
<add> data: [-19, -20, 0, -99, -50, 0]
<add> }],
<add> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<add> }
<add> });
<add>
<add> expect(chart.chartArea.bottom).toBeCloseToPixel(512);
<add> expect(chart.chartArea.left).toBeCloseToPixel(0);
<add> expect(chart.chartArea.right).toBeCloseToPixel(512);
<add> expect(chart.chartArea.top).toBeCloseToPixel(32);
<add>
<add> expect(chart.scale.bottom).toBeCloseToPixel(512);
<add> expect(chart.scale.left).toBeCloseToPixel(0);
<add> expect(chart.scale.right).toBeCloseToPixel(512);
<add> expect(chart.scale.top).toBeCloseToPixel(32);
<add> expect(chart.scale.width).toBeCloseToPixel(512);
<add> expect(chart.scale.height).toBeCloseToPixel(480)
<add> });
<ide>
<del> var xScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
<del> var XConstructor = Chart.scaleService.getScaleConstructor('category');
<del> var xScale = new XConstructor({
<del> ctx: mockContext,
<del> options: xScaleConfig,
<del> chart: {
<del> data: mockData
<add> it('should fit multiple axes in the same position', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale1',
<add> data: [10, 5, 0, 25, 78, -10]
<add> }, {
<add> yAxisID: 'yScale2',
<add> data: [-19, -20, 0, -99, -50, 0]
<add> }],
<add> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> },
<del> id: xScaleID
<del> });
<del>
<del> var yScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear'));
<del> var YConstructor = Chart.scaleService.getScaleConstructor('linear');
<del> var yScale1 = new YConstructor({
<del> ctx: mockContext,
<del> options: yScaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: yScaleID1
<del> });
<del> var yScale2 = new YConstructor({
<del> ctx: mockContext,
<del> options: yScaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: yScaleID2
<del> });
<del>
<del> chartInstance.boxes.push(xScale);
<del> chartInstance.boxes.push(yScale1);
<del> chartInstance.boxes.push(yScale2);
<del>
<del> var canvasWidth = 250;
<del> var canvasHeight = 150;
<del> Chart.layoutService.update(chartInstance, canvasWidth, canvasHeight);
<del>
<del> expect(chartInstance.chartArea).toEqual({
<del> left: 110,
<del> right: 250,
<del> top: 0,
<del> bottom: 83.6977778440511,
<del> });
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'xScale',
<add> type: 'category'
<add> }],
<add> yAxes: [{
<add> id: 'yScale1',
<add> type: 'linear'
<add> }, {
<add> id: 'yScale2',
<add> type: 'linear'
<add> }]
<add> }
<add> }
<add> }, {
<add> height: '150px',
<add> width: '250px'
<add> });
<add>
<add> expect(chart.chartArea.bottom).toBeCloseToPixel(102);
<add> expect(chart.chartArea.left).toBeCloseToPixel(86);
<add> expect(chart.chartArea.right).toBeCloseToPixel(250);
<add> expect(chart.chartArea.top).toBeCloseToPixel(32);
<ide>
<ide> // Is xScale at the right spot
<del> expect(xScale.left).toBe(110);
<del> expect(xScale.right).toBe(250);
<del> expect(xScale.top).toBe(83.6977778440511);
<del> expect(xScale.bottom).toBe(150);
<add> expect(chart.scales.xScale.bottom).toBeCloseToPixel(150);
<add> expect(chart.scales.xScale.left).toBeCloseToPixel(86);
<add> expect(chart.scales.xScale.right).toBeCloseToPixel(250);
<add> expect(chart.scales.xScale.top).toBeCloseToPixel(103);
<add> expect(chart.scales.xScale.labelRotation).toBeCloseTo(50);
<ide>
<ide> // Are yScales at the right spot
<del> expect(yScale1.left).toBe(0);
<del> expect(yScale1.right).toBe(50);
<del> expect(yScale1.top).toBe(0);
<del> expect(yScale1.bottom).toBe(83.6977778440511);
<del>
<del> expect(yScale2.left).toBe(50);
<del> expect(yScale2.right).toBe(110);
<del> expect(yScale2.top).toBe(0);
<del> expect(yScale2.bottom).toBe(83.6977778440511);
<del> });
<del>
<del> // This is an oddball case. What happens is, when the scales are fit the first time they must fit within the assigned size. In this case,
<del> // the labels on the xScale need to rotate to fit. However, when the scales are fit again after the width of the left axis is determined,
<del> // the labels do not need to rotate. Previously, the chart was too small because the chartArea did not expand to take up the space freed up
<del> // due to the lack of label rotation
<del> it('should fit scales that overlap the chart area', function() {
<del> var chartInstance = {
<del> boxes: [],
<del> };
<del>
<del> var scaleID = 'scaleID';
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 0, 25, 78, -10]
<del> }, {
<del> yAxisID: scaleID,
<del> data: [-19, -20, 0, -99, -50, 0]
<del> }],
<del> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
<del> };
<del> var mockContext = window.createMockContext();
<del>
<del> var scaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear'));
<del> var ScaleConstructor = Chart.scaleService.getScaleConstructor('radialLinear');
<del> var scale = new ScaleConstructor({
<del> ctx: mockContext,
<del> options: scaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: scaleID
<del> });
<del>
<del> chartInstance.boxes.push(scale);
<del>
<del> var canvasWidth = 300;
<del> var canvasHeight = 350;
<del> Chart.layoutService.update(chartInstance, canvasWidth, canvasHeight);
<del>
<del> expect(chartInstance.chartArea).toEqual({
<del> left: 0,
<del> right: 300,
<del> top: 0,
<del> bottom: 350,
<del> });
<del>
<del> expect(scale.left).toBe(0);
<del> expect(scale.right).toBe(300);
<del> expect(scale.top).toBe(0);
<del> expect(scale.bottom).toBe(350);
<del> expect(scale.width).toBe(300);
<del> expect(scale.height).toBe(350)
<add> expect(chart.scales.yScale1.bottom).toBeCloseToPixel(102);
<add> expect(chart.scales.yScale1.left).toBeCloseToPixel(0);
<add> expect(chart.scales.yScale1.right).toBeCloseToPixel(41);
<add> expect(chart.scales.yScale1.top).toBeCloseToPixel(32);
<add> expect(chart.scales.yScale1.labelRotation).toBeCloseTo(0);
<add>
<add> expect(chart.scales.yScale2.bottom).toBeCloseToPixel(102);
<add> expect(chart.scales.yScale2.left).toBeCloseToPixel(41);
<add> expect(chart.scales.yScale2.right).toBeCloseToPixel(86);
<add> expect(chart.scales.yScale2.top).toBeCloseToPixel(32);
<add> expect(chart.scales.yScale2.labelRotation).toBeCloseTo(0);
<ide> });
<ide>
<ide> it ('should fix a full width box correctly', function() {
<del> var chartInstance = {
<del> boxes: [],
<del> };
<del>
<del> var xScaleID1= 'xScale1';
<del> var xScaleID2 = 'xScale2';
<del> var yScaleID = 'yScale2';
<del>
<del> var mockData = {
<del> datasets: [{
<del> xAxisID: xScaleID1,
<del> data: [10, 5, 0, 25, 78, -10]
<del> }, {
<del> xAxisID: xScaleID2,
<del> data: [-19, -20, 0, -99, -50, 0]
<del> }],
<del> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
<del> };
<del> var mockContext = window.createMockContext();
<del>
<del> var xScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('category'));
<del> var XConstructor = Chart.scaleService.getScaleConstructor('category');
<del> var xScale1 = new XConstructor({
<del> ctx: mockContext,
<del> options: xScaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: xScaleID1
<del> });
<del> var xScale2 = new XConstructor({
<del> ctx: mockContext,
<del> options: Chart.helpers.extend(Chart.helpers.clone(xScaleConfig), {
<del> position: 'top',
<del> fullWidth: true
<del> }),
<del> chart: {
<del> data: mockData,
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> xAxisID: 'xScale1',
<add> data: [10, 5, 0, 25, 78, -10]
<add> }, {
<add> xAxisID: 'xScale2',
<add> data: [-19, -20, 0, -99, -50, 0]
<add> }],
<add> labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
<ide> },
<del> id: xScaleID2
<del> });
<del>
<del> var yScaleConfig = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear'));
<del> var YConstructor = Chart.scaleService.getScaleConstructor('linear');
<del> var yScale = new YConstructor({
<del> ctx: mockContext,
<del> options: yScaleConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: yScaleID
<del> });
<del>
<del> chartInstance.boxes.push(xScale1);
<del> chartInstance.boxes.push(xScale2);
<del> chartInstance.boxes.push(yScale);
<del>
<del> var canvasWidth = 250;
<del> var canvasHeight = 150;
<del> Chart.layoutService.update(chartInstance, canvasWidth, canvasHeight);
<del>
<del> expect(chartInstance.chartArea).toEqual({
<del> left: 60,
<del> right: 250,
<del> top: 54.495963211660246,
<del> bottom: 83.6977778440511
<del> });
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'xScale1',
<add> type: 'category'
<add> }, {
<add> id: 'xScale2',
<add> type: 'category',
<add> position: 'top',
<add> fullWidth: true
<add> }],
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'linear'
<add> }]
<add> }
<add> }
<add> });
<add>
<add> expect(chart.chartArea.bottom).toBeCloseToPixel(484);
<add> expect(chart.chartArea.left).toBeCloseToPixel(45);
<add> expect(chart.chartArea.right).toBeCloseToPixel(512);
<add> expect(chart.chartArea.top).toBeCloseToPixel(60);
<ide>
<ide> // Are xScales at the right spot
<del> expect(xScale1.left).toBe(60);
<del> expect(xScale1.right).toBe(250);
<del> expect(xScale1.top).toBeCloseTo(83.69, 1e-3);
<del> expect(xScale1.bottom).toBe(150);
<add> expect(chart.scales.xScale1.bottom).toBeCloseToPixel(512);
<add> expect(chart.scales.xScale1.left).toBeCloseToPixel(45);
<add> expect(chart.scales.xScale1.right).toBeCloseToPixel(512);
<add> expect(chart.scales.x1.top).toBeCloseToPixel(484);
<ide>
<del> expect(xScale2.left).toBe(0);
<del> expect(xScale2.right).toBe(250);
<del> expect(xScale2.top).toBe(0);
<del> expect(xScale2.bottom).toBeCloseTo(54.49, 1e-3);
<add> expect(chart.scales.xScale2.bottom).toBeCloseToPixel(28);
<add> expect(chart.scales.xScale2.left).toBeCloseToPixel(0);
<add> expect(chart.scales.xScale2.right).toBeCloseToPixel(512);
<add> expect(chart.scales.xScale2.top).toBeCloseToPixel(0);
<ide>
<ide> // Is yScale at the right spot
<del> expect(yScale.left).toBe(0);
<del> expect(yScale.right).toBe(60);
<del> expect(yScale.top).toBeCloseTo(54.49, 1e-3);
<del> expect(yScale.bottom).toBeCloseTo(83.69, 1e-3);
<add> expect(chart.scales.yScale.bottom).toBeCloseToPixel(484);
<add> expect(chart.scales.yScale.left).toBeCloseToPixel(0);
<add> expect(chart.scales.yScale.right).toBeCloseToPixel(45);
<add> expect(chart.scales.yScale.top).toBeCloseToPixel(60);
<ide> });
<ide> });
<ide><path>test/scale.logarithmic.tests.js
<ide> describe('Logarithmic Scale tests', function() {
<ide>
<del> it('Should register the constructor with the scale service', function() {
<add> beforeEach(function() {
<add> window.addDefaultMatchers(jasmine);
<add> });
<add>
<add> afterEach(function() {
<add> window.releaseAllCharts();
<add> });
<add>
<add> it('should register the constructor with the scale service', function() {
<ide> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<ide> expect(Constructor).not.toBe(undefined);
<ide> expect(typeof Constructor).toBe('function');
<ide> });
<ide>
<del> it('Should have the correct default config', function() {
<add> it('should have the correct default config', function() {
<ide> var defaultConfig = Chart.scaleService.getScaleDefaults('logarithmic');
<ide> expect(defaultConfig).toEqual({
<ide> display: true,
<ide> describe('Logarithmic Scale tests', function() {
<ide> expect(defaultConfig.ticks.callback).toEqual(jasmine.any(Function));
<ide> });
<ide>
<del> it('Should correctly determine the max & min data values', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 5000, 78, 450]
<del> }, {
<del> yAxisID: 'second scale',
<del> data: [1, 1000, 10, 100],
<del> }, {
<del> yAxisID: scaleID,
<del> data: [150]
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: Chart.scaleService.getScaleDefaults('logarithmic'), // use default config for scale
<del> chart: {
<del> data: mockData,
<add> it('should correctly determine the max & min data values', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale0',
<add> data: [42, 1000, 64, 100],
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: [10, 5, 5000, 78, 450]
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: [150]
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e']
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'logarithmic'
<add> }, {
<add> id: 'yScale1',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> expect(scale).not.toEqual(undefined); // must construct
<del> expect(scale.min).toBe(undefined); // not yet set
<del> expect(scale.max).toBe(undefined);
<add> expect(chart.scales.yScale0).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale0.min).toBe(10);
<add> expect(chart.scales.yScale0.max).toBe(1000);
<ide>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(1);
<del> expect(scale.max).toBe(5000);
<add> expect(chart.scales.yScale1).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale1.min).toBe(1);
<add> expect(chart.scales.yScale1.max).toBe(5000);
<ide> });
<ide>
<del> it('Should correctly determine the max & min of string data values', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: ['10', '5', '5000', '78', '450']
<del> }, {
<del> yAxisID: 'second scale',
<del> data: ['1', '1000', '10', '100'],
<del> }, {
<del> yAxisID: scaleID,
<del> data: ['150']
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: Chart.scaleService.getScaleDefaults('logarithmic'), // use default config for scale
<del> chart: {
<del> data: mockData,
<add> it('should correctly determine the max & min of string data values', function() {
<add> var chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale0',
<add> data: ['42', '1000', '64', '100'],
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: ['10', '5', '5000', '78', '450']
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: ['150']
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e']
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'logarithmic'
<add> }, {
<add> id: 'yScale1',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> expect(scale).not.toEqual(undefined); // must construct
<del> expect(scale.min).toBe(undefined); // not yet set
<del> expect(scale.max).toBe(undefined);
<add> expect(chart.scales.yScale0).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale0.min).toBe(10);
<add> expect(chart.scales.yScale0.max).toBe(1000);
<ide>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(1);
<del> expect(scale.max).toBe(5000);
<add> expect(chart.scales.yScale1).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale1.min).toBe(1);
<add> expect(chart.scales.yScale1.max).toBe(5000);
<ide> });
<ide>
<del> it('Should correctly determine the max & min data values when there are hidden datasets', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 5000, 78, 450]
<del> }, {
<del> yAxisID: 'second scale',
<del> data: [1, 1000, 10, 100],
<del> }, {
<del> yAxisID: scaleID,
<del> data: [50000],
<del> hidden: true
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: Chart.scaleService.getScaleDefaults('logarithmic'), // use default config for scale
<del> chart: {
<del> data: mockData
<add> it('should correctly determine the max & min data values when there are hidden datasets', function() {
<add> var chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale1',
<add> data: [10, 5, 5000, 78, 450]
<add> }, {
<add> yAxisID: 'yScale0',
<add> data: [42, 1000, 64, 100],
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: [50000],
<add> hidden: true
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e']
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'logarithmic'
<add> }, {
<add> id: 'yScale1',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> expect(scale).not.toEqual(undefined); // must construct
<del> expect(scale.min).toBe(undefined); // not yet set
<del> expect(scale.max).toBe(undefined);
<del>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(1);
<del> expect(scale.max).toBe(5000);
<add> expect(chart.scales.yScale1).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale1.min).toBe(1);
<add> expect(chart.scales.yScale1.max).toBe(5000);
<ide> });
<ide>
<del> it('Should correctly determine the max & min data values when there is NaN data', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [undefined, 10, null, 5, 5000, NaN, 78, 450]
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var options = Chart.scaleService.getScaleDefaults('logarithmic');
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: options, // use default config for scale
<del> chart: {
<del> data: mockData
<add> it('should correctly determine the max & min data values when there is NaN data', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> data: [undefined, 10, null, 5, 5000, NaN, 78, 450]
<add> }, {
<add> data: [undefined, 28, null, 1000, 500, NaN, 50, 42]
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e', 'f' ,'g']
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> expect(scale).not.toEqual(undefined); // must construct
<del> expect(scale.min).toBe(undefined); // not yet set
<del> expect(scale.max).toBe(undefined);
<del>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(1);
<del> expect(scale.max).toBe(5000);
<add> expect(chart.scales.yScale).not.toEqual(undefined); // must construct
<add> expect(chart.scales.yScale.min).toBe(1);
<add> expect(chart.scales.yScale.max).toBe(5000);
<ide>
<ide> // Turn on stacked mode since it uses it's own
<del> options.stacked = true;
<add> chart.options.scales.yAxes[0].stacked = true;
<add> chart.update();
<ide>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(1);
<del> expect(scale.max).toBe(5000);
<add> expect(chart.scales.yScale.min).toBe(10);
<add> expect(chart.scales.yScale.max).toBe(6000);
<ide> });
<ide>
<del>
<del> it('Should correctly determine the max & min for scatter data', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> xAxisID: scaleID, // for the horizontal scale
<del> yAxisID: scaleID,
<del> data: [{
<del> x: 10,
<del> y: 100
<del> }, {
<del> x: 2,
<del> y: 6
<del> }, {
<del> x: 65,
<del> y: 121
<del> }, {
<del> x: 99,
<del> y: 7
<add> it('should correctly determine the max & min for scatter data', function() {
<add> var chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> data: [
<add> { x: 10, y: 100 },
<add> { x: 2, y: 6 },
<add> { x: 65, y: 121 },
<add> { x: 99, y: 7 }
<add> ]
<ide> }]
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var verticalScale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> xAxes: [{
<add> id: 'xScale',
<add> type: 'logarithmic',
<add> position: 'bottom'
<add> }],
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> verticalScale.update(400, 400);
<del> expect(verticalScale.min).toBe(1);
<del> expect(verticalScale.max).toBe(200);
<del>
<del> var horizontalConfig = Chart.helpers.clone(config);
<del> horizontalConfig.position = 'bottom';
<del> var horizontalScale = new Constructor({
<del> ctx: mockContext,
<del> options: horizontalConfig,
<del> chart: {
<del> data: mockData
<del> },
<del> id: scaleID,
<del> });
<add> expect(chart.scales.xScale.min).toBe(1);
<add> expect(chart.scales.xScale.max).toBe(100);
<ide>
<del> horizontalScale.update(400, 400);
<del> expect(horizontalScale.min).toBe(1);
<del> expect(horizontalScale.max).toBe(100);
<add> expect(chart.scales.yScale.min).toBe(1);
<add> expect(chart.scales.yScale.max).toBe(200);
<ide> });
<ide>
<del> it('Should correctly determine the min and max data values when stacked mode is turned on', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 5, 78, 100],
<del> type: 'bar'
<del> }, {
<del> yAxisID: 'second scale',
<del> data: [-1000, 1000],
<del> }, {
<del> yAxisID: scaleID,
<del> data: [150, 10, 10, 100, 10, 9],
<del> type: 'bar'
<del> }, {
<del> yAxisID: scaleID,
<del> data: [100, 100, 100, 100, 100, 100],
<del> type: 'line'
<del> }]
<del> };
<del>
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> config.stacked = true; // enable scale stacked mode
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should correctly determine the min and max data values when stacked mode is turned on', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> type: 'bar',
<add> yAxisID: 'yScale0',
<add> data: [10, 5, 1, 5, 78, 100]
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: [-1000, 1000],
<add> }, {
<add> type: 'bar',
<add> yAxisID: 'yScale0',
<add> data: [150, 10, 10, 100, 10, 9]
<add> }, {
<add> type: 'line',
<add> yAxisID: 'yScale0',
<add> data: [100, 100, 100, 100, 100, 100]
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e', 'f']
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'logarithmic',
<add> stacked: true
<add> }, {
<add> id: 'yScale1',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(10);
<del> expect(scale.max).toBe(200);
<add> expect(chart.scales.yScale0.min).toBe(10);
<add> expect(chart.scales.yScale0.max).toBe(200);
<ide> });
<ide>
<del> it('Should correctly determine the min and max data values when stacked mode is turned on ignoring hidden datasets', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 5, 78, 100],
<del> type: 'bar'
<del> }, {
<del> yAxisID: 'second scale',
<del> data: [-1000, 1000],
<del> type: 'bar'
<del> }, {
<del> yAxisID: scaleID,
<del> data: [150, 10, 10, 100, 10, 9],
<del> type: 'bar'
<del> }, {
<del> yAxisID: scaleID,
<del> data: [10000, 10000, 10000, 10000, 10000, 10000],
<del> hidden: true,
<del> type: 'bar'
<del> }]
<del> };
<del>
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> config.stacked = true; // enable scale stacked mode
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should correctly determine the min and max data values when stacked mode is turned on ignoring hidden datasets', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale0',
<add> data: [10, 5, 1, 5, 78, 100],
<add> type: 'bar'
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: [-1000, 1000],
<add> type: 'bar'
<add> }, {
<add> yAxisID: 'yScale0',
<add> data: [150, 10, 10, 100, 10, 9],
<add> type: 'bar'
<add> }, {
<add> yAxisID: 'yScale0',
<add> data: [10000, 10000, 10000, 10000, 10000, 10000],
<add> hidden: true,
<add> type: 'bar'
<add> }],
<add> labels: ['a', 'b', 'c', 'd', 'e', 'f']
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'logarithmic',
<add> stacked: true
<add> }, {
<add> id: 'yScale1',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(10);
<del> expect(scale.max).toBe(200);
<add> expect(chart.scales.yScale0.min).toBe(10);
<add> expect(chart.scales.yScale0.max).toBe(200);
<ide> });
<ide>
<del> it('Should ensure that the scale has a max and min that are not equal', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: []
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should ensure that the scale has a max and min that are not equal', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> data: []
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 00);
<del> expect(scale.min).toBe(1);
<del> expect(scale.max).toBe(10);
<add> expect(chart.scales.yScale.min).toBe(1);
<add> expect(chart.scales.yScale.max).toBe(10);
<ide>
<del> mockData.datasets = [{
<del> yAxisID: scaleID,
<del> data: [0.15, 0.15]
<del> }];
<add> chart.data.datasets[0].data = [0.15, 0.15];
<add> chart.update();
<ide>
<del> scale.update(400, 400);
<del> expect(scale.min).toBe(0.01);
<del> expect(scale.max).toBe(1);
<add> expect(chart.scales.yScale.min).toBe(0.01);
<add> expect(chart.scales.yScale.max).toBe(1);
<ide> });
<ide>
<del>
<del> it('Should use the min and max options', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [1, 1, 1, 2, 1, 0]
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del>
<del> config.ticks.min = 10;
<del> config.ticks.max = 1010;
<del>
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should use the min and max options', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> data: [1, 1, 1, 2, 1, 0]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic',
<add> ticks: {
<add> min: 10,
<add> max: 1010,
<add> callback: function(value) {
<add> return value;
<add> }
<add> }
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 00);
<del> scale.buildTicks();
<del> expect(scale.min).toBe(10);
<del> expect(scale.max).toBe(1010);
<del> expect(scale.ticks[0]).toBe(1010);
<del> expect(scale.ticks[scale.ticks.length - 1]).toBe(10);
<add> var yScale = chart.scales.yScale;
<add> var tickCount = yScale.ticks.length;
<add> expect(yScale.min).toBe(10);
<add> expect(yScale.max).toBe(1010);
<add> expect(yScale.ticks[0]).toBe(1010);
<add> expect(yScale.ticks[tickCount - 1]).toBe(10);
<ide> });
<ide>
<del> it('Should generate tick marks', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 25, 78]
<del> }, ]
<del> };
<del>
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: {},
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should generate tick marks', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> data: [10, 5, 1, 25, 78]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic',
<add> ticks: {
<add> callback: function(value) {
<add> return value;
<add> }
<add> }
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> // Set arbitrary width and height for now
<del> scale.width = 50;
<del> scale.height = 400;
<del>
<del> scale.determineDataLimits();
<del> scale.buildTicks();
<del>
<ide> // Counts down because the lines are drawn top to bottom
<del> expect(scale.ticks).toEqual([80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
<del> expect(scale.start).toBe(1);
<del> expect(scale.end).toBe(80);
<add> expect(chart.scales.yScale).toEqual(jasmine.objectContaining({
<add> ticks: [80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
<add> start: 1,
<add> end: 80
<add> }));
<ide> });
<ide>
<del> it('Should generate tick marks in the correct order in reversed mode', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 25, 78]
<del> }, ]
<del> };
<del>
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> config.ticks.reverse = true;
<del>
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: {},
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should generate tick marks in the correct order in reversed mode', function() {
<add> var chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> data: [10, 5, 1, 25, 78]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic',
<add> ticks: {
<add> reverse: true,
<add> callback: function(value) {
<add> return value;
<add> }
<add> }
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> // Set arbitrary width and height for now
<del> scale.width = 50;
<del> scale.height = 400;
<del>
<del> scale.determineDataLimits();
<del> scale.buildTicks();
<del>
<ide> // Counts down because the lines are drawn top to bottom
<del> expect(scale.ticks).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80]);
<del> expect(scale.start).toBe(80);
<del> expect(scale.end).toBe(1);
<add> expect(chart.scales.yScale).toEqual(jasmine.objectContaining({
<add> ticks: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80],
<add> start: 80,
<add> end: 1
<add> }));
<ide> });
<ide>
<del> it('Should build labels using the default template', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 25, 78]
<del> }, ]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should build labels using the default template', function() {
<add> var chart = window.acquireChart({
<add> type: 'line',
<add> data: {
<add> datasets: [{
<add> data: [10, 5, 1, 25, 78]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 400);
<del>
<del> expect(scale.ticks).toEqual(['8e+1', '', '', '5e+1', '', '', '2e+1', '1e+1', '', '', '', '', '5e+0', '', '', '2e+0', '1e+0']);
<add> expect(chart.scales.yScale.ticks).toEqual(['8e+1', '', '', '5e+1', '', '', '2e+1', '1e+1', '', '', '', '', '5e+0', '', '', '2e+0', '1e+0']);
<ide> });
<ide>
<del> it('Should build labels using the user supplied callback', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 25, 78]
<del> }, ]
<del> };
<del>
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> config.ticks.userCallback = function(value, index) {
<del> return index.toString();
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<add> it('should build labels using the user supplied callback', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> data: [10, 5, 1, 25, 78]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale',
<add> type: 'logarithmic',
<add> ticks: {
<add> callback: function(value, index) {
<add> return index.toString();
<add> }
<add> }
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 400);
<del>
<ide> // Just the index
<del> expect(scale.ticks).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']);
<add> expect(chart.scales.yScale.ticks).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']);
<ide> });
<ide>
<del> it('Should correctly get the correct label for a data item', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> yAxisID: scaleID,
<del> data: [10, 5, 5000, 78, 450]
<del> }, {
<del> yAxisID: 'second scale',
<del> data: [1, 1000, 10, 100],
<del> }, {
<del> yAxisID: scaleID,
<del> data: [150]
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var scale = new Constructor({
<del> ctx: mockContext,
<del> options: Chart.scaleService.getScaleDefaults('logarithmic'), // use default config for scale
<del> chart: {
<del> data: mockData,
<add> it('should correctly get the correct label for a data item', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> yAxisID: 'yScale0',
<add> data: [10, 5, 5000, 78, 450]
<add> }, {
<add> yAxisID: 'yScale1',
<add> data: [1, 1000, 10, 100],
<add> }, {
<add> yAxisID: 'yScale0',
<add> data: [150]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'yScale0',
<add> type: 'logarithmic'
<add> }, {
<add> id: 'yScale1',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> scale.update(400, 400);
<del>
<del> expect(scale.getLabelForIndex(0, 2)).toBe(150);
<add> expect(chart.scales.yScale1.getLabelForIndex(0, 2)).toBe(150);
<ide> });
<ide>
<del> it('Should get the correct pixel value for a point', function() {
<del> var scaleID = 'myScale';
<del>
<del> var mockData = {
<del> datasets: [{
<del> xAxisID: scaleID, // for the horizontal scale
<del> yAxisID: scaleID,
<del> data: [10, 5, 1, 25, 78]
<del> }]
<del> };
<del>
<del> var mockContext = window.createMockContext();
<del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('logarithmic'));
<del> var Constructor = Chart.scaleService.getScaleConstructor('logarithmic');
<del> var verticalScale = new Constructor({
<del> ctx: mockContext,
<del> options: config,
<del> chart: {
<del> data: mockData
<del> },
<del> id: scaleID
<del> });
<del>
<del> verticalScale.update(50, 100);
<del>
<del> // Fake out positioning of the scale service
<del> verticalScale.left = 0;
<del> verticalScale.top = 0;
<del> verticalScale.right = 50;
<del> verticalScale.bottom = 110;
<del> verticalScale.paddingTop = 5;
<del> verticalScale.paddingBottom = 5;
<del> verticalScale.width = 50;
<del> verticalScale.height = 110;
<del>
<del> expect(verticalScale.getPixelForValue(80, 0, 0)).toBe(5); // top + paddingTop
<del> expect(verticalScale.getPixelForValue(1, 0, 0)).toBe(105); // bottom - paddingBottom
<del> expect(verticalScale.getPixelForValue(10, 0, 0)).toBeCloseTo(52.4, 1e-4); // halfway
<del> expect(verticalScale.getPixelForValue(0, 0, 0)).toBe(5); // 0 is invalid. force it on top
<del>
<del> var horizontalConfig = Chart.helpers.clone(config);
<del> horizontalConfig.position = 'bottom';
<del> var horizontalScale = new Constructor({
<del> ctx: mockContext,
<del> options: horizontalConfig,
<del> chart: {
<del> data: mockData
<add> it('should get the correct pixel value for a point', function() {
<add> var chart = window.acquireChart({
<add> type: 'bar',
<add> data: {
<add> datasets: [{
<add> xAxisID: 'xScale', // for the horizontal scale
<add> yAxisID: 'yScale',
<add> data: [10, 5, 1, 25, 78]
<add> }],
<add> labels: []
<ide> },
<del> id: scaleID,
<add> options: {
<add> scales: {
<add> yAxes: [{
<add> id: 'xScale',
<add> type: 'logarithmic',
<add> position: 'bottom'
<add> }, {
<add> id: 'yScale',
<add> type: 'logarithmic'
<add> }]
<add> }
<add> }
<ide> });
<ide>
<del> horizontalScale.update(100, 50);
<del>
<del> // Fake out positioning of the scale service
<del> horizontalScale.left = 0;
<del> horizontalScale.top = 0;
<del> horizontalScale.right = 110;
<del> horizontalScale.bottom = 50;
<del> horizontalScale.paddingLeft = 5;
<del> horizontalScale.paddingRight = 5;
<del> horizontalScale.width = 110;
<del> horizontalScale.height = 50;
<del>
<del> expect(horizontalScale.getPixelForValue(80, 0, 0)).toBe(105); // right - paddingRight
<del> expect(horizontalScale.getPixelForValue(1, 0, 0)).toBe(5); // left + paddingLeft
<del> expect(horizontalScale.getPixelForValue(10, 0, 0)).toBeCloseTo(57.5, 1e-4); // halfway
<del> expect(horizontalScale.getPixelForValue(0, 0, 0)).toBe(5); // 0 is invalid, put it on the left.
<add> var xScale = chart.scales.xScale;
<add> expect(xScale.getPixelForValue(80, 0, 0)).toBeCloseToPixel(495); // right - paddingRight
<add> expect(xScale.getPixelForValue( 1, 0, 0)).toBeCloseToPixel(48); // left + paddingLeft
<add> expect(xScale.getPixelForValue(10, 0, 0)).toBeCloseToPixel(283); // halfway
<add> expect(xScale.getPixelForValue( 0, 0, 0)).toBeCloseToPixel(48); // 0 is invalid, put it on the left.
<add>
<add> var yScale = chart.scales.yScale;
<add> expect(yScale.getPixelForValue(80, 0, 0)).toBeCloseToPixel(32); // top + paddingTop
<add> expect(yScale.getPixelForValue( 1, 0, 0)).toBeCloseToPixel(456); // bottom - paddingBottom
<add> expect(yScale.getPixelForValue(10, 0, 0)).toBeCloseToPixel(234); // halfway
<add> expect(yScale.getPixelForValue( 0, 0, 0)).toBeCloseToPixel(32); // 0 is invalid. force it on top
<ide> });
<ide> }); | 3 |
PHP | PHP | support aggregate drivers | 7ba0c22133da7ca99d1ec1459630de01f95130c1 | <ide><path>src/Illuminate/Log/LogManager.php
<ide> public function driver($driver = null)
<ide> protected function get($name)
<ide> {
<ide> try {
<del> return $this->stores[$name] ?? with($this->resolve($name), function ($monolog) use ($name) {
<del> return $this->tap($name, new Logger($monolog, $this->app['events']));
<add> return $this->stores[$name] ?? with($this->resolve($name), function ($logger) use ($name) {
<add> return $this->tap($name, new Logger($logger, $this->app['events']));
<ide> });
<ide> } catch (Throwable $e) {
<ide> return tap($this->createEmergencyLogger(), function ($logger) use ($e) {
<ide> protected function createCustomDriver(array $config)
<ide> return $this->app->make($config['via'])->__invoke($config);
<ide> }
<ide>
<add> /**
<add> * Create a aggregate log driver instance.
<add> *
<add> * @param array $config
<add> * @return \Psr\Log\LoggerInterface
<add> */
<add> protected function createAggregateDriver(array $config)
<add> {
<add> $handlers = collect($config['channels'])->flatMap(function ($channel) {
<add> return $this->channel($channel)->getHandlers();
<add> })->all();
<add>
<add> return new Monolog($this->parseChannel($config), $handlers);
<add> }
<add>
<ide> /**
<ide> * Create an instance of the single file log driver.
<ide> * | 1 |
Mixed | Javascript | fix 404 [ci skip] | 6e28760316d2b1466bf74651e969669e7c57a763 | <ide><path>website/src/components/button.js
<ide> Button.defaultProps = {
<ide> }
<ide>
<ide> Button.propTypes = {
<del> to: PropTypes.string.isRequired,
<add> to: PropTypes.string,
<ide> variant: PropTypes.oneOf(['primary', 'secondary', 'tertiary']),
<ide> large: PropTypes.bool,
<ide> icon: PropTypes.string,
<ide><path>website/src/pages/404.js
<add>import React from 'react'
<add>import { window } from 'browser-monads'
<add>import { graphql } from 'gatsby'
<add>
<add>import Template from '../templates/index'
<add>import { LandingHeader, LandingTitle } from '../components/landing'
<add>import Button from '../components/button'
<add>
<add>export default ({ data, location }) => {
<add> const { nightly } = data.site.siteMetadata
<add> const pageContext = { title: '404 Error', searchExclude: true, isIndex: false }
<add> return (
<add> <Template data={data} pageContext={pageContext} location={location}>
<add> <LandingHeader style={{ minHeight: 400 }} nightly={nightly}>
<add> <LandingTitle>
<add> Ooops, this page
<add> <br />
<add> does not exist!
<add> </LandingTitle>
<add> <br />
<add> <Button onClick={() => window.history.go(-1)} variant="tertiary">
<add> Click here to go back
<add> </Button>
<add> </LandingHeader>
<add> </Template>
<add> )
<add>}
<add>
<add>export const pageQuery = graphql`
<add> query {
<add> site {
<add> siteMetadata {
<add> nightly
<add> title
<add> description
<add> navigation {
<add> text
<add> url
<add> }
<add> docSearch {
<add> apiKey
<add> indexName
<add> }
<add> }
<add> }
<add> }
<add>`
<ide><path>website/src/pages/404.md
<del>---
<del>title: 404 Error
<del>---
<del>
<del>import Error from 'widgets/404.js'
<del>
<del><Error />
<ide><path>website/src/widgets/404.js
<del>import React from 'react'
<del>import { window } from 'browser-monads'
<del>
<del>import { LandingHeader, LandingTitle } from '../components/landing'
<del>import Button from '../components/button'
<del>
<del>export default () => (
<del> <LandingHeader style={{ minHeight: 400 }}>
<del> <LandingTitle>
<del> Ooops, this page
<del> <br />
<del> does not exist!
<del> </LandingTitle>
<del> <br />
<del> <Button onClick={() => window.history.go(-1)} variant="tertiary">
<del> Click here to go back
<del> </Button>
<del> </LandingHeader>
<del>) | 4 |
Go | Go | use errors.is() to handle image store errors | d131147a5cc0f2972f52b487a4b966013749c145 | <ide><path>daemon/images/image_list.go
<ide> package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<ide> "context"
<add> "errors"
<ide> "fmt"
<ide> "sort"
<ide> "time"
<ide> func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions)
<ide> if err != nil {
<ide> // The layer may have been deleted between the call to `Map()` or
<ide> // `Heads()` and the call to `Get()`, so we just ignore this error
<del> if err == layer.ErrLayerDoesNotExist {
<add> if errors.Is(err, layer.ErrLayerDoesNotExist) {
<ide> continue
<ide> }
<ide> return nil, err
<ide><path>image/store.go
<ide> func (is *store) restore() error {
<ide> }
<ide> l, err = is.lss.Get(chainID)
<ide> if err != nil {
<del> if err == layer.ErrLayerDoesNotExist {
<add> if errors.Is(err, layer.ErrLayerDoesNotExist) {
<ide> logrus.WithFields(f{"chainID": chainID, "os": img.OperatingSystem(), "err": err}).Error("not restoring image")
<ide> return nil
<ide> }
<ide><path>layer/layer_test.go
<ide> package layer // import "github.com/docker/docker/layer"
<ide>
<ide> import (
<ide> "bytes"
<add> "errors"
<ide> "io"
<ide> "os"
<ide> "path/filepath"
<ide> func TestStoreRestore(t *testing.T) {
<ide> // Create again with same name, should return error
<ide> if _, err := ls2.CreateRWLayer("some-mount_name", layer3b.ChainID(), nil); err == nil {
<ide> t.Fatal("Expected error creating mount with same name")
<del> } else if err != ErrMountNameConflict {
<add> } else if !errors.Is(err, ErrMountNameConflict) {
<ide> t.Fatal(err)
<ide> }
<ide> | 3 |
Text | Text | add note about debugging worker_threads | 84a95b82204a987fb3fc859e757a8c0df004a1f0 | <ide><path>doc/api/debugger.md
<ide> debugging sessions.)
<ide> If the Chrome browser is older than 66.0.3345.0,
<ide> use `inspector.html` instead of `js_app.html` in the above URL.
<ide>
<add>Chrome DevTools doesn't support debugging [Worker Threads][] yet.
<add>[ndb][] can be used to debug them.
<add>
<ide> [Chrome DevTools Protocol]: https://chromedevtools.github.io/devtools-protocol/
<ide> [V8 Inspector]: #debugger_v8_inspector_integration_for_node_js
<add>[Worker Threads]: worker_threads.html
<add>[ndb]: https://github.com/GoogleChromeLabs/ndb/ | 1 |
Ruby | Ruby | simplify the condions lambda generation | d10cadca0cda894ce4536a3b9d9367bc6f5d9b0e | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def compute_identifier(filter)
<ide> end
<ide>
<ide> def conditions_lambdas
<del> conditions = []
<del>
<del> unless options[:if].empty?
<del> lambdas = Array(options[:if]).map { |c| make_lambda c }
<del> conditions.concat lambdas
<del> end
<del>
<del> unless options[:unless].empty?
<del> lambdas = Array(options[:unless]).map { |c| make_lambda c }
<del> conditions.concat lambdas.map { |l| invert_lambda l }
<del> end
<del> conditions
<add> Array(options[:if]).map { |c| make_lambda c } +
<add> Array(options[:unless]).map { |c| invert_lambda make_lambda c }
<ide> end
<ide>
<ide> def _normalize_legacy_filter(kind, filter) | 1 |
Text | Text | update pr template | d9efd7e25bbe937893a9818cfda62ca3f72ffe0d | <ide><path>.github/pull_request_template.md
<ide> * [ ] All functions and variable names follow Python naming conventions.
<ide> * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
<ide> * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
<del>* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
<add>* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
<ide> * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. | 1 |
Text | Text | improve challenge description in spanish | c957f5d4f2176f8cf5207eb95091dd1eef1cca22 | <ide><path>curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-bootstrap-wells.spanish.md
<ide> localeTitle: Crear Bootstrap Wells
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Bootstrap tiene una clase llamada <code>well</code> que puede crear un sentido visual de profundidad para sus columnas. Anidar una <code>div</code> elemento con la clase <code>well</code> en cada uno de sus <code>col-xs-6</code> <code>div</code> elementos. </section>
<add><section id="description"> Bootstrap tiene una clase llamada <code>well</code> que puede crear una sensación visual de profundidad para sus columnas. Anidar un elemento <code>div</code> con la clase <code>well</code> en cada uno de sus elementos <code>col-xs-6</code> <code>div</code>. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> | 1 |
Javascript | Javascript | delete unused code in console.js | 3592122af3856ac58273dfeeeac59f6439fb93ef | <ide><path>Libraries/polyfills/console.js
<ide> const inspect = (function() {
<ide> return typeof arg === 'function';
<ide> }
<ide>
<del> function isPrimitive(arg) {
<del> return (
<del> arg === null ||
<del> typeof arg === 'boolean' ||
<del> typeof arg === 'number' ||
<del> typeof arg === 'string' ||
<del> typeof arg === 'symbol' || // ES6 symbol
<del> typeof arg === 'undefined'
<del> );
<del> }
<del>
<ide> function objectToString(o) {
<ide> return Object.prototype.toString.call(o);
<ide> } | 1 |
Ruby | Ruby | remove double parenthesis in docs | 46288f5935b03b48b2593c52f947dc4c5c505b90 | <ide><path>actionpack/lib/action_view/helpers/atom_feed_helper.rb
<ide> module AtomFeedHelper
<ide> # app/views/posts/index.atom.builder:
<ide> # atom_feed do |feed|
<ide> # feed.title("My great blog!")
<del> # feed.updated((@posts.first.created_at))
<add> # feed.updated(@posts.first.created_at)
<ide> #
<ide> # for post in @posts
<ide> # feed.entry(post) do |entry| | 1 |
Javascript | Javascript | emit timeout on compat request and response | 32902d09b43e9d7f19eb6178ef5db835652d97c1 | <ide><path>lib/internal/http2/compat.js
<ide> function onStreamCloseRequest() {
<ide> req.emit('close');
<ide> }
<ide>
<add>function onStreamTimeout(kind) {
<add> return function onStreamTimeout() {
<add> const obj = this[kind];
<add> obj.emit('timeout');
<add> };
<add>}
<add>
<ide> class Http2ServerRequest extends Readable {
<ide> constructor(stream, headers, options, rawHeaders) {
<ide> super(options);
<ide> class Http2ServerRequest extends Readable {
<ide> stream.on('error', onStreamError);
<ide> stream.on('aborted', onStreamAbortedRequest);
<ide> stream.on('close', onStreamCloseRequest);
<add> stream.on('timeout', onStreamTimeout(kRequest));
<ide> this.on('pause', onRequestPause);
<ide> this.on('resume', onRequestResume);
<ide> }
<ide> class Http2ServerResponse extends Stream {
<ide> stream.on('aborted', onStreamAbortedResponse);
<ide> stream.on('close', onStreamCloseResponse);
<ide> stream.on('wantTrailers', onStreamTrailersReady);
<add> stream.on('timeout', onStreamTimeout(kResponse));
<ide> }
<ide>
<ide> // User land modules such as finalhandler just check truthiness of this
<ide><path>test/parallel/test-http2-compat-serverrequest-settimeout.js
<ide> server.on('request', (req, res) => {
<ide> req.setTimeout(msecs, common.mustCall(() => {
<ide> res.end();
<ide> }));
<add> req.on('timeout', common.mustCall());
<ide> res.on('finish', common.mustCall(() => {
<ide> req.setTimeout(msecs, common.mustNotCall());
<ide> process.nextTick(() => {
<ide><path>test/parallel/test-http2-compat-serverresponse-settimeout.js
<ide> server.on('request', (req, res) => {
<ide> res.setTimeout(msecs, common.mustCall(() => {
<ide> res.end();
<ide> }));
<add> res.on('timeout', common.mustCall());
<ide> res.on('finish', common.mustCall(() => {
<ide> res.setTimeout(msecs, common.mustNotCall());
<ide> process.nextTick(() => { | 3 |
Javascript | Javascript | note issue with large number and step validation | 62660be328efb890ec8584311ac0346829b9577a | <ide><path>src/ng/directive/input.js
<ide> var inputType = {
<ide> * error docs for more information and an example of how to convert your model if necessary.
<ide> * </div>
<ide> *
<del> * ## Issues with HTML5 constraint validation
<add> *
<add> *
<add> * @knownIssue
<add> *
<add> * ### HTML5 constraint validation and `allowInvalid`
<ide> *
<ide> * In browsers that follow the
<ide> * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
<ide> var inputType = {
<ide> * which means the view / model values in `ngModel` and subsequently the scope value
<ide> * will also be an empty string.
<ide> *
<add> * @knownIssue
<add> *
<add> * ### Large numbers and `step` validation
<add> *
<add> * The `step` validation will not work correctly for very large numbers (e.g. 9999999999) due to
<add> * Javascript's arithmetic limitations. If you need to handle large numbers, purpose-built
<add> * libraries (e.g. https://github.com/MikeMcl/big.js/), can be included into AngularJS by
<add> * {@link guide/forms#modifying-built-in-validators overwriting the validators}
<add> * for `number` and / or `step`, or by {@link guide/forms#custom-validation applying custom validators}
<add> * to an `input[text]` element. The source for `input[number]` type can be used as a starting
<add> * point for both implementations.
<ide> *
<ide> * @param {string} ngModel Assignable AngularJS expression to data-bind to.
<ide> * @param {string=} name Property name of the form under which the control is published. | 1 |
Python | Python | add pure implementation of k-nearest neighbours | b1a769cf44df6f1eec740e10e393fab548e3822a | <ide><path>machine_learning/k_nearest_neighbours.py
<add>import numpy as np
<add>from collections import Counter
<add>from sklearn import datasets
<add>from sklearn.model_selection import train_test_split
<add>
<add>data = datasets.load_iris()
<add>
<add>X = np.array(data['data'])
<add>y = np.array(data['target'])
<add>classes = data['target_names']
<add>
<add>X_train, X_test, y_train, y_test = train_test_split(X, y)
<add>
<add>def euclidean_distance(a, b):
<add> """
<add> Gives the euclidean distance between two points
<add> >>> euclidean_distance([0, 0], [3, 4])
<add> 5.0
<add> >>> euclidean_distance([1, 2, 3], [1, 8, 11])
<add> 10.0
<add> """
<add> return np.linalg.norm(np.array(a) - np.array(b))
<add>
<add>def classifier(train_data, train_target, classes, point, k=5):
<add> """
<add> Classifies the point using the KNN algorithm
<add> k closest points are found (ranked in ascending order of euclidean distance)
<add> Params:
<add> :train_data: Set of points that are classified into two or more classes
<add> :train_target: List of classes in the order of train_data points
<add> :classes: Labels of the classes
<add> :point: The data point that needs to be classifed
<add>
<add> >>> X_train = [[0, 0], [1, 0], [0, 1], [0.5, 0.5], [3, 3], [2, 3], [3, 2]]
<add> >>> y_train = [0, 0, 0, 0, 1, 1, 1]
<add> >>> classes = ['A','B']; point = [1.2,1.2]
<add> >>> classifier(X_train, y_train, classes,point)
<add> 'A'
<add> """
<add> data = zip(train_data, train_target)
<add> # List of distances of all points from the point to be classified
<add> distances = []
<add> for data_point in data:
<add> distance = euclidean_distance(data_point[0], point)
<add> distances.append((distance, data_point[1]))
<add> # Choosing 'k' points with the least distances.
<add> votes = [i[1] for i in sorted(distances)[:k]]
<add> # Most commonly occuring class among them
<add> # is the class into which the point is classified
<add> result = Counter(votes).most_common(1)[0][0]
<add> return classes[result]
<add>
<add>
<add>if __name__ == "__main__":
<add> print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
<ide>\ No newline at end of file | 1 |
Text | Text | add next.js analytics to documentation. | d82672c39739ce7381726105981a6bd59f36fea5 | <ide><path>docs/advanced-features/measuring-performance.md
<ide> ---
<del>description: Measure and track page performance using Next.js's build-in performance relayer
<add>description: Measure and track page performance using Next.js Analytics
<ide> ---
<ide>
<ide> # Measuring performance
<ide>
<del>Next.js has a built-in relayer that allows you to analyze and measure the performance of
<add>[Next.js Analytics](https://nextjs.org/analytics) allows you to analyze and measure the performance of
<ide> pages using different metrics.
<ide>
<del>To measure any of the supported metrics, you will need to create a [custom
<del>App](/docs/advanced-features/custom-app.md) component and define a `reportWebVitals` function:
<add>You can start collecting your [Real Experience Score](https://vercel.com/docs/analytics#metrics) with zero-configuration on [Vercel deployments](https://vercel.com/docs/analytics). There's also support for Analytics if you're [self-hosting](https://vercel.com/docs/analytics#self-hosted).
<add>
<add>The rest of this documentation describes the built-in relayer Next.js Analytics uses.
<add>
<add>## Build Your Own
<add>
<add>First, you will need to create a [custom App](/docs/advanced-features/custom-app.md) component and define a `reportWebVitals` function:
<ide>
<ide> ```js
<ide> // pages/_app.js | 1 |
Python | Python | change a comment in the docker plugin | 6f51c5fd43eeda78063e6d31c2ae45007024e808 | <ide><path>glances/plugins/glances_docker.py
<ide> def update(self):
<ide> # Get stats for all containers
<ide> stats['containers'] = []
<ide> for container in containers:
<del> # Should we display the container stats ?
<add> # Shall we display the stats ?
<ide> if not self.is_display(nativestr(container.name)):
<ide> continue
<ide> | 1 |
PHP | PHP | change url validation to use filter_var | 4e539160217f5520a1dcd1efe00290868e9850e2 | <ide><path>cake/libs/validation.php
<ide> public static function ssn($check, $regex = null, $country = null) {
<ide> * @return boolean Success
<ide> */
<ide> public static function url($check, $strict = false) {
<del> self::__populateIp();
<del> $validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~') . '\/0-9a-z]|(%[0-9a-f]{2}))';
<del> $regex = '/^(?:(?:https?|ftps?|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
<del> '(?:' . self::$__pattern['IPv4'] . '|' . self::$__pattern['hostname'] . ')(?::[1-9][0-9]{0,3})?' .
<del> '(?:\/?|\/' . $validChars . '*)?' .
<del> '(?:\?' . $validChars . '*)?' .
<del> '(?:#' . $validChars . '*)?$/i';
<del> return self::_check($check, $regex);
<add> $flags = array(FILTER_FLAG_HOST_REQUIRED);
<add> if ($strict === true) {
<add> $flags[] = FILTER_FLAG_SCHEME_REQUIRED;
<add> }
<add> return (boolean)filter_var($check, FILTER_VALIDATE_URL, $flags);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | avoid repeated interpolation in regexp | 3c73cc28e0bf12d54f344135b35c5af8feaf0a77 | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_suffix revision=nil
<ide> end
<ide>
<ide> def bottle_native_regex
<del> /(\.#{MacOS.cat}\.bottle\.(\d+\.)?tar\.gz)$/
<add> /(\.#{MacOS.cat}\.bottle\.(\d+\.)?tar\.gz)$/o
<ide> end
<ide>
<ide> def bottle_regex | 1 |
PHP | PHP | remove duplicate code | dd91b0c3e6cc53db300c5b90f594055262318650 | <ide><path>src/Error/ErrorTrap.php
<ide> class ErrorTrap
<ide> public function __construct(array $options = [])
<ide> {
<ide> $this->setConfig($options);
<del> if ($this->_getConfig('errorRenderer') === null) {
<del> $this->setConfig('errorRenderer', $this->chooseErrorRenderer());
<del> }
<ide> }
<ide>
<ide> /**
<ide><path>src/Error/ExceptionTrap.php
<ide> class ExceptionTrap
<ide> public function __construct(array $options = [])
<ide> {
<ide> $this->setConfig($options);
<del> if ($this->_getConfig('exceptionRenderer') === null) {
<del> $this->setConfig('exceptionRenderer', $this->chooseRenderer());
<del> }
<ide> }
<ide>
<ide> /** | 2 |
Ruby | Ruby | remove unnecessary skips | 25b6c0c23694a53176720a6c4330c6730707aaa7 | <ide><path>Library/Homebrew/test/test_os_mac_dependency_collector.rb
<ide> def test_ld64_dep_leopard_or_newer
<ide> end
<ide>
<ide> def test_ant_dep_mavericks_or_newer
<del> skip "Only for Mac OS" unless OS.mac?
<ide> MacOS.stubs(:version).returns(MacOS::Version.new("10.9"))
<ide> @d.add :ant => :build
<ide> assert_equal find_dependency("ant"), Dependency.new("ant", [:build])
<ide> end
<ide>
<ide> def test_ant_dep_pre_mavericks
<del> skip "Only for Mac OS" unless OS.mac?
<ide> MacOS.stubs(:version).returns(MacOS::Version.new("10.7"))
<ide> @d.add :ant => :build
<ide> assert_nil find_dependency("ant") | 1 |
PHP | PHP | fix auth helper | 8cb8de2609f00c7c4e335e932d88f432e4f047d2 | <ide><path>src/Illuminate/Foundation/helpers.php
<ide> function asset($path, $secure = null)
<ide> */
<ide> function auth($guard = null)
<ide> {
<del> return app(AuthFactory::class)->guard($guard);
<add> if (is_null($guard)) {
<add> return app(AuthFactory::class);
<add> } else {
<add> return app(AuthFactory::class)->guard($guard);
<add> }
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | remove validateopts for bundler class | 8f87ab648c1cb76913824d0ff378364b492c481a | <ide><path>local-cli/util/Config.js
<ide> export type ConfigT = {
<ide> extraNodeModules?: {[id: string]: string},
<ide> getAssetExts?: () => Array<string>,
<ide> getTransformModulePath?: () => string,
<del> getTransformOptions?: GetTransformOptions<*>,
<add> getTransformOptions?: GetTransformOptions,
<ide> transformVariants?: () => {[name: string]: Object},
<ide>
<ide> getBlacklistRE(): RegExp,
<ide><path>packager/react-packager/src/Bundler/__tests__/Bundler-test.js
<ide> jest
<ide>
<ide> var Bundler = require('../');
<ide> var Resolver = require('../../Resolver');
<add>var defaults = require('../../../../defaults');
<ide> var sizeOf = require('image-size');
<ide> var fs = require('fs');
<ide>
<add>var commonOptions = {
<add> allowBundleUpdates: false,
<add> assetExts: defaults.assetExts,
<add> cacheVersion: 'smth',
<add> extraNodeModules: {},
<add> platforms: defaults.platforms,
<add> resetCache: false,
<add> watch: false,
<add>};
<add>
<ide> describe('Bundler', function() {
<ide>
<ide> function createModule({
<ide> describe('Bundler', function() {
<ide> };
<ide>
<ide> bundler = new Bundler({
<add> ...commonOptions,
<ide> projectRoots,
<ide> assetServer: assetServer,
<ide> });
<ide> describe('Bundler', function() {
<ide> it('allows overriding the platforms array', () => {
<ide> expect(bundler._opts.platforms).toEqual(['ios', 'android', 'windows', 'web']);
<ide> const b = new Bundler({
<add> ...commonOptions,
<ide> projectRoots,
<ide> assetServer: assetServer,
<ide> platforms: ['android', 'vr'],
<ide><path>packager/react-packager/src/Bundler/index.js
<ide> const Resolver = require('../Resolver');
<ide> const Bundle = require('./Bundle');
<ide> const HMRBundle = require('./HMRBundle');
<ide> const ModuleTransport = require('../lib/ModuleTransport');
<del>const declareOpts = require('../lib/declareOpts');
<ide> const imageSize = require('image-size');
<ide> const path = require('path');
<ide> const version = require('../../../package.json').version;
<ide> const denodeify = require('denodeify');
<del>const defaults = require('../../../defaults');
<ide>
<ide> const {
<ide> sep: pathSeparator,
<ide> const {
<ide> import type AssetServer from '../AssetServer';
<ide> import type Module from '../node-haste/Module';
<ide> import type ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse';
<del>import type {Options as TransformOptions} from '../JSTransformer/worker/worker';
<add>import type {Options as JSTransformerOptions, TransformOptions} from '../JSTransformer/worker/worker';
<ide> import type {Reporter} from '../lib/reporting';
<ide>
<del>export type GetTransformOptions<T> = (
<del> string,
<del> Object,
<del> string => Promise<Array<string>>,
<del>) => T | Promise<T>;
<add>export type GetTransformOptions = (
<add> mainModuleName: string,
<add> options: {},
<add> getDependencies: string => Promise<Array<string>>,
<add>) => {} | Promise<{}>;
<ide>
<ide> const sizeOf = denodeify(imageSize);
<ide>
<ide> const {
<ide> log,
<ide> } = require('../Logger');
<ide>
<del>const validateOpts = declareOpts({
<del> projectRoots: {
<del> type: 'array',
<del> required: true,
<del> },
<del> blacklistRE: {
<del> type: 'object', // typeof regex is object
<del> },
<del> moduleFormat: {
<del> type: 'string',
<del> default: 'haste',
<del> },
<del> polyfillModuleNames: {
<del> type: 'array',
<del> default: [],
<del> },
<del> cacheVersion: {
<del> type: 'string',
<del> default: '1.0',
<del> },
<del> resetCache: {
<del> type: 'boolean',
<del> default: false,
<del> },
<del> transformModulePath: {
<del> type:'string',
<del> required: false,
<del> },
<del> extraNodeModules: {
<del> type: 'object',
<del> required: false,
<del> },
<del> assetExts: {
<del> type: 'array',
<del> default: ['png'],
<del> },
<del> platforms: {
<del> type: 'array',
<del> default: defaults.platforms,
<del> },
<del> watch: {
<del> type: 'boolean',
<del> default: false,
<del> },
<del> assetServer: {
<del> type: 'object',
<del> required: true,
<del> },
<del> transformTimeoutInterval: {
<del> type: 'number',
<del> required: false,
<del> },
<del> allowBundleUpdates: {
<del> type: 'boolean',
<del> default: false,
<del> },
<del> reporter: {
<del> type: 'object',
<del> },
<del>});
<del>
<ide> const assetPropertyBlacklist = new Set([
<ide> 'files',
<ide> 'fileSystemLocation',
<ide> type Options = {
<ide> blacklistRE?: RegExp,
<ide> cacheVersion: string,
<ide> extraNodeModules: {},
<del> getTransformOptions?: GetTransformOptions<*>,
<add> getTransformOptions?: GetTransformOptions,
<ide> moduleFormat: string,
<ide> platforms: Array<string>,
<ide> polyfillModuleNames: Array<string>,
<ide> class Bundler {
<ide> _resolver: Resolver;
<ide> _projectRoots: Array<string>;
<ide> _assetServer: AssetServer;
<del> _getTransformOptions: void | GetTransformOptions<*>;
<add> _getTransformOptions: void | GetTransformOptions;
<ide>
<del> constructor(options: Options) {
<del> const opts = this._opts = validateOpts(options);
<add> constructor(opts: Options) {
<add> this._opts = opts;
<ide>
<ide> opts.projectRoots.forEach(verifyRootExists);
<ide>
<ide> let transformModuleHash;
<ide> try {
<add> /* $FlowFixMe: if transformModulePath is null it'll just be caught */
<ide> const transformModuleStr = fs.readFileSync(opts.transformModulePath);
<ide> transformModuleHash =
<ide> crypto.createHash('sha1').update(transformModuleStr).digest('hex');
<ide> class Bundler {
<ide> platforms: opts.platforms,
<ide> polyfillModuleNames: opts.polyfillModuleNames,
<ide> projectRoots: opts.projectRoots,
<del> reporter: options.reporter,
<add> reporter: opts.reporter,
<ide> resetCache: opts.resetCache,
<ide> transformCacheKey,
<ide> transformCode:
<ide> class Bundler {
<ide> module: Module,
<ide> bundle: Bundle,
<ide> entryFilePath: string,
<del> transformOptions: TransformOptions,
<add> transformOptions: JSTransformerOptions,
<ide> getModuleId: () => number,
<ide> dependencyPairs: Array<[mixed, {path: string}]>,
<ide> assetPlugins: Array<string>,
<ide> class Bundler {
<ide> mainModuleName: string,
<ide> options: {
<ide> dev?: boolean,
<del> platform: string,
<del> hot?: boolean,
<ide> generateSourceMaps?: boolean,
<add> hot?: boolean,
<add> platform: string,
<add> projectRoots: Array<string>,
<ide> },
<del> ) {
<add> ): Promise<TransformOptions> {
<ide> const getDependencies = (entryFile: string) =>
<ide> this.getDependencies({...options, entryFile})
<ide> .then(r => r.dependencies.map(d => d.path));
<ide> const extraOptions = this._getTransformOptions
<ide> ? this._getTransformOptions(mainModuleName, options, getDependencies)
<ide> : null;
<ide> return Promise.resolve(extraOptions)
<del> .then(extraOpts => Object.assign(options, extraOpts));
<add> .then(extraOpts => {
<add> return {...options, ...extraOpts};
<add> });
<ide> }
<ide>
<ide> getResolver() {
<ide><path>packager/react-packager/src/JSTransformer/worker/worker.js
<ide> const invariant = require('invariant');
<ide> const minify = require('./minify');
<ide>
<ide> import type {LogEntry} from '../../Logger/Types';
<del>import type {Ast, SourceMap, TransformOptions} from 'babel-core';
<add>import type {Ast, SourceMap, TransformOptions as BabelTransformOptions} from 'babel-core';
<ide>
<ide> function makeTransformParams(filename, sourceCode, options) {
<ide> if (filename.endsWith('.json')) {
<ide> type Transform = (
<ide> ) => mixed,
<ide> ) => void;
<ide>
<add>export type TransformOptions = {
<add> platform: string,
<add> preloadedModules?: Array<string>,
<add> projectRoots: Array<string>,
<add> ramGroups?: Array<string>,
<add>} & BabelTransformOptions;
<add>
<ide> export type Options = {
<del> transform: {
<del> projectRoots: Array<string>,
<del> ramGroups: Array<string>,
<del> platform: string,
<del> preloadedModules: Array<string>,
<del> } & TransformOptions,
<add> transform: TransformOptions,
<ide> platform: string,
<ide> };
<ide>
<ide><path>packager/react-packager/src/Server/index.js
<ide> type Options = {
<ide> blacklistRE?: RegExp,
<ide> cacheVersion?: string,
<ide> extraNodeModules?: {},
<del> getTransformOptions?: GetTransformOptions<*>,
<add> getTransformOptions?: GetTransformOptions,
<ide> moduleFormat?: string,
<ide> platforms?: Array<string>,
<ide> polyfillModuleNames?: Array<string>,
<ide> class Server {
<ide> blacklistRE: ?RegExp,
<ide> cacheVersion: string,
<ide> extraNodeModules: {},
<del> getTransformOptions?: GetTransformOptions<*>,
<add> getTransformOptions?: GetTransformOptions,
<ide> moduleFormat: string,
<ide> platforms: Array<string>,
<ide> polyfillModuleNames: Array<string>, | 5 |
Go | Go | add test coverage to opts and refactor | dfc6c04fa3f7dcb0e78e9dd5e8e4dd285b98546d | <ide><path>daemon/config.go
<ide> func (config *Config) InstallCommonFlags() {
<ide> flag.StringVar(&config.CorsHeaders, []string{"-api-cors-header"}, "", "Set CORS headers in the remote API")
<ide> // FIXME: why the inconsistency between "hosts" and "sockets"?
<ide> opts.IPListVar(&config.Dns, []string{"#dns", "-dns"}, "DNS server to use")
<del> opts.DnsSearchListVar(&config.DnsSearch, []string{"-dns-search"}, "DNS search domains to use")
<add> opts.DNSSearchListVar(&config.DnsSearch, []string{"-dns-search"}, "DNS search domains to use")
<ide> opts.LabelListVar(&config.Labels, []string{"-label"}, "Set key=value labels to the daemon")
<ide> flag.StringVar(&config.LogConfig.Type, []string{"-log-driver"}, "json-file", "Default driver for container logs")
<ide> opts.LogOptsVar(config.LogConfig.Config, []string{"-log-opt"}, "Set log driver options")
<ide><path>daemon/volumes.go
<ide> func parseBindMount(spec string, mountLabel string, config *runconfig.Config) (*
<ide> case 3:
<ide> bind.Destination = arr[1]
<ide> mode := arr[2]
<del> if !validMountMode(mode) {
<add> isValid, isRw := volume.ValidateMountMode(mode)
<add> if !isValid {
<ide> return nil, fmt.Errorf("invalid mode for volumes-from: %s", mode)
<ide> }
<del> bind.RW = rwModes[mode]
<add> bind.RW = isRw
<ide> // Relabel will apply a SELinux label, if necessary
<ide> bind.Relabel = mode
<ide> default:
<ide> func parseVolumesFrom(spec string) (string, string, error) {
<ide>
<ide> if len(specParts) == 2 {
<ide> mode = specParts[1]
<del> if !validMountMode(mode) {
<add> if isValid, _ := volume.ValidateMountMode(mode); !isValid {
<ide> return "", "", fmt.Errorf("invalid mode for volumes-from: %s", mode)
<ide> }
<ide> }
<ide> return id, mode, nil
<ide> }
<ide>
<del>// read-write modes
<del>var rwModes = map[string]bool{
<del> "rw": true,
<del> "rw,Z": true,
<del> "rw,z": true,
<del> "z,rw": true,
<del> "Z,rw": true,
<del> "Z": true,
<del> "z": true,
<del>}
<del>
<del>// read-only modes
<del>var roModes = map[string]bool{
<del> "ro": true,
<del> "ro,Z": true,
<del> "ro,z": true,
<del> "z,ro": true,
<del> "Z,ro": true,
<del>}
<del>
<del>func validMountMode(mode string) bool {
<del> return roModes[mode] || rwModes[mode]
<del>}
<del>
<ide> func copyExistingContents(source, destination string) error {
<ide> volList, err := ioutil.ReadDir(source)
<ide> if err != nil {
<ide><path>opts/envfile.go
<ide> import (
<ide> "bufio"
<ide> "fmt"
<ide> "os"
<add> "regexp"
<ide> "strings"
<ide> )
<ide>
<del>/*
<del>Read in a line delimited file with environment variables enumerated
<del>*/
<add>var (
<add> // EnvironmentVariableRegexp A regexp to validate correct environment variables
<add> // Environment variables set by the user must have a name consisting solely of
<add> // alphabetics, numerics, and underscores - the first of which must not be numeric.
<add> EnvironmentVariableRegexp = regexp.MustCompile("^[[:alpha:]_][[:alpha:][:digit:]_]*$")
<add>)
<add>
<add>// ParseEnvFile Read in a line delimited file with environment variables enumerated
<ide> func ParseEnvFile(filename string) ([]string, error) {
<ide> fh, err := os.Open(filename)
<ide> if err != nil {
<ide> func ParseEnvFile(filename string) ([]string, error) {
<ide> line := scanner.Text()
<ide> // line is not empty, and not starting with '#'
<ide> if len(line) > 0 && !strings.HasPrefix(line, "#") {
<del> if strings.Contains(line, "=") {
<del> data := strings.SplitN(line, "=", 2)
<add> data := strings.SplitN(line, "=", 2)
<ide>
<del> // trim the front of a variable, but nothing else
<del> variable := strings.TrimLeft(data[0], whiteSpaces)
<del> if strings.ContainsAny(variable, whiteSpaces) {
<del> return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' has white spaces", variable)}
<del> }
<add> // trim the front of a variable, but nothing else
<add> variable := strings.TrimLeft(data[0], whiteSpaces)
<add>
<add> if !EnvironmentVariableRegexp.MatchString(variable) {
<add> return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", variable)}
<add> }
<add> if len(data) > 1 {
<ide>
<ide> // pass the value through, no trimming
<ide> lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
<ide> func ParseEnvFile(filename string) ([]string, error) {
<ide>
<ide> var whiteSpaces = " \t"
<ide>
<add>// ErrBadEnvVariable typed error for bad environment variable
<ide> type ErrBadEnvVariable struct {
<ide> msg string
<ide> }
<ide><path>opts/envfile_test.go
<ide> import (
<ide> "testing"
<ide> )
<ide>
<del>func tmpFileWithContent(content string) (string, error) {
<add>func tmpFileWithContent(content string, t *testing.T) string {
<ide> tmpFile, err := ioutil.TempFile("", "envfile-test")
<ide> if err != nil {
<del> return "", err
<add> t.Fatal(err)
<ide> }
<ide> defer tmpFile.Close()
<ide>
<ide> tmpFile.WriteString(content)
<del> return tmpFile.Name(), nil
<add> return tmpFile.Name()
<ide> }
<ide>
<ide> // Test ParseEnvFile for a file with a few well formatted lines
<ide> func TestParseEnvFileGoodFile(t *testing.T) {
<ide> baz=quux
<ide> # comment
<ide>
<del>foobar=foobaz
<add>_foobar=foobaz
<ide> `
<ide>
<del> tmpFile, err := tmpFileWithContent(content)
<del> if err != nil {
<del> t.Fatal("failed to create test data file")
<del> }
<add> tmpFile := tmpFileWithContent(content, t)
<ide> defer os.Remove(tmpFile)
<ide>
<ide> lines, err := ParseEnvFile(tmpFile)
<ide> if err != nil {
<del> t.Fatal("ParseEnvFile failed; expected success")
<add> t.Fatal(err)
<ide> }
<ide>
<del> expected_lines := []string{
<add> expectedLines := []string{
<ide> "foo=bar",
<ide> "baz=quux",
<del> "foobar=foobaz",
<add> "_foobar=foobaz",
<ide> }
<ide>
<del> if !reflect.DeepEqual(lines, expected_lines) {
<add> if !reflect.DeepEqual(lines, expectedLines) {
<ide> t.Fatal("lines not equal to expected_lines")
<ide> }
<ide> }
<ide>
<ide> // Test ParseEnvFile for an empty file
<ide> func TestParseEnvFileEmptyFile(t *testing.T) {
<del> tmpFile, err := tmpFileWithContent("")
<del> if err != nil {
<del> t.Fatal("failed to create test data file")
<del> }
<add> tmpFile := tmpFileWithContent("", t)
<ide> defer os.Remove(tmpFile)
<ide>
<ide> lines, err := ParseEnvFile(tmpFile)
<ide> if err != nil {
<del> t.Fatal("ParseEnvFile failed; expected success")
<add> t.Fatal(err)
<ide> }
<ide>
<ide> if len(lines) != 0 {
<ide> func TestParseEnvFileNonExistentFile(t *testing.T) {
<ide> if err == nil {
<ide> t.Fatal("ParseEnvFile succeeded; expected failure")
<ide> }
<add> if _, ok := err.(*os.PathError); !ok {
<add> t.Fatalf("Expected a PathError, got [%v]", err)
<add> }
<ide> }
<ide>
<ide> // Test ParseEnvFile for a badly formatted file
<ide> func TestParseEnvFileBadlyFormattedFile(t *testing.T) {
<ide> f =quux
<ide> `
<ide>
<del> tmpFile, err := tmpFileWithContent(content)
<del> if err != nil {
<del> t.Fatal("failed to create test data file")
<del> }
<add> tmpFile := tmpFileWithContent(content, t)
<ide> defer os.Remove(tmpFile)
<ide>
<del> _, err = ParseEnvFile(tmpFile)
<add> _, err := ParseEnvFile(tmpFile)
<ide> if err == nil {
<del> t.Fatal("ParseEnvFile succeeded; expected failure")
<add> t.Fatalf("Expected a ErrBadEnvVariable, got nothing")
<add> }
<add> if _, ok := err.(ErrBadEnvVariable); !ok {
<add> t.Fatalf("Expected a ErrBadEnvVariable, got [%v]", err)
<add> }
<add> expectedMessage := "poorly formatted environment: variable 'f ' is not a valid environment variable"
<add> if err.Error() != expectedMessage {
<add> t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error())
<ide> }
<ide> }
<ide>
<ide> func TestParseEnvFileLineTooLongFile(t *testing.T) {
<ide> content := strings.Repeat("a", bufio.MaxScanTokenSize+42)
<ide> content = fmt.Sprint("foo=", content)
<ide>
<del> tmpFile, err := tmpFileWithContent(content)
<del> if err != nil {
<del> t.Fatal("failed to create test data file")
<del> }
<add> tmpFile := tmpFileWithContent(content, t)
<ide> defer os.Remove(tmpFile)
<ide>
<del> _, err = ParseEnvFile(tmpFile)
<add> _, err := ParseEnvFile(tmpFile)
<ide> if err == nil {
<ide> t.Fatal("ParseEnvFile succeeded; expected failure")
<ide> }
<ide> }
<add>
<add>// ParseEnvFile with a random file, pass through
<add>func TestParseEnvFileRandomFile(t *testing.T) {
<add> content := `first line
<add>another invalid line`
<add> tmpFile := tmpFileWithContent(content, t)
<add> defer os.Remove(tmpFile)
<add>
<add> _, err := ParseEnvFile(tmpFile)
<add>
<add> if err == nil {
<add> t.Fatalf("Expected a ErrBadEnvVariable, got nothing")
<add> }
<add> if _, ok := err.(ErrBadEnvVariable); !ok {
<add> t.Fatalf("Expected a ErrBadEnvvariable, got [%v]", err)
<add> }
<add> expectedMessage := "poorly formatted environment: variable 'first line' is not a valid environment variable"
<add> if err.Error() != expectedMessage {
<add> t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error())
<add> }
<add>}
<ide><path>opts/ip.go
<ide> import (
<ide> "net"
<ide> )
<ide>
<add>// IpOpt type that hold an IP
<ide> type IpOpt struct {
<ide> *net.IP
<ide> }
<ide><path>opts/ip_test.go
<add>package opts
<add>
<add>import (
<add> "net"
<add> "testing"
<add>)
<add>
<add>func TestIpOptString(t *testing.T) {
<add> addresses := []string{"", "0.0.0.0"}
<add> var ip net.IP
<add>
<add> for _, address := range addresses {
<add> stringAddress := NewIpOpt(&ip, address).String()
<add> if stringAddress != address {
<add> t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress)
<add> }
<add> }
<add>}
<add>
<add>func TestNewIpOptInvalidDefaultVal(t *testing.T) {
<add> ip := net.IPv4(127, 0, 0, 1)
<add> defaultVal := "Not an ip"
<add>
<add> ipOpt := NewIpOpt(&ip, defaultVal)
<add>
<add> expected := "127.0.0.1"
<add> if ipOpt.String() != expected {
<add> t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String())
<add> }
<add>}
<add>
<add>func TestNewIpOptValidDefaultVal(t *testing.T) {
<add> ip := net.IPv4(127, 0, 0, 1)
<add> defaultVal := "192.168.1.1"
<add>
<add> ipOpt := NewIpOpt(&ip, defaultVal)
<add>
<add> expected := "192.168.1.1"
<add> if ipOpt.String() != expected {
<add> t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String())
<add> }
<add>}
<add>
<add>func TestIpOptSetInvalidVal(t *testing.T) {
<add> ip := net.IPv4(127, 0, 0, 1)
<add> ipOpt := &IpOpt{IP: &ip}
<add>
<add> invalidIp := "invalid ip"
<add> expectedError := "invalid ip is not an ip address"
<add> err := ipOpt.Set(invalidIp)
<add> if err == nil || err.Error() != expectedError {
<add> t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error())
<add> }
<add>}
<ide><path>opts/opts.go
<ide> import (
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/ulimit"
<add> "github.com/docker/docker/volume"
<ide> )
<ide>
<ide> var (
<del> alphaRegexp = regexp.MustCompile(`[a-zA-Z]`)
<del> domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`)
<del> DefaultHTTPHost = "127.0.0.1" // Default HTTP Host used if only port is provided to -H flag e.g. docker -d -H tcp://:8080
<add> alphaRegexp = regexp.MustCompile(`[a-zA-Z]`)
<add> domainRegexp = regexp.MustCompile(`^(:?(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]))(:?\.(:?[a-zA-Z0-9]|(:?[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])))*)\.?\s*$`)
<add> // DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. docker -d -H tcp://:8080
<add> DefaultHTTPHost = "127.0.0.1"
<add> // DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. docker -d -H tcp://
<ide> // TODO Windows. DefaultHTTPPort is only used on Windows if a -H parameter
<ide> // is not supplied. A better longer term solution would be to use a named
<ide> // pipe as the default on the Windows daemon.
<del> DefaultHTTPPort = 2375 // Default HTTP Port
<del> DefaultUnixSocket = "/var/run/docker.sock" // Docker daemon by default always listens on the default unix socket
<add> DefaultHTTPPort = 2375 // Default HTTP Port
<add> // DefaultUnixSocket Path for the unix socket.
<add> // Docker daemon by default always listens on the default unix socket
<add> DefaultUnixSocket = "/var/run/docker.sock"
<ide> )
<ide>
<add>// ListVar Defines a flag with the specified names and usage, and put the value
<add>// list into ListOpts that will hold the values.
<ide> func ListVar(values *[]string, names []string, usage string) {
<ide> flag.Var(newListOptsRef(values, nil), names, usage)
<ide> }
<ide>
<add>// MapVar Defines a flag with the specified names and usage, and put the value
<add>// map into MapOpt that will hold the values (key,value).
<ide> func MapVar(values map[string]string, names []string, usage string) {
<ide> flag.Var(newMapOpt(values, nil), names, usage)
<ide> }
<ide>
<add>// LogOptsVar Defines a flag with the specified names and usage for --log-opts,
<add>// and put the value map into MapOpt that will hold the values (key,value).
<ide> func LogOptsVar(values map[string]string, names []string, usage string) {
<ide> flag.Var(newMapOpt(values, nil), names, usage)
<ide> }
<ide>
<add>// HostListVar Defines a flag with the specified names and usage and put the
<add>// value into a ListOpts that will hold the values, validating the Host format.
<ide> func HostListVar(values *[]string, names []string, usage string) {
<ide> flag.Var(newListOptsRef(values, ValidateHost), names, usage)
<ide> }
<ide>
<add>// IPListVar Defines a flag with the specified names and usage and put the
<add>// value into a ListOpts that will hold the values, validating the IP format.
<ide> func IPListVar(values *[]string, names []string, usage string) {
<ide> flag.Var(newListOptsRef(values, ValidateIPAddress), names, usage)
<ide> }
<ide>
<del>func DnsSearchListVar(values *[]string, names []string, usage string) {
<del> flag.Var(newListOptsRef(values, ValidateDnsSearch), names, usage)
<add>// DNSSearchListVar Defines a flag with the specified names and usage and put the
<add>// value into a ListOpts that will hold the values, validating the DNS search format.
<add>func DNSSearchListVar(values *[]string, names []string, usage string) {
<add> flag.Var(newListOptsRef(values, ValidateDNSSearch), names, usage)
<ide> }
<ide>
<add>// IPVar Defines a flag with the specified names and usage for IP and will use
<add>// the specified defaultValue if the specified value is not valid.
<ide> func IPVar(value *net.IP, names []string, defaultValue, usage string) {
<ide> flag.Var(NewIpOpt(value, defaultValue), names, usage)
<ide> }
<ide>
<add>// LabelListVar Defines a flag with the specified names and usage and put the
<add>// value into a ListOpts that will hold the values, validating the label format.
<ide> func LabelListVar(values *[]string, names []string, usage string) {
<ide> flag.Var(newListOptsRef(values, ValidateLabel), names, usage)
<ide> }
<ide>
<add>// UlimitMapVar Defines a flag with the specified names and usage for --ulimit,
<add>// and put the value map into a UlimitOpt that will hold the values.
<ide> func UlimitMapVar(values map[string]*ulimit.Ulimit, names []string, usage string) {
<ide> flag.Var(NewUlimitOpt(values), names, usage)
<ide> }
<ide>
<del>// ListOpts type
<add>// ListOpts type that hold a list of values and a validation function.
<ide> type ListOpts struct {
<ide> values *[]string
<ide> validator ValidatorFctType
<ide> }
<ide>
<add>// NewListOpts Create a new ListOpts with the specified validator.
<ide> func NewListOpts(validator ValidatorFctType) ListOpts {
<ide> var values []string
<ide> return *newListOptsRef(&values, validator)
<ide> func (opts *ListOpts) Len() int {
<ide> return len((*opts.values))
<ide> }
<ide>
<del>//MapOpts type
<add>//MapOpts type that holds a map of values and a validation function.
<ide> type MapOpts struct {
<ide> values map[string]string
<ide> validator ValidatorFctType
<ide> }
<ide>
<add>// Set validates if needed the input value and add it to the
<add>// internal map, by splitting on '='.
<ide> func (opts *MapOpts) Set(value string) error {
<ide> if opts.validator != nil {
<ide> v, err := opts.validator(value)
<ide> func newMapOpt(values map[string]string, validator ValidatorFctType) *MapOpts {
<ide> }
<ide> }
<ide>
<del>// Validators
<add>// ValidatorFctType validator that return a validate string and/or an error
<ide> type ValidatorFctType func(val string) (string, error)
<add>
<add>// ValidatorFctListType validator that return a validate list of string and/or an error
<ide> type ValidatorFctListType func(val string) ([]string, error)
<ide>
<add>// ValidateAttach Validates that the specified string is a valid attach option.
<ide> func ValidateAttach(val string) (string, error) {
<ide> s := strings.ToLower(val)
<ide> for _, str := range []string{"stdin", "stdout", "stderr"} {
<ide> if s == str {
<ide> return s, nil
<ide> }
<ide> }
<del> return val, fmt.Errorf("valid streams are STDIN, STDOUT and STDERR.")
<add> return val, fmt.Errorf("valid streams are STDIN, STDOUT and STDERR")
<ide> }
<ide>
<add>// ValidateLink Validates that the specified string has a valid link format (containerName:alias).
<ide> func ValidateLink(val string) (string, error) {
<ide> if _, _, err := parsers.ParseLink(val); err != nil {
<ide> return val, err
<ide> }
<ide> return val, nil
<ide> }
<ide>
<del>// ValidatePath will make sure 'val' is in the form:
<del>// [host-dir:]container-path[:rw|ro] - but doesn't validate the mode part
<add>// ValidateDevice Validate a path for devices
<add>// It will make sure 'val' is in the form:
<add>// [host-dir:]container-path[:mode]
<add>func ValidateDevice(val string) (string, error) {
<add> return validatePath(val, false)
<add>}
<add>
<add>// ValidatePath Validate a path for volumes
<add>// It will make sure 'val' is in the form:
<add>// [host-dir:]container-path[:rw|ro]
<add>// It will also validate the mount mode.
<ide> func ValidatePath(val string) (string, error) {
<add> return validatePath(val, true)
<add>}
<add>
<add>func validatePath(val string, validateMountMode bool) (string, error) {
<ide> var containerPath string
<add> var mode string
<ide>
<ide> if strings.Count(val, ":") > 2 {
<ide> return val, fmt.Errorf("bad format for volumes: %s", val)
<ide> }
<ide>
<del> splited := strings.SplitN(val, ":", 2)
<del> if len(splited) == 1 {
<add> splited := strings.SplitN(val, ":", 3)
<add> if splited[0] == "" {
<add> return val, fmt.Errorf("bad format for volumes: %s", val)
<add> }
<add> switch len(splited) {
<add> case 1:
<ide> containerPath = splited[0]
<del> val = path.Clean(splited[0])
<del> } else {
<add> val = path.Clean(containerPath)
<add> case 2:
<add> if isValid, _ := volume.ValidateMountMode(splited[1]); validateMountMode && isValid {
<add> containerPath = splited[0]
<add> mode = splited[1]
<add> val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode)
<add> } else {
<add> containerPath = splited[1]
<add> val = fmt.Sprintf("%s:%s", splited[0], path.Clean(containerPath))
<add> }
<add> case 3:
<ide> containerPath = splited[1]
<del> val = fmt.Sprintf("%s:%s", splited[0], path.Clean(splited[1]))
<add> mode = splited[2]
<add> if isValid, _ := volume.ValidateMountMode(splited[2]); validateMountMode && !isValid {
<add> return val, fmt.Errorf("bad mount mode specified : %s", mode)
<add> }
<add> val = fmt.Sprintf("%s:%s:%s", splited[0], containerPath, mode)
<ide> }
<ide>
<ide> if !path.IsAbs(containerPath) {
<ide> func ValidatePath(val string) (string, error) {
<ide> return val, nil
<ide> }
<ide>
<add>// ValidateEnv Validate an environment variable and returns it
<add>// It will use EnvironmentVariableRegexp to ensure the name of the environment variable is valid.
<add>// If no value is specified, it returns the current value using os.Getenv.
<ide> func ValidateEnv(val string) (string, error) {
<ide> arr := strings.Split(val, "=")
<ide> if len(arr) > 1 {
<ide> return val, nil
<ide> }
<add> if !EnvironmentVariableRegexp.MatchString(arr[0]) {
<add> return val, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", val)}
<add> }
<ide> if !doesEnvExist(val) {
<ide> return val, nil
<ide> }
<ide> return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil
<ide> }
<ide>
<add>// ValidateIPAddress Validates an Ip address
<ide> func ValidateIPAddress(val string) (string, error) {
<ide> var ip = net.ParseIP(strings.TrimSpace(val))
<ide> if ip != nil {
<ide> func ValidateIPAddress(val string) (string, error) {
<ide> return "", fmt.Errorf("%s is not an ip address", val)
<ide> }
<ide>
<add>// ValidateMACAddress Validates a MAC address
<ide> func ValidateMACAddress(val string) (string, error) {
<ide> _, err := net.ParseMAC(strings.TrimSpace(val))
<ide> if err != nil {
<ide> func ValidateMACAddress(val string) (string, error) {
<ide> return val, nil
<ide> }
<ide>
<del>// Validates domain for resolvconf search configuration.
<add>// ValidateDNSSearch Validates domain for resolvconf search configuration.
<ide> // A zero length domain is represented by .
<del>func ValidateDnsSearch(val string) (string, error) {
<add>func ValidateDNSSearch(val string) (string, error) {
<ide> if val = strings.Trim(val, " "); val == "." {
<ide> return val, nil
<ide> }
<ide> func validateDomain(val string) (string, error) {
<ide> return "", fmt.Errorf("%s is not a valid domain", val)
<ide> }
<ide>
<add>// ValidateExtraHost Validate that the given string is a valid extrahost and returns it
<add>// ExtraHost are in the form of name:ip where the ip has to be a valid ip (ipv4 or ipv6)
<ide> func ValidateExtraHost(val string) (string, error) {
<ide> // allow for IPv6 addresses in extra hosts by only splitting on first ":"
<ide> arr := strings.SplitN(val, ":", 2)
<ide> func ValidateExtraHost(val string) (string, error) {
<ide> return val, nil
<ide> }
<ide>
<add>// ValidateLabel Validate that the given string is a valid label, and returns it
<add>// Labels are in the form on key=value
<ide> func ValidateLabel(val string) (string, error) {
<del> if strings.Count(val, "=") != 1 {
<add> if strings.Count(val, "=") < 1 {
<ide> return "", fmt.Errorf("bad attribute format: %s", val)
<ide> }
<ide> return val, nil
<ide> }
<ide>
<add>// ValidateHost Validate that the given string is a valid host and returns it
<ide> func ValidateHost(val string) (string, error) {
<ide> host, err := parsers.ParseHost(DefaultHTTPHost, DefaultUnixSocket, val)
<ide> if err != nil {
<ide><path>opts/opts_test.go
<ide> package opts
<ide>
<ide> import (
<ide> "fmt"
<del> "net"
<add> "os"
<ide> "strings"
<ide> "testing"
<ide> )
<ide> func TestValidateMACAddress(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestListOpts(t *testing.T) {
<add>func TestListOptsWithoutValidator(t *testing.T) {
<ide> o := NewListOpts(nil)
<ide> o.Set("foo")
<ide> if o.String() != "[foo]" {
<ide> func TestListOpts(t *testing.T) {
<ide> if o.Len() != 2 {
<ide> t.Errorf("%d != 2", o.Len())
<ide> }
<add> o.Set("bar")
<add> if o.Len() != 3 {
<add> t.Errorf("%d != 3", o.Len())
<add> }
<ide> if !o.Get("bar") {
<ide> t.Error("o.Get(\"bar\") == false")
<ide> }
<ide> if o.Get("baz") {
<ide> t.Error("o.Get(\"baz\") == true")
<ide> }
<ide> o.Delete("foo")
<del> if o.String() != "[bar]" {
<del> t.Errorf("%s != [bar]", o.String())
<add> if o.String() != "[bar bar]" {
<add> t.Errorf("%s != [bar bar]", o.String())
<add> }
<add> listOpts := o.GetAll()
<add> if len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" {
<add> t.Errorf("Expected [[bar bar]], got [%v]", listOpts)
<ide> }
<add> mapListOpts := o.GetMap()
<add> if len(mapListOpts) != 1 {
<add> t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts)
<add> }
<add>
<ide> }
<ide>
<del>func TestValidateDnsSearch(t *testing.T) {
<add>func TestListOptsWithValidator(t *testing.T) {
<add> // Re-using logOptsvalidator (used by MapOpts)
<add> o := NewListOpts(logOptsValidator)
<add> o.Set("foo")
<add> if o.String() != "[]" {
<add> t.Errorf("%s != []", o.String())
<add> }
<add> o.Set("foo=bar")
<add> if o.String() != "[]" {
<add> t.Errorf("%s != []", o.String())
<add> }
<add> o.Set("max-file=2")
<add> if o.Len() != 1 {
<add> t.Errorf("%d != 1", o.Len())
<add> }
<add> if !o.Get("max-file=2") {
<add> t.Error("o.Get(\"max-file=2\") == false")
<add> }
<add> if o.Get("baz") {
<add> t.Error("o.Get(\"baz\") == true")
<add> }
<add> o.Delete("max-file=2")
<add> if o.String() != "[]" {
<add> t.Errorf("%s != []", o.String())
<add> }
<add>}
<add>
<add>func TestValidateDNSSearch(t *testing.T) {
<ide> valid := []string{
<ide> `.`,
<ide> `a`,
<ide> func TestValidateDnsSearch(t *testing.T) {
<ide> }
<ide>
<ide> for _, domain := range valid {
<del> if ret, err := ValidateDnsSearch(domain); err != nil || ret == "" {
<del> t.Fatalf("ValidateDnsSearch(`"+domain+"`) got %s %s", ret, err)
<add> if ret, err := ValidateDNSSearch(domain); err != nil || ret == "" {
<add> t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err)
<ide> }
<ide> }
<ide>
<ide> for _, domain := range invalid {
<del> if ret, err := ValidateDnsSearch(domain); err == nil || ret != "" {
<del> t.Fatalf("ValidateDnsSearch(`"+domain+"`) got %s %s", ret, err)
<add> if ret, err := ValidateDNSSearch(domain); err == nil || ret != "" {
<add> t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err)
<ide> }
<ide> }
<ide> }
<ide> func TestValidateExtraHosts(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestIpOptString(t *testing.T) {
<del> addresses := []string{"", "0.0.0.0"}
<del> var ip net.IP
<add>func TestValidateAttach(t *testing.T) {
<add> valid := []string{
<add> "stdin",
<add> "stdout",
<add> "stderr",
<add> "STDIN",
<add> "STDOUT",
<add> "STDERR",
<add> }
<add> if _, err := ValidateAttach("invalid"); err == nil {
<add> t.Fatalf("Expected error with [valid streams are STDIN, STDOUT and STDERR], got nothing")
<add> }
<add>
<add> for _, attach := range valid {
<add> value, err := ValidateAttach(attach)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if value != strings.ToLower(attach) {
<add> t.Fatalf("Expected [%v], got [%v]", attach, value)
<add> }
<add> }
<add>}
<add>
<add>func TestValidateLink(t *testing.T) {
<add> valid := []string{
<add> "name",
<add> "dcdfbe62ecd0:alias",
<add> "7a67485460b7642516a4ad82ecefe7f57d0c4916f530561b71a50a3f9c4e33da",
<add> "angry_torvalds:linus",
<add> }
<add> invalid := map[string]string{
<add> "": "empty string specified for links",
<add> "too:much:of:it": "bad format for links: too:much:of:it",
<add> }
<add>
<add> for _, link := range valid {
<add> if _, err := ValidateLink(link); err != nil {
<add> t.Fatalf("ValidateLink(`%q`) should succeed: error %q", link, err)
<add> }
<add> }
<add>
<add> for link, expectedError := range invalid {
<add> if _, err := ValidateLink(link); err == nil {
<add> t.Fatalf("ValidateLink(`%q`) should have failed validation", link)
<add> } else {
<add> if !strings.Contains(err.Error(), expectedError) {
<add> t.Fatalf("ValidateLink(`%q`) error should contain %q", link, expectedError)
<add> }
<add> }
<add> }
<add>}
<add>
<add>func TestValidatePath(t *testing.T) {
<add> valid := []string{
<add> "/home",
<add> "/home:/home",
<add> "/home:/something/else",
<add> "/with space",
<add> "/home:/with space",
<add> "relative:/absolute-path",
<add> "hostPath:/containerPath:ro",
<add> "/hostPath:/containerPath:rw",
<add> "/rw:/ro",
<add> "/path:rw",
<add> "/path:ro",
<add> "/rw:rw",
<add> }
<add> invalid := map[string]string{
<add> "": "bad format for volumes: ",
<add> "./": "./ is not an absolute path",
<add> "../": "../ is not an absolute path",
<add> "/:../": "../ is not an absolute path",
<add> "/:path": "path is not an absolute path",
<add> ":": "bad format for volumes: :",
<add> "/tmp:": " is not an absolute path",
<add> ":test": "bad format for volumes: :test",
<add> ":/test": "bad format for volumes: :/test",
<add> "tmp:": " is not an absolute path",
<add> ":test:": "bad format for volumes: :test:",
<add> "::": "bad format for volumes: ::",
<add> ":::": "bad format for volumes: :::",
<add> "/tmp:::": "bad format for volumes: /tmp:::",
<add> ":/tmp::": "bad format for volumes: :/tmp::",
<add> "path:ro": "path is not an absolute path",
<add> "/path:/path:sw": "bad mount mode specified : sw",
<add> "/path:/path:rwz": "bad mount mode specified : rwz",
<add> }
<add>
<add> for _, path := range valid {
<add> if _, err := ValidatePath(path); err != nil {
<add> t.Fatalf("ValidatePath(`%q`) should succeed: error %q", path, err)
<add> }
<add> }
<add>
<add> for path, expectedError := range invalid {
<add> if _, err := ValidatePath(path); err == nil {
<add> t.Fatalf("ValidatePath(`%q`) should have failed validation", path)
<add> } else {
<add> if err.Error() != expectedError {
<add> t.Fatalf("ValidatePath(`%q`) error should contain %q, got %q", path, expectedError, err.Error())
<add> }
<add> }
<add> }
<add>}
<add>func TestValidateDevice(t *testing.T) {
<add> valid := []string{
<add> "/home",
<add> "/home:/home",
<add> "/home:/something/else",
<add> "/with space",
<add> "/home:/with space",
<add> "relative:/absolute-path",
<add> "hostPath:/containerPath:ro",
<add> "/hostPath:/containerPath:rw",
<add> "/hostPath:/containerPath:mrw",
<add> }
<add> invalid := map[string]string{
<add> "": "bad format for volumes: ",
<add> "./": "./ is not an absolute path",
<add> "../": "../ is not an absolute path",
<add> "/:../": "../ is not an absolute path",
<add> "/:path": "path is not an absolute path",
<add> ":": "bad format for volumes: :",
<add> "/tmp:": " is not an absolute path",
<add> ":test": "bad format for volumes: :test",
<add> ":/test": "bad format for volumes: :/test",
<add> "tmp:": " is not an absolute path",
<add> ":test:": "bad format for volumes: :test:",
<add> "::": "bad format for volumes: ::",
<add> ":::": "bad format for volumes: :::",
<add> "/tmp:::": "bad format for volumes: /tmp:::",
<add> ":/tmp::": "bad format for volumes: :/tmp::",
<add> "path:ro": "ro is not an absolute path",
<add> }
<add>
<add> for _, path := range valid {
<add> if _, err := ValidateDevice(path); err != nil {
<add> t.Fatalf("ValidateDevice(`%q`) should succeed: error %q", path, err)
<add> }
<add> }
<ide>
<del> for _, address := range addresses {
<del> stringAddress := NewIpOpt(&ip, address).String()
<del> if stringAddress != address {
<del> t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress)
<add> for path, expectedError := range invalid {
<add> if _, err := ValidateDevice(path); err == nil {
<add> t.Fatalf("ValidateDevice(`%q`) should have failed validation", path)
<add> } else {
<add> if err.Error() != expectedError {
<add> t.Fatalf("ValidateDevice(`%q`) error should contain %q, got %q", path, expectedError, err.Error())
<add> }
<add> }
<add> }
<add>}
<add>
<add>func TestValidateEnv(t *testing.T) {
<add> invalids := map[string]string{
<add> "some spaces": "poorly formatted environment: variable 'some spaces' is not a valid environment variable",
<add> "asd!qwe": "poorly formatted environment: variable 'asd!qwe' is not a valid environment variable",
<add> "1asd": "poorly formatted environment: variable '1asd' is not a valid environment variable",
<add> "123": "poorly formatted environment: variable '123' is not a valid environment variable",
<add> }
<add> valids := map[string]string{
<add> "a": "a",
<add> "something": "something",
<add> "_=a": "_=a",
<add> "env1=value1": "env1=value1",
<add> "_env1=value1": "_env1=value1",
<add> "env2=value2=value3": "env2=value2=value3",
<add> "env3=abc!qwe": "env3=abc!qwe",
<add> "env_4=value 4": "env_4=value 4",
<add> "PATH": fmt.Sprintf("PATH=%v", os.Getenv("PATH")),
<add> "PATH=something": "PATH=something",
<add> }
<add> for value, expectedError := range invalids {
<add> _, err := ValidateEnv(value)
<add> if err == nil {
<add> t.Fatalf("Expected ErrBadEnvVariable, got nothing")
<add> }
<add> if _, ok := err.(ErrBadEnvVariable); !ok {
<add> t.Fatalf("Expected ErrBadEnvVariable, got [%s]", err)
<add> }
<add> if err.Error() != expectedError {
<add> t.Fatalf("Expected ErrBadEnvVariable with message [%s], got [%s]", expectedError, err.Error())
<add> }
<add> }
<add> for value, expected := range valids {
<add> actual, err := ValidateEnv(value)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if actual != expected {
<add> t.Fatalf("Expected [%v], got [%v]", expected, actual)
<add> }
<add> }
<add>}
<add>
<add>func TestValidateLabel(t *testing.T) {
<add> if _, err := ValidateLabel("label"); err == nil || err.Error() != "bad attribute format: label" {
<add> t.Fatalf("Expected an error [bad attribute format: label], go %v", err)
<add> }
<add> if actual, err := ValidateLabel("key1=value1"); err != nil || actual != "key1=value1" {
<add> t.Fatalf("Expected [key1=value1], got [%v,%v]", actual, err)
<add> }
<add> // Validate it's working with more than one =
<add> if actual, err := ValidateLabel("key1=value1=value2"); err != nil {
<add> t.Fatalf("Expected [key1=value1=value2], got [%v,%v]", actual, err)
<add> }
<add> // Validate it's working with one more
<add> if actual, err := ValidateLabel("key1=value1=value2=value3"); err != nil {
<add> t.Fatalf("Expected [key1=value1=value2=value2], got [%v,%v]", actual, err)
<add> }
<add>}
<add>
<add>func TestValidateHost(t *testing.T) {
<add> invalid := map[string]string{
<add> "anything": "Invalid bind address format: anything",
<add> "something with spaces": "Invalid bind address format: something with spaces",
<add> "://": "Invalid bind address format: ://",
<add> "unknown://": "Invalid bind address format: unknown://",
<add> "tcp://": "Invalid proto, expected tcp: ",
<add> "tcp://:port": "Invalid bind address format: :port",
<add> "tcp://invalid": "Invalid bind address format: invalid",
<add> "tcp://invalid:port": "Invalid bind address format: invalid:port",
<add> }
<add> valid := map[string]string{
<add> "fd://": "fd://",
<add> "fd://something": "fd://something",
<add> "tcp://:2375": "tcp://127.0.0.1:2375", // default ip address
<add> "tcp://:2376": "tcp://127.0.0.1:2376", // default ip address
<add> "tcp://0.0.0.0:8080": "tcp://0.0.0.0:8080",
<add> "tcp://192.168.0.0:12000": "tcp://192.168.0.0:12000",
<add> "tcp://192.168:8080": "tcp://192.168:8080",
<add> "tcp://0.0.0.0:1234567890": "tcp://0.0.0.0:1234567890", // yeah it's valid :P
<add> "tcp://docker.com:2375": "tcp://docker.com:2375",
<add> "unix://": "unix:///var/run/docker.sock", // default unix:// value
<add> "unix://path/to/socket": "unix://path/to/socket",
<add> }
<add>
<add> for value, errorMessage := range invalid {
<add> if _, err := ValidateHost(value); err == nil || err.Error() != errorMessage {
<add> t.Fatalf("Expected an error for %v with [%v], got [%v]", value, errorMessage, err)
<add> }
<add> }
<add> for value, expected := range valid {
<add> if actual, err := ValidateHost(value); err != nil || actual != expected {
<add> t.Fatalf("Expected for %v [%v], got [%v, %v]", value, expected, actual, err)
<ide> }
<ide> }
<ide> }
<ide><path>opts/ulimit_test.go
<add>package opts
<add>
<add>import (
<add> "testing"
<add>
<add> "github.com/docker/docker/pkg/ulimit"
<add>)
<add>
<add>func TestUlimitOpt(t *testing.T) {
<add> ulimitMap := map[string]*ulimit.Ulimit{
<add> "nofile": {"nofile", 1024, 512},
<add> }
<add>
<add> ulimitOpt := NewUlimitOpt(ulimitMap)
<add>
<add> expected := "[nofile=512:1024]"
<add> if ulimitOpt.String() != expected {
<add> t.Fatalf("Expected %v, got %v", expected, ulimitOpt)
<add> }
<add>
<add> // Valid ulimit append to opts
<add> if err := ulimitOpt.Set("core=1024:1024"); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Invalid ulimit type returns an error and do not append to opts
<add> if err := ulimitOpt.Set("notavalidtype=1024:1024"); err == nil {
<add> t.Fatalf("Expected error on invalid ulimit type")
<add> }
<add> expected = "[nofile=512:1024 core=1024:1024]"
<add> expected2 := "[core=1024:1024 nofile=512:1024]"
<add> result := ulimitOpt.String()
<add> if result != expected && result != expected2 {
<add> t.Fatalf("Expected %v or %v, got %v", expected, expected2, ulimitOpt)
<add> }
<add>
<add> // And test GetList
<add> ulimits := ulimitOpt.GetList()
<add> if len(ulimits) != 2 {
<add> t.Fatalf("Expected a ulimit list of 2, got %v", ulimits)
<add> }
<add>}
<ide><path>runconfig/parse.go
<ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
<ide> flLinks = opts.NewListOpts(opts.ValidateLink)
<ide> flEnv = opts.NewListOpts(opts.ValidateEnv)
<ide> flLabels = opts.NewListOpts(opts.ValidateEnv)
<del> flDevices = opts.NewListOpts(opts.ValidatePath)
<add> flDevices = opts.NewListOpts(opts.ValidateDevice)
<ide>
<ide> ulimits = make(map[string]*ulimit.Ulimit)
<ide> flUlimits = opts.NewUlimitOpt(ulimits)
<ide>
<ide> flPublish = opts.NewListOpts(nil)
<ide> flExpose = opts.NewListOpts(nil)
<ide> flDns = opts.NewListOpts(opts.ValidateIPAddress)
<del> flDnsSearch = opts.NewListOpts(opts.ValidateDnsSearch)
<add> flDnsSearch = opts.NewListOpts(opts.ValidateDNSSearch)
<ide> flExtraHosts = opts.NewListOpts(opts.ValidateExtraHost)
<ide> flVolumesFrom = opts.NewListOpts(nil)
<ide> flLxcOpts = opts.NewListOpts(nil)
<ide><path>runconfig/parse_test.go
<ide> func TestParseRunVolumes(t *testing.T) {
<ide> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds)
<ide> }
<ide>
<del> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:roZ -v /hostVar:/containerVar:rwZ"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:roZ", "/hostVar:/containerVar:rwZ") != nil {
<del> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:roZ -v /hostVar:/containerVar:rwZ` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds)
<add> if _, hostConfig := mustParse(t, "-v /containerTmp:ro -v /containerVar:rw"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/containerTmp:ro", "/containerVar:rw") != nil {
<add> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds)
<add> }
<add>
<add> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:ro,Z -v /hostVar:/containerVar:rw,Z"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:ro,Z", "/hostVar:/containerVar:rw,Z") != nil {
<add> t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro,Z -v /hostVar:/containerVar:rw,Z` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds)
<ide> }
<ide>
<ide> if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:Z -v /hostVar:/containerVar:z"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:Z", "/hostVar:/containerVar:z") != nil {
<ide> func TestParseRunVolumes(t *testing.T) {
<ide> if _, _, err := parse(t, "-v /tmp:"); err == nil {
<ide> t.Fatalf("Error parsing volume flags, `-v /tmp:` should fail but didn't")
<ide> }
<del> if _, _, err := parse(t, "-v /tmp:ro"); err == nil {
<del> t.Fatalf("Error parsing volume flags, `-v /tmp:ro` should fail but didn't")
<del> }
<ide> if _, _, err := parse(t, "-v /tmp::"); err == nil {
<ide> t.Fatalf("Error parsing volume flags, `-v /tmp::` should fail but didn't")
<ide> }
<ide><path>volume/volume.go
<ide> type Volume interface {
<ide> // Unmount unmounts the volume when it is no longer in use.
<ide> Unmount() error
<ide> }
<add>
<add>// read-write modes
<add>var rwModes = map[string]bool{
<add> "rw": true,
<add> "rw,Z": true,
<add> "rw,z": true,
<add> "z,rw": true,
<add> "Z,rw": true,
<add> "Z": true,
<add> "z": true,
<add>}
<add>
<add>// read-only modes
<add>var roModes = map[string]bool{
<add> "ro": true,
<add> "ro,Z": true,
<add> "ro,z": true,
<add> "z,ro": true,
<add> "Z,ro": true,
<add>}
<add>
<add>// ValidateMountMode will make sure the mount mode is valid.
<add>// returns if it's a valid mount mode and if it's read-write or not.
<add>func ValidateMountMode(mode string) (bool, bool) {
<add> return roModes[mode] || rwModes[mode], rwModes[mode]
<add>} | 12 |
Javascript | Javascript | fix more tests | 36a8358ae70cc4e0e862e4ea4c9d638e2f66d252 | <ide><path>local-cli/__mocks__/beeper.js
<add>// [email protected] has a return statement outside of a function
<add>// and therefore doesn't parse. Let's mock it so that we can
<add>// run the tests.
<add>
<add>module.exports = function () {}; | 1 |
PHP | PHP | add cakesession fixture | 2e71ef8f261f9e8226fe5cb80f23f277dbe65944 | <ide><path>lib/Cake/Test/Fixture/CakeSessionFixture.php
<add><?php
<add>/**
<add> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
<add> * @package Cake.Test.Fixture
<add> * @since CakePHP(tm) v 2.3.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>
<add>/**
<add> * Fixture class for the default session configuration
<add> *
<add> * @package Cake.Test.Fixture
<add> */
<add>class CakeSessionFixture extends CakeTestFixture {
<add>
<add>/**
<add> * name property
<add> *
<add> * @var string
<add> */
<add> public $name = 'CakeSession';
<add>
<add>/**
<add> * fields property
<add> *
<add> * @var array
<add> */
<add> public $fields = array(
<add> 'id' => array('type' => 'string', 'length' => 128, 'key' => 'primary'),
<add> 'data' => array('type' => 'text','null' => true),
<add> 'expires' => array('type' => 'integer', 'length' => 11, 'null' => true)
<add> );
<add>
<add>/**
<add> * records property
<add> *
<add> * @var array
<add> */
<add> public $records = array();
<add>} | 1 |
Java | Java | add all test routes as server snapshot tests | 393bf88be695ea7c2907b274038b3f4d0f4a3432 | <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java
<ide> import com.facebook.react.bridge.ReactContext;
<ide> import com.facebook.react.common.LifecycleState;
<ide> import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
<add>import com.facebook.react.modules.core.PermissionAwareActivity;
<add>import com.facebook.react.modules.core.PermissionListener;
<ide> import com.facebook.react.shell.MainReactPackage;
<ide> import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
<ide> import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
<ide> import java.util.concurrent.TimeUnit;
<ide> import javax.annotation.Nullable;
<ide>
<del>public class ReactAppTestActivity extends FragmentActivity implements
<del> DefaultHardwareBackBtnHandler
<del>{
<add>public class ReactAppTestActivity extends FragmentActivity
<add> implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
<ide>
<ide> private static final String DEFAULT_BUNDLE_NAME = "AndroidTestBundle.js";
<ide> private static final int ROOT_VIEW_ID = 8675309;
<ide> public void onRequestPermissionsResult(
<ide> String[] permissions,
<ide> int[] grantResults) {
<ide> }
<add>
<add> @Override
<add> public void requestPermissions(
<add> String[] permissions, int requestCode, PermissionListener listener) {}
<ide> } | 1 |
PHP | PHP | add time() to formhelper | 2eb552fa6599a7758c0d70836d91a718f8f9b71d | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _datetimeOptions($options) {
<ide> return $options;
<ide> }
<ide>
<add>/**
<add> * Generate time inputs.
<add> *
<add> * ### Options:
<add> *
<add> * - `interval` The interval for the minutes select. Defaults to 1
<add> * - `empty` - If true, the empty select option is shown. If a string,
<add> * that string is displayed as the empty element.
<add> * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
<add> * - `value` | `default` The default value to be used by the input. A value in `$this->data`
<add> * matching the field name will override this value. If no default is provided `time()` will be used.
<add> * - `timeFormat` The time format to use, either 12 or 24.
<add> * - `second` Set to true to enable seconds drop down.
<add> *
<add> * To control the order of inputs, and any elements/content between the inputs you
<add> * can override the `dateWidget` template. By default the `dateWidget` template is:
<add> *
<add> * `{{month}}{{day}}{{year}}{{hour}}{{minute}}{{second}}{{meridian}}`
<add> *
<add> * @param string $fieldName Prefix name for the SELECT element
<add> * @param array $options Array of Options
<add> * @return string Generated set of select boxes for time formats chosen.
<add> */
<add> public function time($fieldName, $options = []) {
<add> $options += [
<add> 'empty' => true,
<add> 'value' => null,
<add> 'interval' => 1,
<add> 'round' => null,
<add> 'timeFormat' => 12,
<add> 'second' => false,
<add> ];
<add> $options['year'] = $options['month'] = $options['day'] = false;
<add> $options = $this->_initInputField($fieldName, $options);
<add> $options = $this->_datetimeOptions($options);
<add>
<add> return $this->widget('datetime', $options);
<add> }
<add>
<ide> /**
<ide> * Sets field defaults and adds field to form security input hash.
<ide> * Will also add the error class if the field contains validation errors.
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testCheckboxHiddenField() {
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<add>/**
<add> * Test the time type.
<add> *
<add> * @return void
<add> */
<add> public function testTime() {
<add> $result = $this->Form->time('start_time', array(
<add> 'timeFormat' => 12,
<add> 'interval' => 5,
<add> 'value' => array('hour' => '4', 'minute' => '30', 'meridian' => 'pm')
<add> ));
<add> $this->assertContains('<option value="04" selected="selected">4</option>', $result);
<add> $this->assertContains('<option value="30" selected="selected">30</option>', $result);
<add> $this->assertContains('<option value="pm" selected="selected">pm</option>', $result);
<add> $this->assertNotContains('year', $result);
<add> $this->assertNotContains('month', $result);
<add> $this->assertNotContains('day', $result);
<add>
<add> $result = $this->Form->time('start_time', array(
<add> 'timeFormat' => 12,
<add> 'interval' => 5,
<add> 'value' => '2014-03-08 16:30:00'
<add> ));
<add> $this->assertContains('<option value="04" selected="selected">4</option>', $result);
<add> $this->assertContains('<option value="30" selected="selected">30</option>', $result);
<add> $this->assertContains('<option value="pm" selected="selected">pm</option>', $result);
<add> $this->assertNotContains('year', $result);
<add> $this->assertNotContains('month', $result);
<add> $this->assertNotContains('day', $result);
<add> }
<add>
<ide> /**
<ide> * testDateTime method
<ide> * | 2 |
Text | Text | add article for javascript string.lastindexof() | ef7a13dda30460cd79333d8254083f28e78cca70 | <ide><path>guide/english/javascript/standard-objects/string/string-prototype-lastindexof/index.md
<ide> title: String.prototype.lastIndexOf
<ide> ---
<ide> ## String.prototype.lastIndexOf
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/string/string-prototype-lastindexof/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>The `lastIndexOf()` method returns the first index at which the last occurrence of a specified string can be found in the given String object. If the string is not present, it returns -1.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>**Syntax**
<add>```javascript
<add>str.lastIndexOf(searchValue[, fromIndex])
<add>```
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>### Parameters
<add>* **searchValue** Substring for which you are looking. If this is empty (`''`) and there is no `fromIndex` argument, `lastIndexOf()` will return the string's length.
<ide>
<del>#### More Information:
<del><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>* **fromIndex** Optional. The index at which you want to start the search backwards from. The default value is the string's length.
<add> * If `fromIndex` is negative, the method will behave as though it were 0.
<add> * If `fromIndex` is less than the string's length:
<add> * If `searchValue` is not an empty string (`''`), the string will be searched backwards from `fromIndex`.
<add> * If `searchValue` is an empty string (`''`), the method returns `fromIndex`.
<add> * If `fromIndex` is greater than or equal to the string's length:
<add> * If `searchValue` is not an empty string (`''`), the method will behave as though it were the string's length.
<add> * If `searchValue` is an empty string (`''`), the method returns the string's length.
<ide>
<add>### Description
<add>The `lastIndexOf()` method checks the string from right to left. The index of the first character is 0 and the index of the last character is ``string.length - 1``. The method checks each substring against `searchValue` using strict equality (`===`), which means that this method is case sensitive. Once it finds a substring that returns `true`, it returns the index of its first character.
<ide>
<add>### Examples
<add>```javascript
<add>'Blue Whale'.lastIndexOf('Blue'); // returns 0
<add>'Blue Whale'.lastIndexOf('Blute'); // returns -1
<add>'Blue Whale'.lastIndexOf('blue'); // returns -1
<add>'Blue Whale'.lastIndexOf('Whale', 0); // returns -1
<add>'Blue Whale'.lastIndexOf('Whale', 5); // returns 5
<add>'Blue Whale'.lastIndexOf('Whale', 7); // returns 5
<add>'Blue Whale'.lastIndexOf(''); // returns 10
<add>'Blue Whale'.lastIndexOf('', 9); // returns 9
<add>'Blue Whale'.lastIndexOf('', 10); // returns 10
<add>'Blue Whale'.lastIndexOf('', 11); // returns 10
<add>```
<add>
<add>### More Information:
<add>- [String.prototype.lastIndexOf() on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf) | 1 |
Java | Java | fix error message in resttemplate | f3c2bb65570fe40919d518995ee8a3898f03b069 | <ide><path>spring-web/src/main/java/org/springframework/web/client/RestTemplate.java
<ide> protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCal
<ide> }
<ide> }
<ide> catch (IOException ex) {
<add> String resource = url.toString();
<add> String query = url.getRawQuery();
<add> resource = (query != null ? resource.substring(0, resource.indexOf(query) - 1) : resource);
<ide> throw new ResourceAccessException("I/O error on " + method.name() +
<del> " request for \"" + url + "\": " + ex.getMessage(), ex);
<add> " request for \"" + resource + "\": " + ex.getMessage(), ex);
<ide> }
<ide> finally {
<ide> if (response != null) {
<ide><path>spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> /**
<ide> * @author Arjen Poutsma
<add> * @author Rossen Stoyanchev
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public class RestTemplateTests {
<ide> public void mapNullTemplateVariable() throws Exception {
<ide> given(response.getStatusCode()).willReturn(status);
<ide> given(response.getStatusText()).willReturn(status.getReasonPhrase());
<ide>
<del> Map<String, String> vars = new HashMap<String, String>(2);
<add> Map<String, String> vars = new HashMap<>(2);
<ide> vars.put("first", null);
<ide> vars.put("last", "foo");
<ide> template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, vars);
<ide> public void getForObjectWithCustomUriTemplateHandler() throws Exception {
<ide> given(response.getHeaders()).willReturn(new HttpHeaders());
<ide> given(response.getBody()).willReturn(null);
<ide>
<del> Map<String, String> uriVariables = new HashMap<String, String>(2);
<add> Map<String, String> uriVariables = new HashMap<>(2);
<ide> uriVariables.put("hotel", "1");
<ide> uriVariables.put("publicpath", "pics/logo.png");
<ide> uriVariables.put("scale", "150x150");
<ide> public void postForLocationEntityContentType() throws Exception {
<ide>
<ide> HttpHeaders entityHeaders = new HttpHeaders();
<ide> entityHeaders.setContentType(contentType);
<del> HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
<add> HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
<ide>
<ide> URI result = template.postForLocation("http://example.com", entity);
<ide> assertEquals("Invalid POST result", expected, result);
<ide> public void postForLocationEntityCustomHeader() throws Exception {
<ide>
<ide> HttpHeaders entityHeaders = new HttpHeaders();
<ide> entityHeaders.set("MyHeader", "MyValue");
<del> HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
<add> HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
<ide>
<ide> URI result = template.postForLocation("http://example.com", entity);
<ide> assertEquals("Invalid POST result", expected, result);
<ide> public void optionsForAllow() throws Exception {
<ide> verify(response).close();
<ide> }
<ide>
<add> // Issue: SPR-9325, SPR-13860
<add>
<ide> @Test
<ide> public void ioException() throws Exception {
<add> String url = "http://example.com/resource?access_token=123";
<add>
<ide> given(converter.canRead(String.class, null)).willReturn(true);
<ide> MediaType mediaType = new MediaType("foo", "bar");
<ide> given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType));
<del> given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request);
<add> given(requestFactory.createRequest(new URI(url), HttpMethod.GET)).willReturn(request);
<ide> given(request.getHeaders()).willReturn(new HttpHeaders());
<del> given(request.execute()).willThrow(new IOException());
<add> given(request.execute()).willThrow(new IOException("Socket failure"));
<ide>
<ide> try {
<del> template.getForObject("http://example.com/resource", String.class);
<add> template.getForObject(url, String.class);
<ide> fail("RestClientException expected");
<ide> }
<ide> catch (ResourceAccessException ex) {
<del> // expected
<add> assertEquals("I/O error on GET request for \"http://example.com/resource\": " +
<add> "Socket failure; nested exception is java.io.IOException: Socket failure",
<add> ex.getMessage());
<ide> }
<ide> }
<ide>
<ide> public void exchange() throws Exception {
<ide>
<ide> HttpHeaders entityHeaders = new HttpHeaders();
<ide> entityHeaders.set("MyHeader", "MyValue");
<del> HttpEntity<String> requestEntity = new HttpEntity<String>(body, entityHeaders);
<add> HttpEntity<String> requestEntity = new HttpEntity<>(body, entityHeaders);
<ide> ResponseEntity<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, Integer.class);
<ide> assertEquals("Invalid POST result", expected, result.getBody());
<ide> assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
<ide> public void exchangeParameterizedType() throws Exception {
<ide> responseHeaders.setContentLength(10);
<ide> given(response.getStatusCode()).willReturn(HttpStatus.OK);
<ide> given(response.getHeaders()).willReturn(responseHeaders);
<del> given(response.getBody()).willReturn(new ByteArrayInputStream(new Integer(42).toString().getBytes()));
<add> given(response.getBody()).willReturn(new ByteArrayInputStream(Integer.toString(42).getBytes()));
<ide> given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true);
<ide> given(converter.read(eq(intList.getType()), eq(null), any(HttpInputMessage.class))).willReturn(expected);
<ide> given(response.getStatusCode()).willReturn(HttpStatus.OK);
<ide> public void exchangeParameterizedType() throws Exception {
<ide>
<ide> HttpHeaders entityHeaders = new HttpHeaders();
<ide> entityHeaders.set("MyHeader", "MyValue");
<del> HttpEntity<String> requestEntity = new HttpEntity<String>(requestBody, entityHeaders);
<add> HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, entityHeaders);
<ide> ResponseEntity<List<Integer>> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, intList);
<ide> assertEquals("Invalid POST result", expected, result.getBody());
<ide> assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType()); | 2 |
Python | Python | improve np.sort docstring | 5b0069c08d00e871d74c6533e0b0eeb3107e8f70 | <ide><path>numpy/core/fromnumeric.py
<ide> def sort(a, axis=-1, kind=None, order=None):
<ide>
<ide> .. versionadded:: 1.12.0
<ide>
<del> quicksort has been changed to an introsort which will switch
<del> heapsort when it does not make enough progress. This makes its
<del> worst case O(n*log(n)).
<del>
<del> 'stable' automatically choses the best stable sorting algorithm
<del> for the data type being sorted. It, along with 'mergesort' is
<del> currently mapped to timsort or radix sort depending on the
<del> data type. API forward compatibility currently limits the
<add> quicksort has been changed to `introsort <https://en.wikipedia.org/wiki/Introsort>`_.
<add> When sorting does not make enough progress it switches to
<add> `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_.
<add> This implementation makes quicksort O(n*log(n)) in the worst case.
<add>
<add> 'stable' automatically chooses the best stable sorting algorithm
<add> for the data type being sorted.
<add> It, along with 'mergesort' is currently mapped to
<add> `timsort <https://en.wikipedia.org/wiki/Timsort>`_
<add> or `radix sort <https://en.wikipedia.org/wiki/Radix_sort>`_
<add> depending on the data type.
<add> API forward compatibility currently limits the
<ide> ability to select the implementation and it is hardwired for the different
<ide> data types.
<ide>
<ide> def sort(a, axis=-1, kind=None, order=None):
<ide> Timsort is added for better performance on already or nearly
<ide> sorted data. On random data timsort is almost identical to
<ide> mergesort. It is now used for stable sort while quicksort is still the
<del> default sort if none is chosen. For details of timsort, refer to
<add> default sort if none is chosen. For timsort details, refer to
<ide> `CPython listsort.txt <https://github.com/python/cpython/blob/3.7/Objects/listsort.txt>`_.
<ide> 'mergesort' and 'stable' are mapped to radix sort for integer data types. Radix sort is an
<ide> O(n) sort instead of O(n log n). | 1 |
Text | Text | remove "priority" prop from image docs | 69ff649999a1f0689a9dd7a904ae6840f17d7174 | <ide><path>docs/api-reference/next/image.md
<ide> We recommend setting `sizes` when `layout="responsive"` and your image will not
<ide>
<ide> The quality of the optimized image, an integer between 1 and 100 where 100 is the best quality. Defaults to 75.
<ide>
<del>### priority
<add><!-- ### priority
<ide>
<ide> When true, the image will be considered high priority and [preload](https://web.dev/preload-responsive-images/).
<ide>
<del>Should only be used when the image is visible above the fold. Defaults to false.
<add>Should only be used when the image is visible above the fold. Defaults to false. -->
<ide>
<ide> ## Advanced Props
<ide> | 1 |
PHP | PHP | fix some comments | cc7bef5b85b8192776bbaab79e955f27045acd5c | <ide><path>src/Illuminate/Database/Connectors/SQLiteConnector.php
<ide> public function connect(array $config)
<ide>
<ide> $path = realpath($config['database']);
<ide>
<del> // Here we'll verify that the SQLite database exists before we going further
<add> // Here we'll verify that the SQLite database exists before going any further
<ide> // as the developer probably wants to know if the database exists and this
<ide> // SQLite driver will not throw any exception if it does not by default.
<ide> if ($path === false)
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function morphTo($name = null, $type = null, $id = null)
<ide> );
<ide> }
<ide>
<del> // If we are not eager loading the relationship, we will essentially treat this
<add> // If we are not eager loading the relationship we will essentially treat this
<ide> // as a belongs-to style relationship since morph-to extends that class and
<ide> // we will pass in the appropriate values so that it behaves as expected.
<ide> else
<ide> public function push()
<ide>
<ide> // To sync all of the relationships to the database, we will simply spin through
<ide> // the relationships and save each model via this "push" method, which allows
<del> // us to recurs into all of these nested relations for the model instance.
<add> // us to recurs into all of these nested relations for this model instance.
<ide> foreach ($this->relations as $models)
<ide> {
<ide> foreach (Collection::make($models) as $model)
<ide><path>src/Illuminate/Database/Migrations/Migrator.php
<ide> public function run($path, $pretend = false)
<ide>
<ide> // Once we grab all of the migration files for the path, we will compare them
<ide> // against the migrations that have already been run for this package then
<del> // run all of the outstanding migrations against the database connection.
<add> // run each of the outstanding migrations against a database connection.
<ide> $ran = $this->repository->getRan();
<ide>
<ide> $migrations = array_diff($files, $ran);
<ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> protected function getRouteQueryString(array $parameters)
<ide>
<ide> // Lastly, if there are still parameters remaining, we will fetch the numeric
<ide> // parameters that are in the array and add them to the query string or we
<del> // will build the initial query string if it wasn't started with strings.
<add> // will make the initial query string if it wasn't started with strings.
<ide> if (count($keyed) < count($parameters))
<ide> {
<ide> $query .= '&'.implode(
<ide><path>src/Illuminate/View/View.php
<ide> public function render(Closure $callback = null)
<ide>
<ide> // Once we have the contents of the view, we will flush the sections if we are
<ide> // done rendering all views so that there is nothing left hanging over when
<del> // another view is rendered in the future by the application developers.
<add> // another view is rendered in the future via the application developers.
<ide> $this->environment->flushSectionsIfDoneRendering();
<ide>
<ide> return $response ?: $contents; | 5 |
PHP | PHP | fix use of defunt property $viewclass | 14b5566379cbe235bcea999a26fbea57ac0231e8 | <ide><path>src/View/CellTrait.php
<ide> protected function _createCell(string $className, string $action, ?string $plugi
<ide>
<ide> $class = static::class;
<ide> $builder->setClassName($class);
<del> $instance->viewClass = $class;
<add> $instance->viewBuilder()->setClassName($class);
<ide>
<ide> return $instance;
<ide> }
<ide>
<ide> if (method_exists($this, 'viewBuilder')) {
<ide> $builder->setTheme($this->viewBuilder()->getTheme());
<del> }
<ide>
<del> if (isset($this->viewClass)) {
<del> $builder->setClassName($this->viewClass);
<del> $instance->viewClass = $this->viewClass;
<add> if ($this->viewBuilder()->getClassName() !== null) {
<add> $builder->setClassName($this->viewBuilder()->getClassName());
<add> }
<ide> }
<ide>
<ide> return $instance;
<ide><path>tests/TestCase/View/CellTest.php
<ide> public function testCellInheritsCustomViewClass()
<ide> $view = new CustomJsonView($request, $response);
<ide> $view->setTheme('Pretty');
<ide> $cell = $view->cell('Articles');
<del> $this->assertSame('TestApp\View\CustomJsonView', $cell->viewClass);
<ide> $this->assertSame('TestApp\View\CustomJsonView', $cell->viewBuilder()->getClassName());
<ide> $this->assertSame('Pretty', $cell->viewBuilder()->getTheme());
<ide> }
<ide> public function testCellInheritsController()
<ide> $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
<ide> $controller = new CellTraitTestController($request, $response);
<ide> $controller->viewBuilder()->setTheme('Pretty');
<del> $controller->viewClass = 'Json';
<add> $controller->viewBuilder()->setClassName('Json');
<ide> $cell = $controller->cell('Articles');
<del> $this->assertSame('Json', $cell->viewClass);
<ide> $this->assertSame('Json', $cell->viewBuilder()->getClassName());
<ide> $this->assertSame('Pretty', $cell->viewBuilder()->getTheme());
<ide> } | 2 |
Ruby | Ruby | use ruby_platform in case of cross compiled ruby | 1ca1b1ab9176c780989be7e5a11d27fb97fe663a | <ide><path>railties/lib/rails/engine.rb
<ide> def find_root_with_flag(flag, default=nil)
<ide> root = File.exist?("#{root_path}/#{flag}") ? root_path : default
<ide> raise "Could not find root path for #{self}" unless root
<ide>
<del> RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ?
<add> RUBY_PLATFORM =~ /mswin|mingw/ ?
<ide> Pathname.new(root).expand_path : Pathname.new(root).realpath
<ide> end
<ide> | 1 |
Python | Python | remove unused argument in language | 4ae9ea76845ad141f12d5bfa82ed5975830322ca | <ide><path>spacy/language.py
<ide> def __call__(self, text, disable=[]):
<ide> def make_doc(self, text):
<ide> return self.tokenizer(text)
<ide>
<del> def update(self, docs, golds, drop=0., sgd=None, losses=None,
<del> update_shared=False):
<add> def update(self, docs, golds, drop=0., sgd=None, losses=None):
<ide> """Update the models in the pipeline.
<ide>
<ide> docs (iterable): A batch of `Doc` objects. | 1 |
Ruby | Ruby | add check of argument | 97544ed1770bf3c169f3b8f3711917bbf37045bc | <ide><path>activesupport/lib/active_support/cache.rb
<ide> def read_multi(*names)
<ide> # the cache with the given keys, then that data is returned. Otherwise,
<ide> # the supplied block is called for each key for which there was no data,
<ide> # and the result will be written to the cache and returned.
<add> # Therefore, you need to pass a block that returns the data to be written
<add> # to the cache. If you do not want to write the cache when the cache is
<add> # not found, use #read_multi.
<ide> #
<ide> # Options are passed to the underlying cache implementation.
<ide> #
<ide> def read_multi(*names)
<ide> # # "unknown_key" => "Fallback value for key: unknown_key" }
<ide> #
<ide> def fetch_multi(*names)
<add> raise ArgumentError, "Missing block: `Cache#fetch_multi` requires a block." unless block_given?
<add>
<ide> options = names.extract_options!
<ide> options = merged_options(options)
<ide> results = read_multi(*names, options)
<ide><path>activesupport/test/caching_test.rb
<ide> def test_multi_with_objects
<ide> assert_equal({ foo => "FOO!", bar => "BAM!" }, values)
<ide> end
<ide>
<add> def test_fetch_multi_without_block
<add> assert_raises(ArgumentError) do
<add> @cache.fetch_multi("foo")
<add> end
<add> end
<add>
<ide> def test_read_and_write_compressed_small_data
<ide> @cache.write("foo", "bar", compress: true)
<ide> assert_equal "bar", @cache.read("foo") | 2 |
Python | Python | fix typo in docstring for `densefeatures` | fc00d58f810553a177400e441b903263db96c1e1 | <ide><path>keras/feature_column/dense_features_v2.py
<ide> class DenseFeatures(dense_features.DenseFeatures):
<ide> ```python
<ide> price = tf.feature_column.numeric_column('price')
<ide> keywords_embedded = tf.feature_column.embedding_column(
<del> tf.feature_column.categorical_column_with_hash_bucket("keywords", 10K),
<add> tf.feature_column.categorical_column_with_hash_bucket("keywords", 10000),
<ide> dimensions=16)
<ide> columns = [price, keywords_embedded, ...]
<ide> feature_layer = tf.keras.layers.DenseFeatures(columns) | 1 |
Javascript | Javascript | build alternate browser scripts without vhs | c98912fd92090e81feba3236f0f8d5b4e8c58b03 | <ide><path>build/rollup.js
<ide> const primedBabel = babel({
<ide> plugins: ['external-helpers']
<ide> });
<ide>
<del>const coreEs = {
<add>const core = {
<ide> options: {
<ide> entry: 'src/js/video.js',
<ide> plugins: [
<ide> minifiedUmd.options.plugins.splice(4, 0, uglify({
<ide> }
<ide> }));
<ide>
<add>const coreUmd = {
<add> options: {
<add> entry: 'src/js/video.js',
<add> plugins: [
<add> primedResolve,
<add> json(),
<add> primedCjs,
<add> primedBabel,
<add> args.progress ? progress() : {},
<add> filesize()
<add> ],
<add> legacy: true
<add> },
<add> banner: compiledLicense(Object.assign({includesVtt: true}, bannerData)),
<add> useStrict: false,
<add> format: 'umd',
<add> dest: 'dist/alt/video.core.js'
<add>};
<add>
<add>const minifiedCoreUmd = Object.assign({}, _.cloneDeep(coreUmd), {
<add> dest: 'dist/alt/video.core.min.js'
<add>});
<add>
<add>minifiedCoreUmd.options.plugins.splice(4, 0, uglify({
<add> preserveComments: 'some',
<add> screwIE8: false,
<add> mangle: true,
<add> compress: {
<add> /* eslint-disable camelcase */
<add> sequences: true,
<add> dead_code: true,
<add> conditionals: true,
<add> booleans: true,
<add> unused: true,
<add> if_return: true,
<add> join_vars: true,
<add> drop_console: true
<add> /* eslint-enable camelcase */
<add> }
<add>}));
<add>
<add>/**
<add> * video.js without vtt.js
<add> */
<ide> const novttUmd = Object.assign({}, _.cloneDeep(umd), {
<ide> banner: compiledLicense(Object.assign({includesVtt: false}, bannerData)),
<ide> dest: 'dist/alt/video.novtt.js'
<ide> const minifiedNovttUmd = Object.assign({}, _.cloneDeep(minifiedUmd), {
<ide>
<ide> minifiedNovttUmd.options.plugins.unshift(ignore(['videojs-vtt.js']));
<ide>
<add>/**
<add> * Core video.js without vtt.js
<add> */
<add>const novttCoreUmd = Object.assign({}, _.cloneDeep(coreUmd), {
<add> banner: compiledLicense(Object.assign({includesVtt: false}, bannerData)),
<add> dest: 'dist/alt/video.core.novtt.js'
<add>});
<add>
<add>novttCoreUmd.options.plugins.unshift(ignore(['videojs-vtt.js']));
<add>
<add>const minifiedNovttCoreUmd = Object.assign({}, _.cloneDeep(minifiedCoreUmd), {
<add> banner: compiledLicense(Object.assign({includesVtt: false}, bannerData)),
<add> dest: 'dist/alt/video.core.novtt.min.js'
<add>});
<add>
<add>minifiedNovttUmd.options.plugins.unshift(ignore(['videojs-vtt.js']));
<add>
<ide> function runRollup({options, useStrict, format, dest, banner}) {
<ide> rollup(options)
<ide> .then(function(bundle) {
<ide> function runRollup({options, useStrict, format, dest, banner}) {
<ide> if (!args.watch) {
<ide> if (args.minify) {
<ide> runRollup(minifiedUmd);
<add> runRollup(minifiedCoreUmd);
<ide> runRollup(minifiedNovttUmd);
<add> runRollup(minifiedNovttCoreUmd);
<ide> } else {
<ide> runRollup(es);
<ide> runRollup(cjs);
<ide> runRollup(umd);
<add> runRollup(core);
<add> runRollup(coreUmd);
<ide> runRollup(novttUmd);
<del> runRollup(coreEs);
<add> runRollup(novttCoreUmd);
<ide> }
<ide> } else {
<ide> const props = ['format', 'dest', 'banner', 'useStrict']; | 1 |
Python | Python | fix invalid escape sequence | 2096b6d20d45e990a77ebea6735a41c191f008b0 | <ide><path>numpy/linalg/linalg.py
<ide> def _lstsq_dispatcher(a, b, rcond=None):
<ide>
<ide> @array_function_dispatch(_lstsq_dispatcher)
<ide> def lstsq(a, b, rcond="warn"):
<del> """
<add> r"""
<ide> Return the least-squares solution to a linear matrix equation.
<ide>
<ide> Solves the equation :math:`a x = b` by computing a vector `x` that | 1 |
Ruby | Ruby | support procs for assert_{enqueued,performed}_with | b16c38ab6a9841003ae23a4d007462e39268f82a | <ide><path>activejob/lib/active_job/test_helper.rb
<ide> def assert_no_performed_jobs(only: nil, except: nil, queue: nil, &block)
<ide> # assert_enqueued_with(at: Date.tomorrow.noon, queue: "my_queue")
<ide> # end
<ide> #
<del> # The +at+ and +args+ arguments also accept a proc.
<add> # The given arguments may also be specified as matcher procs that return a
<add> # boolean value indicating whether a job's attribute meets certain criteria.
<ide> #
<del> # To the +at+ proc, it will get passed the actual job's at argument.
<add> # For example, a proc can be used to match a range of times:
<ide> #
<ide> # def test_assert_enqueued_with
<del> # expected_time = ->(at) do
<del> # (Date.yesterday..Date.tomorrow).cover?(at)
<del> # end
<add> # at_matcher = ->(job_at) { (Date.yesterday..Date.tomorrow).cover?(job_at) }
<add> #
<add> # MyJob.set(wait_until: Date.today.noon).perform_later
<ide> #
<del> # MyJob.set(at: Date.today.noon).perform_later
<del> # assert_enqueued_with(job: MyJob, at: expected_time)
<add> # assert_enqueued_with(job: MyJob, at: at_matcher)
<ide> # end
<ide> #
<del> # To the +args+ proc, it will get passed the actual job's arguments
<del> # Your proc needs to return a boolean value determining if
<del> # the job's arguments matches your expectation. This is useful to check only
<del> # for a subset of arguments.
<add> # A proc can also be used to match a subset of a job's args:
<ide> #
<ide> # def test_assert_enqueued_with
<del> # expected_args = ->(job_args) do
<del> # assert job_args.first.key?(:foo)
<del> # end
<add> # args_matcher = ->(job_args) { job_args[0].key?(:foo) }
<ide> #
<del> # MyJob.perform_later(foo: 'bar', other_arg: 'No need to check in the test')
<del> # assert_enqueued_with(job: MyJob, args: expected_args)
<add> # MyJob.perform_later(foo: "bar", other_arg: "No need to check in the test")
<add> #
<add> # assert_enqueued_with(job: MyJob, args: args_matcher)
<ide> # end
<ide> #
<ide> # If a block is passed, asserts that the block will cause the job to be
<ide> def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil, &block)
<ide> # assert_performed_with(at: Date.tomorrow.noon, queue: "my_queue")
<ide> # end
<ide> #
<del> # The +at+ and +args+ arguments also accept a proc.
<add> # The given arguments may also be specified as matcher procs that return a
<add> # boolean value indicating whether a job's attribute meets certain criteria.
<ide> #
<del> # To the +at+ proc, it will get passed the actual job's at argument.
<add> # For example, a proc can be used to match a range of times:
<ide> #
<del> # def test_assert_enqueued_with
<del> # expected_time = ->(at) do
<del> # (Date.yesterday..Date.tomorrow).cover?(at)
<del> # end
<add> # def test_assert_performed_with
<add> # at_matcher = ->(job_at) { (Date.yesterday..Date.tomorrow).cover?(job_at) }
<add> #
<add> # MyJob.set(wait_until: Date.today.noon).perform_later
<add> #
<add> # perform_enqueued_jobs
<ide> #
<del> # MyJob.set(at: Date.today.noon).perform_later
<del> # assert_enqueued_with(job: MyJob, at: expected_time)
<add> # assert_performed_with(job: MyJob, at: at_matcher)
<ide> # end
<ide> #
<del> # To the +args+ proc, it will get passed the actual job's arguments
<del> # Your proc needs to return a boolean value determining if
<del> # the job's arguments matches your expectation. This is useful to check only
<del> # for a subset of arguments.
<add> # A proc can also be used to match a subset of a job's args:
<ide> #
<ide> # def test_assert_performed_with
<del> # expected_args = ->(job_args) do
<del> # assert job_args.first.key?(:foo)
<del> # end
<del> # MyJob.perform_later(foo: 'bar', other_arg: 'No need to check in the test')
<add> # args_matcher = ->(job_args) { job_args[0].key?(:foo) }
<add> #
<add> # MyJob.perform_later(foo: "bar", other_arg: "No need to check in the test")
<ide> #
<ide> # perform_enqueued_jobs
<ide> #
<del> # assert_performed_with(job: MyJob, args: expected_args)
<add> # assert_performed_with(job: MyJob, args: args_matcher)
<ide> # end
<ide> #
<ide> # If a block is passed, that block performs all of the jobs that were
<ide> def flush_enqueued_jobs(only: nil, except: nil, queue: nil, at: nil)
<ide>
<ide> def prepare_args_for_assertion(args)
<ide> args.dup.tap do |arguments|
<del> if arguments[:at] && !arguments[:at].respond_to?(:call)
<add> if arguments[:at].acts_like?(:time)
<ide> at_range = arguments[:at] - 1..arguments[:at] + 1
<ide> arguments[:at] = ->(at) { at_range.cover?(at) }
<ide> end
<ide><path>activejob/test/cases/test_helper_test.rb
<ide> def test_assert_enqueued_with_args
<ide> end
<ide> end
<ide>
<del> def test_assert_enqueued_with_selective_args
<del> args = ->(job_args) do
<del> assert_equal 1, job_args.first[:argument1]
<del> assert job_args.first[:argument2].key?(:b)
<del> end
<add> def test_assert_enqueued_with_supports_matcher_procs
<add> facets = {
<add> job: HelloJob,
<add> args: ["Rails"],
<add> at: Date.tomorrow.noon,
<add> queue: "important",
<add> }
<ide>
<del> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<del> MultipleKwargsJob.perform_later(argument2: { b: 2, a: 1 }, argument1: 1)
<del> end
<del> end
<add> facets[:job].set(queue: facets[:queue], wait_until: facets[:at]).perform_later(*facets[:args])
<ide>
<del> def test_assert_enqueued_with_selective_args_fails
<del> args = ->(job_args) do
<del> false
<del> end
<add> facets.each do |facet, value|
<add> matcher = ->(job_value) { job_value == value }
<add> refuser = ->(job_value) { false }
<ide>
<del> assert_raise ActiveSupport::TestCase::Assertion do
<del> assert_enqueued_with(job: MultipleKwargsJob, args: args) do
<del> MultipleKwargsJob.perform_later(argument2: { b: 2, a: 1 }, argument1: 1)
<add> assert_enqueued_with(**{ facet => matcher })
<add>
<add> assert_raises ActiveSupport::TestCase::Assertion do
<add> assert_enqueued_with(**{ facet => refuser })
<ide> end
<ide> end
<ide> end
<ide> def test_assert_performed_with_with_relative_at_option
<ide> end
<ide> end
<ide>
<del> def test_assert_performed_with_with_at_option_as_a_proc
<del> assert_performed_with(job: HelloJob, at: ->(at) { (4.minutes.from_now..6.minutes.from_now).cover?(at) }) do
<del> HelloJob.set(wait: 5.minutes).perform_later
<del> end
<del>
<del> assert_raise ActiveSupport::TestCase::Assertion do
<del> assert_performed_with(job: HelloJob, at: ->(at) { (1.minute.from_now..3.minutes.from_now).cover?(at) }) do
<del> HelloJob.set(wait: 1.minute).perform_later
<del> end
<del> end
<del> end
<del>
<ide> def test_assert_performed_with_without_block_with_at_option
<ide> HelloJob.set(wait_until: Date.tomorrow.noon).perform_later
<ide>
<ide> def test_assert_performed_with_with_hash_arg
<ide> end
<ide> end
<ide>
<del> def test_assert_performed_with_selective_args
<del> args = ->(job_args) do
<del> assert_equal 1, job_args.first[:argument1]
<del> assert job_args.first[:argument2].key?(:b)
<del> end
<add> def test_assert_performed_with_supports_matcher_procs
<add> facets = {
<add> job: HelloJob,
<add> args: ["Rails"],
<add> at: Date.tomorrow.noon,
<add> queue: "important",
<add> }
<ide>
<del> assert_performed_with(job: MultipleKwargsJob, args: args) do
<del> MultipleKwargsJob.perform_later(argument2: { b: 2, a: 1 }, argument1: 1)
<del> end
<del> end
<add> facets[:job].set(queue: facets[:queue], wait_until: facets[:at]).perform_later(*facets[:args])
<add> perform_enqueued_jobs
<ide>
<del> def test_assert_performed_with_selective_args_fails
<del> args = ->(job_args) do
<del> false
<del> end
<add> facets.each do |facet, value|
<add> matcher = ->(job_value) { job_value == value }
<add> refuser = ->(job_value) { false }
<ide>
<del> assert_raise ActiveSupport::TestCase::Assertion do
<del> assert_performed_with(job: MultipleKwargsJob, args: args) do
<del> MultipleKwargsJob.perform_later(argument2: { b: 2, a: 1 }, argument1: 1)
<add> assert_performed_with(**{ facet => matcher })
<add>
<add> assert_raises ActiveSupport::TestCase::Assertion do
<add> assert_performed_with(**{ facet => refuser })
<ide> end
<ide> end
<ide> end | 2 |
PHP | PHP | remove response from cookiecomponent | ab4a4716cd3fe2c547c222ab1060093003424e86 | <ide><path>src/Controller/Component/CookieComponent.php
<ide> class CookieComponent extends Component
<ide> protected $_loaded = [];
<ide>
<ide> /**
<del> * A reference to the Controller's Cake\Network\Response object
<add> * A reference to the Controller's Cake\Network\Response object.
<add> * Currently unused.
<ide> *
<ide> * @var \Cake\Network\Response
<add> * @deprecated 3.4.0 Will be removed in 4.0.0
<ide> */
<ide> protected $_response = null;
<ide>
<ide> public function initialize(array $config)
<ide>
<ide> $controller = $this->_registry->getController();
<ide>
<del> if ($controller !== null) {
<del> $this->_response =& $controller->response;
<del> }
<del>
<ide> if ($controller === null) {
<ide> $this->request = ServerRequest::createFromGlobals();
<del> $this->_response = new Response();
<ide> }
<ide>
<ide> if (empty($this->_config['path'])) {
<ide> protected function _write($name, $value)
<ide> $config = $this->configKey($name);
<ide> $expires = new Time($config['expires']);
<ide>
<del> $this->_response->cookie([
<add> $response = $this->getController()->response;
<add> $response->cookie([
<ide> 'name' => $name,
<ide> 'value' => $this->_encrypt($value, $config['encryption'], $config['key']),
<ide> 'expire' => $expires->format('U'),
<ide> protected function _delete($name)
<ide> $config = $this->configKey($name);
<ide> $expires = new Time('now');
<ide>
<del> $this->_response->cookie([
<add> $response = $this->getController()->response;
<add> $response->cookie([
<ide> 'name' => $name,
<ide> 'value' => '',
<ide> 'expire' => $expires->format('U') - 42000,
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> class RequestHandlerComponent extends Component
<ide> */
<ide> public $enabled = true;
<ide>
<del> /**
<del> * Holds the reference to Controller::$response
<del> *
<del> * @var \Cake\Network\Response
<del> * @deprecated 3.4.0 Will be removed in 4.0.0
<del> */
<del> public $response;
<del>
<ide> /**
<ide> * Contains the file extension parsed out by the Router
<ide> * | 2 |
Text | Text | improve dep0090 text | c046011388f509b5c3d94804796248d4dcb64cfc | <ide><path>doc/api/deprecations.md
<ide> changes:
<ide> Type: End-of-Life
<ide>
<ide> Node.js used to support all GCM authentication tag lengths which are accepted by
<del>OpenSSL when calling [`decipher.setAuthTag()`][]. Beginning with node v11.0.0,
<del>only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32 bits are
<del>allowed. Authentication tags whose length is not included in this list are
<del>considered invalid in compliance with [NIST SP 800-38D][].
<add>OpenSSL when calling [`decipher.setAuthTag()`][]. Beginning with Node.js
<add>v11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32
<add>bits are allowed. Authentication tags of other lengths are invalid per
<add>[NIST SP 800-38D][].
<ide>
<ide> <a id="DEP0091"></a>
<ide> ### DEP0091: crypto.DEFAULT_ENCODING | 1 |
Javascript | Javascript | improve format() performance further | c490b8ba54df6c730f7bfd02aaafe7c34f571f9e | <ide><path>lib/util.js
<ide> function tryStringify(arg) {
<ide> }
<ide> }
<ide>
<del>const formatRegExp = /%[sdj%]/g;
<ide> exports.format = function(f) {
<ide> if (typeof f !== 'string') {
<ide> const objects = new Array(arguments.length);
<ide> exports.format = function(f) {
<ide> return objects.join(' ');
<ide> }
<ide>
<del> if (arguments.length === 1) return f;
<del>
<del> const len = arguments.length;
<del> const args = new Array(len);
<del> var i;
<del> for (i = 0; i < len; i++) {
<del> args[i] = arguments[i];
<del> }
<del>
<del> i = 1;
<del> var str = f.replace(formatRegExp, function(x) {
<del> if (x === '%%') return '%';
<del> if (i >= len) return x;
<del> switch (x) {
<del> case '%s': return String(args[i++]);
<del> case '%d': return Number(args[i++]);
<del> case '%j': return tryStringify(args[i++]);
<del> // falls through
<del> default:
<del> return x;
<add> var argLen = arguments.length;
<add>
<add> if (argLen === 1) return f;
<add>
<add> var str = '';
<add> var a = 1;
<add> var lastPos = 0;
<add> for (var i = 0; i < f.length;) {
<add> if (f.charCodeAt(i) === 37/*'%'*/ && i + 1 < f.length) {
<add> switch (f.charCodeAt(i + 1)) {
<add> case 100: // 'd'
<add> if (a >= argLen)
<add> break;
<add> if (lastPos < i)
<add> str += f.slice(lastPos, i);
<add> str += Number(arguments[a++]);
<add> lastPos = i = i + 2;
<add> continue;
<add> case 106: // 'j'
<add> if (a >= argLen)
<add> break;
<add> if (lastPos < i)
<add> str += f.slice(lastPos, i);
<add> str += tryStringify(arguments[a++]);
<add> lastPos = i = i + 2;
<add> continue;
<add> case 115: // 's'
<add> if (a >= argLen)
<add> break;
<add> if (lastPos < i)
<add> str += f.slice(lastPos, i);
<add> str += String(arguments[a++]);
<add> lastPos = i = i + 2;
<add> continue;
<add> case 37: // '%'
<add> if (lastPos < i)
<add> str += f.slice(lastPos, i);
<add> str += '%';
<add> lastPos = i = i + 2;
<add> continue;
<add> }
<ide> }
<del> });
<del> while (i < len) {
<del> const x = args[i++];
<add> ++i;
<add> }
<add> if (lastPos === 0)
<add> str = f;
<add> else if (lastPos < f.length)
<add> str += f.slice(lastPos);
<add> while (a < argLen) {
<add> const x = arguments[a++];
<ide> if (x === null || (typeof x !== 'object' && typeof x !== 'symbol')) {
<ide> str += ' ' + x;
<ide> } else { | 1 |
Go | Go | fix spurious overlay errors | 004e56a4d10297093e5cc79237d92fc069aeef7d | <ide><path>libnetwork/agent.go
<ide> func (n *network) addDriverWatches() {
<ide> }
<ide>
<ide> c.agent.networkDB.WalkTable(tableName, func(nid, key string, value []byte) bool {
<del> d.EventNotify(driverapi.Create, n.ID(), tableName, key, value)
<add> if nid == n.ID() {
<add> d.EventNotify(driverapi.Create, nid, tableName, key, value)
<add> }
<add>
<ide> return false
<ide> })
<ide> }
<ide><path>libnetwork/drivers/overlay/ov_network.go
<ide> func (n *network) watchMiss(nlSock *nl.NetlinkSocket) {
<ide> continue
<ide> }
<ide>
<add> if !n.driver.isSerfAlive() {
<add> continue
<add> }
<add>
<ide> mac, IPmask, vtep, err := n.driver.resolvePeer(n.id, neigh.IP)
<ide> if err != nil {
<ide> logrus.Errorf("could not resolve peer %q: %v", neigh.IP, err)
<ide><path>libnetwork/drivers/overlay/peerdb.go
<ide> func (d *driver) peerDbAdd(nid, eid string, peerIP net.IP, peerIPMask net.IPMask
<ide> }
<ide>
<ide> func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMask,
<del> peerMac net.HardwareAddr, vtep net.IP) {
<add> peerMac net.HardwareAddr, vtep net.IP) bool {
<ide> peerDbWg.Wait()
<ide>
<ide> d.peerDb.Lock()
<ide> pMap, ok := d.peerDb.mp[nid]
<ide> if !ok {
<ide> d.peerDb.Unlock()
<del> return
<add> return false
<ide> }
<ide> d.peerDb.Unlock()
<ide>
<ide> func (d *driver) peerDbDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPM
<ide> }
<ide>
<ide> pMap.Lock()
<add>
<add> if pEntry, ok := pMap.mp[pKey.String()]; ok {
<add> // Mismatched endpoint ID(possibly outdated). Do not
<add> // delete peerdb
<add> if pEntry.eid != eid {
<add> pMap.Unlock()
<add> return false
<add> }
<add> }
<add>
<ide> delete(pMap.mp, pKey.String())
<ide> pMap.Unlock()
<add>
<add> return true
<ide> }
<ide>
<ide> func (d *driver) peerDbUpdateSandbox(nid string) {
<ide> func (d *driver) peerDelete(nid, eid string, peerIP net.IP, peerIPMask net.IPMas
<ide> }
<ide>
<ide> if updateDb {
<del> d.peerDbDelete(nid, eid, peerIP, peerIPMask, peerMac, vtep)
<add> if !d.peerDbDelete(nid, eid, peerIP, peerIPMask, peerMac, vtep) {
<add> return nil
<add> }
<ide> }
<ide>
<ide> n := d.network(nid) | 3 |
PHP | PHP | add missing use statement | 00602c54c24667ccf3a64f461079d5458d17761e | <ide><path>src/View/Helper/PaginatorHelper.php
<ide> use Cake\Event\Event;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\Helper;
<add>use Cake\View\View;
<ide>
<ide> /**
<ide> * Pagination Helper class for easy generation of pagination links. | 1 |
Python | Python | simplify architecture and larger-scale test runs | 400b19353de9768805b6a4bcc7bcd72ba57bd001 | <ide><path>examples/pipeline/wiki_entity_linking/run_el.py
<ide> def evaluate(predictions, golds, to_print=True):
<ide> for pred, gold in zip(predictions, golds):
<ide> is_correct = pred == gold
<ide> if not pred:
<del> fn += 1
<add> if not is_correct: # we don't care about tn
<add> fn += 1
<ide> elif is_correct:
<ide> tp += 1
<ide> else:
<ide><path>examples/pipeline/wiki_entity_linking/train_el.py
<ide>
<ide> from spacy._ml import SpacyVectors, create_default_optimizer, zero_init, logistic
<ide>
<del>from thinc.api import chain, concatenate, flatten_add_lengths, with_getitem, clone, with_flatten
<del>from thinc.neural.util import get_array_module
<del>from thinc.v2v import Model, Softmax, Maxout, Affine, ReLu
<del>from thinc.t2v import Pooling, sum_pool, mean_pool, max_pool
<add>from thinc.api import chain, concatenate, flatten_add_lengths, clone
<add>from thinc.v2v import Model, Maxout, Affine
<add>from thinc.t2v import Pooling, mean_pool
<ide> from thinc.t2t import ParametricAttention
<ide> from thinc.misc import Residual
<ide> from thinc.misc import LayerNorm as LN
<ide>
<ide> class EL_Model:
<ide>
<del> PRINT_LOSS = True
<add> PRINT_LOSS = False
<ide> PRINT_F = True
<ide> EPS = 0.0000000005
<ide> CUTOFF = 0.5
<ide>
<ide> INPUT_DIM = 300
<ide> ENTITY_WIDTH = 64
<del> ARTICLE_WIDTH = 64
<del> HIDDEN_1_WIDTH = 256
<del> HIDDEN_2_WIDTH = 64
<add> ARTICLE_WIDTH = 128
<add> HIDDEN_WIDTH = 64
<ide>
<ide> name = "entity_linker"
<ide>
<ide> def train_model(self, training_dir, entity_descr_output, trainlimit=None, devlim
<ide>
<ide> Doc.set_extension("entity_id", default=None)
<ide>
<del> train_instances, train_pos, train_neg, train_doc = self._get_training_data(training_dir,
<del> entity_descr_output,
<del> False,
<del> trainlimit,
<del> to_print=False)
<del>
<del> dev_instances, dev_pos, dev_neg, dev_doc = self._get_training_data(training_dir,
<del> entity_descr_output,
<del> True,
<del> devlimit,
<del> to_print=False)
<add> train_inst, train_pos, train_neg, train_doc = self._get_training_data(training_dir,
<add> entity_descr_output,
<add> False,
<add> trainlimit,
<add> to_print=False)
<add>
<add> dev_inst, dev_pos, dev_neg, dev_doc = self._get_training_data(training_dir,
<add> entity_descr_output,
<add> True,
<add> devlimit,
<add> to_print=False)
<ide> self._begin_training()
<ide>
<del> if self.PRINT_F:
<del> _, _, f_avg_train = -3.42, -3.42, -3.42 # self._test_dev(train_instances, train_pos, train_neg, train_doc, avg=True)
<del> _, _, f_nonavg_train = self._test_dev(train_instances, train_pos, train_neg, train_doc, avg=False)
<del> _, _, f_random_train = self._test_dev(train_instances, train_pos, train_neg, train_doc, calc_random=True)
<del> _, _, f_avg_dev = -3.42, -3.42, -3.42 # self._test_dev(dev_instances, dev_pos, dev_neg, dev_doc, avg=True)
<del> _, _, f_nonavg_dev = self._test_dev(dev_instances, dev_pos, dev_neg, dev_doc, avg=False)
<del> _, _, f_random_dev = self._test_dev(dev_instances, dev_pos, dev_neg, dev_doc, calc_random=True)
<del>
<del> print("random F train", round(f_random_train, 1))
<del> print("random F dev", round(f_random_dev, 1))
<del> print()
<del> print("avg/nonavg F train", round(f_avg_train, 1), round(f_nonavg_train, 1))
<del> print("avg/nonavg F dev", round(f_avg_dev, 1), round(f_nonavg_dev, 1))
<del> print()
<add> print()
<add> self._test_dev(train_inst, train_pos, train_neg, train_doc, print_string="train_random", calc_random=True)
<add> self._test_dev(dev_inst, dev_pos, dev_neg, dev_doc, print_string="dev_random", calc_random=True)
<add> print()
<add> self._test_dev(train_inst, train_pos, train_neg, train_doc, print_string="train_pre", calc_random=False)
<add> self._test_dev(dev_inst, dev_pos, dev_neg, dev_doc, print_string="dev_pre", avg=False)
<ide>
<ide> instance_pos_count = 0
<ide> instance_neg_count = 0
<ide>
<ide> if to_print:
<del> print("Training on", len(train_instances.values()), "articles")
<del> print("Dev test on", len(dev_instances.values()), "articles")
<ide> print()
<del>
<del> article_docs = list()
<del> entities = list()
<del> golds = list()
<del> for article_id, inst_cluster_set in train_instances.items():
<add> print("Training on", len(train_inst.values()), "articles")
<add> print("Dev test on", len(dev_inst.values()), "articles")
<add>
<add> # TODO: proper batches. Currently 1 article at the time
<add> article_count = 0
<add> for article_id, inst_cluster_set in train_inst.items():
<add> # if to_print:
<add> # print()
<add> # print(article_count, "Training on article", article_id)
<add> article_count += 1
<add> article_docs = list()
<add> entities = list()
<add> golds = list()
<ide> for inst_cluster in inst_cluster_set:
<ide> article_docs.append(train_doc[article_id])
<ide> entities.append(train_pos.get(inst_cluster))
<ide> def train_model(self, training_dir, entity_descr_output, trainlimit=None, devlim
<ide> golds.append(float(0.0))
<ide> instance_neg_count += 1
<ide>
<del> for x in range(10):
<del> print("Updating", x)
<ide> self.update(article_docs=article_docs, entities=entities, golds=golds)
<ide>
<del> # eval again
<del> if self.PRINT_F:
<del> _, _, f_avg_train = -3.42, -3.42, -3.42 # self._test_dev(train_instances, train_pos, train_neg, train_doc, avg=True)
<del> _, _, f_nonavg_train = self._test_dev(train_instances, train_pos, train_neg, train_doc, avg=False)
<del> _, _, f_avg_dev = -3.42, -3.42, -3.42 # self._test_dev(dev_instances, dev_pos, dev_neg, dev_doc, avg=True)
<del> _, _, f_nonavg_dev = self._test_dev(dev_instances, dev_pos, dev_neg, dev_doc, avg=False)
<del>
<del> print("avg/nonavg F train", round(f_avg_train, 1), round(f_nonavg_train, 1))
<del> print("avg/nonavg F dev", round(f_avg_dev, 1), round(f_nonavg_dev, 1))
<del> print()
<add> # dev eval
<add> self._test_dev(dev_inst, dev_pos, dev_neg, dev_doc, print_string="dev_inter", avg=False)
<ide>
<ide> if to_print:
<add> print()
<ide> print("Trained on", instance_pos_count, "/", instance_neg_count, "instances pos/neg")
<ide>
<del> def _test_dev(self, dev_instances, dev_pos, dev_neg, dev_doc, avg=False, calc_random=False):
<add> print()
<add> self._test_dev(train_inst, train_pos, train_neg, train_doc, print_string="train_post", calc_random=False)
<add> self._test_dev(dev_inst, dev_pos, dev_neg, dev_doc, print_string="dev_post", avg=False)
<add>
<add> def _test_dev(self, instances, pos, neg, doc, print_string, avg=False, calc_random=False):
<ide> predictions = list()
<ide> golds = list()
<ide>
<del> for article_id, inst_cluster_set in dev_instances.items():
<add> for article_id, inst_cluster_set in instances.items():
<ide> for inst_cluster in inst_cluster_set:
<del> pos_ex = dev_pos.get(inst_cluster)
<del> neg_exs = dev_neg.get(inst_cluster, [])
<add> pos_ex = pos.get(inst_cluster)
<add> neg_exs = neg.get(inst_cluster, [])
<ide>
<ide> article = inst_cluster.split(sep="_")[0]
<ide> entity_id = inst_cluster.split(sep="_")[1]
<del> article_doc = dev_doc[article]
<add> article_doc = doc[article]
<ide>
<ide> if calc_random:
<ide> prediction = self._predict_random(entity=pos_ex)
<ide> def _test_dev(self, dev_instances, dev_pos, dev_neg, dev_doc, avg=False, calc_ra
<ide> predictions.append(prediction)
<ide> golds.append(float(0.0))
<ide>
<del> # TODO: use lowest_mse and combine with prior probability
<add> # TODO: combine with prior probability
<ide> p, r, f = run_el.evaluate(predictions, golds, to_print=False)
<del> return p, r, f
<add> if self.PRINT_F:
<add> # print("p/r/F", print_string, round(p, 1), round(r, 1), round(f, 1))
<add> print("F", print_string, round(f, 1))
<add>
<add> loss, d_scores = self.get_loss(self.model.ops.asarray(predictions), self.model.ops.asarray(golds))
<add> if self.PRINT_LOSS:
<add> print("loss", print_string, round(loss, 5))
<add>
<add> return loss, p, r, f
<ide>
<ide> def _predict(self, article_doc, entity, avg=False, apply_threshold=True):
<ide> if avg:
<ide> def _predict_random(self, entity, apply_threshold=True):
<ide>
<ide> def _build_cnn(self, hidden_entity_width, hidden_article_width):
<ide> with Model.define_operators({">>": chain, "|": concatenate, "**": clone}):
<del> self.entity_encoder = self._encoder(in_width=self.INPUT_DIM, hidden_width=hidden_entity_width) # entity encoding
<del> self.article_encoder = self._encoder(in_width=self.INPUT_DIM, hidden_width=hidden_article_width) # doc encoding
<del>
<del> hidden_input_with = hidden_entity_width + hidden_article_width
<del> hidden_output_with = self.HIDDEN_1_WIDTH
<add> self.entity_encoder = self._encoder(in_width=self.INPUT_DIM, hidden_width=hidden_entity_width)
<add> self.article_encoder = self._encoder(in_width=self.INPUT_DIM, hidden_width=hidden_article_width)
<ide>
<del> convolution_2 = Residual((ExtractWindow(nW=1) >> LN(Maxout(hidden_output_with, hidden_output_with * 3))))
<add> nr_i = hidden_entity_width + hidden_article_width
<add> nr_o = self.HIDDEN_WIDTH
<ide>
<del> self.model = Affine(hidden_output_with, hidden_input_with) \
<del> >> LN(Maxout(hidden_output_with, hidden_output_with)) \
<del> >> convolution_2 \
<del> >> Affine(self.HIDDEN_2_WIDTH, hidden_output_with) \
<del> >> Affine(1, self.HIDDEN_2_WIDTH) \
<del> >> logistic
<add> self.model = Affine(nr_o, nr_i) \
<add> >> LN(Maxout(nr_o, nr_o)) \
<add> >> Affine(1, nr_o) \
<add> >> logistic
<ide>
<ide> @staticmethod
<ide> def _encoder(in_width, hidden_width):
<ide> def _encoder(in_width, hidden_width):
<ide> >> flatten_add_lengths \
<ide> >> ParametricAttention(in_width)\
<ide> >> Pooling(mean_pool) \
<del> >> Residual(zero_init(Maxout(in_width, in_width))) \
<add> >> Residual((ExtractWindow(nW=1) >> LN(Maxout(in_width, in_width * 3)))) \
<ide> >> zero_init(Affine(hidden_width, in_width, drop_factor=0.0))
<ide>
<add> # TODO: ReLu instead of LN(Maxout) ?
<add>
<ide> return encoder
<ide>
<ide> def _begin_training(self):
<ide> self.sgd = create_default_optimizer(self.model.ops)
<ide>
<del> def update(self, article_docs, entities, golds, drop=0.):
<add> @staticmethod
<add> def get_loss(predictions, golds):
<add> d_scores = (predictions - golds)
<add>
<add> loss = (d_scores ** 2).sum()
<add> return loss, d_scores
<add>
<add> def update(self, article_docs, entities, golds, drop=0., apply_threshold=True):
<ide> doc_encodings, bp_doc = self.article_encoder.begin_update(article_docs, drop=drop)
<ide> entity_encodings, bp_encoding = self.entity_encoder.begin_update(entities, drop=drop)
<ide> concat_encodings = [list(entity_encodings[i]) + list(doc_encodings[i]) for i in range(len(entities))]
<ide>
<ide> predictions, bp_model = self.model.begin_update(np.asarray(concat_encodings), drop=drop)
<del>
<ide> predictions = self.model.ops.flatten(predictions)
<ide> golds = self.model.ops.asarray(golds)
<ide>
<del> # print("predictions", predictions)
<del> # print("golds", golds)
<add> loss, d_scores = self.get_loss(predictions, golds)
<ide>
<del> d_scores = (predictions - golds) # / predictions.shape[0]
<del> # print("d_scores (1)", d_scores)
<add> # if self.PRINT_LOSS:
<add> # print("loss train", round(loss, 5))
<ide>
<del> loss = (d_scores ** 2).sum()
<del>
<del> if self.PRINT_LOSS:
<del> print("loss train", round(loss, 5))
<add> # if self.PRINT_F:
<add> # predictions_f = [x for x in predictions]
<add> # if apply_threshold:
<add> # predictions_f = [1.0 if x > self.CUTOFF else 0.0 for x in predictions_f]
<add> # p, r, f = run_el.evaluate(predictions_f, golds, to_print=False)
<add> # print("p/r/F train", round(p, 1), round(r, 1), round(f, 1))
<ide>
<ide> d_scores = d_scores.reshape((-1, 1))
<ide> d_scores = d_scores.astype(np.float32)
<del> # print("d_scores (2)", d_scores)
<ide>
<ide> model_gradient = bp_model(d_scores, sgd=self.sgd)
<ide>
<ide><path>examples/pipeline/wiki_entity_linking/wiki_nel_pipeline.py
<ide>
<ide> # STEP 6: apply the EL algorithm on the training dataset
<ide> if run_training:
<del> print("STEP 6: training ", datetime.datetime.now())
<add> print("STEP 6: training", datetime.datetime.now())
<ide> my_nlp = spacy.load('en_core_web_md')
<ide> trainer = EL_Model(kb=my_kb, nlp=my_nlp)
<del> trainer.train_model(training_dir=TRAINING_DIR, entity_descr_output=ENTITY_DESCR, trainlimit=1, devlimit=1)
<add> trainer.train_model(training_dir=TRAINING_DIR, entity_descr_output=ENTITY_DESCR, trainlimit=2000, devlimit=200)
<ide> print()
<ide>
<ide> # STEP 7: apply the EL algorithm on the dev dataset | 3 |
Ruby | Ruby | restore fetch in stage | 58cecf38cf66117dddb09af0020d3426f1e90da2 | <ide><path>Library/Homebrew/formula.rb
<ide> def patch
<ide> # @private
<ide> def brew
<ide> @prefix_returns_versioned_prefix = true
<del> active_spec.fetch
<ide> stage do |staging|
<ide> staging.retain! if Homebrew.args.keep_tmp?
<ide> prepare_patches
<ide><path>Library/Homebrew/resource.rb
<ide> def clear_cache
<ide> def stage(target = nil, &block)
<ide> raise ArgumentError, "target directory or block is required" unless target || block
<ide>
<add> fetch
<ide> prepare_patches
<ide>
<ide> unpack(target, &block) | 2 |
Javascript | Javascript | remove obscure feature of addobserver | d1b5d49ef8aecc3967fdbaff3156221fa48d061a | <ide><path>packages/ember-metal/lib/observer.js
<ide> function beforeKey(eventName) {
<ide> }
<ide>
<ide> /** @private */
<del>function xformForArgs(args) {
<del> return function (target, method, params) {
<del> var obj = params[0], keyName = changeKey(params[1]), val;
<del> var copy_args = args.slice();
<del> if (method.length>2) {
<del> val = Ember.getPath(Ember.isGlobalPath(keyName) ? window : obj, keyName);
<del> }
<del> copy_args.unshift(obj, keyName, val);
<del> method.apply(target, copy_args);
<del> };
<add>function xformChange(target, method, params) {
<add> var obj = params[0], keyName = changeKey(params[1]), val;
<add> if (method.length>2) {
<add> val = Ember.getPath(Ember.isGlobalPath(keyName) ? window : obj, keyName);
<add> }
<add> method.apply(target, [obj, keyName, val]);
<ide> }
<ide>
<del>var xformChange = xformForArgs([]);
<del>
<ide> /** @private */
<ide> function xformBefore(target, method, params) {
<ide> var obj = params[0], keyName = beforeKey(params[1]), val;
<ide> function xformBefore(target, method, params) {
<ide> }
<ide>
<ide> Ember.addObserver = function(obj, path, target, method) {
<del> var xform;
<del> if (arguments.length > 4) {
<del> var args = array_Slice.call(arguments, 4);
<del> xform = xformForArgs(args);
<del> } else {
<del> xform = xformChange;
<del> }
<del> Ember.addListener(obj, changeEvent(path), target, method, xform);
<add> Ember.addListener(obj, changeEvent(path), target, method, xformChange);
<ide> Ember.watch(obj, path);
<ide> return this;
<ide> };
<ide><path>packages/ember-metal/tests/observer_test.js
<ide> testBoth('addObserver should respect targets with methods', function(get,set){
<ide>
<ide> });
<ide>
<del>testBoth('addObserver should preserve additional context passed when firing the observer', function(get, set) {
<del> var observed = { foo: 'foo' };
<del>
<del> var target1 = {
<del> count: 0,
<del>
<del> didChange: function(obj, keyName, value, ctx1, ctx2) {
<del> equal(ctx1, "biff", "first context is passed");
<del> equal(ctx2, "bang", "second context is passed");
<del> equal(5, arguments.length);
<del> this.count++;
<del> }
<del> };
<del>
<del> Ember.addObserver(observed, 'foo', target1, 'didChange', "biff", "bang");
<del>
<del> set(observed, 'foo', 'BAZ');
<del> equal(target1.count, 1, 'target1 observer should have fired');
<del>
<del> set(observed, 'foo', 'BAZ2');
<del> equal(target1.count, 2, 'target1 observer should have fired');
<del>});
<del>
<del>
<ide> testBoth('addObserver should allow multiple objects to observe a property', function(get, set) { var observed = { foo: 'foo' };
<ide>
<ide> var target1 = { | 2 |
PHP | PHP | allow config['schema'] to be array for postgresql | f3bae8e37fb9ba9c00a7fe71156f1bef37e2435b | <ide><path>src/Illuminate/Database/Connectors/PostgresConnector.php
<ide> public function connect(array $config)
<ide> // may have been specified on the connections. If that is the case we will
<ide> // set the default schema search paths to the specified database schema.
<ide> if (isset($config['schema'])) {
<del> $schema = $config['schema'];
<add> $schema = '"'.(is_array($config['schema']) ? implode('", "', $config['schema']) : $config['schema']).'"';
<ide>
<del> $connection->prepare("set search_path to \"{$schema}\"")->execute();
<add> $connection->prepare("set search_path to {$schema}")->execute();
<ide> }
<ide>
<ide> return $connection;
<ide><path>tests/Database/DatabaseConnectorTest.php
<ide> public function testPostgresSearchPathIsSet()
<ide> $this->assertSame($result, $connection);
<ide> }
<ide>
<add>
<add> public function testPostgresSearchPathArraySupported()
<add> {
<add> $dsn = 'pgsql:host=foo;dbname=bar';
<add> $config = ['host' => 'foo', 'database' => 'bar', 'schema' => ['public', 'user'], 'charset' => 'utf8'];
<add> $connector = $this->getMock('Illuminate\Database\Connectors\PostgresConnector', ['createConnection', 'getOptions'] );
<add> $connection = m::mock('stdClass');
<add> $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->will($this->returnValue(['options']));
<add> $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->will($this->returnValue($connection));
<add> $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection);
<add> $connection->shouldReceive('prepare')->once()->with('set search_path to "public", "user"')->andReturn($connection);
<add> $connection->shouldReceive('execute')->twice();
<add> $result = $connector->connect($config);
<add>
<add> $this->assertSame($result, $connection);
<add> }
<add>
<add>
<ide> public function testSQLiteMemoryDatabasesMayBeConnectedTo()
<ide> {
<ide> $dsn = 'sqlite::memory:'; | 2 |
PHP | PHP | get more functionality working | f109ca168f0cc65098e56fef8d7d4eea077010f7 | <ide><path>src/Console/Command/Task/TestTask.php
<ide> use Cake\Core\Plugin;
<ide> use Cake\Error;
<ide> use Cake\ORM\TableRegistry;
<add>use Cake\Utility\Folder;
<ide> use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide> class TestTask extends BakeTask {
<ide> * @var array
<ide> */
<ide> public $classTypes = [
<del> 'Entity' => 'Model/Entity',
<del> 'Table' => 'Model/Table',
<del> 'Controller' => 'Controller',
<del> 'Component' => 'Controller/Component',
<del> 'Behavior' => 'Model/Behavior',
<del> 'Helper' => 'View/Helper'
<del> ];
<del>
<del>/**
<del> * Mapping between type names and their namespaces
<del> *
<del> * @var array
<del> */
<del> public $classNamespaces = [
<del> 'Model' => 'Model',
<add> 'Entity' => 'Model\Entity',
<add> 'Table' => 'Model\Table',
<ide> 'Controller' => 'Controller',
<ide> 'Component' => 'Controller\Component',
<ide> 'Behavior' => 'Model\Behavior',
<ide> 'Helper' => 'View\Helper'
<ide> ];
<ide>
<ide> /**
<del> * Mapping between packages, and their baseclass
<del> * This is used to create use statements.
<add> * class types that methods can be generated for
<ide> *
<ide> * @var array
<ide> */
<del> public $baseTypes = [
<del> 'Model' => ['Model', 'Model'],
<del> 'Behavior' => ['ModelBehavior', 'Model'],
<del> 'Controller' => ['Controller', 'Controller'],
<del> 'Component' => ['Component', 'Controller'],
<del> 'Helper' => ['Helper', 'View']
<add> public $classSuffixes = [
<add> 'Entity' => '',
<add> 'Table' => 'Table',
<add> 'Controller' => 'Controller',
<add> 'Component' => 'Component',
<add> 'Behavior' => 'Behavior',
<add> 'Helper' => 'Helper'
<ide> ];
<ide>
<ide> /**
<ide> public function execute() {
<ide> return $this->outputClassChoices($this->args[0]);
<ide> }
<ide>
<del> if ($count > 1) {
<del> $type = Inflector::classify($this->args[0]);
<del> if ($this->bake($type, $this->args[1])) {
<del> $this->out('<success>Done</success>');
<del> }
<add> if ($this->bake($this->args[0], $this->args[1])) {
<add> $this->out('<success>Done</success>');
<ide> }
<ide> }
<ide>
<ide> public function outputClassChoices($type) {
<ide> /**
<ide> * Get the possible classes for a given type.
<ide> *
<del> * @param string $type The type name to look for classes in.
<add> * @param string $namespace The namespace fragment to look for classes in.
<ide> * @return array
<ide> */
<del> protected function _getClassOptions($type) {
<add> protected function _getClassOptions($namespace) {
<ide> $classes = [];
<add> $base = APP;
<add> if ($this->plugin) {
<add> $base = Plugin::path($this->plugin);
<add> }
<add> $path = $base . str_replace('\\', DS, $namespace);
<add> $folder = new Folder($path);
<add> list($dirs, $files) = $folder->read();
<add> foreach ($files as $file) {
<add> $classes[] = str_replace('.php', '', $file);
<add> }
<ide> return $classes;
<ide> }
<ide>
<ide> protected function _interactive($type = null) {
<ide> * @return string|boolean
<ide> */
<ide> public function bake($type, $className) {
<del> $plugin = null;
<del> if ($this->plugin) {
<del> $plugin = $this->plugin . '.';
<del> }
<del>
<del> $realType = $this->mapType($type, $plugin);
<ide> $fullClassName = $this->getRealClassName($type, $className);
<ide>
<del> if ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($realType, $fullClassName)) {
<add> if (!empty($this->params['fixtures'])) {
<add> $fixtures = array_map('trim', explode(',', $this->params['fixtures']));
<add> $this->_fixtures = $fixtures;
<add> } elseif ($this->typeCanDetectFixtures($type) && $this->isLoadableClass($realType, $fullClassName)) {
<ide> $this->out(__d('cake_console', 'Bake is detecting possible fixtures...'));
<ide> $testSubject = $this->buildTestSubject($type, $className);
<ide> $this->generateFixtureList($testSubject);
<del> } elseif ($this->interactive) {
<del> $this->getUserFixtures();
<ide> }
<ide>
<ide> $methods = [];
<ide> if (class_exists($fullClassName)) {
<ide> $methods = $this->getTestableMethods($fullClassName);
<ide> }
<ide> $mock = $this->hasMockClass($type, $fullClassName);
<del> list($preConstruct, $construction, $postConstruct) = $this->generateConstructor($type, $fullClassName, $plugin);
<del> $uses = $this->generateUses($type, $realType, $fullClassName);
<add> list($preConstruct, $construction, $postConstruct) = $this->generateConstructor($type, $fullClassName);
<add> $uses = $this->generateUses($type, $fullClassName);
<ide>
<ide> $subject = $className;
<ide> list($namespace, $className) = namespaceSplit($fullClassName);
<ide> public function bake($type, $className) {
<ide> $this->out("\n" . __d('cake_console', 'Baking test case for %s ...', $fullClassName), 1, Shell::QUIET);
<ide>
<ide> $this->Template->set('fixtures', $this->_fixtures);
<del> $this->Template->set('plugin', $plugin);
<add> $this->Template->set('plugin', $this->plugin);
<ide> $this->Template->set(compact(
<ide> 'subject', 'className', 'methods', 'type', 'fullClassName', 'mock',
<ide> 'realType', 'preConstruct', 'postConstruct', 'construction',
<ide> public function bake($type, $className) {
<ide> $out = $this->Template->generate('classes', 'test');
<ide>
<ide> $filename = $this->testCaseFileName($type, $className);
<del> $made = $this->createFile($filename, $out);
<del> if ($made) {
<add> if ($this->createFile($filename, $out)) {
<ide> return $out;
<ide> }
<ide> return false;
<ide> public function buildTestSubject($type, $class) {
<ide> *
<ide> * @param string $type The Type of object you are generating tests for eg. controller.
<ide> * @param string $class the Classname of the class the test is being generated for.
<del> * @param string $plugin The plugin name of the class being generated.
<ide> * @return string Real classname
<ide> */
<del> public function getRealClassName($type, $class, $plugin = null) {
<del> if (strpos('\\', $class)) {
<del> return $class;
<del> }
<add> public function getRealClassName($type, $class) {
<ide> $namespace = Configure::read('App.namespace');
<del> $loadedPlugin = $plugin && Plugin::loaded($plugin);
<del> if ($loadedPlugin) {
<del> $namespace = Plugin::getNamespace($plugin);
<del> }
<del> if ($plugin && !$loadedPlugin) {
<del> $namespace = Inflector::camelize($plugin);
<add> if ($this->plugin) {
<add> $namespace = Plugin::getNamespace($this->plugin);
<ide> }
<del> $subNamespace = $this->classNamespaces[$type];
<del>
<del> $position = strpos($class, $type);
<del>
<del> if (
<del> strtolower($type) !== 'model' &&
<del> ($position === false || strlen($class) - $position !== strlen($type))
<del> ) {
<del> $class .= $type;
<add> $suffix = $this->classSuffixes[$type];
<add> $subSpace = $this->mapType($type);
<add> if ($suffix && strpos($class, $suffix) === false) {
<add> $class .= $suffix;
<ide> }
<del> return $namespace . '\\' . $subNamespace . '\\' . $class;
<add> return $namespace . '\\' . $subSpace . '\\' . $class;
<ide> }
<ide>
<ide> /**
<ide> public function hasMockClass($type) {
<ide> *
<ide> * @param string $type The Type of object you are generating tests for eg. controller
<ide> * @param string $fullClassName The full classname of the class the test is being generated for.
<del> * @param string $plugin The plugin name.
<ide> * @return array Constructor snippets for the thing you are building.
<ide> */
<del> public function generateConstructor($type, $fullClassName, $plugin) {
<add> public function generateConstructor($type, $fullClassName) {
<ide> list($namespace, $className) = namespaceSplit($fullClassName);
<ide> $type = strtolower($type);
<ide> $pre = $construct = $post = '';
<del> if ($type === 'model') {
<del> $construct = "ClassRegistry::init('{$plugin}$className');\n";
<add> if ($type === 'table') {
<add> $construct = "TableRegistry::init('{$className}', ['className' => '{$fullClassName}']);\n";
<ide> }
<del> if ($type === 'behavior') {
<add> if ($type === 'behavior' || $type === 'entity') {
<ide> $construct = "new {$className}();\n";
<ide> }
<ide> if ($type === 'helper') {
<ide> public function generateConstructor($type, $fullClassName, $plugin) {
<ide> * @param string $fullClassName The Classname of the class the test is being generated for.
<ide> * @return array An array containing used classes
<ide> */
<del> public function generateUses($type, $realType, $fullClassName) {
<add> public function generateUses($type, $fullClassName) {
<ide> $uses = [];
<ide> $type = strtolower($type);
<ide> if ($type == 'component') {
<ide> $uses[] = 'Cake\Controller\ComponentRegistry';
<ide> }
<add> if ($type == 'table') {
<add> $uses[] = 'Cake\ORM\TableRegistry';
<add> }
<ide> if ($type == 'helper') {
<ide> $uses[] = 'Cake\View\View';
<ide> }
<ide><path>tests/TestCase/Console/Command/Task/TestTaskTest.php
<ide> public function testOutputClassOptionsForTable() {
<ide> ->with($this->stringContains('2. ArticlesTagsTable'));
<ide> $this->Task->stdout->expects($this->at(3))
<ide> ->method('write')
<del> ->with($this->stringContains('3. AuthorsTable'));
<add> ->with($this->stringContains('3. AuthUsersTable'));
<add> $this->Task->stdout->expects($this->at(4))
<add> ->method('write')
<add> ->with($this->stringContains('4. AuthorsTable'));
<add>
<add> $this->Task->outputClassChoices('Table');
<add> }
<add>
<add>/**
<add> * Test generating class options for table.
<add> *
<add> * @return void
<add> */
<add> public function testOutputClassOptionsForTablePlugin() {
<add> Plugin::load('TestPlugin');
<add>
<add> $this->Task->plugin = 'TestPlugin';
<add> $this->Task->stdout->expects($this->at(0))
<add> ->method('write')
<add> ->with($this->stringContains('You must provide'));
<add> $this->Task->stdout->expects($this->at(1))
<add> ->method('write')
<add> ->with($this->stringContains('1. TestPluginCommentsTable'));
<add>
<ide> $this->Task->outputClassChoices('Table');
<ide> }
<ide>
<ide> public function testGetUserFixtures() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * Dataprovider for class name generation.
<add> *
<add> * @return array
<add> */
<add> public static function realClassProvider() {
<add> return [
<add> ['Entity', 'Article', 'App\Model\Entity\Article'],
<add> ['Entity', 'ArticleEntity', 'App\Model\Entity\ArticleEntity'],
<add> ['Table', 'Posts', 'App\Model\Table\PostsTable'],
<add> ['Table', 'PostsTable', 'App\Model\Table\PostsTable'],
<add> ['Controller', 'Posts', 'App\Controller\PostsController'],
<add> ['Controller', 'PostsController', 'App\Controller\PostsController'],
<add> ['Behavior', 'Timestamp', 'App\Model\Behavior\TimestampBehavior'],
<add> ['Behavior', 'TimestampBehavior', 'App\Model\Behavior\TimestampBehavior'],
<add> ['Helper', 'Form', 'App\View\Helper\FormHelper'],
<add> ['Helper', 'FormHelper', 'App\View\Helper\FormHelper'],
<add> ['Component', 'Auth', 'App\Controller\Component\AuthComponent'],
<add> ['Component', 'AuthComponent', 'App\Controller\Component\AuthComponent'],
<add> ];
<add> }
<add>
<ide> /**
<ide> * test that resolving class names works
<ide> *
<add> * @dataProvider realClassProvider
<ide> * @return void
<ide> */
<del> public function testGetRealClassname() {
<del> $result = $this->Task->getRealClassname('Model', 'Post');
<del> $this->assertEquals('App\Model\Post', $result);
<del>
<del> $result = $this->Task->getRealClassname('Controller', 'Posts');
<del> $this->assertEquals('App\Controller\PostsController', $result);
<del>
<del> $result = $this->Task->getRealClassname('Controller', 'PostsController');
<del> $this->assertEquals('App\Controller\PostsController', $result);
<del>
<del> $result = $this->Task->getRealClassname('Controller', 'AlertTypes');
<del> $this->assertEquals('App\Controller\AlertTypesController', $result);
<del>
<del> $result = $this->Task->getRealClassname('Helper', 'Form');
<del> $this->assertEquals('App\View\Helper\FormHelper', $result);
<del>
<del> $result = $this->Task->getRealClassname('Helper', 'FormHelper');
<del> $this->assertEquals('App\View\Helper\FormHelper', $result);
<del>
<del> $result = $this->Task->getRealClassname('Behavior', 'Tree');
<del> $this->assertEquals('App\Model\Behavior\TreeBehavior', $result);
<del>
<del> $result = $this->Task->getRealClassname('Component', 'Auth');
<del> $this->assertEquals('App\Controller\Component\AuthComponent', $result);
<add> public function testGetRealClassname($type, $name, $expected) {
<add> $result = $this->Task->getRealClassname($type, $name);
<add> $this->assertEquals($expected, $result);
<add> }
<ide>
<del> $result = $this->Task->getRealClassname('Component', 'Utility', 'TestPlugin');
<del> $this->assertEquals('TestPlugin\Controller\Component\UtilityComponent', $result);
<add>/**
<add> * test resolving class names with plugins
<add> *
<add> * @return void
<add> */
<add> public function testGetRealClassnamePlugin() {
<add> Plugin::load('TestPLugin');
<add> $this->Task->plugin = 'TestPlugin';
<add> $result = $this->Task->getRealClassname('Helper', 'Asset');
<add> $expected = 'TestPlugin\View\Helper\AssetHelper';
<add> $this->assertEquals($expected, $result);
<ide> }
<ide>
<ide> /**
<ide> public function testBakeControllerTest() {
<ide> * @return void
<ide> */
<ide> public function testBakeComponentTest() {
<add> $this->markTestIncomplete('Model tests need reworking.');
<ide> Configure::write('App.namespace', 'TestApp');
<ide> $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
<ide>
<ide> public function testBakeComponentTest() {
<ide> * @return void
<ide> */
<ide> public function testBakeBehaviorTest() {
<add> $this->markTestIncomplete('Model tests need reworking.');
<ide> $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
<ide>
<ide> $result = $this->Task->bake('Behavior', 'Example');
<ide> public function testBakeBehaviorTest() {
<ide> * @return void
<ide> */
<ide> public function testBakeHelperTest() {
<del> $this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
<add> $this->Task->expects($this->once())
<add> ->method('createFile')
<add> ->will($this->returnValue(true));
<ide>
<ide> $result = $this->Task->bake('Helper', 'Example');
<ide>
<ide> public function testMockClassGeneration() {
<ide> * @return void
<ide> */
<ide> public function testBakeWithPlugin() {
<add> $this->markTestIncomplete('Model tests need reworking.');
<ide> $this->Task->plugin = 'TestTest';
<ide>
<ide> //fake plugin path
<ide> public static function mapTypeProvider() {
<ide> return array(
<ide> array('controller', 'Controller'),
<ide> array('Controller', 'Controller'),
<del> array('component', 'Controller/Component'),
<del> array('Component', 'Controller/Component'),
<del> array('table', 'Model/Table'),
<del> array('Table', 'Model/Table'),
<del> array('entity', 'Model/Entity'),
<del> array('Entity', 'Model/Entity'),
<del> array('behavior', 'Model/Behavior'),
<del> array('Behavior', 'Model/Behavior'),
<del> array('helper', 'View/Helper'),
<del> array('Helper', 'View/Helper'),
<del> array('Helper', 'View/Helper'),
<add> array('component', 'Controller\Component'),
<add> array('Component', 'Controller\Component'),
<add> array('table', 'Model\Table'),
<add> array('Table', 'Model\Table'),
<add> array('entity', 'Model\Entity'),
<add> array('Entity', 'Model\Entity'),
<add> array('behavior', 'Model\Behavior'),
<add> array('Behavior', 'Model\Behavior'),
<add> array('helper', 'View\Helper'),
<add> array('Helper', 'View\Helper'),
<add> array('Helper', 'View\Helper'),
<ide> );
<ide> }
<ide> | 2 |
Javascript | Javascript | simplify pt-br past relativetime | bb142fcc5ac1a3bfb700b6cbfe0eac5c06374c07 | <ide><path>src/locale/pt-br.js
<ide> export default moment.defineLocale('pt-br', {
<ide> },
<ide> relativeTime : {
<ide> future : 'em %s',
<del> past : '%s atrás',
<add> past : 'há %s',
<ide> s : 'poucos segundos',
<ide> ss : '%d segundos',
<ide> m : 'um minuto',
<ide><path>src/test/locale/pt-br.js
<ide> test('from', function (assert) {
<ide>
<ide> test('suffix', function (assert) {
<ide> assert.equal(moment(30000).from(0), 'em poucos segundos', 'prefix');
<del> assert.equal(moment(0).from(30000), 'poucos segundos atrás', 'suffix');
<add> assert.equal(moment(0).from(30000), 'há poucos segundos', 'prefix');
<ide> });
<ide>
<ide> test('fromNow', function (assert) {
<ide> test('relative time threshold', function (assert) {
<ide> moment.relativeTimeThreshold('ss', 3);
<ide>
<ide> rts.subtract(3, 'seconds');
<del> assert.equal(rts.fromNow(), 'poucos segundos atrás', 'Below custom a few seconds to seconds threshold');
<add> assert.equal(rts.fromNow(), 'há poucos segundos', 'Below custom a few seconds to seconds threshold');
<ide> rts.subtract(1, 'seconds');
<del> assert.equal(rts.fromNow(), '4 segundos atrás', 'Above custom a few seconds to seconds threshold');
<add> assert.equal(rts.fromNow(), 'há 4 segundos', 'Above custom a few seconds to seconds threshold');
<ide>
<ide> moment.relativeTimeThreshold('ss', rtsDefault);
<ide> }); | 2 |
Text | Text | update chinese translation of regular expressions | 2fdc5267e33cb6aaf33c2c7fff0a9576e8b7d9dc | <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.chinese.md
<ide> id: 587d7dba367417b2b2512ba8
<ide> title: Check for All or None
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301338
<ide> localeTitle: 检查全部或无
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时,您要搜索的模式可能包含可能存在或可能不存在的模式。但是,尽管如此,检查它们可能很重要。您可以指定可能存在带问号的元素, <code>?</code> 。这将检查前一个元素中的零个或一个。您可以将此符号视为前一个元素是可选的。例如,美式英语和英式英语略有不同,您可以使用问号来匹配两种拼写。 <blockquote>让美国人=“颜色”; <br>让british =“color”; <br>让rainbowRegex = / colou?r /; <br> rainbowRegex.test(美国); //返回true <br> rainbowRegex.test(英国); //返回true </blockquote></section>
<add><section id='description'>
<add>有时,想要搜寻的匹配模式可能有不确定是否存在的部分。尽管如此,还是想检查它们。
<add>为此,可以使用问号<code>?</code>指定可能存在的元素。这将检查前面的零个或一个元素。可以将此符号视为前面的元素是可选的。
<add>例如,美式英语和英式英语略有不同,可以使用问号来匹配两种拼写。
<add>
<add>```js
<add>let american = "color";
<add>let british = "colour";
<add>let rainbowRegex= /colou?r/;
<add>rainbowRegex.test(american); // Returns true
<add>rainbowRegex.test(british); // Returns true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改正则表达式<code>favRegex</code>以匹配该单词的美国英语(收藏)和英国英语(收藏)版本。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>favRegex</code>以匹配美式英语(favorite)和英式英语(favourite)的单词版本。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用可选的符号, <code>?</code> 。
<add> - text: 你的正则表达式应该使用可选符号<code>?</code>。
<ide> testString: assert(favRegex.source.match(/\?/).length > 0);
<del> - text: 你的正则表达式应该匹配<code>"favorite"</code>
<add> - text: "你的正则表达式应该匹配<code>'favorite'</code>。"
<ide> testString: assert(favRegex.test("favorite"));
<del> - text: 你的正则表达式应该匹配<code>"favourite"</code>
<add> - text: "你的正则表达式应该匹配<code>'favourite'</code>。"
<ide> testString: assert(favRegex.test("favourite"));
<del> - text: 你的正则表达式不应该匹配<code>"fav"</code>
<add> - text: "你的正则表达式不应该匹配<code>'fav'</code>。"
<ide> testString: assert(!favRegex.test("fav"));
<ide>
<ide> ```
<ide> tests:
<ide> let favWord = "favorite";
<ide> let favRegex = /change/; // Change this line
<ide> let result = favRegex.test(favWord);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = favRegex.test(favWord);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let favWord = "favorite";
<add>let favRegex = /favou?r/;
<add>let result = favRegex.test(favWord);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters.chinese.md
<add>---
<add>id: 5c3dda8b4d8df89bea71600f
<add>title: Check For Mixed Grouping of Characters
<add>challengeType: 1
<add>forumTopicId: 301339
<add>localeTitle: 检查混合字符组
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>有时候我们想使用正则表达式里的括号 <code>()</code> 来检查字符组。
<add>如果想在字符串找到 <code>Penguin</code> 或 <code>Pumpkin</code>,可以这个正则表达式:<code>/P(engu|umpk)in/g</code>。
<add>然后使用 <code>test()</code> 方法检查 test 字符串里面是否包含字符组。
<add>
<add>```js
<add>let testStr = "Pumpkin";
<add>let testRegex = /P(engu|umpk)in/g;
<add>testRegex.test(testStr);
<add>// Returns true
<add>```
<add>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>完善正则表达式,使其以区分大小写的方式检查 <code>Franklin Roosevelt</code> 或 <code>Eleanor Roosevelt</code> 的名字,并且应该忽略 middle names。
<add>然后完善代码,使创建的正则检查 <code>myString</code>,根据正则是否匹配返回 <code>true</code> 或 <code>false</code>。
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: 正则 <code>myRegex</code> 测试 <code>Franklin D. Roosevelt</code> 应该返回 <code>true</code>。
<add> testString: myRegex.lastIndex = 0; assert(myRegex.test('Franklin D. Roosevelt'));
<add> - text: 正则 <code>myRegex</code> 测试 <code>Eleanor Roosevelt</code> 应该返回 <code>true</code>。
<add> testString: myRegex.lastIndex = 0; assert(myRegex.test('Eleanor Roosevelt'));
<add> - text: 正则 <code>myRegex</code> 测试 <code>Franklin Rosevelt</code> 应该返回 <code>false</code>。
<add> testString: myRegex.lastIndex = 0; assert(!myRegex.test('Franklin Rosevelt'));
<add> - text: 应该使用 <code>.test()</code> 来测试正则。
<add> testString: assert(code.match(/myRegex.test\(\s*myString\s*\)/));
<add> - text: result 应该返回 <code>true</code>。
<add> testString: assert(result === true);
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add><div id='js-seed'>
<add>
<add>```js
<add>let myString = "Eleanor Roosevelt";
<add>let myRegex = /False/; // Change this line
<add>let result = false; // Change this line
<add>// After passing the challenge experiment with myString and see how the grouping works
<add>```
<add>
<add></div>
<add>
<add>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>let myString = "Eleanor Roosevelt";
<add>let myRegex = /(Franklin|Eleanor).*Roosevelt/;
<add>let result = myRegex.test(myString);
<add>```
<add>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.chinese.md
<ide> id: 587d7db4367417b2b2512b92
<ide> title: Extract Matches
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 提取匹配
<add>forumTopicId: 301340
<add>localeTitle: 提取匹配项
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您只是检查字符串中是否存在模式。您还可以使用<code>.match()</code>方法提取您找到的实际匹配项。要使用<code>.match()</code>方法,请将该方法应用于字符串并传入括号内的正则表达式。这是一个例子: <blockquote> “你好,世界!”。匹配(/ Hello /); <br> //返回[“Hello”] <br>让ourStr =“正则表达式”; <br>让ourRegex = / expressions /; <br> ourStr.match(ourRegex); <br> //返回[“表达式”] </blockquote></section>
<add><section id='description'>
<add>到目前为止,只是检查了一个匹配模式是否存在于字符串中。还可以使用<code>.match()</code>方法来提取找到的实际匹配项。
<add>可以使用字符串来调用<code>.match()</code>方法,并在括号内传入正则表达式。以下是一个示例:
<add>
<add>```js
<add>"Hello, World!".match(/Hello/);
<add>// Returns ["Hello"]
<add>let ourStr = "Regular expressions";
<add>let ourRegex = /expressions/;
<add>ourStr.match(ourRegex);
<add>// Returns ["expressions"]
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">应用<code>.match()</code>方法来提取单词<code>coding</code> 。 </section>
<add><section id='instructions'>
<add>利用<code>.match()</code>方法提取单词<code>coding</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>result</code>应该有单词<code>coding</code>
<add> - text: <code>结果</code>应该包含单词<code>coding</code>。
<ide> testString: assert(result.join() === "coding");
<del> - text: 你的regex <code>codingRegex</code>应该搜索<code>coding</code>
<add> - text: 你的正则表达式<code>codingRegex</code>应该搜寻<code>coding</code>。
<ide> testString: assert(codingRegex.source === "coding");
<del> - text: 您应该使用<code>.match()</code>方法。
<add> - text: 你应该使用<code>.match()</code>方法。
<ide> testString: assert(code.match(/\.match\(.*\)/));
<ide>
<ide> ```
<ide> tests:
<ide> let extractStr = "Extract the word 'coding' from this string.";
<ide> let codingRegex = /change/; // Change this line
<ide> let result = extractStr; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = extractStr; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let extractStr = "Extract the word 'coding' from this string.";
<add>let codingRegex = /coding/; // Change this line
<add>let result = extractStr.match(codingRegex); // Change this line
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.chinese.md
<ide> id: 587d7db6367417b2b2512b9b
<ide> title: Find Characters with Lazy Matching
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 查找具有延迟匹配的字符
<add>forumTopicId: 301341
<add>localeTitle: 用惰性匹配来查找字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在正则表达式中, <code>greedy</code>匹配找到符合正则表达式模式的字符串的最长部分,并将其作为匹配返回。替代方案称为<code>lazy</code>匹配,它找到满足正则表达式模式的字符串的最小可能部分。您可以将regex <code>/t[az]*i/</code>应用于字符串<code>"titanic"</code> 。这个正则表达式基本上是一个以<code>t</code>开头的模式,以<code>i</code>结尾,并且在它们之间有一些字母。默认情况下,正则表达式是<code>greedy</code> ,因此匹配将返回<code>["titani"]</code> 。它找到可能适合模式的最大子串。但是,你可以使用<code>?</code>字符将其更改为<code>lazy</code>匹配。 <code>"titanic"</code>与调整后的正则表达式匹配<code>/t[az]*?i/</code> return <code>["ti"]</code> 。 </section>
<add><section id='description'>
<add>在正则表达式中,<code>贪婪</code>匹配会匹配到符合正则表达式匹配模式的字符串的最长可能部分,并将其作为匹配项返回。另一种方案称为<code>懒惰</code>匹配,它会匹配到满足正则表达式的字符串的最小可能部分。
<add>可以将正则表达式<code>/t[a-z]*i/</code>应用于字符串<code>"titanic"</code>。这个正则表达式是一个以<code>t</code>开始,以<code>i</code>结束,并且中间有一些字母的匹配模式。
<add>正则表达式默认是<code>贪婪</code>匹配,因此匹配返回为<code>["titani"]</code>。它会匹配到适合该匹配模式的最大子字符串。
<add>但是,你可以使用<code>?</code>字符来将其变成<code>懒惰</code>匹配。调整后的正则表达式<code>/t[a-z]*?i/</code>匹配字符串<code>"titanic"</code>返回<code>["ti"]</code>。
<add><strong>注意</strong><br>应该避免使用正则表达式解析 HTML,但是可以用正则表达式匹配 HTML 字符串。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复regex <code>/<.*>/</code>以返回HTML标记<code><h1></code>而不是文本<code>"<h1>Winter is coming</h1>"</code> 。记住通配符<code>.</code>在正则表达式中匹配任何字符。 </section>
<add><section id='instructions'>
<add>修复正则表达式<code>/<.*>/</code>,让它返回 HTML 标签<code><h1></code>,而不是文本<code>"<h1>Winter is coming</h1>"</code>。请记得在正则表达式中使用通配符<code>.</code>来匹配任意字符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>result</code>变量应该是一个包含<code><h1></code>的数组
<del> testString: 'assert(result[0] == "<h1>", "The <code>result</code> variable should be an array with <code><h1></code> in it");'
<add> - text: <code>结果</code>变量应该是一个包含<code><h1></code>的数组。
<add> testString: assert(result[0] == '<h1>');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> let text = "<h1>Winter is coming</h1>";
<ide> let myRegex = /<.*>/; // Change this line
<ide> let result = text.match(myRegex);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = text.match(myRegex);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let text = "<h1>Winter is coming</h1>";
<add>let myRegex = /<.*?>/; // Change this line
<add>let result = text.match(myRegex);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.chinese.md
<ide> id: 587d7db4367417b2b2512b93
<ide> title: Find More Than the First Match
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 找到比第一场比赛更多的东西
<add>forumTopicId: 301342
<add>localeTitle: 全局匹配
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您只能提取或搜索一次模式。 <blockquote>让testStr =“重复,重复,重复”; <br>让ourRegex = /重复/; <br> testStr.match(ourRegex); <br> //返回[“重复”] </blockquote>要多次搜索或提取模式,可以使用<code>g</code>标志。 <blockquote> let repeatRegex = / Repeat / g; <br> testStr.match(repeatRegex); <br> //返回[“重复”,“重复”,“重复”] </blockquote></section>
<add><section id='description'>
<add>到目前为止,只能提取或搜寻一次模式匹配。
<add>
<add>```js
<add>let testStr = "Repeat, Repeat, Repeat";
<add>let ourRegex = /Repeat/;
<add>testStr.match(ourRegex);
<add>// Returns ["Repeat"]
<add>```
<add>
<add>若要多次搜寻或提取模式匹配,可以使用<code>g</code>标志。
<add>
<add>```js
<add>let repeatRegex = /Repeat/g;
<add>testStr.match(repeatRegex);
<add>// Returns ["Repeat", "Repeat", "Repeat"]
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用正则表达式<code>starRegex</code> ,找到并提取字符串<code>twinkleStar</code> <code>"Twinkle"</code>单词。 <strong>注意</strong> <br>你可以在你的正则表达式上有多个标志,比如<code>/search/gi</code> </section>
<add><section id='instructions'>
<add>使用正则表达式<code>starRegex</code>,从字符串<code>twinkleStar</code>中匹配到所有的<code>"Twinkle"</code>单词并提取出来。
<add><strong>注意:</strong><br>在正则表达式上可以有多个标志,比如<code>/search/gi</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式<code>starRegex</code>应该使用全局标志<code>g</code>
<add> - text: 你的正则表达式<code>starRegex</code>应该使用全局标志<code>g</code>。
<ide> testString: assert(starRegex.flags.match(/g/).length == 1);
<del> - text: 你的正则表达式<code>starRegex</code>应该使用不区分大小写的标志<code>i</code>
<add> - text: 你的正则表达式<code>starRegex</code>应该使用忽略大小写标志<code>i</code>。
<ide> testString: assert(starRegex.flags.match(/i/).length == 1);
<del> - text: 您的匹配应匹配<code>"Twinkle"</code>一词的出现次数
<add> - text: "你的匹配应该匹配单词<code>'Twinkle'</code>的两个匹配项。"
<ide> testString: assert(result.sort().join() == twinkleStar.match(/twinkle/gi).sort().join());
<del> - text: 您的匹配<code>result</code>应该包含两个元素。
<add> - text: 你的匹配<code>结果</code>应该包含两个元素。
<ide> testString: assert(result.length == 2);
<ide>
<ide> ```
<ide> tests:
<ide> let twinkleStar = "Twinkle, twinkle, little star";
<ide> let starRegex = /change/; // Change this line
<ide> let result = twinkleStar; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = twinkleStar; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let twinkleStar = "Twinkle, twinkle, little star";
<add>let starRegex = /twinkle/gi;
<add>let result = twinkleStar.match(starRegex);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.chinese.md
<ide> id: 587d7db7367417b2b2512b9c
<ide> title: Find One or More Criminals in a Hunt
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301343
<ide> localeTitle: 在狩猎中找到一个或多个罪犯
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">是时候暂停和测试你的新正则表达式写作技巧了。一群罪犯逃出监狱逃跑,但你不知道有多少人。但是,你知道他们和其他人在一起时会保持紧密联系。你有责任立刻找到所有的罪犯。下面是一个查看如何执行此操作的示例:regex <code>/z+/</code>在连续出现一次或多次时匹配字母<code>z</code> 。它会在以下所有字符串中找到匹配项: <blockquote> “Z” <br> “ZZZZZZ” <br> “ABCzzzz” <br> “zzzzABC” <br> “abczzzzzzzzzzzzzzzzzzzzzabc” </blockquote>但它没有在以下字符串中找到匹配项,因为没有字母<code>z</code>字符: <blockquote> “” <br> “ABC” <br> “ABCABC” </blockquote></section>
<add><section id='description'>
<add>是时候暂停和测试你的新正则表达式写作技巧了。一群罪犯逃出监狱逃跑,但你不知道有多少人。但是,你知道他们和其他人在一起时会保持紧密联系。你有责任立刻找到所有的罪犯。
<add>这里有一个示例来回顾如何做到这一点:
<add>当字母<code>z</code>在一行中出现一次或连续多次时,正则表达式<code>/z+/</code>会匹配到它。它会在以下所有字符串中找到匹配项:
<add>
<add>```js
<add>"z"
<add>"zzzzzz"
<add>"ABCzzzz"
<add>"zzzzABC"
<add>"abczzzzzzzzzzzzzzzzzzzzzabc"
<add>```
<add>
<add>但是它不会在以下字符串中找到匹配项,因为它们中没有字母<code>z</code>:
<add>
<add>```js
<add>""
<add>"ABC"
<add>"abcabc"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写一个<code>greedy</code>正则表达式,在一群其他人中找到一个或多个罪犯。罪犯由大写字母<code>C</code> 。 </section>
<add><section id='instructions'>
<add>编写一个<code>贪婪</code>正则表达式,在一组其他人中匹配到一个或多个罪犯。罪犯由大写字母<code>C</code>表示。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您正则表达式应该匹配<code>one</code>犯罪(“ <code>C</code>中”), <code>"C"</code>
<add> - text: "你的正则表达式应该匹配<code>'C'</code>中的 <em>一个</em> 罪犯('<code>C</code>')。"
<ide> testString: assert('C'.match(reCriminals) && 'C'.match(reCriminals)[0] == 'C');
<del> - text: 您正则表达式应该匹配<code>two</code>罪犯(“ <code>CC</code>中”) <code>"CC"</code>
<add> - text: "你的正则表达式应该匹配<code>'CC'</code>中的 <em>两个</em> 罪犯('<code>CC</code>')。"
<ide> testString: assert('CC'.match(reCriminals) && 'CC'.match(reCriminals)[0] == 'CC');
<del> - text: 你的正则表达式应匹配<code>"P1P5P4CCCP2P6P3"</code>中的<code>three</code>罪犯(“ <code>CCC</code> ”)
<add> - text: "你的正则表达式应该匹配<code>'P1P5P4CCCP2P6P3'</code>中的 <em>三个</em> 罪犯('<code>CCC</code>')。"
<ide> testString: assert('P1P5P4CCCP2P6P3'.match(reCriminals) && 'P1P5P4CCCP2P6P3'.match(reCriminals)[0] == 'CCC');
<del> - text: 你的正则表达式应匹配<code>"P6P2P7P4P5CCCCCP3P1"</code>中的<code>five</code>罪犯(“ <code>CCCCC</code> ”)
<add> - text: "你的正则表达式应该匹配<code>'P6P2P7P4P5CCCCCP3P1'</code>中的 <em>五个</em> 罪犯('<code>CCCCC</code>')。"
<ide> testString: assert('P6P2P7P4P5CCCCCP3P1'.match(reCriminals) && 'P6P2P7P4P5CCCCCP3P1'.match(reCriminals)[0] == 'CCCCC');
<del> - text: 你的正则表达式不应该匹配<code>""</code>中的任何罪犯
<add> - text: "你的正则表达式在<code>''</code>中不应该匹配到任何罪犯。"
<ide> testString: assert(!reCriminals.test(''));
<del> - text: 你的正则表达式不应该匹配<code>"P1P2P3"</code>中的任何罪犯
<add> - text: "你的正则表达式在<code>'P1P2P3'</code>中不应该匹配到任何罪犯。"
<ide> testString: assert(!reCriminals.test('P1P2P3'));
<del> - text: 您正则表达式应该与<code>fifty</code>的罪犯(“ <code>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</code>中”) <code>"P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"</code> 。
<add> - text: "你的正则表达式应该匹配<code>'P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'</code>中的 <em>五十个</em> 罪犯('<code>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</code>')。"
<ide> testString: assert('P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'.match(reCriminals) && 'P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3'.match(reCriminals)[0] == "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC");
<ide>
<ide> ```
<ide> let reCriminals = /./; // Change this line
<ide>
<ide> let matchedCriminals = crowd.match(reCriminals);
<ide> console.log(matchedCriminals);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(matchedCriminals);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>// example crowd gathering
<add>let crowd = 'P1P2P3P4P5P6CCCP7P8P9';
<add>
<add>let reCriminals = /C+/; // Change this line
<add>
<add>let matchedCriminals = crowd.match(reCriminals);
<add>
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.chinese.md
<ide> id: 587d7db4367417b2b2512b91
<ide> title: Ignore Case While Matching
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301344
<ide> localeTitle: 匹配时忽略大小写
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,你已经看过正则表达式来进行字符串的字面匹配。但有时,您可能还希望匹配案例差异。大小写(或有时是大写字母大小写)是大写字母和小写字母之间的区别。大写的示例是<code>"A"</code> , <code>"B"</code>和<code>"C"</code> 。小写的示例是<code>"a"</code> , <code>"b"</code>和<code>"c"</code> 。您可以使用所谓的标志来匹配这两种情况。还有其他标志,但在这里你将专注于忽略大小写的标志 - <code>i</code>旗帜。您可以通过将其附加到正则表达式来使用它。使用此标志的示例是<code>/ignorecase/i</code> 。此正则表达式可以匹配字符串<code>"ignorecase"</code> , <code>"igNoreCase"</code>和<code>"IgnoreCase"</code> 。 </section>
<add><section id='description'>
<add>到目前为止,已经了解了如何用正则表达式来执行字符串的匹配。但有时候,并不关注匹配字母的大小写。
<add>大小写即大写字母和小写字母。大写字母如<code>"A"</code>、<code>"B"</code>和<code>"C"</code>。小写字母如<code>"a"</code>、<code>"b"</code>和<code>"c"</code>。
<add>可以使用标志(flag)来匹配这两种情况。标志有很多,不过这里我们只关注忽略大小写的标志——<code>i</code>。可以通过将它附加到正则表达式之后来使用它。这里给出使用该标志的一个实例<code>/ignorecase/i</code>。这个字符串可以匹配字符串<code>"ignorecase"</code>、<code>"igNoreCase"</code>和<code>"IgnoreCase"</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写一个正则表达式<code>fccRegex</code>来匹配<code>"freeCodeCamp"</code> ,无论它的情况如何。您的正则表达式不应与任何缩写或带有空格的变体匹配。 </section>
<add><section id='instructions'>
<add>编写正则表达式<code>fccRegex</code>以匹配<code>"freeCodeCamp"</code>,忽略大小写。正则表达式不应与任何缩写或带有空格的变体匹配。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该与<code>freeCodeCamp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>freeCodeCamp</code>。
<ide> testString: assert(fccRegex.test('freeCodeCamp'));
<del> - text: 你的正则表达式应该与<code>FreeCodeCamp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>FreeCodeCamp</code>。
<ide> testString: assert(fccRegex.test('FreeCodeCamp'));
<del> - text: 你的正则表达式应该与<code>FreecodeCamp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>FreecodeCamp</code>。
<ide> testString: assert(fccRegex.test('FreecodeCamp'));
<del> - text: 你的正则表达式应该与<code>FreeCodecamp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>FreeCodecamp</code>。
<ide> testString: assert(fccRegex.test('FreeCodecamp'));
<del> - text: 你的正则表达式不应该与<code>Free Code Camp</code>不匹配
<add> - text: 你的正则表达式不应该匹配<code>Free Code Camp</code>。
<ide> testString: assert(!fccRegex.test('Free Code Camp'));
<del> - text: 你的正则表达式应该与<code>FreeCOdeCamp</code>匹配
<add> - text: Your regex should match<code>FreeCOdeCamp</code>。
<ide> testString: assert(fccRegex.test('FreeCOdeCamp'));
<del> - text: 你的正则表达式不应该与<code>FCC</code>匹配
<add> - text: 你的正则表达式不应该匹配<code>FCC</code>。
<ide> testString: assert(!fccRegex.test('FCC'));
<del> - text: 你的正则表达式应该与<code>FrEeCoDeCamp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>FrEeCoDeCamp</code>。
<ide> testString: assert(fccRegex.test('FrEeCoDeCamp'));
<del> - text: 你的正则表达式应该与<code>FrEeCodECamp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>FrEeCodECamp</code>。
<ide> testString: assert(fccRegex.test('FrEeCodECamp'));
<del> - text: 你的正则表达式应该与<code>FReeCodeCAmp</code>匹配
<add> - text: 你的正则表达式应该匹配<code>FReeCodeCAmp</code>。
<ide> testString: assert(fccRegex.test('FReeCodeCAmp'));
<ide>
<ide> ```
<ide> tests:
<ide> let myString = "freeCodeCamp";
<ide> let fccRegex = /change/; // Change this line
<ide> let result = fccRegex.test(myString);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = fccRegex.test(myString);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let myString = "freeCodeCamp";
<add>let fccRegex = /freecodecamp/i; // Change this line
<add>let result = fccRegex.test(myString);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.chinese.md
<ide> id: 587d7db4367417b2b2512b90
<ide> title: Match a Literal String with Different Possibilities
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配具有不同可能性的文字字符串
<add>forumTopicId: 301345
<add>localeTitle: 同时用多种模式匹配文字字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用<code>/coding/</code>等正则表达式,可以在另一个字符串中查找<code>"coding"</code>模式。这对搜索单个字符串很有用,但它仅限于一种模式。您可以使用<code>alternation</code>或<code>OR</code>运算符搜索多个模式: <code>|</code> 。此运算符在其之前或之后匹配模式。例如,如果你想匹配<code>"yes"</code>或<code>"no"</code> ,你想要的正则表达式是<code>/yes|no/</code> 。您还可以搜索两种以上的模式。您可以通过添加更多模式来实现此操作,其中更多<code>OR</code>运算符将它们分开,例如<code>/yes|no|maybe/</code> 。 </section>
<add><section id='description'>
<add>使用正则表达式<code>/coding/</code>,你可以在其他字符串中查找<code>"coding"</code>。
<add>这对于搜寻单个字符串非常有用,但仅限于一种匹配模式。你可以使用<code>|</code>操作符来匹配多个规则。
<add>此操作符匹配操作符前面或后面的字符。例如,如果你想匹配<code>"yes"</code>或<code>"no"</code>,你需要的正则表达式是<code>/yes|no/</code>。
<add>你还可以匹配多个规则,这可以通过添加更多的匹配模式来实现。这些匹配模式将包含更多的<code>|</code>操作符来分隔它们,比如<code>/yes|no|maybe/</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">完成正则表达式<code>petRegex</code>以匹配宠物<code>"dog"</code> , <code>"cat"</code> , <code>"bird"</code>或<code>"fish"</code> 。 </section>
<add><section id='instructions'>
<add>完成正则表达式<code>petRegex</code>以匹配<code>"dog"</code>、<code>"cat"</code>、<code>"bird"</code>或者<code>"fish"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式<code>petRegex</code>应该为字符串<code>"John has a pet dog."</code>返回<code>true</code> <code>"John has a pet dog."</code>
<add> - text: "对于字符串<code>'John has a pet dog.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>true</code>。"
<ide> testString: assert(petRegex.test('John has a pet dog.'));
<del> - text: 你的正则表达式<code>petRegex</code>应该为字符串<code>"Emma has a pet rock."</code>返回<code>false</code> <code>"Emma has a pet rock."</code>
<add> - text: "对于字符串<code>'Emma has a pet rock.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>false</code>。"
<ide> testString: assert(!petRegex.test('Emma has a pet rock.'));
<del> - text: 你的正则表达式<code>petRegex</code>应该为字符串<code>"Emma has a pet bird."</code>返回<code>true</code> <code>"Emma has a pet bird."</code>
<add> - text: "对于字符串<code>'Emma has a pet bird.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>true</code>。"
<ide> testString: assert(petRegex.test('Emma has a pet bird.'));
<del> - text: 你的正则表达式<code>petRegex</code>应该返回<code>true</code>为字符串<code>"Liz has a pet cat."</code>
<add> - text: "对于字符串<code>'Liz has a pet cat.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>true</code>。"
<ide> testString: assert(petRegex.test('Liz has a pet cat.'));
<del> - text: 你的正则表达式<code>petRegex</code>应该返回<code>false</code>为<code>"Kara has a pet dolphin."</code>的字符串<code>"Kara has a pet dolphin."</code>
<add> - text: "对于字符串<code>'Kara has a pet dolphin.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>false</code>。"
<ide> testString: assert(!petRegex.test('Kara has a pet dolphin.'));
<del> - text: 你的正则表达式<code>petRegex</code>应该返回<code>true</code>为字符串<code>"Alice has a pet fish."</code>
<add> - text: "对于字符串<code>'Alice has a pet fish.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>true</code>。"
<ide> testString: assert(petRegex.test('Alice has a pet fish.'));
<del> - text: 你的正则表达式<code>petRegex</code>应该返回<code>false</code>为字符串<code>"Jimmy has a pet computer."</code>
<add> - text: "对于字符串<code>'Jimmy has a pet computer.'</code>,你的正则表达式<code>petRegex</code>的<code>test</code>方法应该返回<code>false</code>。"
<ide> testString: assert(!petRegex.test('Jimmy has a pet computer.'));
<ide>
<ide> ```
<ide> tests:
<ide> let petString = "James has a pet cat.";
<ide> let petRegex = /change/; // Change this line
<ide> let result = petRegex.test(petString);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = petRegex.test(petString);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let petString = "James has a pet cat.";
<add>let petRegex = /dog|cat|bird|fish/; // Change this line
<add>let result = petRegex.test(petString);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.chinese.md
<ide> id: 587d7db7367417b2b2512b9f
<ide> title: Match All Letters and Numbers
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配所有字母和数字
<add>forumTopicId: 301346
<add>localeTitle: 匹配所有的字母和数字
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用字符类,您可以使用<code>[az]</code>搜索字母表中的所有字母。这种字符类很常见,它有一个快捷方式,虽然它还包含一些额外的字符。 JavaScript中与字母表匹配的最接近的字符类是<code>\w</code> 。此快捷方式等于<code>[A-Za-z0-9_]</code> 。此字符类匹配大写和小写字母加数字。注意,此字符类还包括下划线字符( <code>_</code> )。 <blockquote>让longHand = / [A-Za-z0-9 _] + /; <br>让shortHand = / \ w + /; <br>让数字=“42”; <br> let varNames =“important_var”; <br> longHand.test(数字); //返回true <br> shortHand.test(数字); //返回true <br> longHand.test(varNames); //返回true <br> shortHand.test(varNames); //返回true </blockquote>这些快捷方式字符类也称为<code>shorthand character classes</code> 。 </section>
<add><section id='description'>
<add>使用元字符,可以使用<code>[a-z]</code>搜寻字母表中的所有字母。这种元字符是很常见的,它有一个缩写,但这个缩写也包含额外的字符。
<add>JavaScript 中与字母表匹配的最接近的元字符是<code>\w</code>,这个缩写等同于<code>[A-Za-z0-9_]</code>。它不仅可以匹配大小写字母和数字,注意,它还会匹配下划线字符(<code>_</code>)。
<add>
<add>```js
<add>let longHand = /[A-Za-z0-9_]+/;
<add>let shortHand = /\w+/;
<add>let numbers = "42";
<add>let varNames = "important_var";
<add>longHand.test(numbers); // Returns true
<add>shortHand.test(numbers); // Returns true
<add>longHand.test(varNames); // Returns true
<add>shortHand.test(varNames); // Returns true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用速记字符类<code>\w</code>来计算各种引号和字符串中的字母数字字符数。 </section>
<add><section id='instructions'>
<add>使用缩写<code>\w</code>来计算所有引号中字母和数字字符的数量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用全局标志。
<add> - text: 你的正则表达式应该使用全局状态修正符。
<ide> testString: assert(alphabetRegexV2.global);
<del> - text: 你的正则表达式应该使用速记字符
<add> - text: 正则表达式应该使用元字符 <code>\w</code> 匹配字母表里的所有字符。
<ide> testString: assert(/\\w/.test(alphabetRegexV2.source));
<del> - text: 你的正则表达式应该在<code>"The five boxing wizards jump quickly."</code>找到31个字母数字字符<code>"The five boxing wizards jump quickly."</code>
<add> - text: "你的正则表达式应该在<code>'The five boxing wizards jump quickly.'</code>中匹配到 31 个字母数字字符。"
<ide> testString: assert("The five boxing wizards jump quickly.".match(alphabetRegexV2).length === 31);
<del> - text: 你的正则表达式应该在<code>"Pack my box with five dozen liquor jugs."</code>找到32个字母数字字符<code>"Pack my box with five dozen liquor jugs."</code>
<add> - text: "你的正则表达式应该在<code>'Pack my box with five dozen liquor jugs.'</code>中匹配到 32 个字母数字字符。"
<ide> testString: assert("Pack my box with five dozen liquor jugs.".match(alphabetRegexV2).length === 32);
<del> - text: 你的正则表达式应该在<code>"How vexingly quick daft zebras jump!"</code>找到30个字母数字字符<code>"How vexingly quick daft zebras jump!"</code>
<add> - text: "你的正则表达式应该在<code>'How vexingly quick daft zebras jump!'</code>中匹配到 30 个字母数字字符。"
<ide> testString: assert("How vexingly quick daft zebras jump!".match(alphabetRegexV2).length === 30);
<del> - text: 你的正则表达式应该在<code>"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."</code>找到36个字母数字字符<code>"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."</code>
<add> - text: "你的正则表达式应该在<code>'123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.'</code>中匹配到 36 个字母数字字符。"
<ide> testString: assert("123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.".match(alphabetRegexV2).length === 36);
<ide>
<ide> ```
<ide> tests:
<ide> let quoteSample = "The five boxing wizards jump quickly.";
<ide> let alphabetRegexV2 = /change/; // Change this line
<ide> let result = quoteSample.match(alphabetRegexV2).length;
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = quoteSample.match(alphabetRegexV2).length;
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let quoteSample = "The five boxing wizards jump quickly.";
<add>let alphabetRegexV2 = /\w/g; // Change this line
<add>let result = quoteSample.match(alphabetRegexV2).length;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.chinese.md
<ide> id: 587d7db8367417b2b2512ba1
<ide> title: Match All Non-Numbers
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301347
<ide> localeTitle: 匹配所有非数字
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一项挑战显示了如何使用带有小写<code>d</code>的快捷键<code>\d</code>来搜索数字。您也可以使用类似的使用大写<code>D</code>快捷方式搜索非数字。查找非数字字符的快捷方式是<code>\D</code>这等于字符类<code>[^0-9]</code> ,它查找不是0到9之间的数字的单个字符。 </section>
<add><section id='description'>
<add>上一项挑战中展示了如何使用带有小写<code>d</code>的缩写<code>\d</code>来搜寻数字。也可以使用类似的缩写来搜寻非数字,该缩写使用大写的<code>D</code>。
<add>查找非数字字符的缩写是<code>\D</code>。这等同于字符串<code>[^0-9]</code>,它查找不是 0 - 9 之间数字的单个字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用非数字<code>\D</code>的速记字符类来计算电影标题中有多少个非数字。 </section>
<add><section id='instructions'>
<add>使用非数字缩写<code>\D</code>来计算电影标题中有多少非数字。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的正则表达式应使用快捷方式字符来匹配非数字字符
<add> - text: 你的正则表达式应该使用缩写来匹配非数字字符。
<ide> testString: assert(/\\D/.test(noNumRegex.source));
<del> - text: 你的正则表达式应该使用全局标志。
<add> - text: 你的正则表达式应该使用全局状态修正符。
<ide> testString: assert(noNumRegex.global);
<del> - text: 你的正则表达式应该在<code>"9"</code>找不到非数字。
<add> - text: "你的正则表达式在<code>'9'</code>中应该匹配不到非数字。"
<ide> testString: assert("9".match(noNumRegex) == null);
<del> - text: 你的正则表达式应该在<code>"Catch 22"</code>找到6个非数字。
<add> - text: "你的正则表达式应该在<code>'Catch 22'</code>中匹配到 6 个非数字。"
<ide> testString: assert("Catch 22".match(noNumRegex).length == 6);
<del> - text: 你的正则表达式应该在<code>"101 Dalmatians"</code>找到11个非数字。
<add> - text: "你的正则表达式应该在<code>'101 Dalmatians'</code>中匹配到 11 个非数字。"
<ide> testString: assert("101 Dalmatians".match(noNumRegex).length == 11);
<del> - text: '你的正则表达式应该在<code>"One, Two, Three"</code>找到15个非数字。'
<add> - text: "你的正则表达式应该在<code>'One, Two, Three'</code>中匹配到 15 个非数字。"
<ide> testString: assert("One, Two, Three".match(noNumRegex).length == 15);
<del> - text: 你的正则表达式应该在<code>"21 Jump Street"</code>找到12个非数字。
<add> - text: "你的正则表达式应该在<code>'21 Jump Street'</code>中匹配到 12 个非数字。"
<ide> testString: assert("21 Jump Street".match(noNumRegex).length == 12);
<del> - text: '你的正则表达式应该在<code>"2001: A Space Odyssey"</code>找到17个非数字。'
<add> - text: '你的正则表达式应该在<code>"2001: A Space Odyssey"</code>中匹配到 17 个非数字。'
<ide> testString: 'assert("2001: A Space Odyssey".match(noNumRegex).length == 17);'
<ide>
<ide> ```
<ide> tests:
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>let numString = "Your sandwich will be $5.00";
<add>let movieName = "2001: A Space Odyssey";
<ide> let noNumRegex = /change/; // Change this line
<del>let result = numString.match(noNumRegex).length;
<del>
<add>let result = movieName.match(noNumRegex).length;
<ide> ```
<ide>
<ide> </div>
<ide> let result = numString.match(noNumRegex).length;
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let movieName = "2001: A Space Odyssey";
<add>let noNumRegex = /\D/g; // Change this line
<add>let result = movieName.match(noNumRegex).length;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.chinese.md
<ide> id: 5d712346c441eddfaeb5bdef
<ide> title: Match All Numbers
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配所有号码
<add>forumTopicId: 18181
<add>localeTitle: 匹配所有数字
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您已经学习了常用字符串模式(如字母数字)的快捷方式。另一种常见模式是寻找数字或数字。查找数字字符的快捷方式是<code>\d</code> ,小写<code>d</code> 。这等于字符类<code>[0-9]</code> ,它查找0到9之间任意数字的单个字符。 </section>
<add><section id='description'>
<add>已经了解了常见字符串匹配模式的元字符,如字母数字。另一个常见的匹配模式是只寻找数字。
<add>查找数字字符的缩写是<code>\d</code>,注意是小写的<code>d</code>。这等同于元字符<code>[0-9]</code>,它查找 0 到 9 之间任意数字的单个字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用速记字符类<code>\d</code>来计算电影标题中的位数。写出的数字(“六”而不是六)不计算在内。 </section>
<add><section id='instructions'>
<add>使用缩写<code>\d</code>来计算电影标题中有多少个数字。书面数字("six" 而不是 6)不计算在内。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的正则表达式应使用快捷方式字符来匹配数字字符
<add> - text: 你的正则表达式应该使用缩写来匹配数字字符。
<ide> testString: assert(/\\d/.test(numRegex.source));
<del> - text: 你的正则表达式应该使用全局标志。
<add> - text: 你的正则表达式应该使用全局状态修正符。
<ide> testString: assert(numRegex.global);
<del> - text: 你的正则表达式应该在<code>"9"</code>找到1位数。
<add> - text: "你的正则表达式应该在<code>'9'</code>中匹配到 1 个数字。"
<ide> testString: assert("9".match(numRegex).length == 1);
<del> - text: 你的正则表达式应该在<code>"Catch 22"</code>找到2位数字。
<add> - text: "你的正则表达式应该在<code>'Catch 22'</code>中匹配到 2 个数字。"
<ide> testString: assert("Catch 22".match(numRegex).length == 2);
<del> - text: 你的正则表达式应该在<code>"101 Dalmatians"</code>找到3位数字。
<add> - text: "你的正则表达式应该在<code>'101 Dalmatians'</code>中匹配到 3 个数字。"
<ide> testString: assert("101 Dalmatians".match(numRegex).length == 3);
<del> - text: '你的正则表达式应该在<code>"One, Two, Three"</code>找不到数字。'
<add> - text: "你的正则表达式在<code>'One, Two, Three'</code>中应该匹配不到数字。"
<ide> testString: assert("One, Two, Three".match(numRegex) == null);
<del> - text: 您的正则表达式应该在<code>"21 Jump Street"</code>找到2位数字。
<add> - text: "你的正则表达式应该在<code>'21 Jump Street'</code>中匹配到 2 个数字。"
<ide> testString: assert("21 Jump Street".match(numRegex).length == 2);
<del> - text: '你的正则表达式应该在<code>"2001: A Space Odyssey"</code>找到4位数字。'
<add> - text: '你的正则表达式应该在<code>"2001: A Space Odyssey"</code>中匹配到 4 个数字。'
<ide> testString: 'assert("2001: A Space Odyssey".match(numRegex).length == 4);'
<ide>
<ide> ```
<ide> tests:
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>let numString = "Your sandwich will be $5.00";
<add>let movieName = "2001: A Space Odyssey";
<ide> let numRegex = /change/; // Change this line
<del>let result = numString.match(numRegex).length;
<del>
<add>let result = movieName.match(numRegex).length;
<ide> ```
<ide>
<ide> </div>
<ide> let result = numString.match(numRegex).length;
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let movieName = "2001: A Space Odyssey";
<add>let numRegex = /\d/g; // Change this line
<add>let result = movieName.match(numRegex).length;
<add>
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.chinese.md
<ide> id: 587d7db5367417b2b2512b94
<ide> title: Match Anything with Wildcard Period
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配通配符期间的任何内容
<add>forumTopicId: 301348
<add>localeTitle: 用通配符.匹配任何内容
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时您不会(或不需要)知道模式中的确切字符。想到所有匹配的单词,比如拼写错误需要很长时间。幸运的是,您可以使用通配符来节省时间: <code>.</code>通配符<code>.</code>将匹配任何一个字符。通配符也称为<code>dot</code>和<code>period</code> 。您可以像使用正则表达式中的任何其他字符一样使用通配符。例如,如果你想匹配<code>"hug"</code> , <code>"huh"</code> , <code>"hut"</code>和<code>"hum"</code> ,你可以使用正则表达式<code>/hu./</code>来匹配所有四个单词。 <blockquote>让humStr =“我会哼唱一首歌”; <br>让hugStr =“熊抱”; <br>让huRegex = /hu./; <br> humStr.match(huRegex); //返回[“hum”] <br> hugStr.match(huRegex); //返回[“拥抱”] </blockquote></section>
<add><section id='description'>
<add>有时不(或不需要)知道匹配模式中的确切字符。如果要精确匹配到完整的单词,那出现一个拼写错误就会匹配不到。幸运的是,可以使用通配符<code>.</code>来处理这种情况。
<add>通配符<code>.</code>将匹配任何一个字符。通配符也叫<code>dot</code>或<code>period</code>。可以像使用正则表达式中任何其他字符一样使用通配符。例如,如果想匹配<code>"hug"</code>、<code>"huh"</code>、<code>"hut"</code>和<code>"hum"</code>,可以使用正则表达式<code>/hu./</code>匹配以上四个单词。
<add>
<add>```js
<add>let humStr = "I'll hum a song";
<add>let hugStr = "Bear hug";
<add>let huRegex = /hu./;
<add>huRegex.test(humStr); // Returns true
<add>huRegex.test(hugStr); // Returns true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">完成正则表达式<code>unRegex</code> ,使其匹配字符串<code>"run"</code> , <code>"sun"</code> , <code>"fun"</code> , <code>"pun"</code> , <code>"nun"</code>和<code>"bun"</code> 。你的正则表达式应该使用通配符。 </section>
<add><section id='instructions'>
<add>完成正则表达式<code>unRegex</code>以匹配字符串<code>"run"</code>、<code>"sun"</code>、<code>"fun"</code>、<code>"pun"</code>、<code>"nun"</code>和<code>"bun"</code>。正则表达式中应该使用通配符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您应该使用<code>.test()</code>方法。
<add> - text: 你应该使用<code>.test()</code>方法。
<ide> testString: assert(code.match(/\.test\(.*\)/));
<del> - text: 您应该在正则表达式<code>unRegex</code>使用通配符
<add> - text: 你应该在你的正则表达式<code>unRegex</code>中使用通配符。
<ide> testString: assert(/\./.test(unRegex.source));
<del> - text: 你的正则表达式<code>unRegex</code>应该匹配<code>"run"</code> <code>"Let us go on a run."</code> <code>"run"</code>中的<code>"run"</code> <code>"Let us go on a run."</code>
<add> - text: "你的正则表达式<code>unRegex</code>应该在字符串<code>'Let us go on a run.'</code>中匹配到<code>'run'</code>单词。"
<ide> testString: assert(unRegex.test("Let us go on a run."));
<del> - text: 你的正则表达式<code>unRegex</code>应该与<code>"sun"</code> <code>"The sun is out today."</code> <code>"sun"</code>中的<code>"sun"</code>匹配<code>"The sun is out today."</code>
<add> - text: "你的正则表达式<code>unRegex</code>应该在字符串<code>'The sun is out today.'</code>中匹配到<code>'sun'</code>单词。"
<ide> testString: assert(unRegex.test("The sun is out today."));
<del> - text: 你的正则表达式<code>unRegex</code>应该与<code>"fun"</code> <code>"Coding is a lot of fun."</code> <code>"fun"</code>中的<code>"fun"</code>匹配<code>"Coding is a lot of fun."</code>
<add> - text: "你的正则表达式<code>unRegex</code>应该在字符串<code>'Coding is a lot of fun.'</code>中匹配到<code>'fun'</code>单词。"
<ide> testString: assert(unRegex.test("Coding is a lot of fun."));
<del> - text: 你的正则表达式<code>unRegex</code>应该匹配<code>"pun"</code> <code>"Seven days without a pun makes one weak."</code> <code>"pun"</code> <code>"Seven days without a pun makes one weak."</code>
<add> - text: "你的正则表达式<code>unRegex</code>应该在字符串<code>'Seven days without a pun makes one weak.'</code>中匹配到<code>'pun'</code>单词。"
<ide> testString: assert(unRegex.test("Seven days without a pun makes one weak."));
<del> - text: 你的正则表达式<code>unRegex</code>应该与<code>"nun"</code> <code>"One takes a vow to be a nun."</code> <code>"nun"</code>中的<code>"nun"</code>匹配<code>"One takes a vow to be a nun."</code>
<add> - text: "你的正则表达式<code>unRegex</code>应该在字符串<code>'One takes a vow to be a nun.'</code>中匹配到<code>'nun'</code>单词。"
<ide> testString: assert(unRegex.test("One takes a vow to be a nun."));
<del> - text: 你的正则表达式<code>unRegex</code>应该匹配<code>"bun"</code> <code>"She got fired from the hot dog stand for putting her hair in a bun."</code> <code>"bun"</code>中的<code>"bun"</code> <code>"She got fired from the hot dog stand for putting her hair in a bun."</code>
<add> - text: "你的正则表达式<code>unRegex</code>应该在字符串<code>'She got fired from the hot dog stand for putting her hair in a bun.'</code>中匹配到<code>'bun'</code>单词。"
<ide> testString: assert(unRegex.test("She got fired from the hot dog stand for putting her hair in a bun."));
<del> - text: 您的正则表达式<code>unRegex</code>不应与<code>"There is a bug in my code."</code>匹配<code>"There is a bug in my code."</code>
<add> - text: "你的正则表达式<code>unRegex</code>不应该匹配<code>'There is a bug in my code.'</code>。"
<ide> testString: assert(!unRegex.test("There is a bug in my code."));
<del> - text: 您的正则表达式<code>unRegex</code>不应该匹配<code>"Catch me if you can."</code>
<add> - text: "你的正则表达式<code>unRegex</code>不应该匹配<code>'Catch me if you can.'</code>。"
<ide> testString: assert(!unRegex.test("Can me if you can."));
<ide>
<ide> ```
<ide> tests:
<ide> let exampleStr = "Let's have fun with regular expressions!";
<ide> let unRegex = /change/; // Change this line
<ide> let result = unRegex.test(exampleStr);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = unRegex.test(exampleStr);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let exampleStr = "Let's have fun with regular expressions!";
<add>let unRegex = /.un/; // Change this line
<add>let result = unRegex.test(exampleStr);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.chinese.md
<ide> id: 587d7db7367417b2b2512b9d
<ide> title: Match Beginning String Patterns
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配开始字符串模式
<add>forumTopicId: 301349
<add>localeTitle: 匹配字符串的开头
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">先前的挑战表明,正则表达式可用于寻找许多匹配。它们还用于搜索字符串中特定位置的模式。在之前的挑战中,您使用<code>character set</code>内的<code>caret</code>符( <code>^</code> )来创建<code>[^thingsThatWillNotBeMatched]</code>形式的<code>negated character set</code> 。在<code>character set</code> , <code>caret</code>用于在字符串的开头搜索模式。 <blockquote>让firstString =“Ricky是第一个,可以找到。”; <br>让firstRegex = / ^ Ricky /; <br> firstRegex.test(firstString); <br> //返回true <br>让notFirst =“你现在找不到Ricky了。”; <br> firstRegex.test(notFirst); <br> //返回false </blockquote></section>
<add><section id='description'>
<add>回顾一下之前的挑战,正则表达式可以用于查找多项匹配。还可以查询字符串中符合指定匹配模式的字符。
<add>在之前的挑战中,使用<code>字符集</code>中的<code>插入</code>符号(<code>^</code>)来创建一个<code>否定字符集</code>,形如<code>[^thingsThatWillNotBeMatched]</code>。在<code>字符集</code>之外,<code>插入</code>符号用于字符串的开头搜寻匹配模式。
<add>
<add>```js
<add>let firstString = "Ricky is first and can be found.";
<add>let firstRegex = /^Ricky/;
<add>firstRegex.test(firstString);
<add>// Returns true
<add>let notFirst = "You can't find Ricky now.";
<add>firstRegex.test(notFirst);
<add>// Returns false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用正则表达式中的<code>caret</code>只能在字符串<code>rickyAndCal</code>的开头找到<code>"Cal"</code> 。 </section>
<add><section id='instructions'>
<add>在正则表达式中使用<code>^</code>符号,以匹配仅在字符串<code>rickyAndCal</code>的开头出现的<code>"Cal"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该用大写字母搜索<code>"Cal"</code> 。
<add> - text: "你的正则表达式应该搜寻有一个大写字母的<code>'Cal'</code>。"
<ide> testString: assert(calRegex.source == "^Cal");
<ide> - text: 你的正则表达式不应该使用任何标志。
<ide> testString: assert(calRegex.flags == "");
<del> - text: 你的正则表达式应该匹配字符串开头的<code>"Cal"</code> 。
<add> - text: "你的正则表达式应该匹配字符串开头的<code>'Cal'</code>。"
<ide> testString: assert(calRegex.test("Cal and Ricky both like racing."));
<del> - text: 您的正则表达式不应与字符串中间的<code>"Cal"</code>匹配。
<add> - text: "你的正则表达式不应该匹配字符串中间的<code>'Cal'</code>。"
<ide> testString: assert(!calRegex.test("Ricky and Cal both like racing."));
<ide>
<ide> ```
<ide> tests:
<ide> let rickyAndCal = "Cal and Ricky both like racing.";
<ide> let calRegex = /change/; // Change this line
<ide> let result = calRegex.test(rickyAndCal);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = calRegex.test(rickyAndCal);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let rickyAndCal = "Cal and Ricky both like racing.";
<add>let calRegex = /^Cal/; // Change this line
<add>let result = calRegex.test(rickyAndCal);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.chinese.md
<ide> id: 587d7db6367417b2b2512b99
<ide> title: Match Characters that Occur One or More Times
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301350
<ide> localeTitle: 匹配出现一次或多次的字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时,您需要匹配连续出现一次或多次的字符(或字符组)。这意味着它至少发生一次,并且可以重复。您可以使用<code>+</code>字符来检查是否是这种情况。请记住,角色或模式必须连续出现。也就是说,角色必须一个接一个地重复。例如, <code>/a+/g</code>会在<code>"abc"</code>找到一个匹配并返回<code>["a"]</code> 。由于<code>+</code> ,它也会在<code>"aabc"</code>找到一个匹配并返回<code>["aa"]</code> 。如果它是检查字符串<code>"abab"</code> ,它会找到两个匹配并返回<code>["a", "a"]</code>因为<code>a</code>字符不在一行 - 它们之间有一个<code>b</code> 。最后,由于字符串<code>"bcd"</code>没有<code>"a"</code> <code>"bcd"</code> ,因此找不到匹配项。 </section>
<add><section id='description'>
<add>有时,需要匹配出现一次或者连续多次的的字符(或字符组)。这意味着它至少出现一次,并且可能重复出现。
<add>可以使用<code>+</code>符号来检查情况是否如此。记住,字符或匹配模式必须一个接一个地连续出现。
<add>例如,<code>/a+/g</code>会在<code>"abc"</code>中匹配到一个匹配项,并且返回<code>["a"]</code>。因为<code>+</code>的存在,它也会在<code>"aabc"</code>中匹配到一个匹配项,然后返回<code>["aa"]</code>。
<add>如果它是检查字符串<code>"abab"</code>,它将匹配到两个匹配项并且返回<code>["a", "a"]</code>,因为<code>a</code>字符不连续,在它们之间有一个<code>b</code>字符。最后,因为在字符串<code>"bcd"</code>中没有<code>"a"</code>,因此找不到匹配项。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">您希望在<code>"Mississippi"</code>字母<code>s</code>出现一次或多次时找到匹配项。写一个使用<code>+</code>符号的正则表达式。 </section>
<add><section id='instructions'>
<add>想要在字符串<code>"Mississippi"</code>中匹配到出现一次或多次的字母<code>s</code>的匹配项。编写一个使用<code>+</code>符号的正则表达式。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 匹配出现一次或多次的字符
<ide> tests:
<ide> - text: 你的正则表达式<code>myRegex</code>应该使用<code>+</code>符号来匹配一个或多个<code>s</code>字符。
<ide> testString: assert(/\+/.test(myRegex.source));
<del> - text: 你的正则表达式<code>myRegex</code>应该匹配2个项目。
<add> - text: 你的正则表达式<code>myRegex</code>应该匹配两项。
<ide> testString: assert(result.length == 2);
<del> - text: <code>result</code>变量应该是一个包含两个匹配<code>"ss"</code>的数组
<add> - text: "<code>结果</code>变量应该是一个包含两个<code>'ss'</code>匹配项的数组。"
<ide> testString: assert(result[0] == 'ss' && result[1] == 'ss');
<ide>
<ide> ```
<ide> tests:
<ide> let difficultSpelling = "Mississippi";
<ide> let myRegex = /change/; // Change this line
<ide> let result = difficultSpelling.match(myRegex);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = difficultSpelling.match(myRegex);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let difficultSpelling = "Mississippi";
<add>let myRegex = /s+/g; // Change this line
<add>let result = difficultSpelling.match(myRegex);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.chinese.md
<ide> id: 587d7db6367417b2b2512b9a
<ide> title: Match Characters that Occur Zero or More Times
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301351
<ide> localeTitle: 匹配出现零次或多次的字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一项挑战使用加<code>+</code>号来查找出现一次或多次的字符。还有一个选项可以匹配出现零次或多次的字符。执行此操作的字符是<code>asterisk</code>或<code>star</code> <code>asterisk</code> : <code>*</code> 。 <blockquote>让soccerWord =“gooooooooal!”; <br>让gPhrase =“直觉”; <br>让oPhrase =“越过月亮”; <br> let goRegex = / go * /; <br> soccerWord.match(goRegex); //返回[“goooooooo”] <br> gPhrase.match(goRegex); //返回[“g”] <br> oPhrase.match(goRegex); //返回null </blockquote></section>
<add><section id='description'>
<add>上一次的挑战中使用了加号<code>+</code>来查找出现一次或多次的字符。还有一个选项可以匹配出现零次或多次的字符。
<add>执行该操作的字符叫做<code>asterisk</code>或<code>star</code>,即<code>*</code>。
<add>
<add>```js
<add>let soccerWord = "gooooooooal!";
<add>let gPhrase = "gut feeling";
<add>let oPhrase = "over the moon";
<add>let goRegex = /go*/;
<add>soccerWord.match(goRegex); // Returns ["goooooooo"]
<add>gPhrase.match(goRegex); // Returns ["g"]
<add>oPhrase.match(goRegex); // Returns null
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个正则表达式<code>chewieRegex</code>使用的<code>*</code>字符匹配所有上下<code>"a"</code>中的字符<code>chewieQuote</code> 。你的正则表达式不需要标志,它不应该与任何其他引号相匹配。 </section>
<add><section id='instructions'>
<add>在这个挑战里,<code>chewieQuote</code> 已经被初始化为 "Aaaaaaaaaaaaaaaarrrgh!"。创建一个变量为<code>chewieRegex</code>的正则表达式,使用<code>*</code>符号在<code>chewieQuote</code>中匹配<code>"A"</code>及其之后出现的零个或多个<code>"a"</code>。你的正则表达式不需要使用修饰符,也不需要匹配引号。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您正则表达式<code>chewieRegex</code>应该使用<code>*</code>字符匹配零个或多个<code>a</code>字符。
<add> - text: "你的正则表达式<code>chewieRegex</code>应该使用<code>*</code>符号匹配<code>'A'</code>之后出现的零个或多个<code>'a'</code>字符。"
<ide> testString: assert(/\*/.test(chewieRegex.source));
<del> - text: 你的正则表达式<code>chewieRegex</code>应匹配16个字符。
<add> - text: 正则表达式应当匹配 <code>chewieQuote</code> 里的 <code>"A"</code>。
<add> testString: assert(result[0][0] === 'A');
<add> - text: "你的正则表达式应该匹配<code>'Aaaaaaaaaaaaaaaa'</code>。"
<add> testString: assert(result[0] === 'Aaaaaaaaaaaaaaaa');
<add> - text: 你的正则表达式<code>chewieRegex</code>应该匹配 16 个字符。
<ide> testString: assert(result[0].length === 16);
<del> - text: 你的正则表达式应该匹配<code>"Aaaaaaaaaaaaaaaa"</code> 。
<del> testString: assert(result[0] === "Aaaaaaaaaaaaaaaa");
<del> - text: '你的正则表达式不应该与<code>"He made a fair move. Screaming about it can't help you."</code>中的任何角色相匹配<code>"He made a fair move. Screaming about it can't help you."</code>'
<del> testString: assert(!"He made a fair move. Screaming about it can\"t help you.".match(chewieRegex));
<del> - text: '你的正则表达式不应该与<code>"Let him have it. It's not wise to upset a Wookiee."</code>中的任何角色相匹配<code>"Let him have it. It's not wise to upset a Wookiee."</code>'
<del> testString: assert(!"Let him have it. It\"s not wise to upset a Wookiee.".match(chewieRegex));
<add> - text: "你的正则表达式在<code>'He made a fair move. Screaming about it can't help you.'</code>中不应该匹配任何字符。"
<add> testString: assert(!"He made a fair move. Screaming about it can't help you.".match(chewieRegex));
<add> - text: "你的正则表达式在<code>'Let him have it. It's not wise to upset a Wookiee.'</code>中不应该匹配任何字符。"
<add> testString: assert(!"Let him have it. It's not wise to upset a Wookiee.".match(chewieRegex));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!";
<del>let chewieRegex = /change/; // Change this line
<add>let chewieRegex = /change/; // Only change this line
<ide> let result = chewieQuote.match(chewieRegex);
<del>
<ide> ```
<ide>
<ide> </div>
<ide>
<add>## Before Test
<add><div id='js-setup'>
<add>
<add>```js
<add>const chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!";
<add>```
<ide>
<add></div>
<ide>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add> let chewieRegex = /Aa*/;
<add> let result = chewieQuote.match(chewieRegex);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.chinese.md
<ide> id: 587d7db7367417b2b2512b9e
<ide> title: Match Ending String Patterns
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配结束字符串模式
<add>forumTopicId: 301352
<add>localeTitle: 匹配字符串的末尾
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在上一个挑战中,您学会了使用<code>caret</code>来搜索字符串开头的模式。还有一种方法可以在字符串末尾搜索模式。您可以使用正则表达式末尾的<code>dollar sign</code>字符<code>$</code>来搜索字符串的结尾。 <blockquote>让theEnding =“这是一个永无止境的故事”; <br>让storyRegex = / story $ /; <br> storyRegex.test(theEnding); <br> //返回true <br>让noEnding =“有时故事必须结束”; <br> storyRegex.test(noEnding); <br> //返回false <br></blockquote></section>
<add><section id='description'>
<add>在上一个挑战中,学习了使用<code>^</code>符号来搜寻字符串开头的匹配模式。还有一种方法可以搜寻字符串末尾的匹配模式。
<add>可以使用正则表达式的<code>美元</code>符号<code>$</code>来搜寻字符串的结尾。
<add>
<add>```js
<add>let theEnding = "This is a never ending story";
<add>let storyRegex = /story$/;
<add>storyRegex.test(theEnding);
<add>// Returns true
<add>let noEnding = "Sometimes a story will have to end";
<add>storyRegex.test(noEnding);
<add>// Returns false
<add>
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用锚字符( <code>$</code> )来匹配字符串<code>"caboose"</code>在字符串的结尾<code>caboose</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>$</code>在字符串<code>caboose</code>的末尾匹配<code>"caboose"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您应该在正则表达式中使用美元符号<code>$</code> anchor搜索<code>"caboose"</code> 。
<add> - text: "你应该在正则表达式使用美元符号<code>$</code>来搜寻<code>'caboose'</code>。"
<ide> testString: assert(lastRegex.source == "caboose$");
<ide> - text: 你的正则表达式不应该使用任何标志。
<ide> testString: assert(lastRegex.flags == "");
<del> - text: 您应该在字符串末尾匹配<code>"caboose"</code> <code>"The last car on a train is the caboose"</code>
<add> - text: "你应该在字符串<code>'The last car on a train is the caboose'</code>的末尾匹配<code>'caboose'</code>。"
<ide> testString: assert(lastRegex.test("The last car on a train is the caboose"));
<ide>
<ide> ```
<ide> tests:
<ide> let caboose = "The last car on a train is the caboose";
<ide> let lastRegex = /change/; // Change this line
<ide> let result = lastRegex.test(caboose);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = lastRegex.test(caboose);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let caboose = "The last car on a train is the caboose";
<add>let lastRegex = /caboose$/; // Change this line
<add>let result = lastRegex.test(caboose);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.chinese.md
<ide> id: 587d7db8367417b2b2512ba0
<ide> title: Match Everything But Letters and Numbers
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配一切,但字母和数字
<add>forumTopicId: 301353
<add>localeTitle: 匹配除了字母和数字的所有符号
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您已经了解到可以使用快捷键来匹配使用<code>\w</code>字母数字<code>[A-Za-z0-9_]</code> 。您可能想要搜索的自然模式与字母数字相反。您可以使用<code>\W</code>搜索<code>\w</code>的反面。注意,相反的模式使用大写字母。此快捷方式与<code>[^A-Za-z0-9_]</code> 。 <blockquote>让shortHand = / \ W /; <br>让数字=“42%”; <br> let sentence =“Coding!”; <br> numbers.match(简写); //返回[“%”] <br> sentence.match(简写); //返回[“!”] <br></blockquote></section>
<add><section id='description'>
<add>已经了解到可以使用缩写<code>\w</code>来匹配字母和数字<code>[A-Za-z0-9_]</code>。不过,有可能想要搜寻的匹配模式是非字母数字字符。
<add>可以使用<code>\W</code>搜寻和<code>\w</code>相反的匹配模式。注意,相反匹配模式使用大写字母。此缩写与<code>[^A-Za-z0-9_]</code>是一样的。
<add>
<add>```js
<add>let shortHand = /\W/;
<add>let numbers = "42%";
<add>let sentence = "Coding!";
<add>numbers.match(shortHand); // Returns ["%"]
<add>sentence.match(shortHand); // Returns ["!"]
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用速记字符类<code>\W</code>来计算各种引号和字符串中的非字母数字字符数。 </section>
<add><section id='instructions'>
<add>使用缩写<code>\W</code>来计算不同引号和字符串中非字母数字字符的数量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用全局标志。
<add> - text: 你的正则表达式应该使用全局状态修正符。
<ide> testString: assert(nonAlphabetRegex.global);
<del> - text: 你的正则表达式应该在<code>"The five boxing wizards jump quickly."</code>找到6个非字母数字字符<code>"The five boxing wizards jump quickly."</code> 。
<add> - text: "你的正则表达式应该在<code>'The five boxing wizards jump quickly.'</code>中匹配到 6 个非字母数字字符。"
<ide> testString: assert("The five boxing wizards jump quickly.".match(nonAlphabetRegex).length == 6);
<del> - text: 你的正则表达式应该使用速记字符。
<add> - text: 正则表达式应该使用元字符来匹配非字母字符。
<ide> testString: assert(/\\W/.test(nonAlphabetRegex.source));
<del> - text: 你的正则表达式应该在<code>"Pack my box with five dozen liquor jugs."</code>找到8个非字母数字字符<code>"Pack my box with five dozen liquor jugs."</code>
<add> - text: "你的正则表达式应该在<code>'Pack my box with five dozen liquor jugs.'</code>中匹配到 8 个非字母数字字符。"
<ide> testString: assert("Pack my box with five dozen liquor jugs.".match(nonAlphabetRegex).length == 8);
<del> - text: 你的正则表达式应该在<code>"How vexingly quick daft zebras jump!"</code>找到6个非字母数字字符<code>"How vexingly quick daft zebras jump!"</code>
<add> - text: "你的正则表达式应该在<code>'How vexingly quick daft zebras jump!'</code>中匹配到 6 个非字母数字字符。"
<ide> testString: assert("How vexingly quick daft zebras jump!".match(nonAlphabetRegex).length == 6);
<del> - text: 你的正则表达式应该在<code>"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."</code>找到12个非字母数字字符<code>"123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."</code>
<add> - text: "你的正则表达式应该在<code>'123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.'</code>中匹配到 12 个非字母数字字符。"
<ide> testString: assert("123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.".match(nonAlphabetRegex).length == 12);
<ide>
<ide> ```
<ide> tests:
<ide> let quoteSample = "The five boxing wizards jump quickly.";
<ide> let nonAlphabetRegex = /change/; // Change this line
<ide> let result = quoteSample.match(nonAlphabetRegex).length;
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = quoteSample.match(nonAlphabetRegex).length;
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let quoteSample = "The five boxing wizards_jump quickly.";
<add>let nonAlphabetRegex = /\W/g; // Change this line
<add>let result = quoteSample.match(nonAlphabetRegex).length;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.chinese.md
<ide> id: 587d7db5367417b2b2512b96
<ide> title: Match Letters of the Alphabet
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配字母的字母
<add>forumTopicId: 301354
<add>localeTitle: 匹配字母表中的字母
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您了解了如何使用<code>character sets</code>来指定要匹配的一组字符,但是当您需要匹配大范围的字符(例如,字母表中的每个字母)时,这是很多类型。幸运的是,有一个内置功能,使这简短。在<code>character set</code> ,您可以使用<code>hyphen</code>字符来定义要匹配的<code>hyphen</code>范围: <code>-</code> 。例如,要匹配小写字母<code>a</code>到<code>e</code>您将使用<code>[ae]</code> 。 <blockquote>让catStr =“猫”; <br>让batStr =“蝙蝠”; <br>让matStr =“mat”; <br>让bgRegex = / [ae] at /; <br> catStr.match(bgRegex); //返回[“cat”] <br> batStr.match(bgRegex); //返回[“bat”] <br> matStr.match(bgRegex); //返回null </blockquote></section>
<add><section id='description'>
<add>了解了如何使用<code>字符集</code>来指定要匹配的一组字符串,但是当需要匹配大量字符(例如,字母表中的每个字母)时,有一种写法可以让实现这个功能变得简短。
<add>在<code>字符集</code>中,可以使用<code>连字符</code>(<code>-</code>)来定义要匹配的字符范围。
<add>例如,要匹配小写字母<code>a</code>到<code>e</code>,你可以使用<code>[a-e]</code>。
<add>
<add>```js
<add>let catStr = "cat";
<add>let batStr = "bat";
<add>let matStr = "mat";
<add>let bgRegex = /[a-e]at/;
<add>catStr.match(bgRegex); // Returns ["cat"]
<add>batStr.match(bgRegex); // Returns ["bat"]
<add>matStr.match(bgRegex); // Returns null
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">匹配字符串<code>quoteSample</code>中的所有字母。 <strong>注意</strong> <br>务必匹配大写和小写<strong>字母<strong>。</strong></strong> </section>
<add><section id='instructions'>
<add>匹配字符串<code>quoteSample</code>中的所有字母。
<add><strong>注意:</strong><br>一定要同时匹配大小写<strong>字母<strong>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式<code>alphabetRegex</code>应该匹配35项。
<add> - text: 你的正则表达式<code>alphabetRegex</code>应该匹配 35 项。
<ide> testString: assert(result.length == 35);
<ide> - text: 你的正则表达式<code>alphabetRegex</code>应该使用全局标志。
<ide> testString: assert(alphabetRegex.flags.match(/g/).length == 1);
<del> - text: 你的正则表达式<code>alphabetRegex</code>应该使用不区分大小写的标志。
<add> - text: 你的正则表达式<code>alphabetRegex</code>应该使用忽略大小写标志。
<ide> testString: assert(alphabetRegex.flags.match(/i/).length == 1);
<ide>
<ide> ```
<ide> tests:
<ide> let quoteSample = "The quick brown fox jumps over the lazy dog.";
<ide> let alphabetRegex = /change/; // Change this line
<ide> let result = alphabetRegex; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = alphabetRegex; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let quoteSample = "The quick brown fox jumps over the lazy dog.";
<add>let alphabetRegex = /[a-z]/gi; // Change this line
<add>let result = quoteSample.match(alphabetRegex); // Change this line
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.chinese.md
<ide> id: 587d7db3367417b2b2512b8f
<ide> title: Match Literal Strings
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301355
<ide> localeTitle: 匹配文字字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在上一次挑战中,您使用正则表达式<code>/Hello/</code>搜索了单词<code>"Hello"</code> 。该正则表达式搜索字符串<code>"Hello"</code>的文字匹配。这是另一个搜索字符串<code>"Kevin"</code>的文字匹配的示例: <blockquote>让testStr =“你好,我的名字是凯文。”; <br>让testRegex = / Kevin /; <br> testRegex.test(testStr); <br> //返回true </blockquote>任何其他形式的<code>"Kevin"</code>都不匹配。例如,正则表达式<code>/Kevin/</code>将不匹配<code>"kevin"</code>或<code>"KEVIN"</code> 。 <blockquote> let wrongRegex = / kevin /; <br> wrongRegex.test(testStr); <br> //返回false </blockquote>未来的挑战将展示如何匹配其他形式。 </section>
<add><section id='description'>
<add>在上一个挑战中,使用正则表达式<code>/Hello/</code>搜索到了字符串<code>"Hello"</code>。那个正则表达式在字符串中搜寻<code>"Hello"</code>的文字匹配。下面是另一个在字符串中搜寻<code>"Kevin"</code>的示例:
<add>
<add>```js
<add>let testStr = "Hello, my name is Kevin.";
<add>let testRegex = /Kevin/;
<add>testRegex.test(testStr);
<add>// Returns true
<add>```
<add>
<add>任何其他形式的<code>"Kevin"</code>都不会被匹配。例如,正则表达式<code>/Kevin/</code>不会匹配<code>"kevin"</code>或者<code>"KEVIN"</code>。
<add>
<add>```js
<add>let wrongRegex = /kevin/;
<add>wrongRegex.test(testStr);
<add>// Returns false
<add>```
<add>
<add>后续的挑战将为你展示如何匹配其他形式的字符串。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">完成正则表达式<code>waldoRegex</code>在字符串<code>waldoIsHiding</code>使用文字匹配查找<code>"Waldo"</code> 。 </section>
<add><section id='instructions'>
<add>完成正则表达式<code>waldoRegex</code>,在字符串<code>waldoIsHiding</code>中匹配到文本<code>"Waldo"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式<code>waldoRegex</code>应该找到<code>"Waldo"</code>
<add> - text: "你的正则表达式<code>waldoRegex</code>应该匹配到<code>'Waldo'</code>。"
<ide> testString: assert(waldoRegex.test(waldoIsHiding));
<del> - text: 你的正则表达式<code>waldoRegex</code>不应该搜索任何其他内容。
<add> - text: 你的正则表达式<code>waldoRegex</code>不应该搜寻其他的任何内容。
<ide> testString: assert(!waldoRegex.test('Somewhere is hiding in this text.'));
<del> - text: 您应该与正则表达式执行文字字符串匹配。
<add> - text: 你应该使用你的正则表达式对字符串执行文字匹配。
<ide> testString: assert(!/\/.*\/i/.test(code));
<ide>
<ide> ```
<ide> tests:
<ide> let waldoIsHiding = "Somewhere Waldo is hiding in this text.";
<ide> let waldoRegex = /search/; // Change this line
<ide> let result = waldoRegex.test(waldoIsHiding);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = waldoRegex.test(waldoIsHiding);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let waldoIsHiding = "Somewhere Waldo is hiding in this text.";
<add>let waldoRegex = /Waldo/; // Change this line
<add>let result = waldoRegex.test(waldoIsHiding);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.chinese.md
<ide> id: 587d7db9367417b2b2512ba4
<ide> title: Match Non-Whitespace Characters
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 18210
<ide> localeTitle: 匹配非空白字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您学会了使用<code>\s</code>搜索空格,并使用小写<code>s</code> 。您还可以搜索除空格之外的所有内容。使用<code>\S</code>搜索非空格, <code>\S</code>是一个大写的<code>s</code> 。此模式将不匹配空格,回车符,制表符,换页符和换行符。你可以认为它类似于字符类<code>[^ \r\t\f\n\v]</code> 。 <blockquote>让whiteSpace =“空白。到处都是空白!” <br>让nonSpaceRegex = / \ S / g; <br> whiteSpace.match(nonSpaceRegex)。长度; //返回32 </blockquote></section>
<add><section id='description'>
<add>已经学会了如何使用带有小写<code>s</code>的缩写<code>\s</code>来搜寻空白字符。还可以搜寻除了空格之外的所有内容。
<add>使用<code>\S</code>搜寻非空白字符,其中<code>S</code>是大写。此匹配模式将不匹配空格、回车符、制表符、换页符和换行符。可以认为这类似于元字符<code>[^\r\t\f\n\v]</code>。
<add>
<add>```js
<add>let whiteSpace = "Whitespace. Whitespace everywhere!"
<add>let nonSpaceRegex = /\S/g;
<add>whiteSpace.match(nonSpaceRegex).length; // Returns 32
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改正则表达式<code>countNonWhiteSpace</code>以在字符串中查找多个非空白字符。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>countNonWhiteSpace</code>以查找字符串中的多个非空字符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用全局标志。
<add> - text: 你的正则表达式应该使用全局状态修正符。
<ide> testString: assert(countNonWhiteSpace.global);
<del> - text: 你的正则表达式应该使用速记字符
<add> - text: 正则表达式应该使用元字符 <code>\S/code> 来匹配所有的非空格字符。
<ide> testString: assert(/\\S/.test(countNonWhiteSpace.source));
<del> - text: 你的正则表达式应该在<code>"Men are from Mars and women are from Venus."</code>找到35个非空格<code>"Men are from Mars and women are from Venus."</code>
<add> - text: "你的正则表达式应该在<code>'Men are from Mars and women are from Venus.'</code>中匹配到 35 个非空白字符。"
<ide> testString: assert("Men are from Mars and women are from Venus.".match(countNonWhiteSpace).length == 35);
<del> - text: '你的正则表达式应该在<code>"Space: the final frontier."</code>找到23个非空格<code>"Space: the final frontier."</code>'
<add> - text: '你的正则表达式应该在<code>"Space: the final frontier."</code>中匹配到 23 个非空白字符。'
<ide> testString: 'assert("Space: the final frontier.".match(countNonWhiteSpace).length == 23);'
<del> - text: 你的正则表达式应该在<code>"MindYourPersonalSpace"</code>找到21个非空格
<add> - text: "你的正则表达式应该在<code>'MindYourPersonalSpace'</code>中匹配到 21 个非空白字符。"
<ide> testString: assert("MindYourPersonalSpace".match(countNonWhiteSpace).length == 21);
<ide>
<ide> ```
<ide> tests:
<ide> let sample = "Whitespace is important in separating words";
<ide> let countNonWhiteSpace = /change/; // Change this line
<ide> let result = sample.match(countNonWhiteSpace);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = sample.match(countNonWhiteSpace);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let sample = "Whitespace is important in separating words";
<add>let countNonWhiteSpace = /\S/g; // Change this line
<add>let result = sample.match(countNonWhiteSpace);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.chinese.md
<ide> id: 587d7db5367417b2b2512b97
<ide> title: Match Numbers and Letters of the Alphabet
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配数字和字母的字母
<add>forumTopicId: 301356
<add>localeTitle: 匹配字母表中的数字和字母
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用连字符( <code>-</code> )匹配一系列字符不仅限于字母。它也适用于匹配一系列数字。例如, <code>/[0-5]/</code>匹配<code>0</code>到<code>5</code>之间的任何数字,包括<code>0</code>和<code>5</code> 。此外,可以在单个字符集中组合一系列字母和数字。 <blockquote>让jennyStr =“Jenny8675309”; <br>让myRegex = / [a-z0-9] / ig; <br> //匹配jennyStr中的所有字母和数字<br> jennyStr.match(myRegex); </blockquote></section>
<add><section id='description'>
<add>使用连字符(<code>-</code>)匹配字符范围并不仅限于字母。它还可以匹配一系列数字。
<add>例如,<code>/[0-5]/</code>匹配<code>0</code>和<code>5</code>之间的任意数字,包含<code>0</code>和<code>5</code>。
<add>此外,还可以在单个字符集中组合一系列字母和数字。
<add>
<add>```js
<add>let jennyStr = "Jenny8675309";
<add>let myRegex = /[a-z0-9]/ig;
<add>// matches all letters and numbers in jennyStr
<add>jennyStr.match(myRegex);
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个与<code>h</code>和<code>s</code>之间的字母范围匹配的正则表达式,以及介于<code>2</code>和<code>6</code>之间的数字范围。请记住在正则表达式中包含适当的标志。 </section>
<add><section id='instructions'>
<add>创建一个正则表达式,使其可以匹配<code>h</code>和<code>s</code>之间的一系列字母,以及<code>2</code>和<code>6</code>之间的一系列数字。请记得在正则表达式中包含恰当的标志。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式<code>myRegex</code>应该匹配17项。
<add> - text: 你的正则表达式<code>myRegex</code>应该匹配 17 项。
<ide> testString: assert(result.length == 17);
<ide> - text: 你的正则表达式<code>myRegex</code>应该使用全局标志。
<ide> testString: assert(myRegex.flags.match(/g/).length == 1);
<del> - text: 你的正则表达式<code>myRegex</code>应该使用不区分大小写的标志。
<add> - text: 你的正则表达式<code>myRegex</code>应该使用忽略大小写的标志。
<ide> testString: assert(myRegex.flags.match(/i/).length == 1);
<ide>
<ide> ```
<ide> tests:
<ide> let quoteSample = "Blueberry 3.141592653s are delicious.";
<ide> let myRegex = /change/; // Change this line
<ide> let result = myRegex; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = myRegex; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let quoteSample = "Blueberry 3.141592653s are delicious.";
<add>let myRegex = /[h-s2-6]/gi; // Change this line
<add>let result = quoteSample.match(myRegex); // Change this line
<add>
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.chinese.md
<ide> id: 587d7db5367417b2b2512b95
<ide> title: Match Single Character with Multiple Possibilities
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 将单个角色与多种可能性相匹配
<add>forumTopicId: 301357
<add>localeTitle: 将单个字符与多种可能性匹配
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您学习了如何匹配文字模式( <code>/literal/</code> )和通配符( <code>/./</code> )。这些是正则表达式的极端,其中一个找到完全匹配,另一个匹配一切。有两个极端之间可以平衡的选项。您可以使用<code>character classes</code>搜索具有一定灵活性的文字模式。字符类允许您通过将它们放在方括号( <code>[</code>和<code>]</code> )括号内来定义要匹配的一组字符。例如,您想匹配<code>"bag"</code> , <code>"big"</code>和<code>"bug"</code>但不匹配<code>"bog"</code> 。您可以创建regex <code>/b[aiu]g/</code>来执行此操作。 <code>[aiu]</code>是仅匹配字符<code>"a"</code> , <code>"i"</code>或<code>"u"</code>的字符类。 <blockquote>让bigStr =“大”; <br>让bagStr =“bag”; <br>让bugStr =“bug”; <br>让bogStr =“bog”; <br>让bgRegex = / b [aiu] g /; <br> bigStr.match(bgRegex); //返回[“大”] <br> bagStr.match(bgRegex); //返回[“bag”] <br> bugStr.match(bgRegex); //返回[“bug”] <br> bogStr.match(bgRegex); //返回null </blockquote></section>
<add><section id='description'>
<add>已经了解了文字匹配模式(<code>/literal/</code>)和通配符(<code>/./</code>)。这是正则表达式的两种极端情况,一种是精确匹配,而另一种则是匹配所有。在这两种极端情况之间有一个平衡选项。
<add>可以使用<code>字符集</code>搜寻具有一定灵活性的文字匹配模式。可以把字符集放在方括号(<code>[</code>和<code>]</code>)之间来定义一组需要匹配的字符串。
<add>例如,如果想要匹配<code>"bag"</code>、<code>"big"</code>和<code>"bug"</code>,但是不想匹配<code>"bog"</code>。可以创建正则表达式<code>/b[aiu]g/</code>来执行此操作。<code>[aiu]</code>是只匹配字符<code>"a"</code>、<code>"i"</code>或者<code>"u"</code>的字符集。
<add>
<add>```js
<add>let bigStr = "big";
<add>let bagStr = "bag";
<add>let bugStr = "bug";
<add>let bogStr = "bog";
<add>let bgRegex = /b[aiu]g/;
<add>bigStr.match(bgRegex); // Returns ["big"]
<add>bagStr.match(bgRegex); // Returns ["bag"]
<add>bugStr.match(bgRegex); // Returns ["bug"]
<add>bogStr.match(bgRegex); // Returns null
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在正则表达式<code>vowelRegex</code>使用带元音( <code>a</code> , <code>e</code> , <code>i</code> , <code>o</code> , <code>u</code> )的字符类来查找字符串<code>quoteSample</code>中的所有元音。 <strong>注意</strong> <br>确保匹配大写和小写元音。 </section>
<add><section id='instructions'>
<add>使用元音字符集(<code>a</code>、<code>e</code>、<code>i</code>、<code>o</code>、<code>u</code>)在正则表达式<code>vowelRegex</code>中匹配到字符串<code>quoteSample</code>中的所有元音。
<add><strong>注意</strong><br>一定要同时匹配大小写元音。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你应该找到所有25个元音。
<add> - text: 你应该匹配到所有25个元音。
<ide> testString: assert(result.length == 25);
<del> - text: 你的正则表达式<code>vowelRegex</code>应该使用一个字符类。
<add> - text: 你的正则表达式<code>vowelRegex</code>应该使用字符集。
<ide> testString: assert(/\[.*\]/.test(vowelRegex.source));
<ide> - text: 你的正则表达式<code>vowelRegex</code>应该使用全局标志。
<ide> testString: assert(vowelRegex.flags.match(/g/).length == 1);
<del> - text: 你的正则表达式<code>vowelRegex</code>应该使用不区分大小写的标志。
<add> - text: 你的正则表达式<code>vowelRegex</code>应该使用忽略大小写标志。
<ide> testString: assert(vowelRegex.flags.match(/i/).length == 1);
<del> - text: 你的正则表达式不应该与任何辅音匹配。
<add> - text: 你的正则表达式不应该匹配任何辅音。
<ide> testString: assert(!/[b-df-hj-np-tv-z]/gi.test(result.join()));
<ide>
<ide> ```
<ide> tests:
<ide> let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
<ide> let vowelRegex = /change/; // Change this line
<ide> let result = vowelRegex; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = vowelRegex; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it.";
<add>let vowelRegex = /[aeiou]/gi; // Change this line
<add>let result = quoteSample.match(vowelRegex); // Change this line
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.chinese.md
<ide> id: 587d7db6367417b2b2512b98
<ide> title: Match Single Characters Not Specified
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配未指定的单个字符
<add>forumTopicId: 301358
<add>localeTitle: 匹配单个未指定的字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您已创建了一组要匹配的字符,但您也可以创建一组您不想匹配的字符。这些类型的字符集称为<code>negated character sets</code> 。要创建<code>negated character set</code> ,请在<code>caret</code>括号后面和不想匹配的字符前放置一个<code>caret</code> ( <code>^</code> )。例如, <code>/[^aeiou]/gi</code>匹配所有不是元音的字符。请注意字符之类的<code>.</code> , <code>!</code> , <code>[</code> , <code>@</code> , <code>/</code>和空格匹配 - 否定元音字符集仅排除元音字符。 </section>
<add><section id='description'>
<add>到目前为止,已经创建了一个想要匹配的字符集合,但也可以创建一个不想匹配的字符集合。这些类型的字符集称为<code>否定字符集</code>。
<add>要创建<code>否定字符集</code>,需要在开始括号后面和不想匹配的字符前面放置<code>插入字符</code>(即<code>^</code>)。
<add>例如,<code>/[^aeiou]/gi</code>匹配所有非元音字符。注意,字符<code>.</code>、<code>!</code>、<code>[</code>、<code>@</code>、<code>/</code>和空白字符等也会被匹配,该否定字符集仅排除元音字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个匹配所有不是数字或元音的字符的正则表达式。请记住在正则表达式中包含适当的标志。 </section>
<add><section id='instructions'>
<add>创建一个匹配所有非数字或元音字符的正则表达式。请记得在正则表达式中包含恰当的标志。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式<code>myRegex</code>应匹配9项。
<add> - text: 你的正则表达式<code>myRegex</code>应该匹配 9 项。
<ide> testString: assert(result.length == 9);
<ide> - text: 你的正则表达式<code>myRegex</code>应该使用全局标志。
<ide> testString: assert(myRegex.flags.match(/g/).length == 1);
<del> - text: 你的正则表达式<code>myRegex</code>应该使用不区分大小写的标志。
<add> - text: 你的正则表达式<code>myRegex</code>应该使用忽略大小写标志。
<ide> testString: assert(myRegex.flags.match(/i/).length == 1);
<ide>
<ide> ```
<ide> tests:
<ide> let quoteSample = "3 blind mice.";
<ide> let myRegex = /change/; // Change this line
<ide> let result = myRegex; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = myRegex; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let quoteSample = "3 blind mice.";
<add>let myRegex = /[^0-9aeiou]/gi; // Change this line
<add>let result = quoteSample.match(myRegex); // Change this line
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.chinese.md
<ide> id: 587d7db8367417b2b2512ba3
<ide> title: Match Whitespace
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 匹配空白
<add>forumTopicId: 301359
<add>localeTitle: 匹配空白字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">迄今为止的挑战包括匹配的字母和数字字母。您还可以匹配字母之间的空格或空格。您可以使用<code>\s</code>搜索空格,这是一个小写的<code>s</code> 。此模式不仅匹配空格,还匹配回车符,制表符,换页符和换行符。你可以认为它类似于字符类<code>[ \r\t\f\n\v]</code> 。 <blockquote>让whiteSpace =“空白。到处都是空白!” <br>让spaceRegex = / \ s / g; <br> whiteSpace.match(spaceRegex); <br> //返回[“”,“”] <br></blockquote></section>
<add><section id='description'>
<add>迄今为止的挑战包括匹配的字母和数字。还可以匹配字母之间的空格。
<add>可以使用<code>\s</code>搜寻空格,其中<code>s</code>是小写。此匹配模式不仅匹配空格,还匹配回车符、制表符、换页符和换行符,可以将其视为与<code>[\r\t\f\n\v]</code>类似。
<add>
<add>```js
<add>let whiteSpace = "Whitespace. Whitespace everywhere!"
<add>let spaceRegex = /\s/g;
<add>whiteSpace.match(spaceRegex);
<add>// Returns [" ", " "]
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改正则表达式<code>countWhiteSpace</code>以查找字符串中的多个空格字符。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>countWhiteSpace</code>查找字符串中的多个空白字符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用全局标志。
<add> - text: 你的正则表达式应该使用全局状态修正符。
<ide> testString: assert(countWhiteSpace.global);
<del> - text: 你的正则表达式应该使用速记字符
<add> - text: 正则表达式应该使用元字符 <code>\s</code> 匹配所有的空白。
<ide> testString: assert(/\\s/.test(countWhiteSpace.source));
<del> - text: 你的正则表达式应该在<code>"Men are from Mars and women are from Venus."</code>找到八个空格<code>"Men are from Mars and women are from Venus."</code>
<add> - text: "你的正则表达式应该在<code>'Men are from Mars and women are from Venus.'</code>中匹配到 8 个空白字符。"
<ide> testString: assert("Men are from Mars and women are from Venus.".match(countWhiteSpace).length == 8);
<del> - text: '你的正则表达式应该在<code>"Space: the final frontier."</code>找到三个空格<code>"Space: the final frontier."</code>'
<add> - text: '你的正则表达式应该在<code>"Space: the final frontier."</code>中匹配到 3 个空白字符。'
<ide> testString: 'assert("Space: the final frontier.".match(countWhiteSpace).length == 3);'
<del> - text: 您的正则表达式应该在<code>"MindYourPersonalSpace"</code>中找不到空格
<add> - text: "你的正则表达式在<code>'MindYourPersonalSpace'</code>中应该匹配不到空白字符。"
<ide> testString: assert("MindYourPersonalSpace".match(countWhiteSpace) == null);
<ide>
<ide> ```
<ide> tests:
<ide> let sample = "Whitespace is important in separating words";
<ide> let countWhiteSpace = /change/; // Change this line
<ide> let result = sample.match(countWhiteSpace);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = sample.match(countWhiteSpace);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let sample = "Whitespace is important in separating words";
<add>let countWhiteSpace = /\s/g;
<add>let result = sample.match(countWhiteSpace);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.chinese.md
<ide> id: 587d7dba367417b2b2512ba9
<ide> title: Positive and Negative Lookahead
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 积极和消极的前瞻
<add>forumTopicId: 301360
<add>localeTitle: 正向先行断言和负向先行断言
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>Lookaheads</code>是一种模式,它告诉JavaScript在字符串中向前看以进一步检查模式。当您想要在同一个字符串上搜索多个模式时,这非常有用。有两种<code>lookaheads</code> : <code>positive lookahead</code>和<code>negative lookahead</code> 。一个<code>positive lookahead</code>向前看将确保搜索模式中的元素存在,但实际上不匹配它。正向前瞻用作<code>(?=...)</code> ,其中<code>...</code>是不匹配的必需部分。另一方面, <code>negative lookahead</code>将确保搜索模式中的元素不存在。负向前瞻用作<code>(?!...)</code> ,其中<code>...</code>是您不希望在那里的模式。如果不存在负前瞻部分,则返回模式的其余部分。前瞻有点令人困惑,但一些例子会有所帮助。 <blockquote>让quit =“qu”; <br>让noquit =“qt”; <br>让quRegex = / q(?= u)/; <br>让qRegex = / q(?!u)/; <br> quit.match(quRegex); //返回[“q”] <br> noquit.match(qRegex); //返回[“q”] </blockquote> <code>lookaheads</code>更实际用途是检查一个字符串中的两个或更多个模式。这是一个(天真)简单的密码检查器,可以查找3到6个字符和至少一个数字: <blockquote> let password =“abc123”; <br>让checkPass = /(?= \ w {3,6})(?= \ D * \ d)/; <br> checkPass.test(密码); //返回true </blockquote></section>
<add><section id='description'>
<add><code>先行断言</code>是告诉 JavaScript 在字符串中向前查找的匹配模式。当想要在同一个字符串上搜寻多个匹配模式时,这可能非常有用。
<add>有两种<code>先行断言</code>:<code>正向先行断言</code>和<code>负向先行断言</code>。
<add><code>正向先行断言</code>会查看并确保搜索匹配模式中的元素存在,但实际上并不匹配。正向先行断言的用法是<code>(?=...)</code>,其中<code>...</code>就是需要存在但不会被匹配的部分。
<add>另一方面,<code>负向先行断言</code>会查看并确保搜索匹配模式中的元素不存在。负向先行断言的用法是<code>(?!...)</code>,其中<code>...</code>是希望不存在的匹配模式。如果负向先行断言部分不存在,将返回匹配模式的其余部分。
<add>尽管先行断言有点儿令人困惑,但是这些示例会有所帮助。
<add>
<add>```js
<add>let quit = "qu";
<add>let noquit = "qt";
<add>let quRegex= /q(?=u)/;
<add>let qRegex = /q(?!u)/;
<add>quit.match(quRegex); // Returns ["q"]
<add>noquit.match(qRegex); // Returns ["q"]
<add>```
<add>
<add><code>先行断言</code>的更实际用途是检查一个字符串中的两个或更多匹配模式。这里有一个简单的密码检查器,密码规则是 3 到 6 个字符且至少包含一个数字:
<add>
<add>```js
<add>let password = "abc123";
<add>let checkPass = /(?=\w{3,6})(?=\D*\d)/;
<add>checkPass.test(password); // Returns true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>lookaheads</code>在<code>pwRegex</code>匹配长的时间大于5个字符,并有两个连续的数字密码。 </section>
<add><section id='instructions'>
<add>在正则表达式<code>pwRegex</code>中使用<code>先行断言</code>以匹配大于5个字符且有两个连续数字的密码,并且不能以数字开头。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用两个积极的<code>lookaheads</code> 。
<add> - text: 你的正则表达式应该使用两个正向<code>先行断言</code>。
<ide> testString: assert(pwRegex.source.match(/\(\?=.*?\)\(\?=.*?\)/) !== null);
<del> - text: 你的正则表达式不应该匹配<code>"astronaut"</code>
<add> - text: "你的正则表达式不应该匹配<code>'astronaut'</code>。"
<ide> testString: assert(!pwRegex.test("astronaut"));
<del> - text: 你的正则表达式不应该与<code>"airplanes"</code>匹配
<add> - text: "你的正则表达式不应该匹配<code>'airplanes'</code>。"
<ide> testString: assert(!pwRegex.test("airplanes"));
<del> - text: 你的正则表达式不应该匹配<code>"banan1"</code>
<add> - text: 正则不应该匹配 <code>"banan1"</code>
<ide> testString: assert(!pwRegex.test("banan1"));
<del> - text: 你的正则表达式应该匹配<code>"bana12"</code>
<add> - text: "你的正则表达式应该匹配<code>'bana12'</code>。"
<ide> testString: assert(pwRegex.test("bana12"));
<del> - text: 你的正则表达式应该匹配<code>"abc123"</code>
<add> - text: "你的正则表达式应该匹配<code>'abc123'</code>。"
<ide> testString: assert(pwRegex.test("abc123"));
<del> - text: 你的正则表达式不应该匹配<code>"123"</code>
<add> - text: "你的正则表达式不应该匹配<code>'123'</code>。"
<ide> testString: assert(!pwRegex.test("123"));
<del> - text: 你的正则表达式不应该匹配<code>"1234"</code>
<add> - text: "你的正则表达式不应该匹配<code>'1234'</code>。"
<ide> testString: assert(!pwRegex.test("1234"));
<add> - text: 正则不应该匹配 <code>"8pass99"</code>
<add> testString: assert(!pwRegex.test("8pass99"));
<add> - text: 正则不应该匹配 <code>"12abcde"</code>
<add> testString: assert(!pwRegex.test("12abcde"));
<add>
<add>
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> let sampleWord = "astronaut";
<ide> let pwRegex = /change/; // Change this line
<ide> let result = pwRegex.test(sampleWord);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = pwRegex.test(sampleWord);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var pwRegex = /^(?=\w{6})(?=\D+\d{2})/;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.chinese.md
<ide> id: 587d7dbb367417b2b2512bac
<ide> title: Remove Whitespace from Start and End
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 从开始和结束中删除空格
<add>forumTopicId: 301362
<add>localeTitle: 删除开头和结尾的空白
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时字符串周围的空白字符不是必需的,而是存在的。字符串的典型处理是删除字符串开头和结尾处的空格。 </section>
<add><section id='description'>
<add>有时字符串周围存在的空白字符并不是必需的。字符串的典型处理是删除字符串开头和结尾处的空格。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">编写一个正则表达式并使用适当的字符串方法删除字符串开头和结尾的空格。 <strong>注意</strong> <br> <code>.trim()</code>方法可以在这里工作,但您需要使用正则表达式完成此挑战。 </section>
<add><section id='instructions'>
<add>编写一个正则表达式并使用适当的字符串方法删除字符串开头和结尾的空格。
<add><strong>注意:</strong><br><code>.trim()</code>方法在这里也可以实现同样的效果,但是你需要使用正则表达式来完成此项挑战。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>result</code>应该等于<code>"Hello, World!"</code>'
<add> - text: "<code>结果</code>应该等于<code>'Hello, World!'</code>。"
<ide> testString: assert(result == "Hello, World!");
<del> - text: 您不应该使用<code>.trim()</code>方法。
<del> testString: assert(!code.match(/\.trim\([\s\S]*?\)/));
<del> - text: <code>result</code>变量不应设置为等于字符串。
<add> - text: 你不应该使用<code>.trim()</code>方法。
<add> testString: assert(!code.match(/\.trim\(.*?\)/));
<add> - text: <code>结果</code>变量不应该设置为等于字符串。
<ide> testString: assert(!code.match(/result\s*=\s*".*?"/));
<ide>
<ide> ```
<ide> tests:
<ide> let hello = " Hello, World! ";
<ide> let wsRegex = /change/; // Change this line
<ide> let result = hello; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = hello; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let hello = " Hello, World! ";
<add>let wsRegex = /^(\s+)(.+[^\s])(\s+)$/;
<add>let result = hello.replace(wsRegex, '$2');
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.chinese.md
<ide> id: 587d7db8367417b2b2512ba2
<ide> title: Restrict Possible Usernames
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301363
<ide> localeTitle: 限制可能的用户名
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">用户名在互联网上随处可见。它们是用户在自己喜欢的网站上获得独特身份的原因。您需要检查数据库中的所有用户名。以下是用户在创建用户名时必须遵循的一些简单规则。 1)用户名中的唯一数字必须在最后。最后可以有零个或多个。 2)用户名字母可以是小写和大写。 3)用户名必须至少两个字符长。双字母用户名只能使用字母字母。 </section>
<add><section id='description'>
<add>用户名在互联网上随处可见。它们是用户在自己喜欢的网站上的唯一身份。
<add>需要检索数据库中的所有用户名。以下是用户在创建用户名时必须遵守的一些简单规则。
<add>1) 用户名只能是数字字母字符。
<add>2) 用户名中的数字必须在最后,且数字可以有零个或多个。
<add>3) 用户名字母可以是小写字母和大写字母。
<add>4) 用户名长度必须至少为两个字符。两位用户名只能使用字母。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改正则表达式<code>userCheck</code>以适合上面列出的约束。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>userCheck</code>以适合上面列出的约束。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该与<code>JACK</code>匹配
<del> testString: 'assert(userCheck.test("JACK"), "Your regex should match <code>JACK</code>");'
<del> - text: 你的正则表达式不应该与<code>J</code>匹配
<del> testString: 'assert(!userCheck.test("J"), "Your regex should not match <code>J</code>");'
<del> - text: 你的正则表达式应该与<code>Oceans11</code>匹配
<del> testString: 'assert(userCheck.test("Oceans11"), "Your regex should match <code>Oceans11</code>");'
<del> - text: 你的正则表达式应该与<code>RegexGuru</code>匹配
<del> testString: 'assert(userCheck.test("RegexGuru"), "Your regex should match <code>RegexGuru</code>");'
<del> - text: 你的正则表达式不应该与<code>007</code>匹配
<del> testString: 'assert(!userCheck.test("007"), "Your regex should not match <code>007</code>");'
<del> - text: 你的正则表达式不应该匹配<code>9</code>
<del> testString: 'assert(!userCheck.test("9"), "Your regex should not match <code>9</code>");'
<add> - text: 你的正则表达式应该匹配<code>JACK</code>。
<add> testString: assert(userCheck.test("JACK"));
<add> - text: 你的正则表达式不应该匹配<code>J</code>。
<add> testString: assert(!userCheck.test("J"));
<add> - text: 正则表达式应该匹配 <code>Jo</code>。
<add> testString: assert(userCheck.test("Jo"));
<add> - text: 你的正则表达式应该匹配<code>Oceans11</code>。
<add> testString: assert(userCheck.test("Oceans11"));
<add> - text: 你的正则表达式应该匹配<code>RegexGuru</code>。
<add> testString: assert(userCheck.test("RegexGuru"));
<add> - text: 你的正则表达式不应该匹配<code>007</code>。
<add> testString: assert(!userCheck.test("007"));
<add> - text: 你的正则表达式不应该匹配<code>9</code>。
<add> testString: assert(!userCheck.test("9"));
<add> - text: 正则表达式不应该匹配 <code>A1</code>。
<add> testString: assert(!userCheck.test("A1"));
<add> - text: 正则表达式不应该匹配 <code>BadUs3rnam3</code>。
<add> testString: assert(!userCheck.test("BadUs3rnam3"));
<add> - text: 正则表达式应该匹配 <code>Z97</code>。
<add> testString: assert(userCheck.test("Z97"));
<add> - text: 正则表达式不应该匹配 <code>c57bT3</code>。
<add> testString: assert(!userCheck.test("c57bT3"));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> let username = "JackOfAllTrades";
<ide> let userCheck = /change/; // Change this line
<ide> let result = userCheck.test(username);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = userCheck.test(username);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let username = "JackOfAllTrades";
<add>const userCheck = /^[a-z]([0-9]{2,}|[a-z]+\d*)$/i;
<add>let result = userCheck.test(username);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups.chinese.md
<ide> id: 587d7dbb367417b2b2512baa
<ide> title: Reuse Patterns Using Capture Groups
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301364
<ide> localeTitle: 使用捕获组重用模式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您搜索的某些模式将在字符串中多次出现。手动重复该正则表达式是浪费的。有一种更好的方法可以指定何时在字符串中有多个重复子字符串。您可以使用<code>capture groups</code>搜索重复子字符串。括号<code>(</code>和<code>)</code>用于查找重复子串。你把模式的正则表达式重复在括号之间。要指定重复字符串的显示位置,请使用反斜杠( <code>\</code> ),然后使用数字。此数字从1开始,随着您使用的每个其他捕获组而增加。一个例子是<code>\1</code>来匹配第一组。下面的示例匹配以空格分隔的两次出现的任何单词: <blockquote>让repeatStr =“正则表达式正则表达式”; <br> let repeatRegex = /(\ w +)\ s \ 1 /; <br> repeatRegex.test(repeatStr); //返回true <br> repeatStr.match(repeatRegex); //返回[“regex regex”,“regex”] </blockquote>对字符串使用<code>.match()</code>方法将返回一个数组,其中包含与其匹配的字符串及其捕获组。 </section>
<add><section id='description'>
<add>一些你所搜寻的匹配模式会在字符串中出现多次,手动重复该正则表达式太浪费了。有一种更好的方法可以指定何时在字符串中会有多个重复的子字符串。
<add>可以使用<code>捕获组</code>搜寻重复的子字符串。括号<code>(</code>和<code>)</code>可以用来匹配重复的子字符串。只需要把重复匹配模式的正则表达式放在括号中即可。
<add>要指定重复字符串将出现的位置,可以使用反斜杠(<code>\</code>)后接一个数字。这个数字从 1 开始,随着你使用的每个捕获组的增加而增加。这里有一个示例,<code>\1</code>可以匹配第一个组。
<add>下面的示例匹配任意两个被空格分割的单词:
<add>
<add>```js
<add>let repeatStr = "regex regex";
<add>let repeatRegex = /(\w+)\s\1/;
<add>repeatRegex.test(repeatStr); // Returns true
<add>repeatStr.match(repeatRegex); // Returns ["regex regex", "regex"]
<add>```
<add>
<add>在字符串上使用<code>.match()</code>方法将返回一个数组,其中包含它匹配的字符串及其捕获组。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>reRegex</code>使用<code>capture groups</code>来匹配在字符串中仅重复三次的数字,每个数字用空格分隔。 </section>
<add><section id='instructions'>
<add>在正则表达式<code>reRegex</code>中使用<code>捕获组</code>,以匹配在字符串中仅重复三次的数字,每一个都由空格分隔。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用数字的速记字符类。
<add> - text: 你的正则表达式应该使用数字的速记元字符。
<ide> testString: assert(reRegex.source.match(/\\d/));
<del> - text: 您的正则表达式应该重复使用捕获组两次。
<add> - text: 你的正则表达式应该重用两次捕获组。
<ide> testString: assert(reRegex.source.match(/\\1|\\2/g).length >= 2);
<del> - text: 你的正则表达式应该有两个空格来分隔这三个数字。
<add> - text: 你的正则表达式应该有两个空格分隔这三个数字。
<ide> testString: assert(reRegex.source.match(/ |\\s/g).length === 2 || reRegex.source.match(/\(\\s\)(?=.*\\(1|2))/g));
<del> - text: 你的正则表达式应该匹配<code>"42 42 42"</code> 。
<add> - text: "你的正则表达式应该匹配<code>'42 42 42'</code>。"
<ide> testString: assert(reRegex.test("42 42 42"));
<del> - text: 你的正则表达式应该匹配<code>"100 100 100"</code> 。
<add> - text: "你的正则表达式应该匹配<code>'100 100 100'</code>。"
<ide> testString: assert(reRegex.test("100 100 100"));
<del> - text: 你的正则表达式不应该匹配<code>"42 42 42 42"</code> 。
<add> - text: "你的正则表达式不应该匹配<code>'42 42 42 42'</code>。"
<ide> testString: assert.equal(("42 42 42 42").match(reRegex.source), null);
<del> - text: 你的正则表达式不应该匹配<code>"42 42"</code> 。
<add> - text: "你的正则表达式不应该匹配<code>'42 42'</code>。"
<ide> testString: assert.equal(("42 42").match(reRegex.source), null);
<del> - text: 你的正则表达式不应该匹配<code>"101 102 103"</code> 。
<add> - text: "你的正则表达式不应该匹配<code>'101 102 103'</code>。"
<ide> testString: assert(!reRegex.test("101 102 103"));
<del> - text: 你的正则表达式不应该匹配<code>"1 2 3"</code> 。
<add> - text: "你的正则表达式不应该匹配<code>'1 2 3'</code>。"
<ide> testString: assert(!reRegex.test("1 2 3"));
<del> - text: 你的正则表达式应匹配<code>"10 10 10"</code> 。
<add> - text: "你的正则表达式应该匹配<code>'10 10 10'</code>。"
<ide> testString: assert(reRegex.test("10 10 10"));
<ide>
<ide> ```
<ide> tests:
<ide> let repeatNum = "42 42 42";
<ide> let reRegex = /change/; // Change this line
<ide> let result = reRegex.test(repeatNum);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = reRegex.test(repeatNum);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let repeatNum = "42 42 42";
<add>let reRegex = /^(\d+)\s\1\s\1$/;
<add>let result = reRegex.test(repeatNum);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.chinese.md
<ide> id: 587d7db9367417b2b2512ba7
<ide> title: Specify Exact Number of Matches
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 指定完全匹配数
<add>forumTopicId: 301365
<add>localeTitle: 指定匹配的确切数量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用大括号<code>quantity specifiers</code>的较低和较高数量的模式。有时您只需要特定数量的匹配。要指定一定数量的模式,只需在大括号之间放置一个数字。例如,要仅将单词<code>"hah"</code>与字母<code>a</code>匹配<code>3</code>次,您的正则表达式将为<code>/ha{3}h/</code> 。 <blockquote>让A4 =“haaaah”; <br>让A3 =“haaah”; <br>设A100 =“h”+“a”.repeat(100)+“h”; <br> let multipleHA = / ha {3} h /; <br> multipleHA.test(A4); //返回false <br> multipleHA.test(A3); //返回true <br> multipleHA.test(A100); //返回false </blockquote></section>
<add><section id='description'>
<add>可以使用带有花括号的<code>数量说明符</code>来指定匹配模式的上下限。但有时只需要特定数量的匹配。
<add>要指定一定数量的匹配模式,只需在大括号之间放置一个数字。
<add>例如,要只匹配字母<code>a</code>出现<code>3</code>次的单词<code>"hah"</code>,正则表达式应为<code>/ha{3}h/</code>。
<add>
<add>```js
<add>let A4 = "haaaah";
<add>let A3 = "haaah";
<add>let A100 = "h" + "a".repeat(100) + "h";
<add>let multipleHA = /ha{3}h/;
<add>multipleHA.test(A4); // Returns false
<add>multipleHA.test(A3); // Returns true
<add>multipleHA.test(A100); // Returns false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">只有当它有四个字母<code>m</code>时才更改正则表达式<code>timRegex</code>以匹配单词<code>"Timber"</code> 。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>timRegex</code>,以匹配仅有四个字母单词<code>m</code>的单词<code>"Timber"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用大括号。
<add> - text: 你的正则表达式应该使用花括号。
<ide> testString: assert(timRegex.source.match(/{.*?}/).length > 0);
<del> - text: 你的正则表达式不应该与<code>"Timber"</code>匹配
<add> - text: "你的正则表达式不应该匹配<code>'Timber'</code>。"
<ide> testString: assert(!timRegex.test("Timber"));
<del> - text: 你的正则表达式不应该匹配<code>"Timmber"</code>
<add> - text: "你的正则表达式不应该匹配<code>'Timmber'</code>。"
<ide> testString: assert(!timRegex.test("Timmber"));
<del> - text: 你的正则表达式不应该匹配<code>"Timmmber"</code>
<add> - text: "你的正则表达式不应该匹配<code>'Timmmber'</code>。"
<ide> testString: assert(!timRegex.test("Timmmber"));
<del> - text: 你的正则表达式应该匹配<code>"Timmmmber"</code>
<add> - text: "你的正则表达式应该匹配<code>'Timmmmber'</code>。"
<ide> testString: assert(timRegex.test("Timmmmber"));
<del> - text: 你的正则表达式不应该与30 <code>m</code>的<code>"Timber"</code>相匹配。
<add> - text: "你的正则表达式不应该匹配包含 30 个字母<code>m</code>的<code>'Timber'</code>。"
<ide> testString: assert(!timRegex.test("Ti" + "m".repeat(30) + "ber"));
<ide>
<ide> ```
<ide> tests:
<ide> let timStr = "Timmmmber";
<ide> let timRegex = /change/; // Change this line
<ide> let result = timRegex.test(timStr);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = timRegex.test(timStr);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let timStr = "Timmmmber";
<add>let timRegex = /Tim{4}ber/; // Change this line
<add>let result = timRegex.test(timStr);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.chinese.md
<ide> id: 587d7db9367417b2b2512ba6
<ide> title: Specify Only the Lower Number of Matches
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 仅指定较低的匹配数
<add>forumTopicId: 301366
<add>localeTitle: 只指定匹配的下限
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用大括号<code>quantity specifiers</code>的较低和较高数量的模式。有时您只想指定较低数量的模式而没有上限。要仅指定较少的模式数,请保留第一个数字后跟逗号。例如,要仅匹配字符串<code>"hah"</code>与出现至少<code>3</code>次的字母<code>a</code> ,您的正则表达式将是<code>/ha{3,}h/</code> 。 <blockquote>让A4 =“haaaah”; <br>让A2 =“哈哈”; <br>设A100 =“h”+“a”.repeat(100)+“h”; <br> let multipleA = / ha {3,} h /; <br> multipleA.test(A4); //返回true <br> multipleA.test(A2); //返回false <br> multipleA.test(A100); //返回true </blockquote></section>
<add><section id='description'>
<add>可以使用带有花括号的<code>数量说明符</code>来指定匹配模式的上下限。但有时候只想指定匹配模式的下限而不需要指定上限。
<add>为此,在第一个数字后面跟一个逗号即可。
<add>例如,要匹配至少出现<code>3</code>次字母<code>a</code>的字符串<code>"hah"</code>,正则表达式应该是<code>/ha{3,}h/</code>。
<add>
<add>```js
<add>let A4 = "haaaah";
<add>let A2 = "haah";
<add>let A100 = "h" + "a".repeat(100) + "h";
<add>let multipleA = /ha{3,}h/;
<add>multipleA.test(A4); // Returns true
<add>multipleA.test(A2); // Returns false
<add>multipleA.test(A100); // Returns true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">只有当它有四个或更多字母<code>z</code>时才更改正则表达式<code>haRegex</code>以匹配单词<code>"Hazzah"</code> 。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>haRegex</code>,匹配包含四个或更多字母<code>z</code>的单词<code>"Hazzah"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用大括号。
<add> - text: 你的正则表达式应该使用花括号。
<ide> testString: assert(haRegex.source.match(/{.*?}/).length > 0);
<del> - text: 你的正则表达式不应该与<code>"Hazzah"</code>匹配
<add> - text: "你的正则表达式不应该匹配<code>'Hazzah'</code>。"
<ide> testString: assert(!haRegex.test("Hazzah"));
<del> - text: 你的正则表达式不应该与<code>"Hazzzah"</code>匹配
<add> - text: "你的正则表达式不应该匹配<code>'Hazzzah'</code>。"
<ide> testString: assert(!haRegex.test("Hazzzah"));
<del> - text: 你的正则表达应该匹配<code>"Hazzzzah"</code>
<add> - text: 正则表达式应该匹配 <code>"Hazzzzah"</code>
<ide> testString: assert("Hazzzzah".match(haRegex)[0].length === 8);
<del> - text: 你的正则表达应该匹配<code>"Hazzzzzah"</code>
<add> - text: "你的正则表达式应该匹配<code>'Hazzzzah'</code>。"
<ide> testString: assert("Hazzzzzah".match(haRegex)[0].length === 9);
<del> - text: 你的正则表达应该匹配<code>"Hazzzzzzah"</code>
<add> - text: 正则表达式应该匹配 <code>"Hazzzzzzah"</code>
<ide> testString: assert("Hazzzzzzah".match(haRegex)[0].length === 10);
<del> - text: 你的正则表达式应该匹配<code>"Hazzah"</code>和30个<code>z</code> 。
<add> - text: 正则表达式应该匹配 <code>"Hazzah"</code> with 30 <code>z</code>'s in it.
<ide> testString: assert("Hazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzah".match(haRegex)[0].length === 34);
<ide>
<ide> ```
<ide> tests:
<ide> let haStr = "Hazzzzah";
<ide> let haRegex = /change/; // Change this line
<ide> let result = haRegex.test(haStr);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = haRegex.test(haStr);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let haStr = "Hazzzzah";
<add>let haRegex = /Haz{4,}ah/; // Change this line
<add>let result = haRegex.test(haStr);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.chinese.md
<ide> id: 587d7db9367417b2b2512ba5
<ide> title: Specify Upper and Lower Number of Matches
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 指定上下匹配数
<add>forumTopicId: 301367
<add>localeTitle: 指定匹配的上限和下限
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">回想一下,您使用加号<code>+</code>来查找一个或多个字符,使用星号<code>*</code>来查找零个或多个字符。这些很方便,但有时你想要匹配一定范围的模式。您可以使用<code>quantity specifiers</code>模式的下限和上限。数量说明符与大括号( <code>{</code>和<code>}</code> )一起使用。您在大括号之间放置了两个数字 - 用于较低和较高的模式数。例如,为了匹配字母<code>"ah"</code>出现<code>3</code>到<code>5</code>次的字母<code>a</code> ,你的正则表达式将是<code>/a{3,5}h/</code> 。 <blockquote>让A4 =“aaaah”; <br>让A2 =“aah”; <br>令multipleA = / a {3,5} h /; <br> multipleA.test(A4); //返回true <br> multipleA.test(A2); //返回false </blockquote></section>
<add><section id='description'>
<add>回想一下,使用加号<code>+</code>查找一个或多个字符,使用星号<code>*</code>查找零个或多个字符。这些都很方便,但有时需要匹配一定范围的匹配模式。
<add>可以使用<code>数量说明符</code>指定匹配模式的上下限。数量说明符与花括号(<code>{</code>和<code>}</code>)一起使用。可以在花括号之间放两个数字,这两个数字代表匹配模式的上限和下限。
<add>例如,要在字符串<code>"ah"</code>中匹配仅出现<code>3</code>到<code>5</code>次的字母<code>a</code>,正则表达式应为<code>/a{3,5}h/</code>。
<add>
<add>```js
<add>let A4 = "aaaah";
<add>let A2 = "aah";
<add>let multipleA = /a{3,5}h/;
<add>multipleA.test(A4); // Returns true
<add>multipleA.test(A2); // Returns false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改正则表达式<code>ohRegex</code>以匹配单词<code>"Oh no"</code>中的<code>3</code>到<code>6</code>字母<code>h</code> 。 </section>
<add><section id='instructions'>
<add>修改正则表达式<code>ohRegex</code>以匹配在<code>"Oh no"</code>中仅出现<code>3</code>到<code>6</code>次的字母<code>h</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的正则表达式应该使用大括号。
<add> - text: 你的正则表达式应该使用花括号。
<ide> testString: assert(ohRegex.source.match(/{.*?}/).length > 0);
<del> - text: 你的正则表达式不应该匹配<code>"Ohh no"</code>
<add> - text: "你的正则表达式不应该匹配<code>'Ohh no'</code>。"
<ide> testString: assert(!ohRegex.test("Ohh no"));
<del> - text: 你的正则表达式应该匹配<code>"Ohhh no"</code>
<add> - text: "你的正则表达式应该匹配<code>'Ohhh no'</code>。"
<ide> testString: assert("Ohhh no".match(ohRegex)[0].length === 7);
<del> - text: 你的正则表达式应该匹配<code>"Ohhhh no"</code>
<add> - text: 正则表达式应该匹配 <code>"Ohhhh no"</code>。
<ide> testString: assert("Ohhhh no".match(ohRegex)[0].length === 8);
<del> - text: 你的正则表达式应该匹配<code>"Ohhhhh no"</code>
<add> - text: "你的正则表达式应该匹配<code>'Ohhhhh no'</code>。"
<ide> testString: assert("Ohhhhh no".match(ohRegex)[0].length === 9);
<del> - text: 你的正则表达式应该匹配<code>"Ohhhhhh no"</code>
<add> - text: "你的正则表达式应该匹配<code>'Ohhhhhh no'</code>。"
<ide> testString: assert("Ohhhhhh no".match(ohRegex)[0].length === 10);
<del> - text: 你的正则表达式不应该匹配<code>"Ohhhhhhh no"</code>
<add> - text: "你的正则表达式不应该匹配<code>'Ohhhhhhh no'</code>。"
<ide> testString: assert(!ohRegex.test("Ohhhhhhh no"));
<ide>
<ide> ```
<ide> tests:
<ide>
<ide> ## Challenge Seed
<ide> <section id='challengeSeed'>
<del>
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<ide> let ohStr = "Ohhh no";
<ide> let ohRegex = /change/; // Change this line
<ide> let result = ohRegex.test(ohStr);
<del>
<ide> ```
<ide>
<ide> </div>
<del>
<del>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let ohStr = "Ohhh no";
<add>let ohRegex = /Oh{3,6} no/; // Change this line
<add>let result = ohRegex.test(ohStr);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.chinese.md
<ide> id: 587d7dbb367417b2b2512bab
<ide> title: Use Capture Groups to Search and Replace
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用捕获组进行搜索和替换
<add>forumTopicId: 301368
<add>localeTitle: 使用捕获组搜索和替换
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">搜索很有用。但是,当它也更改(或替换)您匹配的文本时,您可以使搜索功能更强大。您可以在字符串上使用<code>.replace()</code>搜索和替换字符串中的文本。 <code>.replace()</code>的输入首先是您要搜索的正则表达式模式。第二个参数是用于替换匹配的字符串或用于执行某些操作的函数。 <blockquote> let wrongText =“天空是银色的。”; <br>让silverRegex = / silver /; <br> wrongText.replace(silverRegex,“blue”); <br> //返回“天空是蓝色的”。 </blockquote>您还可以使用美元符号( <code>$</code> )访问替换字符串中的捕获组。 <blockquote> “Code Camp”.replace(/(\ w +)\ s(\ w +)/,'$ 2 $ 1'); <br> //返回“营地代码” </blockquote></section>
<add><section id='description'>
<add>搜索功能是很有用的。但是,当搜索同时也执行更改(或替换)匹配文本的操作时,搜索功能就会显得更加强大。
<add>可以使用字符串上<code>.replace()</code>方法来搜索并替换字符串中的文本。<code>.replace()</code>的输入首先是想要搜索的正则表达式匹配模式,第二个参数是用于替换匹配的字符串或用于执行某些操作的函数。
<add>
<add>```js
<add>let wrongText = "The sky is silver.";
<add>let silverRegex = /silver/;
<add>wrongText.replace(silverRegex, "blue");
<add>// Returns "The sky is blue."
<add>```
<add>
<add>你还可以使用美元符号(<code>$</code>)访问替换字符串中的捕获组。
<add>
<add>```js
<add>"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');
<add>// Returns "Camp Code"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写一个正则表达式,以便它搜索字符串<code>"good"</code> 。然后更新<code>replaceText</code>变量,将<code>"good"</code>替换为<code>"okey-dokey"</code> 。 </section>
<add><section id='instructions'>
<add>编写一个正则表达式,以搜索字符串<code>"good"</code>。然后更新变量<code>replaceText</code>,用字符串<code>"okey-dokey"</code>替换<code>"good"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您应该使用<code>.replace()</code>来搜索和替换。
<add> - text: 你应该使用<code>.replace()</code>搜索并替换。
<ide> testString: assert(code.match(/\.replace\(.*\)/));
<del> - text: 你的正则表达式应该改变<code>"This sandwich is good."</code> <code>"This sandwich is okey-dokey."</code>
<add> - text: "你的正则表达式应该把<code>'This sandwich is good.'</code>变成<code>'This sandwich is okey-dokey.'</code>。"
<ide> testString: assert(result == "This sandwich is okey-dokey." && replaceText === "okey-dokey");
<ide> - text: 你不应该改变最后一行。
<ide> testString: assert(code.match(/result\s*=\s*huhText\.replace\(.*?\)/));
<ide> let huhText = "This sandwich is good.";
<ide> let fixRegex = /change/; // Change this line
<ide> let replaceText = ""; // Change this line
<ide> let result = huhText.replace(fixRegex, replaceText);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = huhText.replace(fixRegex, replaceText);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let huhText = "This sandwich is good.";
<add>let fixRegex = /good/g; // Change this line
<add>let replaceText = "okey-dokey"; // Change this line
<add>let result = huhText.replace(fixRegex, replaceText);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.chinese.md
<ide> id: 587d7db3367417b2b2512b8e
<ide> title: Using the Test Method
<ide> challengeType: 1
<del>videoUrl: ''
<add>forumTopicId: 301369
<ide> localeTitle: 使用测试方法
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">正则表达式用于编程语言以匹配字符串的一部分。您可以创建模式来帮助您进行匹配。如果你想在字符串<code>"The dog chased the cat"</code>找到单词<code>"the"</code> ,你可以使用以下正则表达式: <code>/the/</code> 。请注意,正则表达式中不需要引号。 JavaScript有多种方法可以使用正则表达式。测试正则表达式的一种方法是使用<code>.test()</code>方法。 <code>.test()</code>方法接受正则表达式,将其应用于字符串(放在括号内),如果模式发现或不存在,则返回<code>true</code>或<code>false</code> 。 <blockquote>让testStr =“freeCodeCamp”; <br>让testRegex = / Code /; <br> testRegex.test(testStr); <br> //返回true </blockquote></section>
<add><section id='description'>
<add>在编程语言中,正则表达式用于匹配指定的字符串。通过正则表达式创建匹配模式(规则)可以帮你完成指定匹配。
<add>如果想要在字符串<code>"The dog chased the cat"</code>中匹配到<code>"the"</code>这个单词,可以使用如下正则表达式:<code>/the/</code>。注意,正则表达式中不需要引号。
<add>JavaScript 中有多种使用正则表达式的方法。测试正则表达式的一种方法是使用<code>.test()</code>方法。<code>.test()</code>方法会把编写的正则表达式和字符串(即括号内的内容)匹配,如果成功匹配到字符,则返回<code>true</code>,反之,返回<code>false</code>。
<add>
<add>```js
<add>let testStr = "freeCodeCamp";
<add>let testRegex = /Code/;
<add>testRegex.test(testStr);
<add>// Returns true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>.test()</code>方法在字符串<code>myString</code>上应用正则表达式<code>myRegex</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>.test()</code>方法,检测字符串<code>myString</code>是否符合正则表达式<code>myRegex</code>定义的规则。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你应该使用<code>.test()</code>来测试正则表达式。
<add> - text: 你应该使用<code>.test()</code>方法来检测正则表达式。
<ide> testString: assert(code.match(/myRegex.test\(\s*myString\s*\)/));
<del> - text: 您的结果应该返回<code>true</code> 。
<add> - text: 你的返回结果应该为<code>true</code>。
<ide> testString: assert(result === true);
<ide>
<ide> ```
<ide> tests:
<ide> let myString = "Hello, World!";
<ide> let myRegex = /Hello/;
<ide> let result = myRegex; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> let result = myRegex; // Change this line
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let myString = "Hello, World!";
<add>let myRegex = /Hello/;
<add>let result = myRegex.test(myString); // Change this line
<ide> ```
<add>
<ide> </section> | 33 |
Python | Python | pass model meta to nlp object in load_model | 08382f21e30ffd38f5905764c01e2ae66787e3d0 | <ide><path>spacy/util.py
<ide> def load_model(name, **overrides):
<ide> model_path = Path(name)
<ide> meta = get_package_meta(model_path)
<ide> cls = get_lang_class(meta['lang'])
<del> nlp = cls(pipeline=meta.get('pipeline', True))
<add> nlp = cls(pipeline=meta.get('pipeline', True), meta=meta)
<ide> return nlp.from_disk(model_path, **overrides)
<ide> elif hasattr(name, 'exists'): # Path or Path-like to model data
<ide> meta = get_package_meta(name)
<ide> cls = get_lang_class(meta['lang'])
<del> nlp = cls(pipeline=meta.get('pipeline', True))
<add> nlp = cls(pipeline=meta.get('pipeline', True), meta=meta)
<ide> return nlp.from_disk(name, **overrides)
<ide> raise IOError("Can't find model '%s'" % name)
<ide>
<ide> def load_model_from_init_py(init_file, **overrides):
<ide> if not model_path.exists():
<ide> raise ValueError("Can't find model directory: %s" % path2str(data_path))
<ide> cls = get_lang_class(meta['lang'])
<del> nlp = cls(pipeline=meta.get('pipeline', True))
<add> nlp = cls(pipeline=meta.get('pipeline', True), meta=meta)
<ide> return nlp.from_disk(data_path, **overrides)
<ide>
<ide>
<ide> def model_from_bytes(model, bytes_data):
<ide> i += 1
<ide> if hasattr(layer, '_layers'):
<ide> queue.extend(layer._layers)
<del>
<add>
<ide>
<ide> def print_table(data, title=None):
<ide> """Print data in table format. | 1 |
PHP | PHP | make encryption optional on iron.io | 726ac155f7e27814058607a2c357fe9e71555b13 | <ide><path>src/Illuminate/Queue/Connectors/IronConnector.php
<ide> public function connect(array $config)
<ide>
<ide> if (isset($config['host'])) $ironConfig['host'] = $config['host'];
<ide>
<del> return new IronQueue(new IronMQ($ironConfig), $this->crypt, $this->request, $config['queue']);
<add> return new IronQueue(new IronMQ($ironConfig), $this->crypt, $this->request, $config['queue'], $config['encrypt']);
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file
<ide><path>src/Illuminate/Queue/IronQueue.php
<ide> class IronQueue extends Queue implements QueueInterface {
<ide> */
<ide> protected $default;
<ide>
<add> /**
<add> * Indicates if the messages should be encrypted.
<add> *
<add> * @var bool
<add> */
<add> protected $shouldEncrypt;
<add>
<ide> /**
<ide> * Create a new IronMQ queue instance.
<ide> *
<ide> * @param \IronMQ $iron
<ide> * @param \Illuminate\Encryption\Encrypter $crypt
<ide> * @param \Illuminate\Http\Request $request
<ide> * @param string $default
<add> * @param bool $shouldEncrypt
<ide> * @return void
<ide> */
<del> public function __construct(IronMQ $iron, Encrypter $crypt, Request $request, $default)
<add> public function __construct(IronMQ $iron, Encrypter $crypt, Request $request, $default, $shouldEncrypt = false)
<ide> {
<ide> $this->iron = $iron;
<ide> $this->crypt = $crypt;
<ide> $this->request = $request;
<ide> $this->default = $default;
<add> $this->shouldEncrypt = $shouldEncrypt;
<ide> }
<ide>
<ide> /**
<ide> public function push($job, $data = '', $queue = null)
<ide> */
<ide> public function pushRaw($payload, $queue = null, array $options = array())
<ide> {
<del> $payload = $this->crypt->encrypt($payload);
<add> if ($this->shouldEncrypt) $payload = $this->crypt->encrypt($payload);
<ide>
<ide> return $this->iron->postMessage($this->getQueue($queue), $payload, $options)->id;
<ide> }
<ide> public function pop($queue = null)
<ide> // queues will be a security hazard to unsuspecting developers using it.
<ide> if ( ! is_null($job))
<ide> {
<del> $job->body = $this->crypt->decrypt($job->body);
<add> $job->body = $this->parseJobBody($job->body);
<ide>
<ide> return new IronJob($this->container, $this, $job);
<ide> }
<ide> protected function marshalPushedJob()
<ide> {
<ide> $r = $this->request;
<ide>
<del> $body = $this->crypt->decrypt($r->getContent());
<add> $body = $this->parseJobBody($r->getContent());
<ide>
<ide> return (object) array(
<ide> 'id' => $r->header('iron-message-id'), 'body' => $body, 'pushed' => true,
<ide> protected function createPayload($job, $data = '', $queue = null)
<ide> return $this->setMeta($payload, 'queue', $this->getQueue($queue));
<ide> }
<ide>
<add> /**
<add> * Parse the job body for firing.
<add> *
<add> * @param string $body
<add> * @return string
<add> */
<add> protected function parseJobBody($body)
<add> {
<add> return $this->shouldEncrypt ? $this->crypt->decrypt($body) : $body;
<add> }
<add>
<ide> /**
<ide> * Get the queue or return the default.
<ide> *
<ide><path>tests/Queue/QueueIronQueueTest.php
<ide> public function tearDown()
<ide>
<ide> public function testPushProperlyPushesJobOntoIron()
<ide> {
<del> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default');
<add> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default', true);
<ide> $crypt->shouldReceive('encrypt')->once()->with(json_encode(array('job' => 'foo', 'data' => array(1, 2, 3), 'attempts' => 1, 'queue' => 'default')))->andReturn('encrypted');
<ide> $iron->shouldReceive('postMessage')->once()->with('default', 'encrypted', array())->andReturn((object) array('id' => 1));
<ide> $queue->push('foo', array(1, 2, 3));
<ide> }
<ide>
<ide>
<del> public function testPushProperlyPushesJobOntoIronWithClosures()
<add> public function testPushProperlyPushesJobOntoIronWithoutEncryption()
<ide> {
<ide> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default');
<add> $crypt->shouldReceive('encrypt')->never();
<add> $iron->shouldReceive('postMessage')->once()->with('default', json_encode(['job' => 'foo', 'data' => [1, 2, 3], 'attempts' => 1, 'queue' => 'default']), array())->andReturn((object) array('id' => 1));
<add> $queue->push('foo', array(1, 2, 3));
<add> }
<add>
<add>
<add> public function testPushProperlyPushesJobOntoIronWithClosures()
<add> {
<add> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default', true);
<ide> $name = 'Foo';
<ide> $closure = new Illuminate\Support\SerializableClosure($innerClosure = function() use ($name) { return $name; });
<ide> $crypt->shouldReceive('encrypt')->once()->with(json_encode(array(
<ide> public function testPushProperlyPushesJobOntoIronWithClosures()
<ide>
<ide> public function testDelayedPushProperlyPushesJobOntoIron()
<ide> {
<del> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default');
<add> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default', true);
<ide> $crypt->shouldReceive('encrypt')->once()->with(json_encode(array(
<ide> 'job' => 'foo', 'data' => array(1, 2, 3), 'attempts' => 1, 'queue' => 'default',
<ide> )))->andReturn('encrypted');
<ide> public function testDelayedPushProperlyPushesJobOntoIron()
<ide> public function testDelayedPushProperlyPushesJobOntoIronWithTimestamp()
<ide> {
<ide> $now = Carbon\Carbon::now();
<del> $queue = $this->getMock('Illuminate\Queue\IronQueue', array('getTime'), array($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default'));
<add> $queue = $this->getMock('Illuminate\Queue\IronQueue', array('getTime'), array($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default', true));
<ide> $queue->expects($this->once())->method('getTime')->will($this->returnValue($now->getTimestamp()));
<ide> $crypt->shouldReceive('encrypt')->once()->with(json_encode(array('job' => 'foo', 'data' => array(1, 2, 3), 'attempts' => 1, 'queue' => 'default')))->andReturn('encrypted');
<ide> $iron->shouldReceive('postMessage')->once()->with('default', 'encrypted', array('delay' => 5))->andReturn((object) array('id' => 1));
<ide> public function testDelayedPushProperlyPushesJobOntoIronWithTimestamp()
<ide>
<ide> public function testPopProperlyPopsJobOffOfIron()
<ide> {
<del> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default');
<add> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default', true);
<ide> $queue->setContainer(m::mock('Illuminate\Container\Container'));
<ide> $iron->shouldReceive('getMessage')->once()->with('default')->andReturn($job = m::mock('IronMQ_Message'));
<ide> $job->body = 'foo';
<ide> public function testPopProperlyPopsJobOffOfIron()
<ide> }
<ide>
<ide>
<add> public function testPopProperlyPopsJobOffOfIronWithoutEncryption()
<add> {
<add> $queue = new Illuminate\Queue\IronQueue($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), m::mock('Illuminate\Http\Request'), 'default');
<add> $queue->setContainer(m::mock('Illuminate\Container\Container'));
<add> $iron->shouldReceive('getMessage')->once()->with('default')->andReturn($job = m::mock('IronMQ_Message'));
<add> $job->body = 'foo';
<add> $crypt->shouldReceive('decrypt')->never();
<add> $result = $queue->pop();
<add>
<add> $this->assertInstanceOf('Illuminate\Queue\Jobs\IronJob', $result);
<add> }
<add>
<add>
<ide> public function testPushedJobsCanBeMarshaled()
<ide> {
<del> $queue = $this->getMock('Illuminate\Queue\IronQueue', array('createPushedIronJob'), array($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), $request = m::mock('Illuminate\Http\Request'), 'default'));
<add> $queue = $this->getMock('Illuminate\Queue\IronQueue', array('createPushedIronJob'), array($iron = m::mock('IronMQ'), $crypt = m::mock('Illuminate\Encryption\Encrypter'), $request = m::mock('Illuminate\Http\Request'), 'default', true));
<ide> $request->shouldReceive('header')->once()->with('iron-message-id')->andReturn('message-id');
<ide> $request->shouldReceive('getContent')->once()->andReturn($content = json_encode(array('foo' => 'bar')));
<ide> $crypt->shouldReceive('decrypt')->once()->with($content)->andReturn($content); | 3 |
Javascript | Javascript | defer reading until listeners could be added | 061342a50075a23e04465e0ac2f33124ab56ea32 | <ide><path>lib/_tls_wrap.js
<ide> function onocspresponse(resp) {
<ide> this.emit('OCSPResponse', resp);
<ide> }
<ide>
<add>function initRead(tls, wrapped) {
<add> // If we were destroyed already don't bother reading
<add> if (!tls._handle)
<add> return;
<add>
<add> // Socket already has some buffered data - emulate receiving it
<add> if (wrapped && wrapped._readableState && wrapped._readableState.length) {
<add> var buf;
<add> while ((buf = wrapped.read()) !== null)
<add> tls._handle.receive(buf);
<add> }
<add>
<add> tls.read(0);
<add>}
<ide>
<ide> /**
<ide> * Provides a wrap of socket stream to do encrypted communication.
<ide> function TLSSocket(socket, options) {
<ide> // starting the flow of the data
<ide> this.readable = true;
<ide> this.writable = true;
<del> this.read(0);
<add>
<add> // Read on next tick so the caller has a chance to setup listeners
<add> process.nextTick(initRead, this, socket);
<ide> }
<ide> util.inherits(TLSSocket, net.Socket);
<ide> exports.TLSSocket = TLSSocket;
<ide> TLSSocket.prototype._init = function(socket, wrap) {
<ide> if (options.handshakeTimeout > 0)
<ide> this.setTimeout(options.handshakeTimeout, this._handleTimeout);
<ide>
<del> // Socket already has some buffered data - emulate receiving it
<del> if (socket && socket._readableState && socket._readableState.length) {
<del> var buf;
<del> while ((buf = socket.read()) !== null)
<del> ssl.receive(buf);
<del> }
<del>
<ide> if (socket instanceof net.Socket) {
<ide> this._parent = socket;
<ide>
<ide><path>test/parallel/test-tls-delayed-attach-error.js
<add>'use strict';
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>if (!common.hasCrypto) {
<add> console.log('1..0 # Skipped: missing crypto');
<add> process.exit();
<add>}
<add>var tls = require('tls');
<add>var fs = require('fs');
<add>var net = require('net');
<add>
<add>var bonkers = new Buffer(1024);
<add>bonkers.fill(42);
<add>
<add>var receivedError = false;
<add>var options = {
<add> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
<add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem')
<add>};
<add>
<add>var server = net.createServer(function(c) {
<add> setTimeout(function() {
<add> var s = new tls.TLSSocket(c, {
<add> isServer: true,
<add> secureContext: tls.createSecureContext(options)
<add> });
<add>
<add> s.on('_tlsError', function() {
<add> receivedError = true;
<add> });
<add>
<add> s.on('close', function() {
<add> server.close();
<add> s.destroy();
<add> });
<add> }, 200);
<add>}).listen(common.PORT, function() {
<add> var c = net.connect({port: common.PORT}, function() {
<add> c.write(bonkers);
<add> });
<add>});
<add>
<add>process.on('exit', function() {
<add> assert.ok(receivedError);
<add>});
<ide><path>test/parallel/test-tls-delayed-attach.js
<ide> var net = require('net');
<ide>
<ide> var sent = 'hello world';
<ide> var received = '';
<del>var ended = 0;
<ide>
<ide> var options = {
<ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
<ide> var server = net.createServer(function(c) {
<ide> });
<ide>
<ide> s.on('end', function() {
<del> ended++;
<ide> server.close();
<ide> s.destroy();
<ide> });
<ide> var server = net.createServer(function(c) {
<ide>
<ide> process.on('exit', function() {
<ide> assert.equal(received, sent);
<del> assert.equal(ended, 1);
<ide> }); | 3 |
Javascript | Javascript | fix events in shadow dom | 60858547ac8e391a845d8b304914b84a5d948d86 | <ide><path>src/helpers/helpers.dom.js
<ide> function _calculatePadding(container, padding, parentDimension) {
<ide> export function getRelativePosition(evt, chart) {
<ide> let mouseX, mouseY;
<ide> const e = evt.originalEvent || evt;
<del> const canvasElement = evt.target || evt.srcElement;
<add> const canvasElement = chart.canvas;
<ide> const boundingRect = canvasElement.getBoundingClientRect();
<ide>
<ide> const touches = e.touches; | 1 |
Text | Text | add test for file metadata project | f132f5157c8cf7c197699e14f4e3dccaaffb20ee | <ide><path>curriculum/challenges/english/05-apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice.english.md
<ide> forumTopicId: 301506
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Build a full stack JavaScript app that is functionally similar to this: <a href='https://file-metadata.freecodecamp.repl.co/' target='_blank'>https://file-metadata.freecodecamp.repl.co/</a>.
<ide> Working on this project will involve you writing your code on Repl.it on our starter project. After completing this project you can copy your public Repl.it URL (to the homepage of your app) into this screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.
<ide> Start this project on Repl.it using <a href='https://repl.it/github/freeCodeCamp/boilerplate-project-filemetadata' target='_blank'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-project-filemetadata/'>this repository</a> on GitHub! If you use Repl.it, remember to save the link to your project somewhere safe!
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide>
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<add> - text: I can provide my own project, not the example URL.
<add> testString: "getUserInput => {
<add> assert(!(new RegExp('.*/file-metadata.freecodecamp.repl.co')).test(getUserInput('url')));
<add> }"
<ide> - text: I can submit a form that includes a file upload.
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const site = await fetch(getUserInput('url'));
<add> const data = await site.text();
<add> const doc = new DOMParser().parseFromString(data, 'text/html');
<add> assert(doc.querySelector('input[type=\"file\"]'));
<add> }"
<ide> - text: The form file input field has the <code>name</code> attribute set to <code>upfile</code>.
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const site = await fetch(getUserInput('url'));
<add> const data = await site.text();
<add> const doc = new DOMParser().parseFromString(data, 'text/html');
<add> assert(doc.querySelector('input[name=\"upfile\"]'));
<add> }"
<ide> - text: When I submit something, I will receive the file <code>name</code>, <code>type</code>, and <code>size</code> in bytes within the JSON response.
<del> testString: ''
<add> testString: "async getUserInput => {
<add> const formData = new FormData();
<add> const fileData = await fetch('https://cdn.freecodecamp.org/weather-icons/01d.png');
<add> const file = await fileData.blob();
<add> formData.append('upfile', file, 'icon');
<add> const data = await fetch(getUserInput('url') + '/api/fileanalyse', {
<add> method: 'POST', body: formData
<add> });
<add> const parsed = await data.json();
<add> assert.property(parsed, 'size');
<add> assert.equal(parsed.name, 'icon');
<add> assert.equal(parsed.type, 'image/png');
<add> }"
<ide>
<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 | 1 |
Text | Text | add `map` function to haskell section | b4b3344cb3a70261dc3d7a1598933e2cc1ad507a | <ide><path>guide/english/haskell/map/index.md
<add>---
<add>title: map function
<add>---
<add>
<add>## `map` function
<add>
<add>The `map` function is a built-in haskell's function that maps a function to each element of a list and return a new list
<add>with the result. Graphically, it would look like this.
<add>```haskell
<add>map f [1,2,3,4]
<add>-- [f 1, f 2, f 3, f 4]
<add>```
<add>
<add>## Signature of `map`
<add>
<add>The signature of the map function is as follows
<add>```haskell
<add>map :: (a -> b) -> [a] -> [b]
<add>```
<add>
<add>## Examples
<add>```haskell
<add>map succ [1..5]
<add>-- [2,3,4,5,6]
<add>
<add>let sample = [(1, 2), (3, 1), (4, 10)]
<add>map fst sample
<add>-- [1,3,4]
<add>
<add>map snd sample
<add>-- [2,1,10]
<add>
<add>import Data.Char (toLower) # to get the toLower
<add>map toLower "HELLO WORLD HASKELL RULEZ!"
<add>-- "hello world haskell rulez!"
<add>``` | 1 |
Javascript | Javascript | update success message for all challenges | 2981d776c7b8d58c0f17cc65c2c3dd1301c283f1 | <ide><path>client/src/templates/Challenges/classic/Show.js
<ide> import MobileLayout from './MobileLayout';
<ide> import DesktopLayout from './DesktopLayout';
<ide> import ToolPanel from '../components/Tool-Panel';
<ide>
<del>import { randomCompliment } from '../utils/get-words';
<ide> import { createGuideUrl } from '../utils';
<ide> import { challengeTypes } from '../../../../utils/challengeTypes';
<ide> import { ChallengeNode } from '../../../redux/propTypes';
<ide> import {
<ide> initTests,
<ide> updateChallengeMeta,
<ide> challengeMounted,
<del> updateSuccessMessage,
<ide> consoleOutputSelector
<ide> } from '../redux';
<ide>
<ide> const mapDispatchToProps = dispatch =>
<ide> createFiles,
<ide> initTests,
<ide> updateChallengeMeta,
<del> challengeMounted,
<del> updateSuccessMessage
<add> challengeMounted
<ide> },
<ide> dispatch
<ide> );
<ide> const propTypes = {
<ide> testString: PropTypes.string
<ide> })
<ide> ),
<del> updateChallengeMeta: PropTypes.func.isRequired,
<del> updateSuccessMessage: PropTypes.func.isRequired
<add> updateChallengeMeta: PropTypes.func.isRequired
<ide> };
<ide>
<ide> const MAX_MOBILE_WIDTH = 767;
<ide> class ShowClassic extends Component {
<ide> createFiles,
<ide> initTests,
<ide> updateChallengeMeta,
<del> updateSuccessMessage,
<ide> data: {
<ide> challengeNode: {
<ide> files,
<ide> class ShowClassic extends Component {
<ide> createFiles(files);
<ide> initTests(tests);
<ide> updateChallengeMeta({ ...challengeMeta, title, challengeType });
<del> updateSuccessMessage(randomCompliment());
<ide> challengeMounted(challengeMeta.id);
<ide> }
<ide>
<ide> class ShowClassic extends Component {
<ide> createFiles,
<ide> initTests,
<ide> updateChallengeMeta,
<del> updateSuccessMessage,
<ide> data: {
<ide> challengeNode: {
<ide> files,
<ide> class ShowClassic extends Component {
<ide> pageContext: { challengeMeta }
<ide> } = this.props;
<ide> if (prevTitle !== currentTitle) {
<del> updateSuccessMessage(randomCompliment());
<ide> createFiles(files);
<ide> initTests(tests);
<ide> updateChallengeMeta({
<ide><path>client/src/templates/Challenges/project/Show.js
<ide> import { bindActionCreators } from 'redux';
<ide> import { graphql } from 'gatsby';
<ide> import Helmet from 'react-helmet';
<ide>
<del>import { randomCompliment } from '../utils/get-words';
<ide> import { ChallengeNode } from '../../../redux/propTypes';
<ide> import {
<ide> challengeMounted,
<ide> updateChallengeMeta,
<del> updateSuccessMessage,
<ide> openModal,
<ide> updateProjectFormValues
<ide> } from '../redux';
<ide> const mapDispatchToProps = dispatch =>
<ide> updateChallengeMeta,
<ide> challengeMounted,
<ide> updateProjectFormValues,
<del> updateSuccessMessage,
<ide> openCompletionModal: () => openModal('completion')
<ide> },
<ide> dispatch
<ide> const propTypes = {
<ide> challengeMeta: PropTypes.object
<ide> }),
<ide> updateChallengeMeta: PropTypes.func.isRequired,
<del> updateProjectFormValues: PropTypes.func.isRequired,
<del> updateSuccessMessage: PropTypes.func.isRequired
<add> updateProjectFormValues: PropTypes.func.isRequired
<ide> };
<ide>
<ide> export class Project extends Component {
<ide> export class Project extends Component {
<ide> challengeNode: { title, challengeType }
<ide> },
<ide> pageContext: { challengeMeta },
<del> updateChallengeMeta,
<del> updateSuccessMessage
<add> updateChallengeMeta
<ide> } = this.props;
<del> updateSuccessMessage(randomCompliment());
<ide> updateChallengeMeta({ ...challengeMeta, title, challengeType });
<ide> challengeMounted(challengeMeta.id);
<ide> }
<ide> export class Project extends Component {
<ide> challengeNode: { title: currentTitle, challengeType }
<ide> },
<ide> pageContext: { challengeMeta },
<del> updateChallengeMeta,
<del> updateSuccessMessage
<add> updateChallengeMeta
<ide> } = this.props;
<del> updateSuccessMessage(randomCompliment());
<ide> if (prevTitle !== currentTitle) {
<ide> updateChallengeMeta({
<ide> ...challengeMeta,
<ide><path>client/src/templates/Challenges/redux/current-challenge-saga.js
<ide> import {
<ide>
<ide> import { post } from '../../../utils/ajax';
<ide>
<add>import { randomCompliment } from '../utils/get-words';
<add>import { updateSuccessMessage } from './';
<add>
<ide> function* currentChallengeSaga({ payload }) {
<ide> const isSignedIn = yield select(isSignedInSelector);
<ide> const currentChallengeId = yield select(currentChallengeIdSelector);
<ide> function* currentChallengeSaga({ payload }) {
<ide> }
<ide> }
<ide>
<add>function* updateSuccessMessageSaga() {
<add> yield put(updateSuccessMessage(randomCompliment()));
<add>}
<add>
<ide> export function createCurrentChallengeSaga(types) {
<ide> return [
<del> takeEvery(types.challengeMounted, currentChallengeSaga)
<add> takeEvery(types.challengeMounted, currentChallengeSaga),
<add> takeEvery(types.challengeMounted, updateSuccessMessageSaga)
<ide> ];
<ide> } | 3 |
Javascript | Javascript | remove old manifest file on request in dev | e3ac50a0d59c5540176478f05c6eb386032aa7bc | <ide><path>server/middlewares/revision-helpers.js
<ide> import manifest from '../rev-manifest.json';
<ide>
<ide> const __DEV__ = process.env.NODE_ENV === 'development';
<add>const manifestPath = '../rev-manifest.json';
<add>
<ide> export default function({ globalPrepend = '' } = {}) {
<ide>
<ide> function rev(manifest, scopedPrepend, asset) {
<ide> export default function({ globalPrepend = '' } = {}) {
<ide> // this means we do not need to restart server on every change to
<ide> // client code
<ide> if (__DEV__) {
<del> const manifest = require('../rev-manifest.json');
<add> // we first need to remove the manifest from require cache
<add> delete require.cache[require.resolve(manifestPath)];
<add> // and re-require
<add> const manifest = require(manifestPath);
<ide> res.locals.rev = rev.bind(null, manifest);
<ide> return next();
<ide> } | 1 |
Javascript | Javascript | ensure readfile[sync] reads from the beginning" | 66f09be74399b61a433a58dfe48c6fd5b9d66594 | <ide><path>lib/fs.js
<ide> ReadFileContext.prototype.read = function() {
<ide> req.oncomplete = readFileAfterRead;
<ide> req.context = this;
<ide>
<del> binding.read(this.fd, buffer, offset, length, this.pos, req);
<add> binding.read(this.fd, buffer, offset, length, -1, req);
<ide> };
<ide>
<ide> ReadFileContext.prototype.close = function(err) {
<ide> function tryCreateBuffer(size, fd, isUserFd) {
<ide> return buffer;
<ide> }
<ide>
<del>function tryReadSync(fd, isUserFd, buffer, pos, len, offset) {
<add>function tryReadSync(fd, isUserFd, buffer, pos, len) {
<ide> var threw = true;
<ide> var bytesRead;
<ide> try {
<del> bytesRead = fs.readSync(fd, buffer, pos, len, offset);
<add> bytesRead = fs.readSync(fd, buffer, pos, len);
<ide> threw = false;
<ide> } finally {
<ide> if (threw && !isUserFd) fs.closeSync(fd);
<ide> fs.readFileSync = function(path, options) {
<ide>
<ide> if (size !== 0) {
<ide> do {
<del> bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos, pos);
<add> bytesRead = tryReadSync(fd, isUserFd, buffer, pos, size - pos);
<ide> pos += bytesRead;
<ide> } while (bytesRead !== 0 && pos < size);
<ide> } else {
<ide> do {
<ide> // the kernel lies about many files.
<ide> // Go ahead and try to read some bytes.
<ide> buffer = Buffer.allocUnsafe(8192);
<del> bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192, pos);
<add> bytesRead = tryReadSync(fd, isUserFd, buffer, 0, 8192);
<ide> if (bytesRead !== 0) {
<ide> buffers.push(buffer.slice(0, bytesRead));
<ide> }
<ide><path>test/parallel/test-fs-readfile-fd-offset.js
<del>'use strict';
<del>const common = require('../common');
<del>const assert = require('assert');
<del>const fs = require('fs');
<del>const path = require('path');
<del>
<del>const filename = path.join(common.tmpDir, 'readfile.txt');
<del>const dataExpected = 'a'.repeat(100);
<del>fs.writeFileSync(filename, dataExpected);
<del>const fileLength = dataExpected.length;
<del>
<del>['r', 'a+'].forEach((mode) => {
<del> const fd = fs.openSync(filename, mode);
<del> assert.strictEqual(fs.readFileSync(fd).length, fileLength);
<del>
<del> // Reading again should result in the same length.
<del> assert.strictEqual(fs.readFileSync(fd).length, fileLength);
<del>
<del> fs.readFile(fd, common.mustCall((err, buf) => {
<del> assert.ifError(err);
<del> assert.strictEqual(buf.length, fileLength);
<del> }));
<del>}); | 2 |
Ruby | Ruby | add tests to document current pruning behavior | 8430307fa5c3e5c4699b1363da5c38ab3ef23822 | <ide><path>Library/Homebrew/test/test_cleaner.rb
<ide> def test_clean_file
<ide> assert_equal 0100444, (@f.lib/'i386.dylib').stat.mode
<ide> end
<ide>
<add> def test_prunes_empty_directories
<add> subdir = @f.bin/'subdir'
<add> subdir.mkpath
<add>
<add> Cleaner.new @f
<add>
<add> assert [email protected]?
<add> assert !subdir.directory?
<add> end
<add>
<add> def test_skip_clean_empty_directory
<add> @f.class.skip_clean 'bin'
<add> @f.bin.mkpath
<add>
<add> Cleaner.new @f
<add>
<add> assert @f.bin.directory?
<add> end
<add>
<add> def test_skip_clean_directory_with_empty_subdir
<add> @f.class.skip_clean 'bin'
<add> subdir = @f.bin/'subdir'
<add> subdir.mkpath
<add>
<add> Cleaner.new @f
<add>
<add> assert @f.bin.directory?
<add> assert subdir.directory?
<add> end
<add>
<ide> def test_fails_to_remove_symlink_when_target_was_pruned_first
<ide> mkpath @f.prefix/'b'
<ide> ln_s 'b', @f.prefix/'a' | 1 |
Ruby | Ruby | fix indentation manually | d8fca795758036e7522591acc99f202f84cad2fe | <ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_bootsnap
<ide> assert_match(/require 'bootsnap\/setup'/, content)
<ide> end
<ide> else
<del> assert_file "Gemfile" do |content|
<add> assert_file "Gemfile" do |content|
<ide> assert_no_match(/bootsnap/, content)
<ide> end
<ide> assert_file "config/boot.rb" do |content| | 1 |
Text | Text | fix quickstart urls module name. closes #902 | 8d4bcb4b4c837f9deb5f81d7af6a397405aa07fa | <ide><path>docs/tutorial/quickstart.md
<ide> We can easily break these down into individual views if we need to, but using vi
<ide>
<ide> ## URLs
<ide>
<del>Okay, now let's wire up the API URLs. On to `quickstart/urls.py`...
<add>Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
<ide>
<ide> from django.conf.urls import patterns, url, include
<ide> from rest_framework import routers | 1 |
Javascript | Javascript | extract timeoutpromise into async-spec-helpers | 87d684132c55b8d7f3d7756680deb87af048917b | <ide><path>spec/async-spec-helpers.js
<ide> export function conditionPromise (condition) {
<ide> })
<ide> }
<ide>
<add>export function timeoutPromise (timeout) {
<add> return new Promise(function (resolve) {
<add> global.setTimeout(resolve, timeout)
<add> })
<add>}
<add>
<ide> function waitsForPromise (fn) {
<ide> const promise = fn()
<ide> // This timeout is 3 minutes. We need to bump it back down once we fix
<ide><path>spec/main-process/atom-application.test.js
<ide> import fs from 'fs-plus'
<ide> import path from 'path'
<ide> import AtomApplication from '../../src/main-process/atom-application'
<ide> import parseCommandLine from '../../src/main-process/parse-command-line'
<add>import {timeoutPromise} from '../async-spec-helpers'
<ide>
<ide> const ATOM_RESOURCE_PATH = path.resolve(__dirname, '..', '..')
<ide>
<ide> describe('AtomApplication', function () {
<ide> await window1.loadedPromise
<ide>
<ide> // wait a bit just to make sure we don't pass due to querying the render process before it loads
<del> await getTimeoutPromise(1000)
<add> await timeoutPromise(1000)
<ide>
<ide> const itemCount = await evalInWebContents(window1.browserWindow.webContents, function (sendBackToMainProcess) {
<ide> sendBackToMainProcess(atom.workspace.getActivePane().getItems().length)
<ide> describe('AtomApplication', function () {
<ide> })
<ide> }
<ide>
<del> function getTimeoutPromise (timeout) {
<del> return new Promise(function (resolve) {
<del> global.setTimeout(resolve, timeout)
<del> })
<del> }
<del>
<ide> function clearElectronSession () {
<ide> return new Promise(function (resolve) {
<ide> electron.session.defaultSession.clearStorageData(function () {
<ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', function () {
<ide> }
<ide> }
<ide>
<del> function timeoutPromise (timeout) {
<del> return new Promise(function (resolve) {
<del> window.setTimeout(resolve, timeout)
<del> })
<del> }
<del>
<ide> function nextAnimationFramePromise () {
<ide> return new Promise(function (resolve) {
<ide> window.requestAnimationFrame(resolve) | 3 |
Python | Python | update description of sep in fromstring | 069362a4eec5d7189a67e857351d377f7b3da761 | <ide><path>numpy/core/_add_newdocs.py
<ide> elements is also ignored.
<ide>
<ide> .. deprecated:: 1.14
<del> If this argument is not provided, `fromstring` falls back on the
<del> behaviour of `frombuffer` after encoding unicode string inputs as
<del> either utf-8 (python 3), or the default encoding (python 2).
<add> Passing ``sep=''``, the default, is deprecated since it will
<add> trigger the deprecated binary mode of this function. This mode
<add> interprets `string` as binary bytes, rather than ASCII text with
<add> decimal numbers, an operation which is better spelt
<add> ``frombuffer(string, dtype, count)``. If `string` contains unicode
<add> text, the binary mode of `fromstring` will first encode it into
<add> bytes using either utf-8 (python 3) or the default encoding
<add> (python 2), neither of which produce sane results.
<ide>
<ide> Returns
<ide> ------- | 1 |
Python | Python | remove trailing commas | 51ab7b35af66715d3b29f8c97642e09959dc7f56 | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def GiB(value):
<ide> 'extra': {
<ide> 'cpu': 128
<ide> }
<del> },
<add> }
<ide> }
<ide>
<ide> # From <https://aws.amazon.com/marketplace/help/200777880>
<ide> def GiB(value):
<ide> 't2.small',
<ide> 't2.medium',
<ide> 't2.large',
<del> 'x1.32xlarge',
<add> 'x1.32xlarge'
<ide> ]
<ide> },
<ide> # Asia Pacific (Tokyo) Region | 1 |
Text | Text | deprecate private http properties | 86996c5838f7ee38e3cc96b3c65c8ca6965a36a2 | <ide><path>doc/api/deprecations.md
<ide> The `NODE_REPL_MODE` environment variable is used to set the underlying
<ide> `replMode` of an interactive `node` session. Its default value, `magic`, is
<ide> similarly deprecated in favor of `sloppy`.
<ide>
<add><a id="DEP0066"></a>
<add>### DEP0066: outgoingMessage.\_headers, outgoingMessage.\_headerNames
<add>
<add>Type: Documentation-only
<add>
<add>The `http` module `outgoingMessage._headers` and `outgoingMessage._headerNames`
<add>properties have been deprecated. Please instead use one of the public methods
<add>(e.g. `outgoingMessage.getHeader()`, `outgoingMessage.getHeaders()`,
<add>`outgoingMessage.getHeaderNames()`, `outgoingMessage.hasHeader()`,
<add>`outgoingMessage.removeHeader()`, `outgoingMessage.setHeader()`) for working
<add>with outgoing headers.
<add>
<add>*Note*: `outgoingMessage._headers` and `outgoingMessage._headerNames` were never
<add>documented as officially supported properties.
<add>
<add><a id="DEP0067"></a>
<add>### DEP0067: OutgoingMessage.prototype.\_renderHeaders
<add>
<add>Type: Documentation-only
<add>
<add>The `http` module `OutgoingMessage.prototype._renderHeaders()` API has been
<add>deprecated.
<add>
<add>*Note*: `OutgoingMessage.prototype._renderHeaders` was never documented as
<add>an officially supported API.
<add>
<ide> [alloc]: buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding
<ide> [alloc_unsafe_size]: buffer.html#buffer_class_method_buffer_allocunsafe_size
<ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size | 1 |
Java | Java | drop introspector.flushfromcaches calls completely | defc1d31574ea6b3faa5ed84c4aa23c808b0c7cf | <ide><path>spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java
<ide> private CachedIntrospectionResults(Class<?> beanClass) throws BeansException {
<ide> }
<ide> this.beanInfo = beanInfo;
<ide>
<del> // Only bother with flushFromCaches if the Introspector actually cached...
<del> if (!shouldIntrospectorIgnoreBeaninfoClasses) {
<del> // Immediately remove class from Introspector cache, to allow for proper
<del> // garbage collection on class loader shutdown - we cache it here anyway,
<del> // in a GC-friendly manner. In contrast to CachedIntrospectionResults,
<del> // Introspector does not use WeakReferences as values of its WeakHashMap!
<del> Class<?> classToFlush = beanClass;
<del> do {
<del> Introspector.flushFromCaches(classToFlush);
<del> classToFlush = classToFlush.getSuperclass();
<del> }
<del> while (classToFlush != null);
<del> }
<del>
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
<ide> } | 1 |
Ruby | Ruby | compare checksums case-insensitively | 5ab0488918c4df609dda69b6affa17023274d9b9 | <ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def fetch
<ide> the_tarball, _ = f.fetch
<ide> next unless the_tarball.kind_of? Pathname
<ide>
<del> previous_md5 = f.instance_variable_get(:@md5)
<del> previous_sha1 = f.instance_variable_get(:@sha1)
<del> previous_sha2 = f.instance_variable_get(:@sha256)
<add> previous_md5 = f.instance_variable_get(:@md5).to_s.downcase
<add> previous_sha1 = f.instance_variable_get(:@sha1).to_s.downcase
<add> previous_sha2 = f.instance_variable_get(:@sha256).to_s.downcase
<ide>
<ide> puts "MD5: #{the_tarball.md5}"
<ide> puts "SHA1: #{the_tarball.sha1}"
<ide> puts "SHA256: #{the_tarball.sha2}"
<ide>
<del> unless previous_md5.nil? or previous_md5.empty? or the_tarball.md5 == previous_md5
<add> unless previous_md5.nil? or previous_md5.empty? or the_tarball.md5 == previous_md5
<ide> opoo "Formula reports different MD5: #{previous_md5}"
<ide> end
<ide> unless previous_sha1.nil? or previous_sha1.empty? or the_tarball.sha1 == previous_sha1
<ide> opoo "Formula reports different SHA1: #{previous_sha1}"
<ide> end
<del> unless previous_sha2.nil? or previous_sha2.empty? or the_tarball.sha2 == previous_sha2
<add> unless previous_sha2.nil? or previous_sha2.empty? or the_tarball.sha2 == previous_sha2
<ide> opoo "Formula reports different SHA256: #{previous_sha2}"
<ide> end
<ide> end | 1 |
Javascript | Javascript | add support for array-like objects | f467dc3dd5fe0a046f91488bd92d1098855aaf1b | <ide><path>src/ng/filter/limitTo.js
<ide> * @kind function
<ide> *
<ide> * @description
<del> * Creates a new array or string containing only a specified number of elements. The elements
<del> * are taken from either the beginning or the end of the source array, string or number, as specified by
<del> * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
<del> * converted to a string.
<add> * Creates a new array or string containing only a specified number of elements. The elements are
<add> * taken from either the beginning or the end of the source array, string or number, as specified by
<add> * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
<add> * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
<add> * it is converted to a string.
<ide> *
<del> * @param {Array|string|number} input Source array, string or number to be limited.
<del> * @param {string|number} limit The length of the returned array or string. If the `limit` number
<add> * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
<add> * @param {string|number} limit - The length of the returned array or string. If the `limit` number
<ide> * is positive, `limit` number of items from the beginning of the source array/string are copied.
<ide> * If the number is negative, `limit` number of items from the end of the source array/string
<ide> * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
<ide> * the input will be returned unchanged.
<del> * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
<del> * indicates an offset from the end of `input`. Defaults to `0`.
<del> * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
<del> * had less than `limit` elements.
<add> * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
<add> * `begin` indicates an offset from the end of `input`. Defaults to `0`.
<add> * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
<add> * less than `limit` elements.
<ide> *
<ide> * @example
<ide> <example module="limitToExample">
<ide> function limitToFilter() {
<ide> if (isNaN(limit)) return input;
<ide>
<ide> if (isNumber(input)) input = input.toString();
<del> if (!isArray(input) && !isString(input)) return input;
<add> if (!isArrayLike(input)) return input;
<ide>
<ide> begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
<ide> begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
<ide>
<ide> if (limit >= 0) {
<del> return input.slice(begin, begin + limit);
<add> return sliceFn(input, begin, begin + limit);
<ide> } else {
<ide> if (begin === 0) {
<del> return input.slice(limit, input.length);
<add> return sliceFn(input, limit, input.length);
<ide> } else {
<del> return input.slice(Math.max(0, begin + limit), begin);
<add> return sliceFn(input, Math.max(0, begin + limit), begin);
<ide> }
<ide> }
<ide> };
<ide> }
<add>
<add>function sliceFn(input, begin, end) {
<add> if (isString(input)) return input.slice(begin, end);
<add>
<add> return slice.call(input, begin, end);
<add>}
<ide><path>test/ng/filter/limitToSpec.js
<ide> describe('Filter: limitTo', function() {
<ide> var items;
<ide> var str;
<ide> var number;
<add> var arrayLike;
<ide> var limitTo;
<ide>
<ide> beforeEach(inject(function($filter) {
<ide> items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
<ide> str = "tuvwxyz";
<ide> number = 100.045;
<add> arrayLike = {
<add> 0: 'a',
<add> 1: 'b',
<add> 2: 'c',
<add> 3: 'd',
<add> 4: 'e',
<add> 5: 'f',
<add> 6: 'g',
<add> 7: 'h',
<add> get length() {
<add> return Object.keys(this).length - 1;
<add> }
<add> };
<ide> limitTo = $filter('limitTo');
<ide> }));
<ide>
<ide> describe('Filter: limitTo', function() {
<ide> expect(limitTo(str, '3')).toEqual("tuv");
<ide> expect(limitTo(number, 3)).toEqual("100");
<ide> expect(limitTo(number, '3')).toEqual("100");
<add> expect(limitTo(arrayLike, 3)).toEqual(['a', 'b', 'c']);
<add> expect(limitTo(arrayLike, '3')).toEqual(['a', 'b', 'c']);
<ide> });
<ide>
<ide> it('should return the first X items beginning from index Y when X and Y are positive', function() {
<ide> expect(limitTo(items, 3, '3')).toEqual(['d', 'e', 'f']);
<ide> expect(limitTo(items, '3', 3)).toEqual(['d', 'e', 'f']);
<ide> expect(limitTo(str, 3, 3)).toEqual("wxy");
<ide> expect(limitTo(str, '3', '3')).toEqual("wxy");
<add> expect(limitTo(arrayLike, 3, 3)).toEqual(['d', 'e', 'f']);
<add> expect(limitTo(arrayLike, '3', '3')).toEqual(['d', 'e', 'f']);
<ide> });
<ide>
<ide> it('should return the first X items beginning from index Y when X is positive and Y is negative', function() {
<ide> expect(limitTo(items, 3, '-3')).toEqual(['f', 'g', 'h']);
<ide> expect(limitTo(items, '3', -3)).toEqual(['f', 'g', 'h']);
<ide> expect(limitTo(str, 3, -3)).toEqual("xyz");
<ide> expect(limitTo(str, '3', '-3')).toEqual("xyz");
<add> expect(limitTo(arrayLike, 3, '-3')).toEqual(['f', 'g', 'h']);
<add> expect(limitTo(arrayLike, '3', -3)).toEqual(['f', 'g', 'h']);
<ide> });
<ide>
<ide> it('should return the last X items when X is negative', function() {
<ide> describe('Filter: limitTo', function() {
<ide> expect(limitTo(str, '-3')).toEqual("xyz");
<ide> expect(limitTo(number, -3)).toEqual("045");
<ide> expect(limitTo(number, '-3')).toEqual("045");
<add> expect(limitTo(arrayLike, -3)).toEqual(['f', 'g', 'h']);
<add> expect(limitTo(arrayLike, '-3')).toEqual(['f', 'g', 'h']);
<ide> });
<ide>
<ide> it('should return the last X items until index Y when X and Y are negative', function() {
<ide> expect(limitTo(items, -3, '-3')).toEqual(['c', 'd', 'e']);
<ide> expect(limitTo(items, '-3', -3)).toEqual(['c', 'd', 'e']);
<ide> expect(limitTo(str, -3, -3)).toEqual("uvw");
<ide> expect(limitTo(str, '-3', '-3')).toEqual("uvw");
<add> expect(limitTo(arrayLike, -3, '-3')).toEqual(['c', 'd', 'e']);
<add> expect(limitTo(arrayLike, '-3', -3)).toEqual(['c', 'd', 'e']);
<ide> });
<ide>
<ide> it('should return the last X items until index Y when X is negative and Y is positive', function() {
<ide> expect(limitTo(items, -3, '4')).toEqual(['b', 'c', 'd']);
<ide> expect(limitTo(items, '-3', 4)).toEqual(['b', 'c', 'd']);
<ide> expect(limitTo(str, -3, 4)).toEqual("uvw");
<ide> expect(limitTo(str, '-3', '4')).toEqual("uvw");
<add> expect(limitTo(arrayLike, -3, '4')).toEqual(['b', 'c', 'd']);
<add> expect(limitTo(arrayLike, '-3', 4)).toEqual(['b', 'c', 'd']);
<ide> });
<ide>
<ide> it('should return an empty array when X = 0', function() {
<ide> expect(limitTo(items, 0)).toEqual([]);
<ide> expect(limitTo(items, '0')).toEqual([]);
<add> expect(limitTo(arrayLike, 0)).toEqual([]);
<add> expect(limitTo(arrayLike, '0')).toEqual([]);
<ide> });
<ide>
<ide> it('should return entire array when X cannot be parsed', function() {
<del> expect(limitTo(items, 'bogus')).toEqual(items);
<del> expect(limitTo(items, 'null')).toEqual(items);
<del> expect(limitTo(items, 'undefined')).toEqual(items);
<del> expect(limitTo(items, null)).toEqual(items);
<del> expect(limitTo(items, undefined)).toEqual(items);
<add> expect(limitTo(items, 'bogus')).toBe(items);
<add> expect(limitTo(items, 'null')).toBe(items);
<add> expect(limitTo(items, 'undefined')).toBe(items);
<add> expect(limitTo(items, null)).toBe(items);
<add> expect(limitTo(items, undefined)).toBe(items);
<add> expect(limitTo(arrayLike, 'bogus')).toBe(arrayLike);
<add> expect(limitTo(arrayLike, 'null')).toBe(arrayLike);
<add> expect(limitTo(arrayLike, 'undefined')).toBe(arrayLike);
<add> expect(limitTo(arrayLike, null)).toBe(arrayLike);
<add> expect(limitTo(arrayLike, undefined)).toBe(arrayLike);
<ide> });
<ide>
<ide> it('should return an empty string when X = 0', function() {
<ide> describe('Filter: limitTo', function() {
<ide> expect(limitTo(str, '3', 'undefined')).toEqual(limitTo(str, '3'));
<ide> expect(limitTo(str, '-3', null)).toEqual(limitTo(str, '-3', 0));
<ide> expect(limitTo(str, 3, undefined)).toEqual(limitTo(str, 3));
<add> expect(limitTo(arrayLike, 3, 'bogus')).toEqual(limitTo(arrayLike, 3, 0));
<add> expect(limitTo(arrayLike, -3, 'null')).toEqual(limitTo(arrayLike, -3));
<add> expect(limitTo(arrayLike, '3', 'undefined')).toEqual(limitTo(arrayLike, '3', 0));
<add> expect(limitTo(arrayLike, '-3', null)).toEqual(limitTo(arrayLike, '-3'));
<add> expect(limitTo(arrayLike, 3, undefined)).toEqual(limitTo(arrayLike, 3, 0));
<ide> });
<ide>
<del> it('should return input if not String or Array or Number', function() {
<add> it('should return input if not array-like or Number', function() {
<ide> expect(limitTo(null, 1)).toEqual(null);
<ide> expect(limitTo(undefined, 1)).toEqual(undefined);
<ide> expect(limitTo({}, 1)).toEqual({});
<ide> describe('Filter: limitTo', function() {
<ide> expect(limitTo(items, '9')).toEqual(items);
<ide> expect(limitTo(items, -9)).toEqual(items);
<ide> expect(limitTo(items, '-9')).toEqual(items);
<add> expect(limitTo(arrayLike, 9)).toEqual(items);
<add> expect(limitTo(arrayLike, '9')).toEqual(items);
<add> expect(limitTo(arrayLike, -9)).toEqual(items);
<add> expect(limitTo(arrayLike, '-9')).toEqual(items);
<ide>
<ide> expect(limitTo(items, 9)).not.toBe(items);
<add> expect(limitTo(arrayLike, 9)).not.toBe(arrayLike);
<ide> });
<ide>
<ide> it('should return the entire string if X exceeds input length', function() {
<ide> describe('Filter: limitTo', function() {
<ide> expect(limitTo(items, 'Infinity')).toEqual(items);
<ide> expect(limitTo(items, -Infinity)).toEqual(items);
<ide> expect(limitTo(items, '-Infinity')).toEqual(items);
<add> expect(limitTo(arrayLike, Infinity)).toEqual(items);
<add> expect(limitTo(arrayLike, 'Infinity')).toEqual(items);
<add> expect(limitTo(arrayLike, -Infinity)).toEqual(items);
<add> expect(limitTo(arrayLike, '-Infinity')).toEqual(items);
<ide> });
<ide>
<ide> it('should return the entire string when limited by Infinity', function() {
<ide> describe('Filter: limitTo', function() {
<ide> it('should return an empty array if Y exceeds input length', function() {
<ide> expect(limitTo(items, '3', 12)).toEqual([]);
<ide> expect(limitTo(items, -3, '12')).toEqual([]);
<add> expect(limitTo(arrayLike, '3', 12)).toEqual([]);
<add> expect(limitTo(arrayLike, -3, '12')).toEqual([]);
<ide> });
<ide>
<ide> it('should return an empty string if Y exceeds input length', function() {
<ide> describe('Filter: limitTo', function() {
<ide> expect(limitTo(items, '-4', -12)).toEqual(['e', 'f', 'g', 'h']);
<ide> expect(limitTo(str, 4, '-12')).toEqual("tuvw");
<ide> expect(limitTo(str, '-4', -12)).toEqual("wxyz");
<add> expect(limitTo(arrayLike, 4, '-12')).toEqual(['a', 'b', 'c', 'd']);
<add> expect(limitTo(arrayLike, '-4', -12)).toEqual(['e', 'f', 'g', 'h']);
<ide> });
<ide>
<ide> it('should return the entire string beginning from Y if X is positive and X+Y exceeds input length', function() {
<ide> expect(limitTo(items, 7, 3)).toEqual(['d', 'e', 'f', 'g', 'h']);
<ide> expect(limitTo(items, 7, -3)).toEqual(['f', 'g', 'h']);
<ide> expect(limitTo(str, 6, 3)).toEqual("wxyz");
<ide> expect(limitTo(str, 6, -3)).toEqual("xyz");
<add> expect(limitTo(arrayLike, 7, 3)).toEqual(['d', 'e', 'f', 'g', 'h']);
<add> expect(limitTo(arrayLike, 7, -3)).toEqual(['f', 'g', 'h']);
<ide> });
<ide>
<ide> it('should return the entire string until index Y if X is negative and X+Y exceeds input length', function() {
<ide> expect(limitTo(items, -7, 3)).toEqual(['a', 'b', 'c']);
<ide> expect(limitTo(items, -7, -3)).toEqual(['a', 'b', 'c', 'd', 'e']);
<ide> expect(limitTo(str, -6, 3)).toEqual("tuv");
<ide> expect(limitTo(str, -6, -3)).toEqual("tuvw");
<add> expect(limitTo(arrayLike, -7, 3)).toEqual(['a', 'b', 'c']);
<add> expect(limitTo(arrayLike, -7, -3)).toEqual(['a', 'b', 'c', 'd', 'e']);
<add> });
<add>
<add> it('should not throw an error if used with an array like object', function() {
<add> function getArguments() {
<add> return arguments;
<add> }
<add> var argsObj = getArguments({name: 'Misko'}, {name: 'Igor'}, {name: 'Brad'});
<add>
<add> var nodeList = jqLite("<p><span>Misko</span><span>Igor</span><span>Brad</span></p>")[0].childNodes;
<add>
<add> expect(limitTo(argsObj, 2).length).toBe(2);
<add> expect(limitTo('abc', 1).length).toBe(1);
<add> expect(limitTo(nodeList, 2).length).toBe(2);
<ide> });
<ide> }); | 2 |
Javascript | Javascript | use ownerdocument.body.contains for ie11 | 4169ddd9b7cc11f8275432cd9b73cb65d6f4dece | <ide><path>src/js/video.js
<ide> function videojs(id, options, ready) {
<ide> throw new TypeError('The element or ID supplied is not valid. (videojs)');
<ide> }
<ide>
<del> // document.contains(el) will only check if el is contained within that one document.
<add> // document.body.contains(el) will only check if el is contained within that one document.
<ide> // This causes problems for elements in iframes.
<ide> // Instead, use the element's ownerDocument instead of the global document.
<ide> // This will make sure that the element is indeed in the dom of that document.
<ide> // Additionally, check that the document in question has a default view.
<ide> // If the document is no longer attached to the dom, the defaultView of the document will be null.
<del> if (!el.ownerDocument.defaultView || !el.ownerDocument.contains(el)) {
<add> if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
<ide> log.warn('The element supplied is not included in the DOM');
<ide> }
<ide> | 1 |
Text | Text | fix typos in n-api docs | 7dd3adf6dd4284353993977584ee807c25397046 | <ide><path>doc/api/n-api.md
<ide> NAPI_EXTERN napi_status napi_create_reference(napi_env env,
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This API create a new reference with the specified reference count
<add>This API creates a new reference with the specified reference count
<ide> to the `Object` passed in.
<ide>
<ide> #### napi_delete_reference
<ide> napi_status napi_set_element(napi_env env,
<ide>
<ide> Returns `napi_ok` if the API succeeded.
<ide>
<del>This API sets and element on the `Object` passed in.
<add>This API sets an element on the `Object` passed in.
<ide>
<ide> #### napi_get_element
<ide> <!-- YAML | 1 |
Ruby | Ruby | add cask caveats to the end-of-operation summary | 155feba8e057e8dc66661ad6fe8021a30a5c4e93 | <ide><path>Library/Homebrew/cask/installer.rb
<ide> def self.caveats(cask)
<ide> caveats = cask.caveats
<ide> return if caveats.empty?
<ide>
<add> Homebrew.messages.record_caveats(cask.token, caveats)
<add>
<ide> <<~EOS
<ide> #{ohai_title "Caveats"}
<ide> #{caveats}
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def caveats
<ide>
<ide> @show_summary_heading = true
<ide> ohai "Caveats", caveats.to_s
<del> Homebrew.messages.record_caveats(formula, caveats)
<add> Homebrew.messages.record_caveats(formula.name, caveats)
<ide> end
<ide>
<ide> sig { void }
<ide><path>Library/Homebrew/messages.rb
<ide> def initialize
<ide> @install_times = []
<ide> end
<ide>
<del> def record_caveats(f, caveats)
<del> @caveats.push(formula: f.name, caveats: caveats)
<add> def record_caveats(package, caveats)
<add> @caveats.push(package: package, caveats: caveats)
<ide> end
<ide>
<ide> def formula_installed(f, elapsed_time)
<ide> def display_caveats(force: false)
<ide>
<ide> oh1 "Caveats"
<ide> @caveats.each do |c|
<del> ohai c[:formula], c[:caveats]
<add> ohai c[:package], c[:caveats]
<ide> end
<ide> end
<ide> | 3 |
Go | Go | add timestamp and change untagged -> untag | b8d52ec2669332988a972bff3b5f5d2e9d526b33 | <ide><path>server.go
<ide> import (
<ide> "runtime"
<ide> "strings"
<ide> "sync"
<add> "time"
<ide> )
<ide>
<ide> func (srv *Server) DockerVersion() APIVersion {
<ide> func (srv *Server) deleteImage(img *Image, repoName, tag string) ([]APIRmi, erro
<ide> }
<ide> if tagDeleted {
<ide> imgs = append(imgs, APIRmi{Untagged: img.ShortID()})
<del> srv.SendEvent("untagged", img.ShortID())
<add> srv.SendEvent("untag", img.ShortID())
<ide> }
<ide> if len(srv.runtime.repositories.ByID()[img.ID]) == 0 {
<ide> if err := srv.deleteImageAndChildren(img.ID, &imgs); err != nil {
<ide> func NewServer(flGraphPath string, autoRestart, enableCors bool, dns ListOpts) (
<ide>
<ide> func (srv *Server) SendEvent(action, id string) {
<ide> for _, c := range srv.events {
<del> c <- utils.JSONMessage{Status: action, ID: id}
<add> c <- utils.JSONMessage{Status: action, ID: id, Time: time.Now().Unix()}
<ide> }
<ide> }
<ide>
<ide><path>utils/utils.go
<ide> type JSONMessage struct {
<ide> Progress string `json:"progress,omitempty"`
<ide> Error string `json:"error,omitempty"`
<ide> ID string `json:"id,omitempty"`
<add> Time int64 `json:"time,omitempty"`
<ide> }
<ide>
<ide> func (jm *JSONMessage) Display(out io.Writer) (error) {
<add> if jm.Time != 0 {
<add> fmt.Fprintf(out, "[%s] ", time.Unix(jm.Time, 0))
<add> }
<ide> if jm.Progress != "" {
<ide> fmt.Fprintf(out, "%s %s\r", jm.Status, jm.Progress)
<ide> } else if jm.Error != "" { | 2 |
Python | Python | add some epty space after the quilook plugin | 5f9a59b1dc129aa797768be25c1c4176b9f1448c | <ide><path>glances/plugins/glances_quicklook.py
<ide> def msg_curse(self, args=None, max_width=10):
<ide> ret.append(self.curse_add_line(bar.pre_char, decoration='BOLD'))
<ide> ret.append(self.curse_add_line(str(bar), self.get_views(key=key, option='decoration')))
<ide> ret.append(self.curse_add_line(bar.post_char, decoration='BOLD'))
<add> ret.append(self.curse_add_line(' '))
<ide> ret.append(self.curse_new_line())
<ide> else:
<ide> try:
<ide> def msg_curse(self, args=None, max_width=10):
<ide> ret.append(self.curse_add_line(bar.pre_char, decoration='BOLD'))
<ide> ret.append(self.curse_add_line(str(bar), self.get_views(key=key, option='decoration')))
<ide> ret.append(self.curse_add_line(bar.post_char, decoration='BOLD'))
<add> ret.append(self.curse_add_line(' '))
<ide> ret.append(self.curse_new_line())
<ide>
<ide> # Return the message with decoration | 1 |
Text | Text | revise collaborator material in governance.md | 557bd861aad28f737d7e83d4bfd035ad84c3d5be | <ide><path>GOVERNANCE.md
<ide> privileges include but are not limited to:
<ide> * Commit access to the [nodejs/node][] repository
<ide> * Access to the Node.js continuous integration (CI) jobs
<ide>
<del>Modifications of the contents of the nodejs/node repository are made on
<del>a collaborative basis. Anybody with a GitHub account may propose a
<del>modification via pull request and it will be considered by the project
<del>Collaborators.
<add>Both Collaborators and non-Collaborators may propose changes to the Node.js
<add>source code. The mechanism to propose such a change is a GitHub pull request.
<add>Collaborators are responsible for reviewing and merging (_landing_)
<add>pull requests.
<ide>
<ide> At least two Collaborators must approve a pull request before the pull request
<del>lands. (One Collaborator approval is enough if the pull request has been open
<add>can land. (One Collaborator approval is enough if the pull request has been open
<ide> for more than 7 days.) Approving a pull request indicates that the Collaborator
<ide> accepts responsibility for the change. Approval must be from Collaborators who
<ide> are not authors of the change.
<ide>
<del>If one or more Collaborators oppose a proposed change, then the change cannot
<del>be accepted unless:
<del>
<del>* Discussions and/or additional changes result in no Collaborators objecting to
<del> the change. Previously-objecting Collaborators do not necessarily have to
<del> sign off on the change, but they should not be opposed to it.
<del>* The change is escalated to the TSC and the TSC votes to approve the change.
<del> This should only happen if disagreements between Collaborators cannot be
<del> resolved through discussion.
<add>If a Collaborator opposes a proposed change, then the change cannot land. The
<add>exception is if the TSC votes to approve the change despite the opposition.
<add>Usually, involving the TSC is unnecessary. Often, discussions or further changes
<add>result in Collaborators removing their opposition.
<ide>
<ide> See:
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.