content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
fix integer division in (i)fftshift
550df270b2daf3eb231e2232269b987d4b6120f4
<ide><path>numpy/fft/helper.py <ide> def fftshift(x,axes=None): <ide> y = tmp <ide> for k in axes: <ide> n = tmp.shape[k] <del> p2 = (n+1)/2 <add> p2 = (n+1)//2 <ide> mylist = concatenate((arange(p2,n),arange(p2))) <ide> y = take(y,mylist,k) <ide> return y <ide> def ifftshift(x,axes=None): <ide> y = tmp <ide> for k in axes: <ide> n = tmp.shape[k] <del> p2 = n-(n+1)/2 <add> p2 = n-(n+1)//2 <ide> mylist = concatenate((arange(p2,n),arange(p2))) <ide> y = take(y,mylist,k) <ide> return y
1
Javascript
Javascript
fix edgecase with script this context
979e6e40a88ae2e973c59449a50752ef239bea9d
<ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js <ide> module.exports = class HarmonyImportDependencyParserPlugin { <ide> parser.state.module.addDependency(dep); <ide> return true; <ide> }); <del> if (this.strictThisContextOnImports) { <del> // only in case when we strictly follow the spec we need a special case here <del> parser.hooks.callMemberChain <del> .for("imported var") <del> .tap("HarmonyImportDependencyParserPlugin", (expr, name, members) => { <del> if (members.length <= 0) return; <del> const settings = parser.state.harmonySpecifier.get(name); <del> if (settings.ids.length > 0) return false; <del> const ids = settings.ids.concat(members); <del> const dep = new HarmonyImportSpecifierDependency( <del> settings.source, <del> settings.sourceOrder, <del> ids, <del> name, <del> expr.callee.range, <del> this.strictExportPresence <del> ); <del> dep.directImport = false; <del> dep.namespaceObjectAsContext = true; <del> dep.loc = expr.callee.loc; <del> parser.state.module.addDependency(dep); <del> if (expr.arguments) parser.walkExpressions(expr.arguments); <del> return true; <del> }); <del> } <del> parser.hooks.call <add> parser.hooks.callMemberChain <ide> .for("imported var") <del> .tap("HarmonyImportDependencyParserPlugin", expr => { <add> .tap("HarmonyImportDependencyParserPlugin", (expr, name, members) => { <ide> const args = expr.arguments; <ide> expr = expr.callee; <del> if (expr.type !== "Identifier") return; <del> const name = expr.name; <ide> const settings = parser.state.harmonySpecifier.get(name); <add> const ids = settings.ids.concat(members); <ide> const dep = new HarmonyImportSpecifierDependency( <ide> settings.source, <ide> settings.sourceOrder, <del> settings.ids, <add> ids, <ide> name, <ide> expr.range, <ide> this.strictExportPresence <ide> ); <del> dep.directImport = true; <add> dep.directImport = false; <ide> dep.call = true; <add> // only in case when we strictly follow the spec we need a special case here <add> dep.namespaceObjectAsContext = <add> members.length > 0 && this.strictThisContextOnImports; <ide> dep.loc = expr.loc; <ide> parser.state.module.addDependency(dep); <ide> if (args) parser.walkExpressions(args); <ide><path>lib/dependencies/HarmonyImportSpecifierDependency.js <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> const ids = this.getIds(moduleGraph); <ide> return new DependencyReference( <ide> () => moduleGraph.getModule(this), <del> ids.length > 0 && !this.namespaceObjectAsContext <del> ? [ids] <del> : DependencyReference.NS_OBJECT_IMPORTED, <add> [this.namespaceObjectAsContext ? ids.slice(0, -1) : ids], <ide> false, <ide> this.sourceOrder <ide> ); <ide><path>test/cases/parsing/harmony-deep-exports/cjs.js <add>module.exports = { <add> a: { b: { c: { d: () => 42 } } } <add>}; <ide><path>test/cases/parsing/harmony-deep-exports/index.js <ide> it("should allow to reexport namespaces 3", () => { <ide> C2.CC.counter.increment(); <ide> expect(C2.CC.counter.counter).toBe(1); <ide> }); <add> <add>import CJS from "./cjs"; <add> <add>it("should be able to call a deep function in commonjs", () => { <add> expect(CJS.a.b.c.d()).toBe(42); <add>});
4
Text
Text
remove duplicate changelog entry
7b2d76400591a1f2ed066dfe16b97631ff97d6b0
<ide><path>CHANGELOG.md <ide> * [FEATURE] Components and helpers registered on the container can be rendered in templates via their dasherized names. E.g. {{helper-name}} or {{component-name}} <ide> * [FEATURE] Add a `didTransition` hook to the router. <ide> * [FEATURE] Add a non-block form link-to helper. E.g {{link-to "About us" "about"}} will have "About us" as link text and will transition to the "about" route. Everything works as with the block form link-to. <del>* [FEATURE] Add support for nested loading/error substates. A loading substate will be entered when a slow-to-resolve promise is returned from one of the Route#model hooks during a transition and an appropriately-named loading template/route can be found. An error substate will be entered when one of the Route#model hooks returns a rejecting promise and an appropriately-named error template/route can be found. <ide> * [FEATURE] Add sortBy using Ember.compare to the Enumerable mixin <ide> * [FEATURE reduceComputedSelf] reduceComputed dependent keys may refer to @this. <ide> * [BUGFIX] reduceComputed handle out of range indexes.
1
Text
Text
add 2.12.0-beta.1 to changelog.md
885d038a8fb53f899a87ab6c63ef58566cc806f3
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### 2.12.0-beta.1 (January 23, 2017) <add> <add>- [#14360](https://github.com/emberjs/ember.js/pull/14360) [FEATURE factory-for] Implement `factoryFor`. <add>- [#14751](https://github.com/emberjs/ember.js/pull/14751) [DEPRECATION} Deprecate `Ember.K`. <add>- [#14756](https://github.com/emberjs/ember.js/pull/14756) [PERF] Disable costly `eventManager` support when unused. <add>- [#14794](https://github.com/emberjs/ember.js/pull/14794) [BUGFIX] Fix query param stickiness between models in ember-engines. <add>- [#14851](https://github.com/emberjs/ember.js/pull/14851) [PERF] only `LOG_VIEW_LOOKUPS` in debug <add>- [#14829](https://github.com/emberjs/ember.js/pull/14829) [PERF] only `logLibraryVersions` in debug mode <add>- [#14852](https://github.com/emberjs/ember.js/pull/14852) [PERF] only `LOG_TRANSITIONS` and `LOG_TRANSITIONS_INTERNAL` in debug <add>- [#14854](https://github.com/emberjs/ember.js/pull/14854) [PER] only `LOG_ACTIVE_GENERATION` and `LOG_RESOLVER` in debug <add> <add> <ide> ### 2.11.0 (January 23, 2017) <ide> <ide> - [#14762](https://github.com/emberjs/ember.js/pull/14762) [BUGFIX] Ensure subexpressions can be used for `{{input}}`'s `type`.
1
Go
Go
improve error message for copy missing destination
5d05a8291314b8f727b04b504b8d7fc7ed7f42da
<ide><path>builder/dockerfile/instructions/parse.go <ide> func parseLabel(req parseRequest) (*LabelCommand, error) { <ide> <ide> func parseAdd(req parseRequest) (*AddCommand, error) { <ide> if len(req.args) < 2 { <del> return nil, errAtLeastTwoArguments("ADD") <add> return nil, errNoDestinationArgument("ADD") <ide> } <ide> flChown := req.flags.AddString("chown", "") <ide> if err := req.flags.Parse(); err != nil { <ide> func parseAdd(req parseRequest) (*AddCommand, error) { <ide> <ide> func parseCopy(req parseRequest) (*CopyCommand, error) { <ide> if len(req.args) < 2 { <del> return nil, errAtLeastTwoArguments("COPY") <add> return nil, errNoDestinationArgument("COPY") <ide> } <ide> flChown := req.flags.AddString("chown", "") <ide> flFrom := req.flags.AddString("from", "") <ide> func errExactlyOneArgument(command string) error { <ide> return errors.Errorf("%s requires exactly one argument", command) <ide> } <ide> <del>func errAtLeastTwoArguments(command string) error { <del> return errors.Errorf("%s requires at least two arguments", command) <add>func errNoDestinationArgument(command string) error { <add> return errors.Errorf("%s requires at least two arguments, but only one was provided. Destination could not be determined.", command) <ide> } <ide> <ide> func errBlankCommandNames(command string) error { <ide><path>builder/dockerfile/instructions/parse_test.go <ide> func TestCommandsAtLeastOneArgument(t *testing.T) { <ide> } <ide> } <ide> <del>func TestCommandsAtLeastTwoArgument(t *testing.T) { <add>func TestCommandsNoDestinationArgument(t *testing.T) { <ide> commands := []string{ <ide> "ADD", <ide> "COPY", <ide> func TestCommandsAtLeastTwoArgument(t *testing.T) { <ide> ast, err := parser.Parse(strings.NewReader(command + " arg1")) <ide> require.NoError(t, err) <ide> _, err = ParseInstruction(ast.AST.Children[0]) <del> assert.EqualError(t, err, errAtLeastTwoArguments(command).Error()) <add> assert.EqualError(t, err, errNoDestinationArgument(command).Error()) <ide> } <ide> } <ide>
2
Ruby
Ruby
prefer strings over regex expressions
6922ba6cb61e4c833cca0b302bc1cf0f93f7ce93
<ide><path>actionpack/test/dispatch/debug_exceptions_test.rb <ide> def raise_nested_exceptions <ide> def call(env) <ide> env["action_dispatch.show_detailed_exceptions"] = @detailed <ide> req = ActionDispatch::Request.new(env) <add> template = ActionView::Template.new(File.read(__FILE__), __FILE__, ActionView::Template::Handlers::Raw.new, {}) <add> <ide> case req.path <del> when %r{/pass} <add> when "/pass" <ide> [404, { "X-Cascade" => "pass" }, self] <del> when %r{/not_found} <add> when "/not_found" <ide> raise AbstractController::ActionNotFound <del> when %r{/runtime_error} <add> when "/runtime_error" <ide> raise RuntimeError <del> when %r{/method_not_allowed} <add> when "/method_not_allowed" <ide> raise ActionController::MethodNotAllowed <del> when %r{/intercepted_error} <add> when "/intercepted_error" <ide> raise InterceptedErrorInstance <del> when %r{/unknown_http_method} <add> when "/unknown_http_method" <ide> raise ActionController::UnknownHttpMethod <del> when %r{/not_implemented} <add> when "/not_implemented" <ide> raise ActionController::NotImplemented <del> when %r{/unprocessable_entity} <add> when "/unprocessable_entity" <ide> raise ActionController::InvalidAuthenticityToken <del> when %r{/not_found_original_exception} <add> when "/not_found_original_exception" <ide> begin <ide> raise AbstractController::ActionNotFound.new <ide> rescue <del> raise ActionView::Template::Error.new("template") <add> raise ActionView::Template::Error.new(template) <ide> end <del> when %r{/missing_template} <add> when "/missing_template" <ide> raise ActionView::MissingTemplate.new(%w(foo), "foo/index", %w(foo), false, "mailer") <del> when %r{/bad_request} <add> when "/bad_request" <ide> raise ActionController::BadRequest <del> when %r{/missing_keys} <add> when "/missing_keys" <ide> raise ActionController::UrlGenerationError, "No route matches" <del> when %r{/parameter_missing} <add> when "/parameter_missing" <ide> raise ActionController::ParameterMissing, :missing_param_key <del> when %r{/original_syntax_error} <add> when "/original_syntax_error" <ide> eval "broke_syntax =" # `eval` need for raise native SyntaxError at runtime <del> when %r{/syntax_error_into_view} <add> when "/syntax_error_into_view" <ide> begin <ide> eval "broke_syntax =" <ide> rescue Exception <del> template = ActionView::Template.new(File.read(__FILE__), <del> __FILE__, <del> ActionView::Template::Handlers::Raw.new, <del> {}) <ide> raise ActionView::Template::Error.new(template) <ide> end <del> when %r{/framework_raises} <add> when "/framework_raises" <ide> method_that_raises <del> when %r{/nested_exceptions} <add> when "/nested_exceptions" <ide> raise_nested_exceptions <ide> else <ide> raise "puke!"
1
Javascript
Javascript
fix model accuracy table [ci skip]
bb54f54369be830651658191807c4e8625abb48c
<ide><path>website/src/templates/models.js <del>import React, { useEffect, useState, useMemo } from 'react' <add>import React, { useEffect, useState, useMemo, Fragment } from 'react' <ide> import { StaticQuery, graphql } from 'gatsby' <ide> import { window } from 'browser-monads' <ide> <ide> function formatVectors(data) { <ide> <ide> function formatAccuracy(data) { <ide> if (!data) return null <del> const labels = { tags_acc: 'POS', ents_f: 'NER F', ents_p: 'NER P', ents_r: 'NER R' } <add> const labels = { <add> las: 'LAS', <add> uas: 'UAS', <add> tags_acc: 'TAG', <add> ents_f: 'NER F', <add> ents_p: 'NER P', <add> ents_r: 'NER R', <add> } <ide> const isSyntax = key => ['tags_acc', 'las', 'uas'].includes(key) <ide> const isNer = key => key.startsWith('ents_') <del> return Object.keys(data).map(key => ({ <del> label: labels[key] || key.toUpperCase(), <del> value: data[key].toFixed(2), <del> help: MODEL_META[key], <del> type: isNer(key) ? 'ner' : isSyntax(key) ? 'syntax' : null, <del> })) <add> return Object.keys(data) <add> .filter(key => labels[key]) <add> .map(key => ({ <add> label: labels[key], <add> value: data[key].toFixed(2), <add> help: MODEL_META[key], <add> type: isNer(key) ? 'ner' : isSyntax(key) ? 'syntax' : null, <add> })) <ide> } <ide> <ide> function formatModelMeta(data) { <ide> function formatModelMeta(data) { <ide> function formatSources(data = []) { <ide> const sources = data.map(s => (isString(s) ? { name: s } : s)) <ide> return sources.map(({ name, url, author }, i) => ( <del> <> <add> <Fragment key={i}> <ide> {i > 0 && <br />} <ide> {name && url ? <Link to={url}>{name}</Link> : name} <ide> {author && ` (${author})`} <del> </> <add> </Fragment> <ide> )) <ide> } <ide> <ide> const Model = ({ name, langId, langName, baseUrl, repo, compatibility, hasExampl <ide> </Td> <ide> <Td> <ide> {labelNames.map((label, i) => ( <del> <> <add> <Fragment key={i}> <ide> {i > 0 && ', '} <ide> <InlineCode wrap key={label}> <ide> {label} <ide> </InlineCode> <del> </> <add> </Fragment> <ide> ))} <ide> </Td> <ide> </Tr>
1
Python
Python
pass documents to tensorizer, not 'features'
e37a50a436643c201a7ecb088325c9b94593fabd
<ide><path>spacy/language.py <ide> def update(self, docs, golds, drop=0., sgd=None, losses=None, <ide> self._optimizer = Adam(Model.ops, 0.001) <ide> sgd = self._optimizer <ide> tok2vec = self.pipeline[0] <del> feats = tok2vec.doc2feats(docs) <ide> grads = {} <ide> def get_grads(W, dW, key=None): <ide> grads[key] = (W, dW) <ide> pipes = list(self.pipeline[1:]) <ide> random.shuffle(pipes) <del> tokvecses, bp_tokvecses = tok2vec.model.begin_update(feats, drop=drop) <add> tokvecses, bp_tokvecses = tok2vec.model.begin_update(docs, drop=drop) <ide> all_d_tokvecses = [tok2vec.model.ops.allocate(tv.shape) for tv in tokvecses] <ide> for proc in pipes: <ide> if not hasattr(proc, 'update'):
1
Ruby
Ruby
remove patch for old jruby versions
56dbfa8537d8d5b3a316022fb7a9d13794288c51
<ide><path>activesupport/lib/active_support/core_ext/class/subclasses.rb <ide> # frozen_string_literal: true <ide> <ide> class Class <del> begin <del> # Test if this Ruby supports each_object against singleton_class <del> ObjectSpace.each_object(Numeric.singleton_class) { } <del> <del> # Returns an array with all classes that are < than its receiver. <del> # <del> # class C; end <del> # C.descendants # => [] <del> # <del> # class B < C; end <del> # C.descendants # => [B] <del> # <del> # class A < B; end <del> # C.descendants # => [B, A] <del> # <del> # class D < C; end <del> # C.descendants # => [B, A, D] <del> def descendants <del> descendants = [] <del> ObjectSpace.each_object(singleton_class) do |k| <del> next if k.singleton_class? <del> descendants.unshift k unless k == self <del> end <del> descendants <del> end <del> rescue StandardError # JRuby 9.0.4.0 and earlier <del> def descendants <del> descendants = [] <del> ObjectSpace.each_object(Class) do |k| <del> descendants.unshift k if k < self <del> end <del> descendants.uniq! <del> descendants <add> # Returns an array with all classes that are < than its receiver. <add> # <add> # class C; end <add> # C.descendants # => [] <add> # <add> # class B < C; end <add> # C.descendants # => [B] <add> # <add> # class A < B; end <add> # C.descendants # => [B, A] <add> # <add> # class D < C; end <add> # C.descendants # => [B, A, D] <add> def descendants <add> descendants = [] <add> ObjectSpace.each_object(singleton_class) do |k| <add> next if k.singleton_class? <add> descendants.unshift k unless k == self <ide> end <add> descendants <ide> end <ide> <ide> # Returns an array with the direct children of +self+.
1
Go
Go
add wait4 after kill
30ba7546cb5a1ff7e4915c5a25dd8d72b3bf735b
<ide><path>daemon/execdriver/native/driver.go <ide> func (d *driver) Terminate(p *execdriver.Command) error { <ide> } <ide> if started == currentStartTime { <ide> err = syscall.Kill(p.Process.Pid, 9) <add> syscall.Wait4(p.Process.Pid, nil, 0, nil) <ide> } <ide> d.removeContainerRoot(p.ID) <ide> return err
1
PHP
PHP
put str_object back in
4bee6d1bca5b94155455a26d1db47b6d8654edd7
<ide><path>laravel/helpers.php <ide> function str_finish($value, $cap) <ide> return rtrim($value, $cap).$cap; <ide> } <ide> <add>/** <add> * Determine if the given object has a toString method. <add> * <add> * @param object $value <add> * @return bool <add> */ <add>function str_object($value) <add>{ <add> return is_object($value) and method_exists($value, '__toString'); <add>} <add> <ide> /** <ide> * Get the root namespace of a given class. <ide> *
1
Javascript
Javascript
release script tweaks
ac0e670545bb85770c71154e93ef17dc6c08e8a4
<ide><path>scripts/release/build-commands/add-git-tag.js <ide> const chalk = require('chalk'); <ide> const {execUnlessDry, logPromise} = require('../utils'); <ide> <ide> const run = async ({cwd, dry, version}) => { <del> await execUnlessDry(`git tag -a ${version} -m "Tagging ${version} release"`, { <del> cwd, <del> dry, <del> }); <add> await execUnlessDry( <add> `git tag -a v${version} -m "Tagging ${version} release"`, <add> { <add> cwd, <add> dry, <add> } <add> ); <ide> }; <ide> <ide> module.exports = async ({cwd, dry, version}) => { <ide> return logPromise( <ide> run({cwd, dry, version}), <del> `Creating git tag ${chalk.yellow.bold(version)}` <add> `Creating git tag ${chalk.yellow.bold(`v${version}`)}` <ide> ); <ide> }; <ide><path>scripts/release/build-commands/build-artifacts.js <ide> const run = async ({cwd, dry, version}) => { <ide> }; <ide> <ide> module.exports = async params => { <del> return logPromise(run(params), 'Building artifacts'); <add> return logPromise(run(params), 'Building artifacts', true); <ide> }; <ide><path>scripts/release/build-commands/check-npm-permissions.js <ide> <ide> const chalk = require('chalk'); <ide> const {execRead, logPromise} = require('../utils'); <del>const {projects} = require('../config'); <ide> <del>module.exports = async () => { <add>module.exports = async ({packages}) => { <ide> const currentUser = await execRead('npm whoami'); <ide> const failedProjects = []; <ide> <ide> module.exports = async () => { <ide> }; <ide> <ide> await logPromise( <del> Promise.all(projects.map(checkProject)), <add> Promise.all(packages.map(checkProject)), <ide> `Checking ${chalk.yellow.bold(currentUser)}'s NPM permissions` <ide> ); <ide> <ide><path>scripts/release/build-commands/check-package-dependencies.js <ide> const chalk = require('chalk'); <ide> const {readJson} = require('fs-extra'); <ide> const {join} = require('path'); <del>const {dependencies, projects} = require('../config'); <add>const {dependencies} = require('../config'); <ide> const {logPromise} = require('../utils'); <ide> <del>const check = async ({cwd}) => { <add>const check = async ({cwd, packages}) => { <ide> const rootPackage = await readJson(join(cwd, 'package.json')); <ide> <ide> const projectPackages = []; <del> for (let i = 0; i < projects.length; i++) { <del> const project = projects[i]; <add> for (let i = 0; i < packages.length; i++) { <add> const project = packages[i]; <ide> projectPackages.push( <ide> await readJson(join(cwd, join('packages', project), 'package.json')) <ide> ); <ide> const check = async ({cwd}) => { <ide> } <ide> }; <ide> <del>module.exports = async ({cwd}) => { <del> return logPromise(check({cwd}), 'Checking runtime dependencies'); <add>module.exports = async params => { <add> return logPromise(check(params), 'Checking runtime dependencies'); <ide> }; <ide><path>scripts/release/build-commands/run-automated-tests.js <ide> module.exports = async ({cwd}) => { <ide> ); <ide> await logPromise( <ide> runYarnTask(cwd, 'jest', 'Jest failed'), <del> 'Running Jest tests' <add> 'Running Jest tests', <add> true <ide> ); <ide> }; <ide><path>scripts/release/build-commands/update-package-versions.js <ide> const {readFileSync, writeFileSync} = require('fs'); <ide> const {readJson, writeJson} = require('fs-extra'); <ide> const {join} = require('path'); <ide> const semver = require('semver'); <del>const {projects} = require('../config'); <ide> const {execUnlessDry, logPromise} = require('../utils'); <ide> <del>const update = async ({cwd, dry, version}) => { <add>const update = async ({cwd, dry, packages, version}) => { <ide> try { <ide> // Update root package.json <ide> const packagePath = join(cwd, 'package.json'); <ide> const update = async ({cwd, dry, version}) => { <ide> <ide> await writeJson(path, json, {spaces: 2}); <ide> }; <del> await Promise.all(projects.map(updateProjectPackage)); <add> await Promise.all(packages.map(updateProjectPackage)); <ide> <ide> // Version sanity check <ide> await exec('yarn version-check', {cwd}); <ide><path>scripts/release/build.js <ide> const {exec} = require('child_process'); <ide> const run = async () => { <ide> const chalk = require('chalk'); <ide> const logUpdate = require('log-update'); <add> const {getPublicPackages} = require('./utils'); <ide> <ide> const addGitTag = require('./build-commands/add-git-tag'); <ide> const buildArtifacts = require('./build-commands/build-artifacts'); <ide> const run = async () => { <ide> <ide> try { <ide> const params = parseBuildParameters(); <add> params.packages = getPublicPackages(); <ide> <ide> await checkEnvironmentVariables(params); <ide> await validateVersion(params); <ide><path>scripts/release/config.js <ide> <ide> const dependencies = ['fbjs', 'object-assign', 'prop-types']; <ide> <del>// TODO: enumerate all non-private package folders in packages/*? <del>const projects = [ <del> 'react', <del> 'react-art', <del> 'react-call-return', <del> 'react-dom', <del> 'react-reconciler', <del> 'react-test-renderer', <del>]; <del> <ide> const paramDefinitions = [ <ide> { <ide> name: 'dry', <ide> const paramDefinitions = [ <ide> module.exports = { <ide> dependencies, <ide> paramDefinitions, <del> projects, <ide> }; <ide><path>scripts/release/publish-commands/publish-to-npm.js <ide> const {readJson} = require('fs-extra'); <ide> const {join} = require('path'); <ide> const semver = require('semver'); <ide> const {execRead, execUnlessDry, logPromise} = require('../utils'); <del>const {projects} = require('../config'); <ide> <del>const push = async ({cwd, dry, version}) => { <add>const push = async ({cwd, dry, packages, version}) => { <ide> const errors = []; <ide> const isPrerelease = semver.prerelease(version); <ide> const tag = isPrerelease ? 'next' : 'latest'; <ide> const push = async ({cwd, dry, version}) => { <ide> } <ide> } <ide> } catch (error) { <del> errors.push(error.message); <add> errors.push(error.stack); <ide> } <ide> }; <ide> <del> await Promise.all(projects.map(publishProject)); <add> await Promise.all(packages.map(publishProject)); <ide> <ide> if (errors.length > 0) { <ide> throw Error( <ide> chalk` <ide> Failure publishing to NPM <ide> <del> {white ${errors.join('\n')}}` <add> {white ${errors.join('\n\n')}}` <ide> ); <ide> } <ide> }; <ide><path>scripts/release/publish.js <ide> <ide> const chalk = require('chalk'); <ide> const logUpdate = require('log-update'); <add>const {getPublicPackages} = require('./utils'); <ide> <ide> const checkBuildStatus = require('./publish-commands/check-build-status'); <ide> const commitChangelog = require('./publish-commands/commit-changelog'); <ide> const publishToNpm = require('./publish-commands/publish-to-npm'); <ide> // Follows the steps outlined in github.com/facebook/react/issues/10620 <ide> const run = async () => { <ide> const params = parsePublishParams(); <add> params.packages = getPublicPackages(); <ide> <ide> try { <ide> await checkBuildStatus(params); <ide><path>scripts/release/utils.js <ide> const chalk = require('chalk'); <ide> const {dots} = require('cli-spinners'); <ide> const {exec} = require('child-process-promise'); <add>const {readdirSync, readFileSync} = require('fs'); <ide> const logUpdate = require('log-update'); <add>const {join} = require('path'); <ide> <ide> const execRead = async (command, options) => { <ide> const {stdout} = await exec(command, options); <ide> const execUnlessDry = async (command, {cwd, dry}) => { <ide> } <ide> }; <ide> <add>const getPublicPackages = () => { <add> const packagesRoot = join(__dirname, '..', '..', 'packages'); <add> <add> return readdirSync(packagesRoot).filter(dir => { <add> const packagePath = join(packagesRoot, dir, 'package.json'); <add> const packageJSON = JSON.parse(readFileSync(packagePath)); <add> <add> return packageJSON.private !== true; <add> }); <add>}; <add> <ide> const getUnexecutedCommands = () => { <ide> if (unexecutedCommands.length > 0) { <ide> return chalk` <ide> const getUnexecutedCommands = () => { <ide> } <ide> }; <ide> <del>const logPromise = async (promise, text, completedLabel = '') => { <add>const logPromise = async (promise, text, isLongRunningTask = false) => { <ide> const {frames, interval} = dots; <ide> <ide> let index = 0; <ide> <add> const inProgressMessage = `- this may take a few ${ <add> isLongRunningTask ? 'minutes' : 'seconds' <add> }`; <add> <ide> const id = setInterval(() => { <ide> index = ++index % frames.length; <ide> logUpdate( <del> `${chalk.yellow(frames[index])} ${text} ${chalk.gray( <del> '- this may take a few seconds' <del> )}` <add> `${chalk.yellow(frames[index])} ${text} ${chalk.gray(inProgressMessage)}` <ide> ); <ide> }, interval); <ide> <ide> const logPromise = async (promise, text, completedLabel = '') => { <ide> <ide> clearInterval(id); <ide> <del> logUpdate(`${chalk.green('✓')} ${text} ${chalk.gray(completedLabel)}`); <add> logUpdate(`${chalk.green('✓')} ${text}`); <ide> logUpdate.done(); <ide> <ide> return returnValue; <ide> const logPromise = async (promise, text, completedLabel = '') => { <ide> module.exports = { <ide> execRead, <ide> execUnlessDry, <add> getPublicPackages, <ide> getUnexecutedCommands, <ide> logPromise, <ide> };
11
Mixed
Javascript
throw error on content-length mismatch
91020db9333c720ca201dd7a6a3b8d4d505b119c
<ide><path>doc/api/errors.md <ide> When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path. <ide> <ide> <a id="ERR_FS_CP_FIFO_PIPE"></a> <ide> <add>### `ERR_HTTP_CONTENT_LENGTH_MISMATCH` <add> <add>Response body size doesn't match with the specified content-length header value. <add> <add><a id="ERR_HTTP_CONTENT_LENGTH_MISMATCH"></a> <add> <ide> ### `ERR_FS_CP_FIFO_PIPE` <ide> <ide> <!-- <ide><path>doc/api/http.md <ide> the data is read it will consume memory that can eventually lead to a <ide> For backward compatibility, `res` will only emit `'error'` if there is an <ide> `'error'` listener registered. <ide> <del>Node.js does not check whether Content-Length and the length of the <del>body which has been transmitted are equal or not. <add>Set `Content-Length` header to limit the response body size. Mismatching the <add>`Content-Length` header value will result in an \[`Error`]\[] being thrown, <add>identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][]. <add> <add>`Content-Length` value should be in bytes, not characters. Use <add>[`Buffer.byteLength()`][] to determine the length of the body in bytes. <ide> <ide> ### Event: `'abort'` <ide> <ide> const server = http.createServer((req, res) => { <ide> }); <ide> ``` <ide> <del>`Content-Length` is given in bytes, not characters. Use <add>`Content-Length` is read in bytes, not characters. Use <ide> [`Buffer.byteLength()`][] to determine the length of the body in bytes. Node.js <del>does not check whether `Content-Length` and the length of the body which has <add>will check whether `Content-Length` and the length of the body which has <ide> been transmitted are equal or not. <ide> <ide> Attempting to set a header field name or value that contains invalid characters <del>will result in a [`TypeError`][] being thrown. <add>will result in a \[`Error`]\[] being thrown. <ide> <ide> ### `response.writeProcessing()` <ide> <ide> added: v18.8.0 <ide> Set the maximum number of idle HTTP parsers. **Default:** `1000`. <ide> <ide> [RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt <add>[`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`]: errors.md#err_http_content_length_mismatch <ide> [`'checkContinue'`]: #event-checkcontinue <ide> [`'finish'`]: #event-finish <ide> [`'request'`]: #event-request <ide><path>lib/_http_outgoing.js <ide> const { <ide> Array, <ide> ArrayIsArray, <ide> ArrayPrototypeJoin, <add> MathAbs, <ide> MathFloor, <ide> NumberPrototypeToString, <ide> ObjectCreate, <ide> const { <ide> } = require('internal/async_hooks'); <ide> const { <ide> codes: { <add> ERR_HTTP_CONTENT_LENGTH_MISMATCH, <ide> ERR_HTTP_HEADERS_SENT, <ide> ERR_HTTP_INVALID_HEADER_VALUE, <ide> ERR_HTTP_TRAILER_INVALID, <ide> const HIGH_WATER_MARK = getDefaultHighWaterMark(); <ide> <ide> const kCorked = Symbol('corked'); <ide> const kUniqueHeaders = Symbol('kUniqueHeaders'); <add>const kBytesWritten = Symbol('kBytesWritten'); <add>const kEndCalled = Symbol('kEndCalled'); <ide> <ide> const nop = () => {}; <ide> <ide> function OutgoingMessage() { <ide> this._removedContLen = false; <ide> this._removedTE = false; <ide> <add> this.strictContentLength = false; <add> this[kBytesWritten] = 0; <add> this[kEndCalled] = false; <ide> this._contentLength = null; <ide> this._hasBody = true; <ide> this._trailer = ''; <ide> OutgoingMessage.prototype._send = function _send(data, encoding, callback) { <ide> // This is a shameful hack to get the headers and first body chunk onto <ide> // the same packet. Future versions of Node are going to take care of <ide> // this at a lower level and in a more general way. <del> if (!this._headerSent) { <add> if (!this._headerSent && this._header !== null) { <add> // `this._header` can be null if OutgoingMessage is used without a proper Socket <add> // See: /test/parallel/test-http-outgoing-message-inheritance.js <ide> if (typeof data === 'string' && <ide> (encoding === 'utf8' || encoding === 'latin1' || !encoding)) { <ide> data = this._header + data; <ide> OutgoingMessage.prototype._send = function _send(data, encoding, callback) { <ide> return this._writeRaw(data, encoding, callback); <ide> }; <ide> <add>function _getMessageBodySize(chunk, headers, encoding) { <add> if (Buffer.isBuffer(chunk)) return chunk.length; <add> const chunkLength = chunk ? Buffer.byteLength(chunk, encoding) : 0; <add> const headerLength = headers ? headers.length : 0; <add> if (headerLength === chunkLength) return 0; <add> if (headerLength < chunkLength) return MathAbs(chunkLength - headerLength); <add> return chunkLength; <add>} <ide> <ide> OutgoingMessage.prototype._writeRaw = _writeRaw; <ide> function _writeRaw(data, encoding, callback) { <ide> function _writeRaw(data, encoding, callback) { <ide> encoding = null; <ide> } <ide> <add> // TODO(sidwebworks): flip the `strictContentLength` default to `true` in a future PR <add> if (this.strictContentLength && conn && conn.writable && !this._removedContLen && this._hasBody) { <add> const skip = conn._httpMessage.statusCode === 304 || (this.hasHeader('transfer-encoding') || this.chunkedEncoding); <add> <add> if (typeof this._contentLength === 'number' && !skip) { <add> const size = _getMessageBodySize(data, conn._httpMessage._header, encoding); <add> <add> if ((size + this[kBytesWritten]) > this._contentLength) { <add> throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(size + this[kBytesWritten], this._contentLength); <add> } <add> <add> if (this[kEndCalled] && (size + this[kBytesWritten]) !== this._contentLength) { <add> throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(size + this[kBytesWritten], this._contentLength); <add> } <add> <add> this[kBytesWritten] += size; <add> } <add> } <add> <ide> if (conn && conn._httpMessage === this && conn.writable) { <ide> // There might be pending data in the this.output buffer. <ide> if (this.outputData.length) { <ide> function matchHeader(self, state, field, value) { <ide> break; <ide> case 'content-length': <ide> state.contLen = true; <add> self._contentLength = value; <ide> self._removedContLen = false; <ide> break; <ide> case 'date': <ide> OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { <ide> encoding = null; <ide> } <ide> <add> this[kEndCalled] = true; <add> <ide> if (chunk) { <ide> if (this.finished) { <ide> onError(this, <ide><path>lib/internal/errors.js <ide> E('ERR_HTTP2_TRAILERS_NOT_READY', <ide> 'Trailing headers cannot be sent until after the wantTrailers event is ' + <ide> 'emitted', Error); <ide> E('ERR_HTTP2_UNSUPPORTED_PROTOCOL', 'protocol "%s" is unsupported.', Error); <add>E('ERR_HTTP_CONTENT_LENGTH_MISMATCH', <add> 'Response body\'s content-length of %s byte(s) does not match the content-length of %s byte(s) set in header', Error); <ide> E('ERR_HTTP_HEADERS_SENT', <ide> 'Cannot %s headers after they are sent to the client', Error); <ide> E('ERR_HTTP_INVALID_HEADER_VALUE', <ide><path>test/parallel/test-http-content-length-mismatch.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>function shouldThrowOnMoreBytes() { <add> const server = http.createServer(common.mustCall((req, res) => { <add> res.strictContentLength = true; <add> res.setHeader('Content-Length', 5); <add> res.write('hello'); <add> assert.throws(() => { <add> res.write('a'); <add> }, { <add> code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH' <add> }); <add> res.statusCode = 200; <add> res.end(); <add> })); <add> <add> server.listen(0, () => { <add> const req = http.get({ <add> port: server.address().port, <add> }, common.mustCall((res) => { <add> res.resume(); <add> assert.strictEqual(res.statusCode, 200); <add> server.close(); <add> })); <add> req.end(); <add> }); <add>} <add> <add>function shouldNotThrow() { <add> const server = http.createServer(common.mustCall((req, res) => { <add> res.strictContentLength = true; <add> res.write('helloaa'); <add> res.statusCode = 200; <add> res.end('ending'); <add> })); <add> <add> server.listen(0, () => { <add> http.get({ <add> port: server.address().port, <add> }, common.mustCall((res) => { <add> res.resume(); <add> assert.strictEqual(res.statusCode, 200); <add> server.close(); <add> })); <add> }); <add>} <add> <add> <add>function shouldThrowOnFewerBytes() { <add> const server = http.createServer(common.mustCall((req, res) => { <add> res.strictContentLength = true; <add> res.setHeader('Content-Length', 5); <add> res.write('a'); <add> res.statusCode = 200; <add> assert.throws(() => { <add> res.end(); <add> }, { <add> code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH' <add> }); <add> res.end('aaaa'); <add> })); <add> <add> server.listen(0, () => { <add> http.get({ <add> port: server.address().port, <add> }, common.mustCall((res) => { <add> res.resume(); <add> assert.strictEqual(res.statusCode, 200); <add> server.close(); <add> })); <add> }); <add>} <add> <add>shouldThrowOnMoreBytes(); <add>shouldNotThrow(); <add>shouldThrowOnFewerBytes(); <ide><path>test/parallel/test-http-outgoing-properties.js <ide> const OutgoingMessage = http.OutgoingMessage; <ide> msg._implicitHeader = function() {}; <ide> assert.strictEqual(msg.writableLength, 0); <ide> msg.write('asd'); <del> assert.strictEqual(msg.writableLength, 7); <add> assert.strictEqual(msg.writableLength, 3); <ide> } <ide> <ide> { <ide><path>test/parallel/test-http-response-multi-content-length.js <ide> function test(server) { <ide> { <ide> const server = http.createServer((req, res) => { <ide> res.setHeader('content-length', [2, 1]); <del> res.end('ok'); <add> res.end('k'); <ide> }); <ide> <ide> test(server);
7
Python
Python
enable dynamic padding with truncation
27d0e01d755dc14309617c06eb4d55c246183c98
<ide><path>examples/text-classification/run_glue.py <ide> def main(): <ide> # Padding strategy <ide> if data_args.pad_to_max_length: <ide> padding = "max_length" <del> max_length = data_args.max_seq_length <ide> else: <ide> # We will pad later, dynamically at batch creation, to the max sequence length in each batch <ide> padding = False <del> max_length = None <ide> <ide> # Some models have set the order of the labels to use, so let's make sure we do use it. <ide> label_to_id = None <ide> def preprocess_function(examples): <ide> args = ( <ide> (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) <ide> ) <del> result = tokenizer(*args, padding=padding, max_length=max_length, truncation=True) <add> result = tokenizer(*args, padding=padding, max_length=data_args.max_seq_length, truncation=True) <ide> <ide> # Map labels to IDs (not necessary for GLUE tasks) <ide> if label_to_id is not None and "label" in examples:
1
Javascript
Javascript
remove unnecessary copy of modules
4eecad3a8308720e9d5f608266861e40eb23a56f
<ide><path>lib/optimize/ConcatenatedModule.js <ide> class ConcatenatedModule extends Module { <ide> this._numberOfConcatenatedModules = modules.size; <ide> <ide> // Graph <del> const modulesSet = new Set(modules); <del> <ide> this.dependencies = []; <ide> <ide> this.warnings = []; <ide> this.errors = []; <ide> this._orderedConcatenationList = ConcatenatedModule._createConcatenationList( <ide> rootModule, <del> modulesSet, <add> modules, <ide> compilation <ide> ); <ide> for (const info of this._orderedConcatenationList) { <ide> class ConcatenatedModule extends Module { <ide> for (const d of m.dependencies.filter( <ide> dep => <ide> !(dep instanceof HarmonyImportDependency) || <del> !modulesSet.has(compilation.moduleGraph.getModule(dep)) <add> !modules.has(compilation.moduleGraph.getModule(dep)) <ide> )) { <ide> this.dependencies.push(d); <ide> }
1
Ruby
Ruby
remove noise from am tests
7b58423251344824b58825d5b5e6597cb3e5c21c
<ide><path>actionmailer/test/test_helper_test.rb <ide> require 'abstract_unit' <add>require 'active_support/testing/stream' <ide> <ide> class TestHelperMailer < ActionMailer::Base <ide> def test <ide> def test <ide> end <ide> <ide> class TestHelperMailerTest < ActionMailer::TestCase <add> include ActiveSupport::Testing::Stream <add> <ide> def test_setup_sets_right_action_mailer_options <ide> assert_equal :test, ActionMailer::Base.delivery_method <ide> assert ActionMailer::Base.perform_deliveries <ide> def test_assert_no_emails_failure <ide> def test_assert_enqueued_emails <ide> assert_nothing_raised do <ide> assert_enqueued_emails 1 do <del> TestHelperMailer.test.deliver_later <add> silence_stream($stdout) do <add> TestHelperMailer.test.deliver_later <add> end <ide> end <ide> end <ide> end <ide> <ide> def test_assert_enqueued_emails_too_few_sent <ide> error = assert_raise ActiveSupport::TestCase::Assertion do <ide> assert_enqueued_emails 2 do <del> TestHelperMailer.test.deliver_later <add> silence_stream($stdout) do <add> TestHelperMailer.test.deliver_later <add> end <ide> end <ide> end <ide> <ide> def test_assert_enqueued_emails_too_few_sent <ide> def test_assert_enqueued_emails_too_many_sent <ide> error = assert_raise ActiveSupport::TestCase::Assertion do <ide> assert_enqueued_emails 1 do <del> TestHelperMailer.test.deliver_later <del> TestHelperMailer.test.deliver_later <add> silence_stream($stdout) do <add> TestHelperMailer.test.deliver_later <add> TestHelperMailer.test.deliver_later <add> end <ide> end <ide> end <ide> <ide> def test_assert_no_enqueued_emails <ide> def test_assert_no_enqueued_emails_failure <ide> error = assert_raise ActiveSupport::TestCase::Assertion do <ide> assert_no_enqueued_emails do <del> TestHelperMailer.test.deliver_later <add> silence_stream($stdout) do <add> TestHelperMailer.test.deliver_later <add> end <ide> end <ide> end <ide>
1
Go
Go
fix autorun issue within docker build
ae0d555022411025607acce43ea1929bafd7174a
<ide><path>buildfile.go <ide> func (b *buildFile) CmdRun(args string) error { <ide> return err <ide> } <ide> <del> cmd, env := b.config.Cmd, b.config.Env <add> cmd := b.config.Cmd <ide> b.config.Cmd = nil <ide> MergeConfig(b.config, config) <ide> <add> utils.Debugf("Commang to be executed: %v", b.config.Cmd) <add> <ide> if cache, err := b.srv.ImageGetCached(b.image, config); err != nil { <ide> return err <ide> } else if cache != nil { <ide> func (b *buildFile) CmdRun(args string) error { <ide> if err != nil { <ide> return err <ide> } <del> b.config.Cmd, b.config.Env = cmd, env <del> return b.commit(cid) <add> if err := b.commit(cid, cmd); err != nil { <add> return err <add> } <add> b.config.Cmd = cmd <add> return nil <ide> } <ide> <ide> func (b *buildFile) CmdEnv(args string) error { <ide> func (b *buildFile) CmdExpose(args string) error { <ide> } <ide> <ide> func (b *buildFile) CmdInsert(args string) error { <add> <ide> if b.image == "" { <ide> return fmt.Errorf("Please provide a source image with `from` prior to insert") <ide> } <ide> func (b *buildFile) CmdInsert(args string) error { <ide> } <ide> defer file.Body.Close() <ide> <add> cmd := b.config.Cmd <ide> b.config.Cmd = []string{"echo", "INSERT", sourceUrl, "in", destPath} <ide> cid, err := b.run() <ide> if err != nil { <ide> func (b *buildFile) CmdInsert(args string) error { <ide> return err <ide> } <ide> <del> return b.commit(cid) <add> return b.commit(cid, cmd) <ide> } <ide> <ide> func (b *buildFile) CmdAdd(args string) error { <ide> func (b *buildFile) CmdAdd(args string) error { <ide> orig := strings.Trim(tmp[0], " ") <ide> dest := strings.Trim(tmp[1], " ") <ide> <add> cmd := b.config.Cmd <ide> b.config.Cmd = []string{"echo", "PUSH", orig, "in", dest} <ide> cid, err := b.run() <ide> if err != nil { <ide> func (b *buildFile) CmdAdd(args string) error { <ide> } <ide> } <ide> <del> return b.commit(cid) <add> return b.commit(cid, cmd) <ide> } <ide> <ide> func (b *buildFile) run() (string, error) { <ide> func (b *buildFile) run() (string, error) { <ide> return c.Id, nil <ide> } <ide> <del>func (b *buildFile) commit(id string) error { <add>// Commit the container <id> with the autorun command <autoCmd> <add>func (b *buildFile) commit(id string, autoCmd []string) error { <ide> if b.image == "" { <ide> return fmt.Errorf("Please provide a source image with `from` prior to commit") <ide> } <ide> func (b *buildFile) commit(id string) error { <ide> return fmt.Errorf("An error occured while creating the container") <ide> } <ide> <add> // Note: Actually copy the struct <add> autoConfig := *b.config <add> autoConfig.Cmd = autoCmd <ide> // Commit the container <del> image, err := b.builder.Commit(container, "", "", "", b.maintainer, nil) <add> image, err := b.builder.Commit(container, "", "", "", b.maintainer, &autoConfig) <ide> if err != nil { <ide> return err <ide> } <ide> func (b *buildFile) Build(dockerfile, context io.Reader) (string, error) { <ide> fmt.Fprintf(b.out, "===> %v\n", b.image) <ide> } <ide> if b.needCommit { <del> if err := b.commit(""); err != nil { <add> if err := b.commit("", nil); err != nil { <ide> return "", err <ide> } <ide> }
1
Python
Python
improve worker benchmark
f75e9de9a012837369f7ee7f0f5f6b95935a0c5c
<ide><path>funtests/bench/worker.py <del>import time <del> <del>from celery import Celery <del> <del>celery = Celery() <del>celery.conf.update(BROKER_TRANSPORT="memory", <del> BROKER_POOL_LIMIT=1, <del> CELERY_PREFETCH_MULTIPLIER=0, <del> CELERY_DISABLE_RATE_LIMITS=True, <del> CELERY_BACKEND=None) <del> <del> <del>def bench_consumer(n=10000): <del> from celery.worker import WorkController <del> from celery.worker import state <del> <del> worker = WorkController(app=celery, pool_cls="solo") <del> time_start = [None] <del> <del> @celery.task() <del> def it(i): <del> if not i: <del> time_start[0] = time.time() <del> elif i == n - 1: <del> print(time.time() - time_start[0]) <del> <del> @celery.task() <del> def shutdown_worker(): <del> raise SystemExit() <del> <del> for i in xrange(n): <del> it.delay(i) <del> shutdown_worker.delay() <del> <del> try: <del> worker.start() <del> except SystemExit: <del> assert sum(state.total_count.values()) == n + 1 <del> <del> <del>if __name__ == "__main__": <del> bench_consumer() <ide><path>funtests/benchmarks/bench_worker.py <add>import os <add>import sys <add>import time <add> <add>from celery import Celery <add> <add>celery = Celery(__name__) <add>celery.conf.update(BROKER_TRANSPORT="amqp", <add> BROKER_POOL_LIMIT=10, <add> CELERY_PREFETCH_MULTIPLIER=0, <add> CELERY_DISABLE_RATE_LIMITS=True, <add> CELERY_BACKEND=None) <add> <add> <add>@celery.task() <add>def shutdown_worker(): <add> print("SHUTTING DOWN") <add> raise SystemExit() <add> <add> <add>@celery.task(cur=0, time_start=None, queue="bench.worker") <add>def it(_, n): <add> i = it.cur # use internal counter, as ordering can be skewed <add> # by previous runs, or the broker. <add> if i and not i % 1000: <add> print >> sys.stderr, i <add> if not i: <add> it.time_start = time.time() <add> elif i == n - 1: <add> print("consume: %s" % (time.time() - it.time_start, )) <add> shutdown_worker.delay() <add> it.cur += 1 <add> <add> <add>def bench_apply(n=50000): <add> time_start = time.time() <add> celery.TaskSet(it.subtask((i, n)) for i in xrange(n)).apply_async() <add> print("apply: %s" % (time.time() - time_start, )) <add> <add> <add>def bench_consume(n=50000): <add> from celery.worker import WorkController <add> from celery.worker import state <add> <add> import logging <add> #celery.log.setup_logging_subsystem(loglevel=logging.DEBUG) <add> worker = celery.WorkController(pool_cls="solo", <add> queues=["bench.worker"]) <add> <add> try: <add> print("STARTING WORKER") <add> worker.start() <add> except SystemExit: <add> assert sum(state.total_count.values()) == n + 1 <add> <add> <add>def bench_both(n=50000): <add> bench_apply(n) <add> bench_consumer(n) <add> <add> <add>def main(argv=sys.argv): <add> if len(argv) < 2: <add> print("Usage: %s [apply|consume|both]" % (os.path.basename(argv[0]), )) <add> return sys.exit(1) <add> return {"apply": bench_apply, <add> "consume": bench_consume, <add> "both": bench_both}[argv[1]]() <add> <add> <add>if __name__ == "__main__": <add> main()
2
PHP
PHP
fix cs errors
59e392c21d6cb218b7d6496431ddcb01d7c7156a
<ide><path>src/Datasource/SimplePaginator.php <ide> <?php <add>declare(strict_types=1); <add> <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testDeleteStripAliasesFromConditions() <ide> 'OR' => [ <ide> $query->newExpr()->eq(new IdentifierExpression('c.name'), 'zap'), <ide> 'd.name' => 'baz', <del> (new Query($this->connection))->select(['e.name'])->where(['e.name' => 'oof']) <del> ] <del> ] <add> (new Query($this->connection))->select(['e.name'])->where(['e.name' => 'oof']), <add> ], <add> ], <ide> ], <ide> ]); <ide> <ide><path>tests/TestCase/Datasource/PaginatorTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Datasource; <ide> <del>use Cake\Core\Configure; <del>use Cake\Datasource\ConnectionManager; <del>use Cake\Datasource\EntityInterface; <del>use Cake\Datasource\Exception\PageOutOfBoundsException; <del>use Cake\Datasource\Paginator; <del>use Cake\Datasource\RepositoryInterface; <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <ide> <ide> class PaginatorTest extends TestCase <ide> */ <ide> public $fixtures = [ <ide> 'core.Posts', 'core.Articles', 'core.ArticlesTags', <del> 'core.Authors', 'core.AuthorsTags', 'core.Tags' <add> 'core.Authors', 'core.AuthorsTags', 'core.Tags', <ide> ]; <ide> <ide> /** <ide> public function testPaginateCustomFinder() <ide> 'finder' => 'published', <ide> 'fields' => ['id', 'title'], <ide> 'maxLimit' => 10, <del> ] <add> ], <ide> ]; <ide> <ide> $this->loadFixtures('Posts'); <ide><path>tests/TestCase/Datasource/PaginatorTestTrait.php <ide> <?php <add>declare(strict_types=1); <add> <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> use Cake\Datasource\Exception\PageOutOfBoundsException; <ide> use Cake\Datasource\Paginator; <ide> use Cake\Datasource\RepositoryInterface; <del>use Cake\ORM\Entity; <ide> <ide> trait PaginatorTestTrait <ide> { <ide> public function testPaginateExtraParams() <ide> 'contain' => ['PaginatorAuthor'], <ide> 'maxLimit' => 10, <ide> 'group' => 'PaginatorPosts.published', <del> 'order' => ['PaginatorPosts.id' => 'ASC'] <add> 'order' => ['PaginatorPosts.id' => 'ASC'], <ide> ], <ide> ]; <ide> $table = $this->_getMockPosts(['query']); <ide> public function testPaginateCustomFinderOptions() <ide> $this->loadFixtures('Posts'); <ide> $settings = [ <ide> 'PaginatorPosts' => [ <del> 'finder' => ['author' => ['author_id' => 1]] <del> ] <add> 'finder' => ['author' => ['author_id' => 1]], <add> ], <ide> ]; <ide> $table = $this->getTableLocator()->get('PaginatorPosts'); <ide> <ide> $expected = $table <ide> ->find('author', [ <ide> 'conditions' => [ <del> 'PaginatorPosts.author_id' => 1 <del> ] <add> 'PaginatorPosts.author_id' => 1, <add> ], <ide> ]) <ide> ->count(); <ide> $result = $this->Paginator->paginate($table, [], $settings)->count(); <ide> public function testMergeOptionsCustomScope() <ide> 'scope' => [ <ide> 'page' => 2, <ide> 'limit' => 5, <del> ] <add> ], <ide> ]; <ide> <ide> $settings = [ <ide> public function testMergeOptionsCustomFindKey() <ide> { <ide> $params = [ <ide> 'page' => 10, <del> 'limit' => 10 <add> 'limit' => 10, <ide> ]; <ide> $settings = [ <ide> 'page' => 1, <ide> 'limit' => 20, <ide> 'maxLimit' => 100, <del> 'finder' => 'myCustomFind' <add> 'finder' => 'myCustomFind', <ide> ]; <ide> $defaults = $this->Paginator->getDefaults('Post', $settings); <ide> $result = $this->Paginator->mergeOptions($params, $defaults); <ide> public function testMergeOptionsQueryString() <ide> { <ide> $params = [ <ide> 'page' => 99, <del> 'limit' => 75 <add> 'limit' => 75, <ide> ]; <ide> $settings = [ <ide> 'page' => 1, <ide> public function testMergeOptionsDefaultWhiteList() <ide> 'fields' => ['bad.stuff'], <ide> 'recursive' => 1000, <ide> 'conditions' => ['bad.stuff'], <del> 'contain' => ['bad'] <add> 'contain' => ['bad'], <ide> ]; <ide> $settings = [ <ide> 'page' => 1, <ide> public function testMergeOptionsExtraWhitelist() <ide> 'fields' => ['bad.stuff'], <ide> 'recursive' => 1000, <ide> 'conditions' => ['bad.stuff'], <del> 'contain' => ['bad'] <add> 'contain' => ['bad'], <ide> ]; <ide> $settings = [ <ide> 'page' => 1, <ide> public function testMergeOptionsExtraWhitelist() <ide> $defaults = $this->Paginator->getDefaults('Post', $settings); <ide> $result = $this->Paginator->mergeOptions($params, $defaults); <ide> $expected = [ <del> 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'fields' => ['bad.stuff'], 'whitelist' => ['limit', 'sort', 'page', 'direction', 'fields'] <add> 'page' => 10, 'limit' => 10, 'maxLimit' => 100, 'fields' => ['bad.stuff'], 'whitelist' => ['limit', 'sort', 'page', 'direction', 'fields'], <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testMergeOptionsMaxLimit() <ide> 'limit' => 100, <ide> 'maxLimit' => 100, <ide> 'paramType' => 'named', <del> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'], <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testMergeOptionsMaxLimit() <ide> 'limit' => 10, <ide> 'maxLimit' => 10, <ide> 'paramType' => 'named', <del> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'], <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testGetDefaultMaxLimit() <ide> 'limit' => 2, <ide> 'maxLimit' => 10, <ide> 'order' => [ <del> 'Users.username' => 'asc' <add> 'Users.username' => 'asc', <ide> ], <ide> ]; <ide> $defaults = $this->Paginator->getDefaults('Post', $settings); <ide> public function testGetDefaultMaxLimit() <ide> 'limit' => 2, <ide> 'maxLimit' => 10, <ide> 'order' => [ <del> 'Users.username' => 'asc' <add> 'Users.username' => 'asc', <ide> ], <del> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'], <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> <ide> public function testGetDefaultMaxLimit() <ide> 'limit' => 100, <ide> 'maxLimit' => 10, <ide> 'order' => [ <del> 'Users.username' => 'asc' <add> 'Users.username' => 'asc', <ide> ], <ide> ]; <ide> $defaults = $this->Paginator->getDefaults('Post', $settings); <ide> public function testGetDefaultMaxLimit() <ide> 'limit' => 10, <ide> 'maxLimit' => 10, <ide> 'order' => [ <del> 'Users.username' => 'asc' <add> 'Users.username' => 'asc', <ide> ], <del> 'whitelist' => ['limit', 'sort', 'page', 'direction'] <add> 'whitelist' => ['limit', 'sort', 'page', 'direction'], <ide> ]; <ide> $this->assertEquals($expected, $result); <ide> } <ide> public function testValidateSortInvalid() <ide> $params = [ <ide> 'page' => 1, <ide> 'sort' => 'id', <del> 'direction' => 'herp' <add> 'direction' => 'herp', <ide> ]; <ide> $this->Paginator->paginate($table, $params); <ide> $pagingParams = $this->Paginator->getPagingParams(); <ide> public function testValidateSortAndDirectionAliased() <ide> $queryParams = [ <ide> 'page' => 1, <ide> 'sort' => 'title', <del> 'direction' => 'asc' <add> 'direction' => 'asc', <ide> ]; <ide> <ide> $this->Paginator->paginate($table, $queryParams, $options); <ide> public function testValidateSortRetainsOriginalSortValue() <ide> $params = [ <ide> 'page' => 1, <ide> 'sort' => 'id', <del> 'direction' => 'herp' <add> 'direction' => 'herp', <ide> ]; <ide> $options = [ <del> 'sortWhitelist' => ['id'] <add> 'sortWhitelist' => ['id'], <ide> ]; <ide> $this->Paginator->paginate($table, $params, $options); <ide> $pagingParams = $this->Paginator->getPagingParams(); <ide> public function testOutOfRangePageNumberGetsClamped() <ide> $this->assertSame( <ide> [ <ide> 'requestedPage' => 3000, <del> 'pagingParams' => $this->Paginator->getPagingParams() <add> 'pagingParams' => $this->Paginator->getPagingParams(), <ide> ], <ide> $exception->getAttributes() <ide> ); <ide> public function testValidateSortWhitelistFailure() <ide> $options = [ <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'sortWhitelist' => ['title', 'id'] <add> 'sortWhitelist' => ['title', 'id'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortWhitelistTrusted() <ide> $options = [ <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'sortWhitelist' => ['body'] <add> 'sortWhitelist' => ['body'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortWhitelistEmpty() <ide> $options = [ <ide> 'order' => [ <ide> 'body' => 'asc', <del> 'foo.bar' => 'asc' <add> 'foo.bar' => 'asc', <ide> ], <ide> 'sort' => 'body', <ide> 'direction' => 'asc', <del> 'sortWhitelist' => [] <add> 'sortWhitelist' => [], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortWhitelistNotInSchema() <ide> $options = [ <ide> 'sort' => 'score', <ide> 'direction' => 'asc', <del> 'sortWhitelist' => ['score'] <add> 'sortWhitelist' => ['score'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortWhitelistMultiple() <ide> $options = [ <ide> 'order' => [ <ide> 'body' => 'asc', <del> 'foo.bar' => 'asc' <add> 'foo.bar' => 'asc', <ide> ], <del> 'sortWhitelist' => ['body', 'foo.bar'] <add> 'sortWhitelist' => ['body', 'foo.bar'], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> $expected = [ <ide> 'model.body' => 'asc', <del> 'foo.bar' => 'asc' <add> 'foo.bar' => 'asc', <ide> ]; <ide> $this->assertEquals($expected, $result['order']); <ide> } <ide> public function testValidateSortMultiple() <ide> $options = [ <ide> 'order' => [ <ide> 'author_id' => 'asc', <del> 'title' => 'asc' <del> ] <add> 'title' => 'asc', <add> ], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> $expected = [ <ide> 'model.author_id' => 'asc', <del> 'model.title' => 'asc' <add> 'model.title' => 'asc', <ide> ]; <ide> <ide> $this->assertEquals($expected, $result['order']); <ide> public function testValidateSortMultipleWithQuery() <ide> 'direction' => 'desc', <ide> 'order' => [ <ide> 'author_id' => 'asc', <del> 'title' => 'asc' <del> ] <add> 'title' => 'asc', <add> ], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> $expected = [ <ide> 'model.created' => 'desc', <ide> 'model.author_id' => 'asc', <del> 'model.title' => 'asc' <add> 'model.title' => 'asc', <ide> ]; <ide> $this->assertEquals($expected, $result['order']); <ide> <ide> public function testValidateSortMultipleWithQuery() <ide> 'direction' => 'desc', <ide> 'order' => [ <ide> 'author_id' => 'asc', <del> 'title' => 'asc' <del> ] <add> 'title' => 'asc', <add> ], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortMultipleWithQueryAndAliasedDefault() <ide> 'sort' => 'created', <ide> 'direction' => 'desc', <ide> 'order' => [ <del> 'model.created' => 'asc' <del> ] <add> 'model.created' => 'asc', <add> ], <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> <ide> public function testValidateSortWithString() <ide> $model = $this->mockAliasHasFieldModel(); <ide> <ide> $options = [ <del> 'order' => 'model.author_id DESC' <add> 'order' => 'model.author_id DESC', <ide> ]; <ide> $result = $this->Paginator->validateSort($model, $options); <ide> $expected = 'model.author_id DESC'; <ide> public function testPaginateMaxLimit() <ide> 'maxLimit' => 100, <ide> ]; <ide> $params = [ <del> 'limit' => '1000' <add> 'limit' => '1000', <ide> ]; <ide> $this->Paginator->paginate($table, $params, $settings); <ide> $pagingParams = $this->Paginator->getPagingParams(); <ide> $this->assertEquals(100, $pagingParams['PaginatorPosts']['limit']); <ide> $this->assertEquals(100, $pagingParams['PaginatorPosts']['perPage']); <ide> <ide> $params = [ <del> 'limit' => '10' <add> 'limit' => '10', <ide> ]; <ide> $this->Paginator->paginate($table, $params, $settings); <ide> $pagingParams = $this->Paginator->getPagingParams(); <ide> public function testPaginateCustomFindCount() <ide> { <ide> $settings = [ <ide> 'finder' => 'published', <del> 'limit' => 2 <add> 'limit' => 2, <ide> ]; <ide> $table = $this->_getMockPosts(['query']); <ide> $query = $this->_getMockFindQuery(); <ide> public function testPaginateQuery() <ide> 'contain' => ['PaginatorAuthor'], <ide> 'maxLimit' => 10, <ide> 'group' => 'PaginatorPosts.published', <del> 'order' => ['PaginatorPosts.id' => 'ASC'] <del> ] <add> 'order' => ['PaginatorPosts.id' => 'ASC'], <add> ], <ide> ]; <ide> $table = $this->_getMockPosts(['find']); <ide> $query = $this->_getMockFindQuery($table); <ide> public function testPaginateQueryWithLimit() <ide> 'maxLimit' => 10, <ide> 'limit' => 5, <ide> 'group' => 'PaginatorPosts.published', <del> 'order' => ['PaginatorPosts.id' => 'ASC'] <del> ] <add> 'order' => ['PaginatorPosts.id' => 'ASC'], <add> ], <ide> ]; <ide> $table = $this->_getMockPosts(['find']); <ide> $query = $this->_getMockFindQuery($table); <ide> protected function _getMockPosts($methods = []) <ide> 'title' => ['type' => 'string', 'null' => false], <ide> 'body' => 'text', <ide> 'published' => ['type' => 'string', 'length' => 1, 'default' => 'N'], <del> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]] <del> ] <add> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]], <add> ], <ide> ]]) <ide> ->getMock(); <ide> } <ide><path>tests/TestCase/Datasource/SimplePaginatorTest.php <ide> <?php <add>declare(strict_types=1); <add> <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> class SimplePaginatorTest extends PaginatorTest <ide> */ <ide> public $fixtures = [ <ide> 'core.Posts', 'core.Articles', 'core.ArticlesTags', <del> 'core.Authors', 'core.AuthorsTags', 'core.Tags' <add> 'core.Authors', 'core.AuthorsTags', 'core.Tags', <ide> ]; <ide> <ide> /** <ide> public function testPaginateCustomFindFieldsArray() <ide> $settings = [ <ide> 'finder' => 'list', <ide> 'conditions' => ['PaginatorPosts.published' => 'Y'], <del> 'limit' => 2 <add> 'limit' => 2, <ide> ]; <ide> $results = $this->Paginator->paginate($table, [], $settings); <ide> <ide> public function testPaginateCustomFinder() <ide> 'finder' => 'published', <ide> 'fields' => ['id', 'title'], <ide> 'maxLimit' => 10, <del> ] <add> ], <ide> ]; <ide> <ide> $this->loadFixtures('Posts'); <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testMethodsWhenThereIsNoPageCount() <ide> 'sort' => null, <ide> 'direction' => null, <ide> 'limit' => null, <del> ] <del> ] <del> ] <add> ], <add> ], <add> ], <ide> ]); <ide> <ide> $view = new View($request);
6
Javascript
Javascript
reuse timer in `settimeout().unref()`
3eecdf9f1422640c7439507cb39ffb3dff57b3e4
<ide><path>lib/timers.js <ide> function listOnTimeoutNT(list) { <ide> } <ide> <ide> <del>const unenroll = exports.unenroll = function(item) { <add>function reuse(item) { <ide> L.remove(item); <ide> <ide> var list = lists[item._idleTimeout]; <del> // if empty then stop the watcher <del> debug('unenroll'); <add> // if empty - reuse the watcher <ide> if (list && L.isEmpty(list)) { <add> debug('reuse hit'); <add> list.stop(); <add> delete lists[item._idleTimeout]; <add> return list; <add> } <add> <add> return null; <add>} <add> <add> <add>const unenroll = exports.unenroll = function(item) { <add> var list = reuse(item); <add> if (list) { <ide> debug('unenroll: list empty'); <ide> list.close(); <del> delete lists[item._idleTimeout]; <ide> } <ide> // if active is called later, then we want to make sure not to insert again <ide> item._idleTimeout = -1; <ide> Timeout.prototype.unref = function() { <ide> if (!this._idleStart) this._idleStart = now; <ide> var delay = this._idleStart + this._idleTimeout - now; <ide> if (delay < 0) delay = 0; <del> exports.unenroll(this); <ide> <ide> // Prevent running cb again when unref() is called during the same cb <del> if (this._called && !this._repeat) return; <add> if (this._called && !this._repeat) { <add> exports.unenroll(this); <add> return; <add> } <add> <add> var handle = reuse(this); <ide> <del> this._handle = new Timer(); <add> this._handle = handle || new Timer(); <ide> this._handle.owner = this; <ide> this._handle[kOnTimeout] = unrefdHandle; <ide> this._handle.start(delay, 0); <ide><path>test/parallel/test-timers-unrefed-in-beforeexit.js <add>'use strict'; <add> <add>require('../common'); <add>const assert = require('assert'); <add> <add>var once = 0; <add> <add>process.on('beforeExit', () => { <add> if (once > 1) <add> throw new RangeError('beforeExit should only have been called once!'); <add> <add> setTimeout(() => {}, 1).unref(); <add> once++; <add>}); <add> <add>process.on('exit', (code) => { <add> if (code !== 0) return; <add> <add> assert.strictEqual(once, 1); <add>});
2
Java
Java
check stomp headers against ending backslash
18033486aec5de46833a2437026a0494c6485460
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompDecoder.java <ide> private String unescape(String inString) { <ide> <ide> while (index >= 0) { <ide> sb.append(inString.substring(pos, index)); <add> if((index + 1) >= inString.length()) { <add> throw new StompConversionException("Illegal escape sequence at index " + index + ": " + inString); <add> } <ide> Character c = inString.charAt(index + 1); <ide> if (c == 'r') { <ide> sb.append('\r'); <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/BufferingStompDecoderTests.java <ide> public void incompleteCommand() throws InterruptedException { <ide> assertEquals(0, messages.size()); <ide> } <ide> <add> @Test(expected = StompConversionException.class) // SPR-12418 <add> public void endingBackslashHeaderValueCheck() throws InterruptedException { <add> BufferingStompDecoder stompDecoder = new BufferingStompDecoder(STOMP_DECODER, 128); <add> String payload = "SEND\na:alpha\\\n\nMessage body\0"; <add> stompDecoder.decode(toByteBuffer(payload)); <add> } <add> <ide> <ide> private ByteBuffer toByteBuffer(String chunk) { <ide> return ByteBuffer.wrap(chunk.getBytes(Charset.forName("UTF-8")));
2
Text
Text
add punctuation in lines 23, 35, and 83.
1cbbee03809dbb7251564c4b5f625f4b80946721
<ide><path>guide/english/css/box-shadow/index.md <ide> A box shadow can be described with several properties including: <ide> ``` <ide> * #### inset (default: none) <ide> If not specified, the shadow is assumed to be a drop shadow (as if the box were raised above the content). <del>The presence of the `inset` keyword changes the shadow to one inside the frame <add>The presence of the `inset` keyword changes the shadow to one inside the frame. <ide> <ide> * #### offset-x offset-y <ide> These are two `length` values to set the shadow offset. <offset-x> specifies the horizontal distance. Negative values place the shadow to the left of the element. `offset-y` specifies the vertical distance. Negative values place the shadow above the element. See `length` for possible units. <ide> This is a third `length` value. The larger this value, the bigger the blur, so t <ide> This is a fourth <length> value. Positive values will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink. If not specified, it will be 0 (the shadow will be the same size as the element). <ide> <ide> * #### color <del>This value is used to set the color of the shadow, usually defined with hex `#000000`, rgba value `rgba(55,89,88,0.8)` or rgb value `rgb(55,89,88)` <add>This value is used to set the color of the shadow, usually defined with hex `#000000`, rgba value `rgba(55,89,88,0.8)` or rgb value `rgb(55,89,88)`. <ide> <ide> #### Extended <ide> <ide> div { <ide> box-shadow: inset 10px 10px 5px #ccc; <ide> } <ide> ``` <del>It uses very similar code, but with inset value, which displays shadow inside the div element <add>It uses very similar code, but with inset value, which displays shadow inside the div element. <ide> <ide> ![image](https://raw.githubusercontent.com/krzysiekh/images/master/box-shadow2.png) <ide>
1
PHP
PHP
fix comment about bundle caching
a0379ea48d361a02deb9bb1a259a1341f2e192e0
<ide><path>application/config/application.php <ide> | <ide> | All bundles have a "bundle.info" file which contains information such <ide> | as the name of a bundle and the URIs it responds to. This value is <del> | the number of that bundle info is cached. <add> | the number of minutes that bundle info is cached. <ide> | <ide> | Auto: <ide> |
1
Text
Text
add readme for flax clm
d36fce8237eab3af6d717da8530d6edafd045e1e
<ide><path>examples/flax/language-modeling/README.md <ide> Training statistics can be accessed on [tfhub.de](https://tensorboard.dev/experi <ide> For a step-by-step walkthrough of how to do masked language modeling in Flax, please have a <ide> look at [this](https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/masked_language_modeling_flax.ipynb) google colab. <ide> <add>## Causal language modeling <add> <add>In the following, we demonstrate how to train an auto-regressive causal transformer model <add>in JAX/Flax. <add>More specifically, we pretrain a randomely initialized [**`gpt2`**](https://huggingface.co/gpt2) model in Norwegian on a single TPUv3-8. <add>to pre-train 124M [**`gpt2`**](https://huggingface.co/gpt2) <add>in Norwegian on a single TPUv3-8 pod. <add> <add>The example script uses the 🤗 Datasets library. You can easily customize them to your needs if you need extra processing on your datasets. <add> <add>Let's start by creating a folder to save the trained model and a symbolic link to the `run_clm_flax.py` script. <add> <add>```bash <add>export MODEL_DIR="./norwegian-gpt2" <add>mkdir -p ${MODEL_DIR} <add>ln -s ~/transformers/examples/flax/language-modeling/run_clm_flax.py run_clm_flax.py <add>``` <add> <add>Next, we'll follow the same steps as above in [Train tokenizer](#train-tokenizer) to train the tokenizer. <add> <add>### Create configuration <add> <add>Next, we create the model's configuration file. This is as simple <add>as loading and storing [`**gpt2**`](https://huggingface.co/gpt2) <add>in the local model folder: <add> <add>```python <add>from transformers import GPT2Config <add> <add>model_dir = "./norwegian-gpt2" # ${MODEL_DIR} <add> <add>config = GPT2Config.from_pretrained("gpt2", resid_pdrop=0.0, embd_pdrop=0.0, attn_pdrop=0.0) <add>config.save_pretrained(model_dir) <add>``` <add> <add>### Train model <add> <add>Next we can run the example script to pretrain the model: <add> <add>```bash <add>./run_clm_flax.py \ <add> --output_dir="./runs" \ <add> --model_type="gpt2" \ <add> --config_name="${MODEL_DIR}" \ <add> --tokenizer_name="${MODEL_DIR}" \ <add> --dataset_name="oscar" \ <add> --dataset_config_name="unshuffled_deduplicated_no" \ <add> --do_train --do_eval \ <add> --block_size="512" \ <add> --per_device_train_batch_size="64" \ <add> --per_device_eval_batch_size="64" \ <add> --learning_rate="5e-3" --warmup_steps="1000" \ <add> --adam_beta1="0.9" --adam_beta2="0.98" --weight_decay="0.01" \ <add> --overwrite_output_dir \ <add> --num_train_epochs="20" \ <add>``` <add> <add>Training should converge at a loss and perplexity <add>of 3.24 and 25.72 respectively after 20 epochs on a single TPUv3-8. <add>This should take less than ~21 hours. <add>Training statistics can be accessed on [tfhub.de](https://tensorboard.dev/experiment/2zEhLwJ0Qp2FAkI3WVH9qA). <add> <ide> <ide> ## Runtime evaluation <ide>
1
Javascript
Javascript
add missing license header
d8b6d260c965c154d3a1997e613597a50c140656
<ide><path>src/utils/__tests__/onlyChild-test.js <ide> /** <add> * Copyright 2013 Facebook, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> * <ide> * @emails react-core <ide> * @jsx React.DOM <ide> */
1
Ruby
Ruby
create etc if it doesn't exist
cf2a8913c57621b8b3e109d55016e26e4f92066c
<ide><path>Library/Homebrew/formula_installer.rb <ide> def git_etc_preinstall <ide> def git_etc_postinstall <ide> return unless quiet_system 'git', '--version' <ide> <del> etc = HOMEBREW_PREFIX+'etc' <ide> preinstall_branch = "#{f.name}-preinstall" <ide> default_branch = "#{f.name}-default" <ide> merged = false <del> etc.cd do <add> f.etc.mkpath <add> f.etc.cd do <ide> if quiet_system 'git', 'diff', '--exit-code', preinstall_branch <ide> quiet_system 'git', 'branch', default_branch <ide> quiet_system 'git', 'branch', '-D', preinstall_branch
1
Go
Go
add metadata function to layer store
a7e096832123280d26df3c121ecad8dd012060b9
<ide><path>daemon/container_operations_windows.go <ide> func (daemon *Daemon) populateCommand(c *container.Container, env []string) erro <ide> } <ide> } <ide> <del> m, err := layer.RWLayerMetadata(daemon.layerStore, c.ID) <add> m, err := daemon.layerStore.Metadata(c.ID) <ide> if err != nil { <ide> return derr.ErrorCodeGetLayerMetadata.WithArgs(err) <ide> } <ide><path>daemon/inspect.go <ide> import ( <ide> "github.com/docker/docker/container" <ide> "github.com/docker/docker/daemon/exec" <ide> "github.com/docker/docker/daemon/network" <del> "github.com/docker/docker/layer" <ide> "github.com/docker/docker/pkg/version" <ide> ) <ide> <ide> func (daemon *Daemon) getInspectData(container *container.Container, size bool) <ide> <ide> contJSONBase.GraphDriver.Name = container.Driver <ide> <del> image, err := daemon.imageStore.Get(container.ImageID) <del> if err != nil { <del> return nil, err <del> } <del> l, err := daemon.layerStore.Get(image.RootFS.ChainID()) <del> if err != nil { <del> return nil, err <del> } <del> defer layer.ReleaseAndLog(daemon.layerStore, l) <del> <del> graphDriverData, err := l.Metadata() <add> graphDriverData, err := daemon.layerStore.Metadata(container.ID) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>distribution/xfer/download_test.go <ide> func (ls *mockLayerStore) Changes(id string) ([]archive.Change, error) { <ide> return nil, errors.New("not implemented") <ide> } <ide> <add>func (ls *mockLayerStore) Metadata(id string) (map[string]string, error) { <add> return nil, errors.New("not implemented") <add>} <add> <ide> type mockDownloadDescriptor struct { <ide> currentDownloads *int32 <ide> id string <ide><path>integration-cli/docker_cli_inspect_test.go <ide> func (s *DockerSuite) TestInspectContainerGraphDriver(c *check.C) { <ide> return <ide> } <ide> <add> imageDeviceID, err := inspectField("busybox", "GraphDriver.Data.DeviceId") <add> c.Assert(err, checker.IsNil) <add> <ide> deviceID, err := inspectField(out, "GraphDriver.Data.DeviceId") <ide> c.Assert(err, checker.IsNil) <ide> <add> c.Assert(imageDeviceID, checker.Not(checker.Equals), deviceID) <add> <ide> _, err = strconv.Atoi(deviceID) <ide> c.Assert(err, checker.IsNil, check.Commentf("failed to inspect DeviceId of the image: %s, %v", deviceID, err)) <ide> <ide><path>layer/layer.go <ide> type Store interface { <ide> Unmount(id string) error <ide> DeleteMount(id string) ([]Metadata, error) <ide> Changes(id string) ([]archive.Change, error) <add> Metadata(id string) (map[string]string, error) <ide> } <ide> <ide> // MetadataTransaction represents functions for setting layer metadata <ide><path>layer/layer_store.go <ide> func (ls *layerStore) assembleTar(graphID string, metadata io.ReadCloser, size * <ide> return pR, nil <ide> } <ide> <add>// Metadata returns the low level metadata from the mount with the given name <add>func (ls *layerStore) Metadata(name string) (map[string]string, error) { <add> ls.mountL.Lock() <add> m := ls.mounts[name] <add> ls.mountL.Unlock() <add> if m == nil { <add> return nil, ErrMountDoesNotExist <add> } <add> return ls.driver.GetMetadata(m.mountID) <add>} <add> <ide> type naiveDiffPathDriver struct { <ide> graphdriver.Driver <ide> } <ide><path>layer/layer_windows.go <ide> func GetLayerPath(s Store, layer ChainID) (string, error) { <ide> return path, nil <ide> } <ide> <del>// RWLayerMetadata returns the graph metadata for the provided <del>// mount name. <del>func RWLayerMetadata(s Store, name string) (map[string]string, error) { <del> ls, ok := s.(*layerStore) <del> if !ok { <del> return nil, errors.New("unsupported layer store") <del> } <del> ls.mountL.Lock() <del> defer ls.mountL.Unlock() <del> <del> ml, ok := ls.mounts[name] <del> if !ok { <del> return nil, errors.New("mount does not exist") <del> } <del> <del> return ls.driver.GetMetadata(ml.mountID) <del>} <del> <ide> func (ls *layerStore) RegisterDiffID(graphID string, size int64) (Layer, error) { <ide> var err error // this is used for cleanup in existingLayer case <ide> diffID, err := digest.FromBytes([]byte(graphID))
7
Text
Text
update version number
5b082ca65cd460c4ace9267be61e9f33143ff1c5
<ide><path>README.md <ide> recommend using the [app skeleton](https://github.com/cakephp/app) as <ide> a starting point. For existing applications you can run the following: <ide> <ide> ``` bash <del>$ composer require cakephp/cakephp:"~3.4" <add>$ composer require cakephp/cakephp:"~3.5" <ide> ``` <ide> <ide> ## Running Tests
1
Javascript
Javascript
improve output for tobemarkedasselected
4b06637f703d2a94baedfda64a8e3ac8eea26403
<ide><path>test/helpers/matchers.js <ide> beforeEach(function() { <ide> return { <ide> compare: function(actual) { <ide> var errors = []; <add> var optionVal = toJson(actual.value); <add> <ide> if (actual.selected === null || typeof actual.selected === 'undefined' || actual.selected === false) { <del> errors.push('Expected option property "selected" to be truthy'); <add> errors.push('Expected option with value ' + optionVal + ' to have property "selected" set to truthy'); <ide> } <ide> <ide> // Support: IE 9 only <ide> if (msie !== 9 && actual.hasAttribute('selected') === false) { <del> errors.push('Expected option to have attribute "selected"'); <add> errors.push('Expected option with value ' + optionVal + ' to have attribute "selected"'); <ide> } <ide> <ide> var result = { <ide> beforeEach(function() { <ide> }, <ide> negativeCompare: function(actual) { <ide> var errors = []; <add> var optionVal = toJson(actual.value); <add> <ide> if (actual.selected) { <del> errors.push('Expected option property "selected" to be falsy'); <add> errors.push('Expected option with value ' + optionVal + ' property "selected" to be falsy'); <ide> } <ide> <ide> // Support: IE 9 only <ide> if (msie !== 9 && actual.hasAttribute('selected')) { <del> errors.push('Expected option not to have attribute "selected"'); <add> errors.push('Expected option with value ' + optionVal + ' not to have attribute "selected"'); <ide> } <ide> <ide> var result = {
1
Ruby
Ruby
move optimize_helper? to the helper instance
d783ba2029bf523faae7d5a53ccfabeffaf3ff6c
<ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def self.create(route, options) <ide> end <ide> <ide> def initialize(route, options) <del> @options = options <add> @options = options <ide> @segment_keys = route.segment_keys <add> @route = route <add> end <add> <add> def optimize_helper? <add> @route.requirements.except(:controller, :action).empty? <ide> end <ide> <ide> def url_else(t, args) <ide> def define_url_helper(route, name, options) <ide> # end <ide> # end <ide> #END_EVAL <del> ohelp = optimize_helper?(route) <del> ohelper = optimized_helper(route) <del> arg_size = route.required_parts.size <ide> <ide> helper = UrlHelper.create(route, options.dup) <ide> <add> ohelp = helper.optimize_helper? <add> ohelper = optimized_helper(route) <add> arg_size = route.required_parts.size <add> <ide> @module.module_eval do <ide> define_method(name) do |*args| <add> #helper.call t, args <add> <ide> if ohelp && args.size == arg_size && !args.last.is_a?(Hash) && optimize_routes_generation? <ide> helper.url_if(self, eval("\"#{ohelper}\"")) <ide> else <ide> def define_url_helper(route, name, options) <ide> helpers << name <ide> end <ide> <del> # Clause check about when we need to generate an optimized helper. <del> def optimize_helper?(route) #:nodoc: <del> route.requirements.except(:controller, :action).empty? <del> end <del> <ide> # Generates the interpolation to be used in the optimized helper. <ide> def optimized_helper(route) <ide> string_route = route.ast.to_s
1
Python
Python
update error messages for legacy_rnn code
a99929176052e0c98cf3c7916d12b88633cab535
<ide><path>keras/layers/legacy_rnn/rnn_cell_impl.py <ide> def _concat(prefix, suffix, static=False): <ide> if p.shape.ndims == 0: <ide> p = tf.compat.v1.expand_dims(p, 0) <ide> elif p.shape.ndims != 1: <del> raise ValueError("prefix tensor must be either a scalar or vector, " <del> "but saw tensor: %s" % p) <add> raise ValueError( <add> "Prefix tensor must be either a scalar or vector, " <add> f"but received tensor: {p}") <ide> else: <ide> p = tf.TensorShape(prefix) <ide> p_static = p.as_list() if p.ndims is not None else None <ide> def _concat(prefix, suffix, static=False): <ide> s = tf.compat.v1.expand_dims(s, 0) <ide> elif s.shape.ndims != 1: <ide> raise ValueError("suffix tensor must be either a scalar or vector, " <del> "but saw tensor: %s" % s) <add> f"but received tensor: {s}") <ide> else: <ide> s = tf.TensorShape(suffix) <ide> s_static = s.as_list() if s.ndims is not None else None <ide> def _concat(prefix, suffix, static=False): <ide> shape = shape.as_list() if shape.ndims is not None else None <ide> else: <ide> if p is None or s is None: <del> raise ValueError("Provided a prefix or suffix of None: %s and %s" % <del> (prefix, suffix)) <add> raise ValueError( <add> "Prefix or suffix can't be None. " <add> f"Received prefix = {prefix} and suffix = {suffix}") <ide> shape = tf.concat((p, s), 0) <ide> return shape <ide> <ide> def get_initial_state(self, inputs=None, batch_size=None, dtype=None): <ide> if inputs.shape.dims[0].value != static_batch_size: <ide> raise ValueError( <ide> "batch size from input tensor is different from the " <del> "input param. Input tensor batch: {}, batch_size: {}".format( <del> inputs.shape.dims[0].value, batch_size)) <add> f"input param. Input tensor batch: {inputs.shape.dims[0].value}, " <add> f"batch_size: {batch_size}") <ide> <ide> if dtype is not None and inputs.dtype != dtype: <ide> raise ValueError( <ide> "dtype from input tensor is different from the " <del> "input param. Input tensor dtype: {}, dtype: {}".format( <del> inputs.dtype, dtype)) <add> f"input param. Input tensor dtype: {inputs.dtype}, dtype: {dtype}") <ide> <ide> batch_size = inputs.shape.dims[0].value or tf.compat.v1.shape(inputs)[0] <ide> dtype = inputs.dtype <ide> if batch_size is None or dtype is None: <ide> raise ValueError( <ide> "batch_size and dtype cannot be None while constructing initial " <del> "state: batch_size={}, dtype={}".format(batch_size, dtype)) <add> f"state: batch_size={batch_size}, dtype={dtype}") <ide> return self.zero_state(batch_size, dtype) <ide> <ide> def zero_state(self, batch_size, dtype): <ide> def output_size(self): <ide> @tf_utils.shape_type_conversion <ide> def build(self, inputs_shape): <ide> if inputs_shape[-1] is None: <del> raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % <del> str(inputs_shape)) <add> raise ValueError( <add> "Expected inputs.shape[-1] to be known, " <add> f"received shape: {inputs_shape}") <ide> _check_supported_dtypes(self.dtype) <ide> <ide> input_depth = inputs_shape[-1] <ide> def output_size(self): <ide> @tf_utils.shape_type_conversion <ide> def build(self, inputs_shape): <ide> if inputs_shape[-1] is None: <del> raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % <del> str(inputs_shape)) <add> raise ValueError( <add> "Expected inputs.shape[-1] to be known, " <add> f"received shape: {inputs_shape}") <ide> _check_supported_dtypes(self.dtype) <ide> input_depth = inputs_shape[-1] <ide> self._gate_kernel = self.add_variable( <ide> class LSTMStateTuple(_LSTMStateTuple): <ide> def dtype(self): <ide> (c, h) = self <ide> if c.dtype != h.dtype: <del> raise TypeError("Inconsistent internal state: %s vs %s" % <del> (str(c.dtype), str(h.dtype))) <add> raise TypeError("Inconsistent dtypes for internal state: " <add> f"{c.dtype} vs {h.dtype}") <ide> return c.dtype <ide> <ide> <ide> def output_size(self): <ide> @tf_utils.shape_type_conversion <ide> def build(self, inputs_shape): <ide> if inputs_shape[-1] is None: <del> raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % <del> str(inputs_shape)) <add> raise ValueError( <add> "Expected inputs.shape[-1] to be known, " <add> f"received shape: {inputs_shape}") <ide> _check_supported_dtypes(self.dtype) <ide> input_depth = inputs_shape[-1] <ide> h_depth = self._num_units <ide> def output_size(self): <ide> @tf_utils.shape_type_conversion <ide> def build(self, inputs_shape): <ide> if inputs_shape[-1] is None: <del> raise ValueError("Expected inputs.shape[-1] to be known, saw shape: %s" % <del> str(inputs_shape)) <add> raise ValueError( <add> "Expected inputs.shape[-1] to be known, " <add> "received shape: {inputs_shape}") <ide> _check_supported_dtypes(self.dtype) <ide> input_depth = inputs_shape[-1] <ide> h_depth = self._num_units if self._num_proj is None else self._num_proj <ide> def call(self, inputs, state): <ide> <ide> input_size = inputs.get_shape().with_rank(2).dims[1].value <ide> if input_size is None: <del> raise ValueError("Could not infer input size from inputs.get_shape()[-1]") <add> raise ValueError( <add> "Could not infer input size from inputs.get_shape()[-1]." <add> f"Received input shape: {inputs.get_shape()}") <ide> <ide> # i = input_gate, j = new_input, f = forget_gate, o = output_gate <ide> lstm_matrix = tf.matmul( <ide> def __init__(self, cells, state_is_tuple=True): <ide> if not cells: <ide> raise ValueError("Must specify at least one cell for MultiRNNCell.") <ide> if not tf.nest.is_nested(cells): <del> raise TypeError("cells must be a list or tuple, but saw: %s." % cells) <add> raise TypeError(f"cells must be a list or tuple, but received: {cells}.") <ide> <ide> if len(set(id(cell) for cell in cells)) < len(cells): <ide> logging.log_first_n( <ide> def __init__(self, cells, state_is_tuple=True): <ide> self._state_is_tuple = state_is_tuple <ide> if not state_is_tuple: <ide> if any(tf.nest.is_nested(c.state_size) for c in self._cells): <del> raise ValueError("Some cells return tuples of states, but the flag " <del> "state_is_tuple is not set. State sizes are: %s" % <del> str([c.state_size for c in self._cells])) <add> raise ValueError( <add> "Some cells return tuples of states, but the flag " <add> "state_is_tuple is not set. " <add> f"State sizes are: {[c.state_size for c in self._cells]}") <ide> <ide> @property <ide> def state_size(self): <ide> def call(self, inputs, state): <ide> if self._state_is_tuple: <ide> if not tf.nest.is_nested(state): <ide> raise ValueError( <del> "Expected state to be a tuple of length %d, but received: %s" % <del> (len(self.state_size), state)) <add> f"Expected state to be a tuple of length {len(self.state_size)}" <add> f", but received: {state}") <ide> cur_state = state[i] <ide> else: <ide> cur_state = tf.slice(state, [0, cur_state_pos], <ide> def _check_supported_dtypes(dtype): <ide> dtype = tf.as_dtype(dtype) <ide> if not (dtype.is_floating or dtype.is_complex): <ide> raise ValueError("RNN cell only supports floating point inputs, " <del> "but saw dtype: %s" % dtype) <add> f"but received dtype: {dtype}") <ide><path>keras/layers/legacy_rnn/rnn_cell_wrapper_impl.py <ide> def dropout_state_filter_visitor(s): <ide> <ide> if (dropout_state_filter_visitor is not None and <ide> not callable(dropout_state_filter_visitor)): <del> raise TypeError("dropout_state_filter_visitor must be callable") <add> raise TypeError("dropout_state_filter_visitor must be callable. " <add> f"Received: {dropout_state_filter_visitor}") <ide> self._dropout_state_filter = ( <ide> dropout_state_filter_visitor or _default_dropout_state_filter_visitor) <ide> with tf.name_scope("DropoutWrapperInit"): <ide> def tensor_and_const_value(v): <ide> tensor_prob, const_prob = tensor_and_const_value(prob) <ide> if const_prob is not None: <ide> if const_prob < 0 or const_prob > 1: <del> raise ValueError("Parameter %s must be between 0 and 1: %d" % <del> (attr, const_prob)) <add> raise ValueError( <add> f"Parameter {attr} must be between 0 and 1. " <add> "Received {const_prob}") <ide> setattr(self, "_%s" % attr, float(const_prob)) <ide> else: <ide> setattr(self, "_%s" % attr, tensor_prob) <ide> def _serialize_function_to_config(function): <ide> output_type = "function" <ide> module = function.__module__ <ide> else: <del> raise ValueError("Unrecognized function type for input: {}".format( <del> type(function))) <add> raise ValueError( <add> f"Unrecognized function type for input: {type(function)}") <ide> <ide> return output, output_type, module <ide> <ide> def _parse_config_to_function(config, custom_objects, func_attr_name, <ide> function = generic_utils.func_load( <ide> config[func_attr_name], globs=globs) <ide> else: <del> raise TypeError("Unknown function type:", function_type) <add> raise TypeError( <add> f"Unknown function type received: {function_type}. " <add> "Expected types are ['function', 'lambda']") <ide> return function <ide> <ide>
2
PHP
PHP
add required uses to template
d5012f0e331578b72262cc05519e90df76c64436
<ide><path>lib/Cake/Console/Templates/skel/Model/AppModel.php <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <ide> <add>App::uses('Model', 'Model'); <add> <ide> /** <ide> * Application model for Cake. <ide> *
1
Javascript
Javascript
update code style
5ab4aa1c53b498f4f99d1dccfa293c8e24cb1bcb
<ide><path>editor/js/Sidebar.Object.js <ide> Sidebar.Object = function ( editor ) { <ide> var cameraViewRow = new UI.Row().setDisplay( editor.selected !== null && editor.selected.isCamera ? 'block' : 'none' ); <ide> container.add( cameraViewRow ); <ide> <del> cameraViewRow.add( new UI.Text(strings.getKey( 'sidebar/object/view' )).setWidth('90px')); <add> cameraViewRow.add( new UI.Text( strings.getKey( 'sidebar/object/view' ) ).setWidth( '90px' ) ); <add> <add> var cameraViewCheckbox = new UI.Checkbox( false ).onChange( update ).onClick( function () { <ide> <del> var cameraViewCheckbox = new UI.Checkbox(false).onChange(update).onClick(function() { <ide> var object = editor.selected; <del> if(object.isCamera !== true) return; <del> <del> if(sceneCameras.indexOf(object) === -1) <del> { <del> if(sceneCameras.length === 4) <del> { <del> alert("Only 4 scene cameras can be shown at once."); <del> cameraViewCheckbox.setValue(false); <add> if ( object.isCamera !== true ) return; <add> <add> if ( sceneCameras.indexOf( object ) === - 1 ) { <add> <add> if ( sceneCameras.length === 4 ) { <add> <add> alert( "Only 4 scene cameras can be shown at once." ); <add> cameraViewCheckbox.setValue( false ); <ide> return; <add> <ide> } <ide> <del> sceneCameras.push(object); <del> cameraViewCheckbox.setValue(true); <del> } <del> else <del> { <del> sceneCameras.splice(sceneCameras.indexOf(object), 1); <del> cameraViewCheckbox.setValue(false); <add> sceneCameras.push( object ); <add> cameraViewCheckbox.setValue( true ); <add> <add> } else { <add> <add> sceneCameras.splice( sceneCameras.indexOf( object ), 1 ); <add> cameraViewCheckbox.setValue( false ); <add> <ide> } <ide> <ide> signals.sceneGraphChanged.dispatch(); <del> }); <add> <add> } ); <ide> cameraViewRow.add( cameraViewCheckbox ); <ide> <ide> // <ide> Sidebar.Object = function ( editor ) { <ide> <ide> } <ide> <del> if(object.isCamera === true) { <add> if ( object.isCamera === true ) { <ide> <del> cameraViewRow.setDisplay('block'); <del> cameraViewCheckbox.setValue(sceneCameras.indexOf(object) !== -1) <add> cameraViewRow.setDisplay( 'block' ); <add> cameraViewCheckbox.setValue( sceneCameras.indexOf( object ) !== - 1 ); <add> <add> } else { <add> <add> cameraViewRow.setDisplay( 'none' ); <ide> <del> } <del> else { <del> cameraViewRow.setDisplay('none'); <ide> } <ide> <ide> objectVisible.setValue( object.visible ); <ide><path>editor/js/Sidebar.Settings.Viewport.js <ide> Sidebar.Settings.Viewport = function ( editor ) { <ide> <ide> container.add( new UI.Text( strings.getKey( 'sidebar/settings/viewport/view' ) ).setWidth( '90px' ) ); <ide> <del> var sceneViewOptions = new UI.Select().setOptions({ <del> left : 'left', <del> right : 'right', <del> top : 'top', <del> bottom : 'bottom' <del> }); <del> <del> if(config.getKey('sceneView') !== undefined) <del> { <del> sceneViewOptions.setValue(config.getKey('sceneView')); <del> } <del> else <del> { <del> sceneViewOptions.setValue('left'); <add> var sceneViewOptions = new UI.Select().setOptions( { <add> left: 'left', <add> right: 'right', <add> top: 'top', <add> bottom: 'bottom' <add> } ); <add> <add> if ( config.getKey( 'sceneCameraView' ) !== undefined ) { <add> <add> sceneViewOptions.setValue( config.getKey( 'sceneCameraView' ) ); <add> <add> } else { <add> <add> sceneViewOptions.setValue( 'left' ); <add> <ide> } <del> <del> sceneViewOptions.onChange(function() <del> { <del> config.setKey('sceneView', sceneViewOptions.getValue()); <add> <add> sceneViewOptions.onChange( function () { <add> <add> config.setKey( 'sceneCameraView', sceneViewOptions.getValue() ); <ide> signals.sceneGraphChanged.dispatch(); <del> }); <del> container.add(sceneViewOptions); <add> <add> } ); <add> container.add( sceneViewOptions ); <ide> <ide> /* <ide> var snapSize = new UI.Number( 25 ).setWidth( '40px' ).onChange( update ); <ide><path>editor/js/Storage.js <ide> var Storage = function () { <ide> <ide> var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; <ide> <del> if ( indexedDB === undefined ) { <add> if ( indexedDB === undefined ) { <ide> <ide> console.warn( 'Storage: IndexedDB not available.' ); <ide> return { init: function () {}, get: function () {}, set: function () {}, clear: function () {} }; <ide><path>editor/js/Viewport.js <ide> var Viewport = function ( editor ) { <ide> <ide> renderer.autoClear = false; <ide> renderer.autoUpdateScene = false; <del> renderer.setScissorTest(true); <add> renderer.setScissorTest( true ); <ide> renderer.setPixelRatio( window.devicePixelRatio ); <ide> renderer.setSize( container.dom.offsetWidth, container.dom.offsetHeight ); <ide> <ide> var Viewport = function ( editor ) { <ide> <ide> var width = container.dom.offsetWidth; <ide> var height = container.dom.offsetHeight; <del> <del> viewport.set(0, 0, width, height); <del> renderScene(camera, viewport, true); <ide> <del> switch(config.getKey('sceneView')) <del> { <add> viewport.set( 0, 0, width, height ); <add> renderScene( camera, viewport, true ); <add> <add> switch ( config.getKey( 'sceneCameraView' ) ) { <add> <ide> case 'left': <del> for(var i = 0; i < sceneCameras.length; ++i) { <del> viewport.set(0, height * 0.25 * i, width * 0.25, height * 0.25); <del> renderScene(sceneCameras[i], viewport); <add> for ( var i = 0; i < sceneCameras.length; ++ i ) { <add> <add> viewport.set( 0, height * 0.25 * i, width * 0.25, height * 0.25 ); <add> renderScene( sceneCameras[ i ], viewport ); <add> <ide> } <ide> break; <ide> case 'right': <del> for(var i = 0; i < sceneCameras.length; ++i) { <del> viewport.set(width * 0.75, height * 0.25 * i, width * 0.25, height * 0.25); <del> renderScene(sceneCameras[i], viewport); <add> for ( var i = 0; i < sceneCameras.length; ++ i ) { <add> <add> viewport.set( width * 0.75, height * 0.25 * i, width * 0.25, height * 0.25 ); <add> renderScene( sceneCameras[ i ], viewport ); <add> <ide> } <ide> break; <ide> case 'bottom': <del> for(var i = 0; i < sceneCameras.length; ++i) { <del> viewport.set(width * 0.25 * i, 0, width * 0.25, height * 0.25); <del> renderScene(sceneCameras[i], viewport); <add> for ( var i = 0; i < sceneCameras.length; ++ i ) { <add> <add> viewport.set( width * 0.25 * i, 0, width * 0.25, height * 0.25 ); <add> renderScene( sceneCameras[ i ], viewport ); <add> <ide> } <ide> break; <ide> case 'top': <del> for(var i = 0; i < sceneCameras.length; ++i) { <del> viewport.set(width * 0.25 * i, height * 0.75, width * 0.25, height * 0.25); <del> renderScene(sceneCameras[i], viewport); <add> for ( var i = 0; i < sceneCameras.length; ++ i ) { <add> <add> viewport.set( width * 0.25 * i, height * 0.75, width * 0.25, height * 0.25 ); <add> renderScene( sceneCameras[ i ], viewport ); <add> <ide> } <ide> break; <ide> default: <del> console.error("Unknown scene view type: " + config.getKey("sceneView")); <add> console.error( "Unknown scene view type: " + config.getKey( "sceneCameraView" ) ); <ide> break; <add> <ide> } <add> <ide> } <ide> <del> function renderScene(cam, viewport, showHelpers) <del> { <del> renderer.setViewport(viewport); <del> renderer.setScissor(viewport); <add> function renderScene( cam, viewport, showHelpers ) { <add> <add> renderer.setViewport( viewport ); <add> renderer.setScissor( viewport ); <ide> renderer.render( scene, cam ); <ide> <ide> if ( showHelpers === true && renderer instanceof THREE.RaytracingRenderer === false ) { <ide> <ide> renderer.render( sceneHelpers, cam ); <ide> <ide> } <add> <ide> } <ide> <ide> return container;
4
PHP
PHP
apply fixes from styleci
7c23b7479e734eb22fa2befeaf9738876891c48a
<ide><path>src/Illuminate/Filesystem/Filesystem.php <ide> public function link($target, $link) <ide> <ide> $mode = $this->isDirectory($target) ? 'J' : 'H'; <ide> <del> exec("mklink /{$mode} ".escapeshellarg($link)." ".escapeshellarg($target)); <add> exec("mklink /{$mode} ".escapeshellarg($link).' '.escapeshellarg($target)); <ide> } <ide> <ide> /**
1
Mixed
Ruby
add expression support on the schema default
5fd30ac52d9f8fcdba98b92cdb82868f6686596c
<ide><path>activerecord/CHANGELOG.md <add>* Add expression support on the schema default. <add> <add> Example: <add> <add> create_table :posts do |t| <add> t.datetime :published_at, default: -> { 'NOW()' } <add> end <add> <add> *Ryuta Kamizono* <add> <ide> * Fix regression when loading fixture files with symbol keys. <ide> <ide> Fixes #22584. <ide><path>activerecord/lib/active_record/connection_adapters/abstract/quoting.rb <ide> def quote_table_name_for_assignment(table, attr) <ide> quote_table_name("#{table}.#{attr}") <ide> end <ide> <del> def quote_default_expression(value, column) #:nodoc: <del> value = lookup_cast_type(column.sql_type).serialize(value) <del> quote(value) <add> def quote_default_expression(value, column) # :nodoc: <add> if value.is_a?(Proc) <add> value.call <add> else <add> value = lookup_cast_type(column.sql_type).serialize(value) <add> quote(value) <add> end <ide> end <ide> <ide> def quoted_true <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb <ide> def schema_scale(column) <ide> def schema_default(column) <ide> type = lookup_cast_type_from_column(column) <ide> default = type.deserialize(column.default) <del> unless default.nil? <add> if default.nil? <add> schema_expression(column) <add> else <ide> type.type_cast_for_schema(default) <ide> end <ide> end <ide> <add> def schema_expression(column) <add> "-> { #{column.default_function.inspect} }" if column.default_function <add> end <add> <ide> def schema_collation(column) <ide> column.collation.inspect if column.collation <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb <ide> def quoted_date(value) #:nodoc: <ide> end <ide> end <ide> <del> # Does not quote function default values for UUID columns <del> def quote_default_expression(value, column) #:nodoc: <del> if column.type == :uuid && value =~ /\(\)/ <del> value <add> def quote_default_expression(value, column) # :nodoc: <add> if value.is_a?(Proc) <add> value.call <add> elsif column.type == :uuid && value =~ /\(\)/ <add> value # Does not quote function default values for UUID columns <ide> elsif column.respond_to?(:array?) <ide> value = type_cast_from_column(column, value) <ide> quote(value) <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb <ide> def column_spec_for_primary_key(column) <ide> spec[:id] = ':bigserial' <ide> elsif column.type == :uuid <ide> spec[:id] = ':uuid' <del> spec[:default] = column.default_function.inspect <add> spec[:default] = schema_default(column) || 'nil' <ide> else <ide> spec[:id] = column.type.inspect <ide> spec.merge!(prepare_column_options(column).delete_if { |key, _| [:name, :type, :null].include?(key) }) <ide> def schema_type(column) <ide> end <ide> end <ide> <del> def schema_default(column) <del> if column.default_function <del> column.default_function.inspect unless column.serial? <del> else <del> super <del> end <add> def schema_expression(column) <add> super unless column.serial? <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb <ide> def test_pk_and_sequence_for_uuid_primary_key <ide> <ide> def test_schema_dumper_for_uuid_primary_key <ide> schema = dump_table_schema "pg_uuids" <del> assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema) <del> assert_match(/t\.uuid "other_uuid", default: "uuid_generate_v4\(\)"/, schema) <add> assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: -> { "uuid_generate_v1\(\)" }/, schema) <add> assert_match(/t\.uuid "other_uuid", default: -> { "uuid_generate_v4\(\)" }/, schema) <ide> end <ide> <ide> def test_schema_dumper_for_uuid_primary_key_with_custom_default <ide> schema = dump_table_schema "pg_uuids_2" <del> assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: "my_uuid_generator\(\)"/, schema) <del> assert_match(/t\.uuid "other_uuid_2", default: "my_uuid_generator\(\)"/, schema) <add> assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: -> { "my_uuid_generator\(\)" }/, schema) <add> assert_match(/t\.uuid "other_uuid_2", default: -> { "my_uuid_generator\(\)" }/, schema) <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/defaults_test.rb <ide> require "cases/helper" <add>require 'support/schema_dumping_helper' <ide> require 'models/default' <ide> require 'models/entrant' <ide> <ide> def test_default_strings_containing_single_quotes <ide> end <ide> end <ide> <add>if current_adapter?(:PostgreSQLAdapter) <add> class PostgresqlDefaultExpressionTest < ActiveRecord::TestCase <add> include SchemaDumpingHelper <add> <add> test "schema dump includes default expression" do <add> output = dump_table_schema("defaults") <add> assert_match %r/t\.date\s+"modified_date",\s+default: -> { "\('now'::text\)::date" }/, output <add> assert_match %r/t\.date\s+"modified_date_function",\s+default: -> { "now\(\)" }/, output <add> assert_match %r/t\.datetime\s+"modified_time",\s+default: -> { "now\(\)" }/, output <add> assert_match %r/t\.datetime\s+"modified_time_function",\s+default: -> { "now\(\)" }/, output <add> end <add> end <add>end <add> <ide> if current_adapter?(:Mysql2Adapter) <ide> class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase <ide> # ActiveRecord::Base#create! (and #save and other related methods) will <ide><path>activerecord/test/schema/postgresql_specific_schema.rb <ide> t.uuid :uuid_parent_id <ide> end <ide> <del> %w(postgresql_times postgresql_oids defaults postgresql_timestamp_with_zones <add> create_table :defaults, force: true do |t| <add> t.date :modified_date, default: -> { 'CURRENT_DATE' } <add> t.date :modified_date_function, default: -> { 'now()' } <add> t.date :fixed_date, default: '2004-01-01' <add> t.datetime :modified_time, default: -> { 'CURRENT_TIMESTAMP' } <add> t.datetime :modified_time_function, default: -> { 'now()' } <add> t.datetime :fixed_time, default: '2004-01-01 00:00:00.000000-00' <add> t.column :char1, 'char(1)', default: 'Y' <add> t.string :char2, limit: 50, default: 'a varchar field' <add> t.text :char3, default: 'a text field' <add> t.bigint :bigint_default, default: -> { '0::bigint' } <add> t.text :multiline_default, default: '--- [] <add> <add>' <add> end <add> <add> %w(postgresql_times postgresql_oids postgresql_timestamp_with_zones <ide> postgresql_partitioned_table postgresql_partitioned_table_parent).each do |table_name| <ide> drop_table table_name, if_exists: true <ide> end <ide> execute "SELECT setval('#{seq_name}', 100)" <ide> end <ide> <del> execute <<_SQL <del> CREATE TABLE defaults ( <del> id serial primary key, <del> modified_date date default CURRENT_DATE, <del> modified_date_function date default now(), <del> fixed_date date default '2004-01-01', <del> modified_time timestamp default CURRENT_TIMESTAMP, <del> modified_time_function timestamp default now(), <del> fixed_time timestamp default '2004-01-01 00:00:00.000000-00', <del> char1 char(1) default 'Y', <del> char2 character varying(50) default 'a varchar field', <del> char3 text default 'a text field', <del> bigint_default bigint default 0::bigint, <del> multiline_default text DEFAULT '--- [] <del> <del>'::text <del>); <del>_SQL <del> <ide> execute <<_SQL <ide> CREATE TABLE postgresql_times ( <ide> id SERIAL PRIMARY KEY,
8
Javascript
Javascript
improve assert message in internet test
9960e53c5490c5ec678ea8e5095cb8ca76b641fc
<ide><path>test/internet/test-dgram-broadcast-multi-process.js <ide> if (process.argv[2] !== 'child') { <ide> worker.pid, <ide> count); <ide> <del> assert.strictEqual( <del> count, <del> messages.length, <del> 'A worker received an invalid multicast message' <del> ); <add> assert.strictEqual(count, messages.length); <ide> }); <ide> <ide> clearTimeout(timer);
1
Ruby
Ruby
create separate middleware stack for initializer
b0506b086fa1b59b072aaf7de99f01846fce10a4
<ide><path>railties/lib/rails/configuration.rb <ide> def framework_root_path <ide> defined?(::RAILS_FRAMEWORK_ROOT) ? ::RAILS_FRAMEWORK_ROOT : "#{root_path}/vendor/rails" <ide> end <ide> <del> # TODO: Fix this when there is an application object <ide> def middleware <del> require 'action_controller' <del> ActionController::Dispatcher.middleware <add> require 'action_dispatch' <add> @middleware ||= ActionDispatch::MiddlewareStack.new <ide> end <ide> <ide> # Loads and returns the contents of the #database_configuration_file. The <ide><path>railties/lib/rails/initializer.rb <ide> def self.run(initializer = nil, config = nil) <ide> <ide> Initializer.default.add :build_application do <ide> if configuration.frameworks.include?(:action_controller) <add> ActionController::Dispatcher.middleware = configuration.middleware <ide> Rails.application = Rails::Application.new <ide> end <ide> end <ide><path>railties/test/fcgi_dispatcher_test.rb <ide> require 'action_controller' <ide> require 'rails/fcgi_handler' <ide> <del>Dispatcher.middleware.clear <del> <ide> class RailsFCGIHandlerTest < Test::Unit::TestCase <ide> def setup <ide> @log = StringIO.new
3
PHP
PHP
fix code style
81e3c2378fecf7a7861d31f41ec665fecc65ebf7
<ide><path>src/Illuminate/Notifications/Messages/SlackAttachment.php <ide> public function footer($footer) <ide> public function footerIcon($icon) <ide> { <ide> $this->footerIcon = $icon; <add> <ide> return $this; <ide> } <ide>
1
Python
Python
remove unused imports
5d9212c44cd659003c9de2c642f049c6da7f4ca8
<ide><path>spacy/lang/id/tag_map.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>from ...symbols import POS, PUNCT, SYM, ADJ, CCONJ, NUM, DET, ADV, ADP, X, VERB <del>from ...symbols import NOUN, PROPN, PART, INTJ, SPACE, PRON, AUX, SCONJ <add>from ...symbols import POS, PUNCT, ADJ, CCONJ, NUM, DET, ADV, ADP, X, VERB <add>from ...symbols import NOUN, PRON, AUX, SCONJ <ide> <ide> <ide> # POS explanations for indonesian available from https://www.aclweb.org/anthology/Y12-1014
1
Javascript
Javascript
fix colour settings of beforelabel and beforebody
0bd0654efb4a19f192a485d88daadbe8ee2f44c0
<ide><path>src/core/core.tooltip.js <ide> module.exports = function(Chart) { <ide> }; <ide> <ide> // Before body lines <add> ctx.fillStyle = mergeOpacity(vm.bodyFontColor, opacity); <ide> helpers.each(vm.beforeBody, fillLineOfText); <ide> <ide> var drawColorBoxes = vm.displayColors; <ide> xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0; <ide> <ide> // Draw body lines now <ide> helpers.each(body, function(bodyItem, i) { <add> var textColor = mergeOpacity(vm.labelTextColors[i], opacity); <add> ctx.fillStyle = textColor; <ide> helpers.each(bodyItem.before, fillLineOfText); <ide> <ide> helpers.each(bodyItem.lines, function(line) { <ide> module.exports = function(Chart) { <ide> // Inner square <ide> ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity); <ide> ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2); <del> var textColor = mergeOpacity(vm.labelTextColors[i], opacity); <ide> ctx.fillStyle = textColor; <ide> } <ide>
1
Javascript
Javascript
fix next challenge unknown bug
ca01115674172a6a12ef6086256fc16dbd7e9db5
<ide><path>server/boot/challenge.js <ide> import _ from 'lodash'; <ide> import moment from 'moment'; <del>import R from 'ramda'; <ide> import { Observable } from 'rx'; <ide> import assign from 'object.assign'; <ide> import debugFactory from 'debug'; <ide> import { <ide> } from '../utils/middleware'; <ide> <ide> const debug = debugFactory('freecc:challenges'); <del>var challengeMapWithNames = utils.getChallengeMapWithNames(); <del>var challengeMapWithIds = utils.getChallengeMapWithIds(); <del>var challengeMapWithDashedNames = utils.getChallengeMapWithDashedNames(); <del>var challangesRegex = /^(bonfire|waypoint|zipline|basejump)/i; <add>const challengeMapWithNames = utils.getChallengeMapWithNames(); <add>const challengeMapWithIds = utils.getChallengeMapWithIds(); <add>const challengeMapWithDashedNames = utils.getChallengeMapWithDashedNames(); <add>const challangesRegex = /^(bonfire|waypoint|zipline|basejump)/i; <add>const firstChallenge = 'waypoint-say-hello-to-html-elements'; <ide> <del>var dasherize = utils.dasherize; <del>var unDasherize = utils.unDasherize; <del> <del>var getMDNLinks = utils.getMDNLinks; <add>const dasherize = utils.dasherize; <add>const unDasherize = utils.unDasherize; <add>const getMDNLinks = utils.getMDNLinks; <ide> <ide> function numberWithCommas(x) { <ide> return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); <ide> } <ide> <ide> function updateUserProgress(user, challengeId, completedChallenge) { <del> var alreadyCompleted = user.completedChallenges.some(({ id }) => { <add> const alreadyCompleted = user.completedChallenges.some(({ id }) => { <ide> return id === challengeId; <ide> }); <ide> <ide> function updateUserProgress(user, challengeId, completedChallenge) { <ide> module.exports = function(app) { <ide> const router = app.loopback.Router(); <ide> <add> const challengesQuery = { <add> order: [ <add> 'order ASC', <add> 'suborder ASC' <add> ] <add> }; <add> <add> // challenge model <ide> const Challenge = app.models.Challenge; <add> // challenge find query stream <ide> const findChallenge$ = observeMethod(Challenge, 'find'); <add> // create a stream of all the challenges <add> const challenge$ = findChallenge$(challengesQuery) <add> .flatMap(challenges => Observable.from(challenges)) <add> .shareReplay(); <add> <add> // create a stream of challenge blocks <add> const blocks$ = challenge$ <add> // group challenges by block | returns a stream of observables <add> .groupBy(challenge => challenge.block) <add> // turn block group stream into an array <add> .flatMap(block$ => block$.toArray()) <add> // turn array into stream of object <add> .map(blockArray => ({ <add> name: blockArray[0].block, <add> dashedName: dasherize(blockArray[0].block), <add> challenges: blockArray <add> })); <ide> <ide> const User = app.models.User; <ide> const userCount$ = observeMethod(User, 'count'); <ide> module.exports = function(app) { <ide> // serve index + 1 challenge <ide> // otherwise increment block key and serve the first challenge in that block <ide> // unless the next block is undefined, which means no next block <del> var nextChallengeName; <del> <del> var challengeId = String(req.user.currentChallenge.challengeId); <del> var challengeBlock = req.user.currentChallenge.challengeBlock; <del> // TODO(berks) fix index call here <del> var indexOfChallenge = challengeMapWithIds[challengeBlock] <del> .indexOf(challengeId); <del> <del> if (indexOfChallenge + 1 <del> < challengeMapWithIds[challengeBlock].length) { <del> nextChallengeName = <del> challengeMapWithDashedNames[challengeBlock][++indexOfChallenge]; <del> } else if (typeof challengeMapWithIds[++challengeBlock] !== 'undefined') { <del> nextChallengeName = R.head(challengeMapWithDashedNames[challengeBlock]); <del> } else { <del> req.flash('errors', { <del> msg: 'It looks like you have finished all of our challenges.' + <del> ' Great job! Now on to helping nonprofits!' <del> }); <del> nextChallengeName = R.head(challengeMapWithDashedNames[0].challenges); <del> } <del> <del> saveUser(req.user) <add> let nextChallengeName = firstChallenge; <add> <add> const challengeId = req.user.currentChallenge.challengeId; <add> // find challenge <add> return challenge$ <add> .filter(({ id }) => id === challengeId) <add> // now lets find the block it belongs to <add> .flatMap(challenge => { <add> // find the index of the block this challenge resides in <add> const blockIndex$ = blocks$ <add> .findIndex(({ name }) => name === challenge.block); <add> <add> return blockIndex$ <add> .flatMap(blockIndex => { <add> // could not find block? <add> if (blockIndex === -1) { <add> return Observable.throw( <add> 'could not find challenge block for ' + challenge.block <add> ); <add> } <add> const nextBlock$ = blocks$.elementAt(blockIndex + 1); <add> const firstChallengeOfNextBlock$ = nextBlock$ <add> .map(block => block.challenges[0]); <add> <add> return blocks$ <add> .elementAt(blockIndex) <add> .flatMap(block => { <add> // find where our challenge lies in the block <add> const challengeIndex$ = Observable.from(block.challenges) <add> .findIndex(({ id }) => id === challengeId); <add> <add> // grab next challenge in this block <add> return challengeIndex$ <add> .map(index => { <add> return block.challenges[index + 1]; <add> }) <add> .flatMap(nextChallenge => { <add> if (!nextChallenge) { <add> return firstChallengeOfNextBlock$; <add> } <add> return Observable.just(nextChallenge); <add> }); <add> }); <add> }); <add> }) <add> .map(nextChallenge => { <add> nextChallengeName = nextChallenge.dashedName; <add> return nextChallengeName; <add> }) <add> .flatMap(() => { <add> return saveUser(req.user); <add> }) <ide> .subscribe( <ide> function() {}, <ide> next, <ide> function() { <add> debug('next challengeName', nextChallengeName); <add> if (!nextChallengeName || nextChallengeName === firstChallenge) { <add> req.flash('errors', { <add> msg: 'It looks like you have finished all of our challenges.' + <add> ' Great job! Now on to helping nonprofits!' <add> }); <add> return res.redirect('/challenges/' + firstChallenge); <add> } <ide> res.redirect('/challenges/' + nextChallengeName); <ide> } <ide> ); <add> <ide> } <ide> <ide> function returnCurrentChallenge(req, res, next) { <ide> if (!req.user.currentChallenge) { <ide> req.user.currentChallenge = {}; <ide> req.user.currentChallenge.challengeId = challengeMapWithIds['0'][0]; <ide> req.user.currentChallenge.challengeName = challengeMapWithNames['0'][0]; <del> req.user.currentChallenge.challengeBlock = '0'; <ide> req.user.currentChallenge.dashedName = <ide> challengeMapWithDashedNames['0'][0]; <ide> } <ide> module.exports = function(app) { <ide> req.user.currentChallenge = { <ide> challengeId: challenge.id, <ide> challengeName: challenge.name, <del> dashedName: challenge.dashedName, <del> challengeBlock: R.head(R.flatten(Object.keys(challengeMapWithIds) <del> .map(function(key) { <del> return challengeMapWithIds[key] <del> .filter(function(elem) { <del> return elem === '' + challenge.id; <del> }) <del> .map(function() { <del> return key; <del> }); <del> }) <del> )) <add> dashedName: challenge.dashedName <ide> }; <ide> } <ide> <ide> module.exports = function(app) { <ide> const camperCount$ = userCount$() <ide> .map(camperCount => numberWithCommas(camperCount)); <ide> <del> const query = { <del> order: [ <del> 'order ASC', <del> 'suborder ASC' <del> ] <del> }; <del> <del> // create a stream of all the challenges <del> const challenge$ = findChallenge$(query) <del> .flatMap(challenges => Observable.from(challenges)) <del> .shareReplay(); <del> <ide> // create a stream of an array of all the challenge blocks <ide> const blocks$ = challenge$ <ide> // mark challenge completed
1
Javascript
Javascript
fix lint errors
a6999e4a823a674010f97fc86771a565b9292758
<ide><path>src/lines-tile-component.js <ide> module.exports = class LinesTileComponent { <ide> for (const lineId of Object.keys(this.newTileState.lines)) { <ide> const oldLineState = this.oldTileState.lines[lineId] <ide> const newLineState = this.newTileState.lines[lineId] <del> const lineNode = this.lineNodesByLineId[lineId] <ide> for (const decorationId of Object.keys(oldLineState.precedingBlockDecorations)) { <ide> if (!newLineState.precedingBlockDecorations.hasOwnProperty(decorationId)) { <ide> const {topRulerNode, blockDecorationNode, bottomRulerNode} = <ide><path>src/style-manager.js <ide> function transformDeprecatedShadowDOMSelectors (css, context) { <ide> if (transformedSelectors.length > 0) { <ide> deprecationMessage = 'Starting from Atom v1.13.0, the contents of `atom-text-editor` elements ' <ide> deprecationMessage += 'are no longer encapsulated within a shadow DOM boundary. ' <del> deprecationMessage += 'This means you should stop using \`:host\` and \`::shadow\` ' <del> deprecationMessage += 'pseudo-selectors, and prepend all your syntax selectors with \`syntax--\`. ' <add> deprecationMessage += 'This means you should stop using `:host` and `::shadow` ' <add> deprecationMessage += 'pseudo-selectors, and prepend all your syntax selectors with `syntax--`. ' <ide> deprecationMessage += 'To prevent breakage with existing style sheets, Atom will automatically ' <ide> deprecationMessage += 'upgrade the following selectors:\n\n' <ide> deprecationMessage += transformedSelectors <ide> .map((selector) => `* \`${selector.before}\` => \`${selector.after}\``) <ide> .join('\n\n') + '\n\n' <del> deprecationMessage += 'Automatic translation of selectors will be removed in a few release cycles to minimize startup time. ' <add> deprecationMessage += 'Automatic translation of selectors will be removed in a few release cycles to minimize startup time. ' <ide> deprecationMessage += 'Please, make sure to upgrade the above selectors as soon as possible.' <ide> } <ide> return {source: transformedSource.toString(), deprecationMessage}
2
Ruby
Ruby
treat utc times nicer
637642c8b85707779af45f80a104dd84be6a904d
<ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb <ide> def seconds_since_midnight <ide> # Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options <ide> # (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and <ide> # minute is passed, then sec and usec is set to 0. <del> def change(options, time_factory_method = :local) <add> def change(options) <ide> ::Time.send( <del> time_factory_method, <add> self.utc? ? :utc : :local, <ide> options[:year] || self.year, <ide> options[:month] || self.month, <ide> options[:mday] || self.mday, <ide> def since(seconds) <ide> end <ide> <ide> # Returns a new Time representing the time a number of specified months ago <del> def months_ago(months, time_factory_method = :local) <add> def months_ago(months) <ide> if months >= self.month <del> change({ :year => self.year - 1, :month => 12 }, time_factory_method).months_ago(months - self.month) <add> change(:year => self.year - 1, :month => 12).months_ago(months - self.month) <ide> else <del> change({ :year => self.year, :month => self.month - months }, time_factory_method) <add> change(:year => self.year, :month => self.month - months) <ide> end <ide> end <ide> <del> def months_since(months, time_factory_method = :local) <add> def months_since(months) <ide> if months + self.month > 12 <del> change({ :year => self.year + 1, :month => 1 }, time_factory_method).months_since( <del> months - (self.month == 1 ? 12 : (self.month + 1)) <del> ) <add> change(:year => self.year + 1, :month => 1).months_since(months - (self.month == 1 ? 12 : (self.month + 1))) <ide> else <del> change({ :year => self.year, :month => self.month + months }, time_factory_method) <add> change(:year => self.year, :month => self.month + months) <ide> end <ide> end <ide> <ide> def yesterday <ide> def tomorrow <ide> self.since(1.day) <ide> end <del> <del> # Returns a new Time of the current day at 9:00 (am) in the morning <del> def in_the_morning(time_factory_method = :local) <del> change({:hour => 9}, time_factory_method) <del> end <del> <del> # Returns a new Time of the current day at 14:00 in the afternoon <del> def in_the_afternoon(time_factory_method = :local) <del> change({:hour => 14}, time_factory_method) <del> end <ide> end <ide> end <ide> end <ide><path>activesupport/test/core_ext/time_ext_test.rb <ide> def test_tomorrow <ide> assert_equal Time.local(2005,2,23,10,10,10), Time.local(2005,2,22,10,10,10).tomorrow <ide> assert_equal Time.local(2005,3,2,10,10,10), Time.local(2005,2,28,10,10,10).tomorrow.tomorrow <ide> end <del> <del> def test_in_the_morning <del> assert_equal Time.local(2005,2,22,9), Time.local(2005,2,22,15,15,10).in_the_morning <del> assert_equal Time.local(2005,2,22,9), Time.local(2005,2,22,3,15,10).in_the_morning <del> end <del> <del> def test_in_the_morning <del> assert_equal Time.local(2005,2,22,14), Time.local(2005,2,22,15,15,10).in_the_afternoon <del> assert_equal Time.local(2005,2,22,14), Time.local(2005,2,22,3,15,10).in_the_afternoon <del> end <ide> <ide> def test_change <ide> assert_equal Time.local(2006,2,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:year => 2006) <ide> assert_equal Time.local(2005,6,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:month => 6) <ide> assert_equal Time.local(2012,9,22,15,15,10), Time.local(2005,2,22,15,15,10).change(:year => 2012, :month => 9) <del> assert_equal Time.local(2005,2,22,16), Time.local(2005,2,22,15,15,10).change(:hour => 16) <del> assert_equal Time.local(2005,2,22,16,45), Time.local(2005,2,22,15,15,10).change(:hour => 16, :min => 45) <del> assert_equal Time.local(2005,2,22,15,45), Time.local(2005,2,22,15,15,10).change(:min => 45) <add> assert_equal Time.local(2005,2,22,16), Time.local(2005,2,22,15,15,10).change(:hour => 16) <add> assert_equal Time.local(2005,2,22,16,45), Time.local(2005,2,22,15,15,10).change(:hour => 16, :min => 45) <add> assert_equal Time.local(2005,2,22,15,45), Time.local(2005,2,22,15,15,10).change(:min => 45) <add> end <add> <add> def test_utc_change <add> assert_equal Time.utc(2006,2,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:year => 2006) <add> assert_equal Time.utc(2005,6,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:month => 6) <add> assert_equal Time.utc(2012,9,22,15,15,10), Time.utc(2005,2,22,15,15,10).change(:year => 2012, :month => 9) <add> assert_equal Time.utc(2005,2,22,16), Time.utc(2005,2,22,15,15,10).change(:hour => 16) <add> assert_equal Time.utc(2005,2,22,16,45), Time.utc(2005,2,22,15,15,10).change(:hour => 16, :min => 45) <add> assert_equal Time.utc(2005,2,22,15,45), Time.utc(2005,2,22,15,15,10).change(:min => 45) <ide> end <ide> end <ide>\ No newline at end of file
2
PHP
PHP
fix condition to work better on sqlserver
4278aac5d18fffe29c98ba767d7e854e23097cbd
<ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testCastResults() <ide> ->select(['a' => 'id']) <ide> ->from('profiles') <ide> ->setSelectTypeMap($typeMap) <del> ->where(['id' => 1]) <add> ->where(['user_id' => 1]) <ide> ->execute() <ide> ->fetchAll('assoc'); <ide> $this->assertSame([['user_id' => 1, 'is_active' => false, 'a' => 1]], $results);
1
Go
Go
remove unnescessary conversions
2c31edbbb64aa86e76aed60d48fec4eb530cf9f6
<ide><path>daemon/graphdriver/devmapper/devmapper_test.go <ide> func initLoopbacks() error { <ide> // only create new loopback files if they don't exist <ide> if _, err := os.Stat(loopPath); err != nil { <ide> if mkerr := syscall.Mknod(loopPath, <del> uint32(statT.Mode|syscall.S_IFBLK), int((7<<8)|(i&0xff)|((i&0xfff00)<<12))); mkerr != nil { <add> uint32(statT.Mode|syscall.S_IFBLK), int((7<<8)|(i&0xff)|((i&0xfff00)<<12))); mkerr != nil { // nolint: unconvert <ide> return mkerr <ide> } <ide> os.Chown(loopPath, int(statT.Uid), int(statT.Gid)) <ide><path>daemon/info_unix_test.go <ide> func TestParseInitVersion(t *testing.T) { <ide> } <ide> <ide> for _, test := range tests { <del> version, commit, err := parseInitVersion(string(test.output)) <add> version, commit, err := parseInitVersion(test.output) <ide> if test.invalid { <ide> assert.Check(t, is.ErrorContains(err, "")) <ide> } else { <ide> spec: 1.0.0 <ide> } <ide> <ide> for _, test := range tests { <del> version, commit, err := parseRuncVersion(string(test.output)) <add> version, commit, err := parseRuncVersion(test.output) <ide> if test.invalid { <ide> assert.Check(t, is.ErrorContains(err, "")) <ide> } else { <ide><path>image/fs_test.go <ide> func TestFSGetInvalidData(t *testing.T) { <ide> store, cleanup := defaultFSStoreBackend(t) <ide> defer cleanup() <ide> <del> id, err := store.Set([]byte("foobar")) <add> dgst, err := store.Set([]byte("foobar")) <ide> assert.Check(t, err) <ide> <del> dgst := digest.Digest(id) <del> <ide> err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, string(dgst.Algorithm()), dgst.Hex()), []byte("foobar2"), 0600) <ide> assert.Check(t, err) <ide> <del> _, err = store.Get(id) <add> _, err = store.Get(dgst) <ide> assert.Check(t, is.ErrorContains(err, "failed to verify")) <ide> } <ide> <ide> func TestFSGetSet(t *testing.T) { <ide> }) <ide> <ide> for _, tc := range tcases { <del> id, err := store.Set([]byte(tc.input)) <add> id, err := store.Set(tc.input) <ide> assert.Check(t, err) <ide> assert.Check(t, is.Equal(tc.expected, id)) <ide> } <ide><path>image/store_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/layer" <del> digest "github.com/opencontainers/go-digest" <ide> "gotest.tools/assert" <ide> "gotest.tools/assert/cmp" <ide> ) <ide> func TestRestore(t *testing.T) { <ide> assert.NilError(t, err) <ide> assert.Check(t, cmp.Equal(ID(id1), sid1)) <ide> <del> sid1, err = is.Search(digest.Digest(id1).Hex()[:6]) <add> sid1, err = is.Search(id1.Hex()[:6]) <ide> assert.NilError(t, err) <ide> assert.Check(t, cmp.Equal(ID(id1), sid1)) <ide> <del> invalidPattern := digest.Digest(id1).Hex()[1:6] <add> invalidPattern := id1.Hex()[1:6] <ide> _, err = is.Search(invalidPattern) <ide> assert.ErrorContains(t, err, "No such image") <ide> } <ide><path>pkg/archive/archive_unix_test.go <ide> func getNlink(path string) (uint64, error) { <ide> return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) <ide> } <ide> // We need this conversion on ARM64 <add> // nolint: unconvert <ide> return uint64(statT.Nlink), nil <ide> } <ide> <ide><path>pkg/idtools/idtools_unix_test.go <ide> func TestNewIDMappings(t *testing.T) { <ide> <ide> gids, err := tempUser.GroupIds() <ide> assert.Check(t, err) <del> group, err := user.LookupGroupId(string(gids[0])) <add> group, err := user.LookupGroupId(gids[0]) <ide> assert.Check(t, err) <ide> <ide> idMapping, err := NewIdentityMapping(tempUser.Username, group.Name) <ide><path>pkg/ioutils/fswriters_test.go <ide> func TestAtomicWriteToFile(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Error statting file: %v", err) <ide> } <del> if expected := os.FileMode(testMode); st.Mode() != expected { <add> if expected := testMode; st.Mode() != expected { <ide> t.Fatalf("Mode mismatched, expected %o, got %o", expected, st.Mode()) <ide> } <ide> } <ide> func TestAtomicWriteSetCommit(t *testing.T) { <ide> if err != nil { <ide> t.Fatalf("Error statting file: %v", err) <ide> } <del> if expected := os.FileMode(testMode); st.Mode() != expected { <add> if expected := testMode; st.Mode() != expected { <ide> t.Fatalf("Mode mismatched, expected %o, got %o", expected, st.Mode()) <ide> } <ide> <ide><path>pkg/system/chtimes_unix_test.go <ide> func TestChtimesLinux(t *testing.T) { <ide> } <ide> <ide> stat := f.Sys().(*syscall.Stat_t) <del> aTime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) <add> aTime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert <ide> if aTime != unixEpochTime { <ide> t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) <ide> } <ide> func TestChtimesLinux(t *testing.T) { <ide> } <ide> <ide> stat = f.Sys().(*syscall.Stat_t) <del> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) <add> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert <ide> if aTime != unixEpochTime { <ide> t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) <ide> } <ide> func TestChtimesLinux(t *testing.T) { <ide> } <ide> <ide> stat = f.Sys().(*syscall.Stat_t) <del> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) <add> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert <ide> if aTime != unixEpochTime { <ide> t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) <ide> } <ide> func TestChtimesLinux(t *testing.T) { <ide> } <ide> <ide> stat = f.Sys().(*syscall.Stat_t) <del> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) <add> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert <ide> if aTime != afterUnixEpochTime { <ide> t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, aTime) <ide> } <ide> func TestChtimesLinux(t *testing.T) { <ide> } <ide> <ide> stat = f.Sys().(*syscall.Stat_t) <del> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) <add> aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert <ide> if aTime.Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { <ide> t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), aTime.Truncate(time.Second)) <ide> } <ide><path>restartmanager/restartmanager_test.go <ide> import ( <ide> <ide> func TestRestartManagerTimeout(t *testing.T) { <ide> rm := New(container.RestartPolicy{Name: "always"}, 0).(*restartManager) <del> var duration = time.Duration(1 * time.Second) <add> var duration = 1 * time.Second <ide> should, _, err := rm.ShouldRestart(0, false, duration) <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestRestartManagerTimeout(t *testing.T) { <ide> func TestRestartManagerTimeoutReset(t *testing.T) { <ide> rm := New(container.RestartPolicy{Name: "always"}, 0).(*restartManager) <ide> rm.timeout = 5 * time.Second <del> var duration = time.Duration(10 * time.Second) <add> var duration = 10 * time.Second <ide> _, _, err := rm.ShouldRestart(0, false, duration) <ide> if err != nil { <ide> t.Fatal(err)
9
Python
Python
add compat shim for sqlalchemy to avoid warnings
aa8bffdb4e2daa0d086f79382cf001e2ef6dcb62
<ide><path>airflow/compat/sqlalchemy.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>from sqlalchemy import Table <add>from sqlalchemy.engine import Connection <add> <add>try: <add> from sqlalchemy import inspect <add>except AttributeError: <add> from sqlalchemy.engine.reflection import Inspector <add> <add> inspect = Inspector.from_engine <add> <add>__all__ = ["has_table", "inspect"] <add> <add> <add>def has_table(conn: Connection, table: Table): <add> try: <add> return inspect(conn).has_table(table) <add> except AttributeError: <add> return table.exists(conn) <ide><path>airflow/migrations/versions/03afc6b6f902_increase_length_of_fab_ab_view_menu_.py <ide> <ide> import sqlalchemy as sa <ide> from alembic import op <del>from sqlalchemy.engine.reflection import Inspector <ide> <add>from airflow.compat.sqlalchemy import inspect <ide> from airflow.migrations.db_types import StringID <ide> <ide> # revision identifiers, used by Alembic. <ide> def upgrade(): <ide> """Apply Increase length of ``Flask-AppBuilder`` ``ab_view_menu.name`` column""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> <ide> if "ab_view_menu" in tables: <ide> def upgrade(): <ide> def downgrade(): <ide> """Unapply Increase length of ``Flask-AppBuilder`` ``ab_view_menu.name`` column""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> if "ab_view_menu" in tables: <ide> if conn.dialect.name == "sqlite": <ide><path>airflow/migrations/versions/1507a7289a2f_create_is_encrypted.py <ide> """ <ide> import sqlalchemy as sa <ide> from alembic import op <del>from sqlalchemy.engine.reflection import Inspector <add> <add>from airflow.compat.sqlalchemy import inspect <ide> <ide> # revision identifiers, used by Alembic. <ide> revision = '1507a7289a2f' <ide> def upgrade(): <ide> # true for users who are upgrading from a previous version of Airflow <ide> # that predates Alembic integration <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> <ide> # this will only be true if 'connection' already exists in the db, <ide> # but not if alembic created it in a previous migration <ide><path>airflow/migrations/versions/33ae817a1ff4_add_kubernetes_resource_checkpointing.py <ide> """ <ide> import sqlalchemy as sa <ide> from alembic import op <del>from sqlalchemy.engine.reflection import Inspector <add> <add>from airflow.compat.sqlalchemy import inspect <ide> <ide> # revision identifiers, used by Alembic. <ide> revision = '33ae817a1ff4' <ide> <ide> def upgrade(): <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> <ide> if RESOURCE_TABLE not in inspector.get_table_names(): <ide> columns_and_constraints = [ <ide> def upgrade(): <ide> <ide> def downgrade(): <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> <ide> if RESOURCE_TABLE in inspector.get_table_names(): <ide> op.drop_table(RESOURCE_TABLE) <ide><path>airflow/migrations/versions/3c20cacc0044_add_dagrun_run_type.py <ide> import sqlalchemy as sa <ide> from alembic import op <ide> from sqlalchemy import Column, Integer, String <del>from sqlalchemy.engine.reflection import Inspector <ide> from sqlalchemy.ext.declarative import declarative_base <ide> <add>from airflow.compat.sqlalchemy import inspect <ide> from airflow.utils.types import DagRunType <ide> <ide> # revision identifiers, used by Alembic. <ide> def upgrade(): <ide> run_type_col_type = sa.String(length=50) <ide> <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> dag_run_columns = [col.get('name') for col in inspector.get_columns("dag_run")] <ide> <ide> if "run_type" not in dag_run_columns: <ide><path>airflow/migrations/versions/92c57b58940d_add_fab_tables.py <ide> <ide> import sqlalchemy as sa <ide> from alembic import op <del>from sqlalchemy.engine.reflection import Inspector <add> <add>from airflow.compat.sqlalchemy import inspect <ide> <ide> # revision identifiers, used by Alembic. <ide> revision = '92c57b58940d' <ide> def upgrade(): <ide> """Create FAB Tables""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> if "ab_permission" not in tables: <ide> op.create_table( <ide> def upgrade(): <ide> def downgrade(): <ide> """Drop FAB Tables""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> fab_tables = [ <ide> "ab_permission", <ide><path>airflow/migrations/versions/bbf4a7ad0465_remove_id_column_from_xcom.py <ide> <ide> from alembic import op <ide> from sqlalchemy import Column, Integer <del>from sqlalchemy.engine.reflection import Inspector <add> <add>from airflow.compat.sqlalchemy import inspect <ide> <ide> # revision identifiers, used by Alembic. <ide> revision = 'bbf4a7ad0465' <ide> def create_constraints(operator, column_name, constraint_dict): <ide> def upgrade(): <ide> """Apply Remove id column from xcom""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> <ide> with op.batch_alter_table('xcom') as bop: <ide> xcom_columns = [col.get('name') for col in inspector.get_columns("xcom")] <ide><path>airflow/migrations/versions/bef4f3d11e8b_drop_kuberesourceversion_and_.py <ide> <ide> import sqlalchemy as sa <ide> from alembic import op <del>from sqlalchemy.engine.reflection import Inspector <add> <add>from airflow.compat.sqlalchemy import inspect <ide> <ide> # revision identifiers, used by Alembic. <ide> revision = 'bef4f3d11e8b' <ide> def upgrade(): <ide> """Apply Drop ``KubeResourceVersion`` and ``KubeWorkerId``entifier tables""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> <ide> if WORKER_UUID_TABLE in tables: <ide> def upgrade(): <ide> def downgrade(): <ide> """Unapply Drop ``KubeResourceVersion`` and ``KubeWorkerId``entifier tables""" <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> <ide> if WORKER_UUID_TABLE not in tables: <ide><path>airflow/migrations/versions/cc1e65623dc7_add_max_tries_column_to_task_instance.py <ide> import sqlalchemy as sa <ide> from alembic import op <ide> from sqlalchemy import Column, Integer, String <del>from sqlalchemy.engine.reflection import Inspector <ide> from sqlalchemy.ext.declarative import declarative_base <ide> <ide> from airflow import settings <add>from airflow.compat.sqlalchemy import inspect <ide> from airflow.models import DagBag <ide> <ide> # revision identifiers, used by Alembic. <ide> def upgrade(): <ide> # Checking task_instance table exists prevent the error of querying <ide> # non-existing task_instance table. <ide> connection = op.get_bind() <del> inspector = Inspector.from_engine(connection) <add> inspector = inspect(connection) <ide> tables = inspector.get_table_names() <ide> <ide> if 'task_instance' in tables: <ide><path>airflow/migrations/versions/cf5dc11e79ad_drop_user_and_chart.py <ide> import sqlalchemy as sa <ide> from alembic import op <ide> from sqlalchemy.dialects import mysql <del>from sqlalchemy.engine.reflection import Inspector <add> <add>from airflow.compat.sqlalchemy import inspect <ide> <ide> # revision identifiers, used by Alembic. <ide> revision = 'cf5dc11e79ad' <ide> def upgrade(): <ide> # But before we can delete the users table we need to drop the FK <ide> <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> <ide> if 'known_event' in tables: <ide><path>airflow/migrations/versions/e38be357a868_update_schema_for_smart_sensor.py <ide> import sqlalchemy as sa <ide> from alembic import op <ide> from sqlalchemy import func <del>from sqlalchemy.engine.reflection import Inspector <ide> <add>from airflow.compat.sqlalchemy import inspect <ide> from airflow.migrations.db_types import TIMESTAMP, StringID <ide> <ide> # revision identifiers, used by Alembic. <ide> def upgrade(): <ide> <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> if 'sensor_instance' in tables: <ide> return <ide> def upgrade(): <ide> <ide> def downgrade(): <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> if 'sensor_instance' in tables: <ide> op.drop_table('sensor_instance') <ide><path>airflow/migrations/versions/e3a246e0dc1_current_schema.py <ide> import sqlalchemy as sa <ide> from alembic import op <ide> from sqlalchemy import func <del>from sqlalchemy.engine.reflection import Inspector <ide> <add>from airflow.compat.sqlalchemy import inspect <ide> from airflow.migrations.db_types import StringID <ide> <ide> # revision identifiers, used by Alembic. <ide> <ide> def upgrade(): <ide> conn = op.get_bind() <del> inspector = Inspector.from_engine(conn) <add> inspector = inspect(conn) <ide> tables = inspector.get_table_names() <ide> <ide> if 'connection' not in tables: <ide><path>airflow/utils/db.py <ide> from sqlalchemy.orm.session import Session <ide> <ide> from airflow import settings <add>from airflow.compat.sqlalchemy import has_table <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <ide> from airflow.jobs.base_job import BaseJob # noqa: F401 <ide> def drop_airflow_models(connection): <ide> <ide> migration_ctx = MigrationContext.configure(connection) <ide> version = migration_ctx._version <del> if version.exists(connection): <add> if has_table(connection, version): <ide> version.drop(connection) <ide> <ide> <ide><path>airflow/www/fab_security/sqla/manager.py <ide> from flask_appbuilder.models.sqla import Base <ide> from flask_appbuilder.models.sqla.interface import SQLAInterface <ide> from sqlalchemy import and_, func, literal <del>from sqlalchemy.engine.reflection import Inspector <ide> from sqlalchemy.orm.exc import MultipleResultsFound <ide> from werkzeug.security import generate_password_hash <ide> <add>from airflow.compat import sqlalchemy as sqla_compat <ide> from airflow.www.fab_security.manager import BaseSecurityManager <ide> from airflow.www.fab_security.sqla.models import ( <ide> Action, <ide> def register_views(self): <ide> def create_db(self): <ide> try: <ide> engine = self.get_session.get_bind(mapper=None, clause=None) <del> inspector = Inspector.from_engine(engine) <add> inspector = sqla_compat.inspect(engine) <ide> if "ab_user" not in inspector.get_table_names(): <ide> log.info(c.LOGMSG_INF_SEC_NO_DB) <ide> Base.metadata.create_all(engine) <ide><path>tests/serialization/test_dag_serialization.py <ide> def test_extra_serialized_field_and_operator_links( <ide> assert serialized_dag["dag"]["tasks"][0]["_operator_extra_links"] == serialized_links <ide> <ide> # Test all the extra_links are set <del> assert set(simple_task.extra_links) == set(links.keys()) | {'airflow', 'github', 'google'} <add> assert set(simple_task.extra_links) == {*links, 'airflow', 'github', 'google'} <ide> <ide> dr = dag_maker.create_dagrun(execution_date=test_date) <ide> (ti,) = dr.task_instances <ide> def test_extra_serialized_field_and_operator_links( <ide> value=bash_command, <ide> task_id=simple_task.task_id, <ide> dag_id=simple_task.dag_id, <del> execution_date=test_date, <add> run_id=dr.run_id, <ide> ) <ide> <ide> # Test Deserialized inbuilt link
15
Text
Text
add reference to ndppd
b1a1cff368e7b7e4c6ad198cf53561d4edf50d38
<ide><path>docs/sources/articles/networking.md <ide> device to the container network: <ide> <ide> You have to execute the `ip -6 neigh add proxy ...` command for every IPv6 <ide> address in your Docker subnet. Unfortunately there is no functionality for <del>adding a whole subnet by executing one command. <add>adding a whole subnet by executing one command. An alternative approach would be to <add>use an NDP proxy daemon such as [ndppd](https://github.com/DanielAdolfsson/ndppd). <ide> <ide> ### Docker IPv6 cluster <ide>
1
Go
Go
keep info.securityoptions a string slice
514ca09426e5d023753101ffa6ac3a21b0e0efb5
<ide><path>api/server/router/system/system_routes.go <ide> import ( <ide> "github.com/docker/docker/api/types/registry" <ide> timetypes "github.com/docker/docker/api/types/time" <ide> "github.com/docker/docker/api/types/versions" <del> "github.com/docker/docker/api/types/versions/v1p24" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "golang.org/x/net/context" <ide> ) <ide> func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *ht <ide> <ide> if versions.LessThan(httputils.VersionFromContext(ctx), "1.25") { <ide> // TODO: handle this conversion in engine-api <del> oldInfo := &v1p24.Info{ <del> InfoBase: info.InfoBase, <add> type oldInfo struct { <add> *types.Info <add> ExecutionDriver string <add> } <add> old := &oldInfo{ <add> Info: info, <ide> ExecutionDriver: "<not supported>", <ide> } <del> for _, s := range info.SecurityOptions { <del> if s.Key == "Name" { <del> oldInfo.SecurityOptions = append(oldInfo.SecurityOptions, s.Value) <del> } <add> nameOnlySecurityOptions := []string{} <add> kvSecOpts, err := types.DecodeSecurityOptions(old.SecurityOptions) <add> if err != nil { <add> return err <add> } <add> for _, s := range kvSecOpts { <add> nameOnlySecurityOptions = append(nameOnlySecurityOptions, s.Name) <ide> } <del> return httputils.WriteJSON(w, http.StatusOK, oldInfo) <add> old.SecurityOptions = nameOnlySecurityOptions <add> return httputils.WriteJSON(w, http.StatusOK, old) <ide> } <ide> return httputils.WriteJSON(w, http.StatusOK, info) <ide> } <ide><path>api/types/types.go <ide> package types <ide> <ide> import ( <add> "errors" <add> "fmt" <ide> "io" <ide> "os" <add> "strings" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types/container" <ide> type Commit struct { <ide> Expected string <ide> } <ide> <del>// InfoBase contains the base response of Remote API: <add>// Info contains response of Remote API: <ide> // GET "/info" <del>type InfoBase struct { <add>type Info struct { <ide> ID string <ide> Containers int <ide> ContainersRunning int <ide> type InfoBase struct { <ide> ContainerdCommit Commit <ide> RuncCommit Commit <ide> InitCommit Commit <add> SecurityOptions []string <ide> } <ide> <del>// SecurityOpt holds key/value pair about a security option <del>type SecurityOpt struct { <add>// KeyValue holds a key/value pair <add>type KeyValue struct { <ide> Key, Value string <ide> } <ide> <del>// Info contains response of Remote API: <del>// GET "/info" <del>type Info struct { <del> *InfoBase <del> SecurityOptions []SecurityOpt <add>// SecurityOpt contains the name and options of a security option <add>type SecurityOpt struct { <add> Name string <add> Options []KeyValue <add>} <add> <add>// DecodeSecurityOptions decodes a security options string slice to a type safe <add>// SecurityOpt <add>func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { <add> so := []SecurityOpt{} <add> for _, opt := range opts { <add> // support output from a < 1.13 docker daemon <add> if !strings.Contains(opt, "=") { <add> so = append(so, SecurityOpt{Name: opt}) <add> continue <add> } <add> secopt := SecurityOpt{} <add> split := strings.Split(opt, ",") <add> for _, s := range split { <add> kv := strings.SplitN(s, "=", 2) <add> if len(kv) != 2 { <add> return nil, fmt.Errorf("invalid security option %q", s) <add> } <add> if kv[0] == "" || kv[1] == "" { <add> return nil, errors.New("invalid empty security option") <add> } <add> if kv[0] == "name" { <add> secopt.Name = kv[1] <add> continue <add> } <add> secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) <add> } <add> so = append(so, secopt) <add> } <add> return so, nil <ide> } <ide> <ide> // PluginsInfo is a temp struct holding Plugins name <ide><path>api/types/versions/v1p24/types.go <del>// Package v1p24 provides specific API types for the API version 1, patch 24. <del>package v1p24 <del> <del>import "github.com/docker/docker/api/types" <del> <del>// Info is a backcompatibility struct for the API 1.24 <del>type Info struct { <del> *types.InfoBase <del> ExecutionDriver string <del> SecurityOptions []string <del>} <ide><path>cli/command/system/info.go <ide> func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error { <ide> fmt.Fprintf(dockerCli.Out(), "\n") <ide> } <ide> if len(info.SecurityOptions) != 0 { <add> kvs, err := types.DecodeSecurityOptions(info.SecurityOptions) <add> if err != nil { <add> return err <add> } <ide> fmt.Fprintf(dockerCli.Out(), "Security Options:\n") <del> for _, o := range info.SecurityOptions { <del> switch o.Key { <del> case "Name": <del> fmt.Fprintf(dockerCli.Out(), " %s\n", o.Value) <del> case "Profile": <del> if o.Value != "default" { <del> fmt.Fprintf(dockerCli.Err(), " WARNING: You're not using the default seccomp profile\n") <add> for _, so := range kvs { <add> fmt.Fprintf(dockerCli.Out(), " %s\n", so.Name) <add> for _, o := range so.Options { <add> switch o.Key { <add> case "profile": <add> if o.Value != "default" { <add> fmt.Fprintf(dockerCli.Err(), " WARNING: You're not using the default seccomp profile\n") <add> } <add> fmt.Fprintf(dockerCli.Out(), " Profile: %s\n", o.Value) <ide> } <del> fmt.Fprintf(dockerCli.Out(), " %s: %s\n", o.Key, o.Value) <ide> } <ide> } <ide> } <ide><path>client/info_test.go <ide> func TestInfo(t *testing.T) { <ide> return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) <ide> } <ide> info := &types.Info{ <del> InfoBase: &types.InfoBase{ <del> ID: "daemonID", <del> Containers: 3, <del> }, <add> ID: "daemonID", <add> Containers: 3, <ide> } <ide> b, err := json.Marshal(info) <ide> if err != nil { <ide><path>daemon/info.go <ide> package daemon <ide> <ide> import ( <add> "fmt" <ide> "os" <ide> "runtime" <ide> "sync/atomic" <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> } <ide> }) <ide> <del> securityOptions := []types.SecurityOpt{} <add> securityOptions := []string{} <ide> if sysInfo.AppArmor { <del> securityOptions = append(securityOptions, types.SecurityOpt{Key: "Name", Value: "apparmor"}) <add> securityOptions = append(securityOptions, "name=apparmor") <ide> } <ide> if sysInfo.Seccomp && supportsSeccomp { <ide> profile := daemon.seccompProfilePath <ide> if profile == "" { <ide> profile = "default" <ide> } <del> securityOptions = append(securityOptions, <del> types.SecurityOpt{Key: "Name", Value: "seccomp"}, <del> types.SecurityOpt{Key: "Profile", Value: profile}, <del> ) <add> securityOptions = append(securityOptions, fmt.Sprintf("name=seccomp,profile=%s", profile)) <ide> } <ide> if selinuxEnabled() { <del> securityOptions = append(securityOptions, types.SecurityOpt{Key: "Name", Value: "selinux"}) <add> securityOptions = append(securityOptions, "name=selinux") <ide> } <ide> uid, gid := daemon.GetRemappedUIDGID() <ide> if uid != 0 || gid != 0 { <del> securityOptions = append(securityOptions, types.SecurityOpt{Key: "Name", Value: "userns"}) <add> securityOptions = append(securityOptions, "name=userns") <ide> } <ide> <del> v := &types.InfoBase{ <add> v := &types.Info{ <ide> ID: daemon.ID, <ide> Containers: int(cRunning + cPaused + cStopped), <ide> ContainersRunning: int(cRunning), <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> HTTPSProxy: sockets.GetProxyEnv("https_proxy"), <ide> NoProxy: sockets.GetProxyEnv("no_proxy"), <ide> LiveRestoreEnabled: daemon.configStore.LiveRestoreEnabled, <add> SecurityOptions: securityOptions, <ide> Isolation: daemon.defaultIsolation, <ide> } <ide> <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> } <ide> v.Name = hostname <ide> <del> i := &types.Info{ <del> InfoBase: v, <del> SecurityOptions: securityOptions, <del> } <del> <del> return i, nil <add> return v, nil <ide> } <ide> <ide> // SystemVersion returns version information about the daemon. <ide><path>daemon/info_unix.go <ide> import ( <ide> ) <ide> <ide> // FillPlatformInfo fills the platform related info. <del>func (daemon *Daemon) FillPlatformInfo(v *types.InfoBase, sysInfo *sysinfo.SysInfo) { <add>func (daemon *Daemon) FillPlatformInfo(v *types.Info, sysInfo *sysinfo.SysInfo) { <ide> v.MemoryLimit = sysInfo.MemoryLimit <ide> v.SwapLimit = sysInfo.SwapLimit <ide> v.KernelMemory = sysInfo.KernelMemory <ide><path>daemon/info_windows.go <ide> import ( <ide> ) <ide> <ide> // FillPlatformInfo fills the platform related info. <del>func (daemon *Daemon) FillPlatformInfo(v *types.InfoBase, sysInfo *sysinfo.SysInfo) { <add>func (daemon *Daemon) FillPlatformInfo(v *types.Info, sysInfo *sysinfo.SysInfo) { <ide> }
8
Go
Go
fix race condition on container stop
29bdcaf3cfe0f4bfeed9f7f59ca8f6ad2f41dfd9
<ide><path>daemon/container.go <ide> func (container *Container) Kill() error { <ide> <ide> // 1. Send SIGKILL <ide> if err := container.killPossiblyDeadProcess(9); err != nil { <del> return err <add> // While normally we might "return err" here we're not going to <add> // because if we can't stop the container by this point then <add> // its probably because its already stopped. Meaning, between <add> // the time of the IsRunning() call above and now it stopped. <add> // Also, since the err return will be exec driver specific we can't <add> // look for any particular (common) error that would indicate <add> // that the process is already dead vs something else going wrong. <add> // So, instead we'll give it up to 2 more seconds to complete and if <add> // by that time the container is still running, then the error <add> // we got is probably valid and so we return it to the caller. <add> <add> if container.IsRunning() { <add> container.WaitStop(2 * time.Second) <add> if container.IsRunning() { <add> return err <add> } <add> } <ide> } <ide> <ide> // 2. Wait for the process to die, in last resort, try to kill the process directly
1
Ruby
Ruby
use magic number for adobe air
04e97e82db43d085bfc73e8e46e52634aabe0d53
<ide><path>Library/Homebrew/unpack_strategy/air.rb <ide> class Air <ide> using Magic <ide> <ide> def self.can_extract?(path) <del> path.extname == ".air" <add> mime_type = "application/vnd.adobe.air-application-installer-package+zip" <add> path.magic_number.match?(/.{59}#{Regexp.escape(mime_type)}/) <ide> end <ide> <ide> def dependencies
1
Ruby
Ruby
fix java_home on macos
d6bba1c4938ea9c9a9d58ba2f209775dd71a8537
<ide><path>Library/Homebrew/extend/os/language/java.rb <add># typed: strict <add># frozen_string_literal: true <add> <add>require "extend/os/mac/language/java" if OS.mac? <ide><path>Library/Homebrew/extend/os/mac/language/java.rb <add># typed: true <add># frozen_string_literal: true <add> <add>module Language <add> module Java <add> def self.java_home(version = nil) <add> find_openjdk_formula(version)&.opt_libexec&.join("openjdk.jdk/Contents/Home") <add> end <add> end <add>end <ide><path>Library/Homebrew/language/java.rb <ide> def self.overridable_java_home_env(version = nil) <ide> end <ide> end <ide> end <add> <add>require "extend/os/language/java"
3
Ruby
Ruby
use curl to download hermes tarball
5ff7f809dc9eb9adb707c11c8c9ffb98b2658aa5
<ide><path>scripts/react_native_pods.rb <ide> def downloadAndConfigureHermesSource(react_native_path) <ide> end <ide> <ide> hermes_tarball_url = hermes_tarball_base_url + hermes_tag <del> # GitHub does not provide a last-modified header, so we cannot rely on wget's --timestamping <ide> hermes_tag_sha = %x[git ls-remote https://github.com/facebook/hermes #{hermes_tag} | cut -f 1].strip <ide> hermes_tarball_path = "#{download_dir}/hermes-#{hermes_tag_sha}.tar.gz" <ide> <ide> if (!File.exist?(hermes_tarball_path)) <del> Pod::UI.puts '[Hermes] Downloading Hermes source code' <del> system("wget -q -O #{hermes_tarball_path} #{hermes_tarball_url}") <add> Pod::UI.puts "[Hermes] Downloading Hermes source code (#{hermes_tarball_url})" <add> system("curl #{hermes_tarball_url} -Lo #{hermes_tarball_path}") <ide> end <del> system("tar -xzf #{hermes_tarball_path} --strip-components=1 -C #{hermes_dir}") <add> Pod::UI.puts "[Hermes] Extracting Hermes (#{hermes_tag_sha})" <ide> <ide> hermesc_macos_path = "#{sdks_dir}/hermesc/macos/build_host_hermesc" <ide> hermesc_macos_link = "#{hermes_dir}/utils/build_host_hermesc"
1
Javascript
Javascript
remove optimistic update
d172edecf77610f6e426d128d11b659260dd62e5
<ide><path>common/app/routes/Hikes/flux/Actions.js <ide> export default Actions({ <ide> } <ide> <ide> // challenge completed <del> const optimisticSave = isSignedIn ? <del> this.post$('/completed-challenge', { id, name, challengeType }) : <del> Observable.just(true); <add> let update$; <add> if (isSignedIn) { <add> const body = { id, name, challengeType }; <add> update$ = this.postJSON$('/completed-challenge', body) <add> // if post fails, will retry once <add> .retry(3) <add> .map(({ alreadyCompleted, points }) => ({ <add> transform(state) { <add> return { <add> ...state, <add> points, <add> toast: { <add> message: <add> 'Challenge saved.' + <add> (alreadyCompleted ? '' : ' First time Completed!'), <add> title: 'Saved', <add> type: 'info', <add> id: state.toast && state.toast.id ? state.toast.id + 1 : 1 <add> } <add> }; <add> } <add> })) <add> .catch((errObj => { <add> const err = new Error(errObj.message); <add> err.stack = errObj.stack; <add> return { <add> transform(state) { return { ...state, err }; } <add> }; <add> })); <add> } else { <add> update$ = Observable.just({ transform: (() => {}) }); <add> } <add> <add> const challengeCompleted$ = Observable.just({ <add> transform(state) { <add> const { hikes, currentHike: { id } } = state.hikesApp; <add> const currentHike = findNextHike(hikes, id); <add> <add> return { <add> ...state, <add> points: isSignedIn ? state.points + 1 : state.points, <add> hikesApp: { <add> ...state.hikesApp, <add> currentHike, <add> showQuestions: false, <add> currentQuestion: 1, <add> mouse: [0, 0] <add> }, <add> toast: { <add> title: 'Congratulations!', <add> message: 'Hike completed.' + (isSignedIn ? ' Saving...' : ''), <add> id: state.toast && state.toast.id ? <add> state.toast.id + 1 : <add> 1, <add> type: 'success' <add> }, <add> location: { <add> action: 'PUSH', <add> pathname: currentHike && currentHike.dashedName ? <add> `/hikes/${ currentHike.dashedName }` : <add> '/hikes' <add> } <add> }; <add> } <add> }); <ide> <ide> const correctAnswer = { <ide> transform(state) { <ide> export default Actions({ <ide> } <ide> }; <ide> <del> return Observable.just({ <del> transform(state) { <del> const { hikes, currentHike: { id } } = state.hikesApp; <del> const currentHike = findNextHike(hikes, id); <del> <del> return { <del> ...state, <del> points: isSignedIn ? state.points + 1 : state.points, <del> hikesApp: { <del> ...state.hikesApp, <del> currentHike, <del> showQuestions: false, <del> currentQuestion: 1, <del> mouse: [0, 0] <del> }, <del> toast: { <del> title: 'Congratulations!', <del> message: 'Hike completed', <del> id: state.toast && typeof state.toast.id === 'number' ? <del> state.toast.id + 1 : <del> 0, <del> type: 'success' <del> }, <del> location: { <del> action: 'PUSH', <del> pathname: currentHike && currentHike.dashedName ? <del> `/hikes/${ currentHike.dashedName }` : <del> '/hikes' <del> } <del> }; <del> }, <del> optimistic: optimisticSave <del> }) <add> return Observable.merge(challengeCompleted$, update$) <ide> .delay(300) <ide> .startWith(correctAnswer) <ide> .catch(err => Observable.just({
1
Text
Text
fix spelling and proper nouns
e50719332e691c97aaae8d3103407d6db2a789ee
<ide><path>guides/source/asset_pipeline.md <ide> the comment operator on that line to later enable the asset pipeline: <ide> <ide> To set asset compression methods, set the appropriate configuration options <ide> in `production.rb` - `config.assets.css_compressor` for your CSS and <del>`config.assets.js_compressor` for your Javascript: <add>`config.assets.js_compressor` for your JavaScript: <ide> <ide> ```ruby <ide> config.assets.css_compressor = :yui <ide> exception indicating the name of the missing file(s). <ide> <ide> #### Far-future Expires Header <ide> <del>Precompiled assets exist on the filesystem and are served directly by your web <add>Precompiled assets exist on the file system and are served directly by your web <ide> server. They do not have far-future headers by default, so to get the benefit of <ide> fingerprinting you'll have to update your server configuration to add those <ide> headers. <ide> gem. <ide> ```ruby <ide> config.assets.css_compressor = :yui <ide> ``` <del>The other option for compressing CSS if you have the sass-rails gem installed is <add>The other option for compressing CSS if you have the sass-rails gem installed is <ide> <ide> ```ruby <ide> config.assets.css_compressor = :sass <ide> The X-Sendfile header is a directive to the web server to ignore the response <ide> from the application, and instead serve a specified file from disk. This option <ide> is off by default, but can be enabled if your server supports it. When enabled, <ide> this passes responsibility for serving the file to the web server, which is <del>faster. Have a look at [send_file](http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file) <add>faster. Have a look at [send_file](http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file) <ide> on how to use this feature. <ide> <ide> Apache and nginx support this option, which can be enabled in <ide><path>guides/source/command_line.md <ide> $ rails generate scaffold HighScore game:string score:integer <ide> <ide> The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything. <ide> <del>The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. <add>The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. <ide> <ide> ```bash <ide> $ rake db:migrate
2
Python
Python
expose classes used in documentation
e817747941c75c8e14f0e93755ec648269f8a14d
<ide><path>src/transformers/__init__.py <ide> from .tokenization_roberta import RobertaTokenizer, RobertaTokenizerFast <ide> from .tokenization_t5 import T5Tokenizer <ide> from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer, TransfoXLTokenizerFast <del>from .tokenization_utils import PreTrainedTokenizer, TensorType <add>from .tokenization_utils import ( <add> BatchEncoding, <add> PreTrainedTokenizer, <add> PreTrainedTokenizerFast, <add> SpecialTokensMixin, <add> TensorType, <add>) <ide> from .tokenization_xlm import XLMTokenizer <ide> from .tokenization_xlm_roberta import XLMRobertaTokenizer <ide> from .tokenization_xlnet import SPIECE_UNDERLINE, XLNetTokenizer <add> <add># Trainer <ide> from .trainer_utils import EvalPrediction <ide> from .training_args import TrainingArguments <ide> from .training_args_tf import TFTrainingArguments
1
Python
Python
clarify rcond normalization in linalg.pinv
3f22c3e0565561874298be33e129397c32c7e8a1
<ide><path>numpy/linalg/linalg.py <ide> def pinv(a, rcond=1e-15, hermitian=False): <ide> Matrix or stack of matrices to be pseudo-inverted. <ide> rcond : (...) array_like of float <ide> Cutoff for small singular values. <del> Singular values smaller (in modulus) than <del> `rcond` * largest_singular_value (again, in modulus) <del> are set to zero. Broadcasts against the stack of matrices <add> Singular values less than or equal to <add> ``rcond * largest_singular_value`` are set to zero. <add> Broadcasts against the stack of matrices. <ide> hermitian : bool, optional <ide> If True, `a` is assumed to be Hermitian (symmetric if real-valued), <ide> enabling a more efficient method for finding singular values.
1
Python
Python
fix small typo
b23e873e0fcca3aab6eec829caa43d4bff5a9379
<ide><path>keras/callbacks.py <ide> class CSVLogger(Callback): <ide> model.fit(X_train, Y_train, callbacks=[csv_logger]) <ide> ``` <ide> <del> Arguments <add> # Arguments <ide> filename: filename of the csv file, e.g. 'run/log.csv'. <ide> separator: string used to separate elements in the csv file. <ide> append: True: append if file exists (useful for continuing <ide> class LambdaCallback(Callback): <ide> """Callback for creating simple, custom callbacks on-the-fly. <ide> <ide> This callback is constructed with anonymous functions that will be called <del> at the appropiate time. Note that the callbacks expects positional <add> at the appropriate time. Note that the callbacks expects positional <ide> arguments, as: <ide> - `on_epoch_begin` and `on_epoch_end` expect two positional arguments: `epoch`, `logs` <ide> - `on_batch_begin` and `on_batch_end` expect two positional arguments: `batch`, `logs`
1
Javascript
Javascript
add known_issues test for gh-2148
33c27f8fcffd7b0c6d609fdd4503b4f7a3c45bcd
<ide><path>test/known_issues/test-stdout-buffer-flush-on-exit.js <add>'use strict'; <add>// Refs: https://github.com/nodejs/node/issues/2148 <add> <add>require('../common'); <add>const assert = require('assert'); <add>const execSync = require('child_process').execSync; <add> <add>const longLine = 'foo bar baz quux quuz aaa bbb ccc'.repeat(65536); <add> <add>if (process.argv[2] === 'child') { <add> process.on('exit', () => { <add> console.log(longLine); <add> }); <add> process.exit(); <add>} <add> <add>const cmd = `${process.execPath} ${__filename} child`; <add>const stdout = execSync(cmd).toString().trim(); <add> <add>assert.strictEqual(stdout, longLine);
1
Javascript
Javascript
fix hijackstdout behavior in console
1ffd01cf7fbf66b1bd9bdf5ae6630cdf228f0a3b
<ide><path>test/common/index.js <ide> function hijackStdWritable(name, listener) { <ide> <ide> stream.writeTimes = 0; <ide> stream.write = function(data, callback) { <del> listener(data); <add> try { <add> listener(data); <add> } catch (e) { <add> process.nextTick(() => { throw e; }); <add> } <add> <ide> _write.call(stream, data, callback); <ide> stream.writeTimes++; <ide> }; <ide><path>test/parallel/test-common.js <ide> const HIJACK_TEST_ARRAY = [ 'foo\n', 'bar\n', 'baz\n' ]; <ide> common[`restoreStd${txt}`](); <ide> assert.strictEqual(originalWrite, stream.write); <ide> }); <add> <add>// hijackStderr and hijackStdout again <add>// for console <add>[[ 'err', 'error' ], [ 'out', 'log' ]].forEach(([ type, method ]) => { <add> common[`hijackStd${type}`](common.mustCall(function(data) { <add> assert.strictEqual(data, 'test\n'); <add> <add> // throw an error <add> throw new Error(`console ${type} error`); <add> })); <add> <add> console[method]('test'); <add> common[`restoreStd${type}`](); <add>}); <add> <add>let uncaughtTimes = 0; <add>process.on('uncaughtException', common.mustCallAtLeast(function(e) { <add> assert.strictEqual(uncaughtTimes < 2, true); <add> assert.strictEqual(e instanceof Error, true); <add> assert.strictEqual( <add> e.message, <add> `console ${([ 'err', 'out' ])[uncaughtTimes++]} error`); <add>}, 2));
2
Java
Java
add retrywhen example to javadoc
a78f0f5e81b03ab948bf57b9db43c18b0a15fc7d
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public final Observable<T> retry(Func2<Integer, Throwable, Boolean> predicate) { <ide> * <img width="640" height="430" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/retryWhen.f.png" alt=""> <ide> * <p> <ide> * {@code retryWhen} operates by default on the {@code trampoline} {@link Scheduler}. <add> * <add> * Example: <add> * <add> * This retries 3 times, each time incrementing the number of seconds it waits. <add> * <add> * <pre> {@code <add> * Observable.create((Subscriber<? super String> s) -> { <add> * System.out.println("subscribing"); <add> * s.onError(new RuntimeException("always fails")); <add> * }).retryWhen(attempts -> { <add> * return attempts.zip(Observable.range(1, 3), (n, i) -> i).flatMap(i -> { <add> * System.out.println("delay retry by " + i + " second(s)"); <add> * return Observable.timer(i, TimeUnit.SECONDS); <add> * }); <add> * }).toBlocking().forEach(System.out::println); <add> * } </pre> <add> * <add> * Output is: <add> * <add> * <pre> {@code <add> * subscribing <add> * delay retry by 1 second(s) <add> * subscribing <add> * delay retry by 2 second(s) <add> * subscribing <add> * delay retry by 3 second(s) <add> * subscribing <add> * } </pre> <ide> * <ide> * @param notificationHandler <ide> * recieves an Observable of notifications with which a user can complete or error, aborting the retry.
1
Javascript
Javascript
support new flare hook, unstable_uselistener
270f34f7f0e1d121c340937fe3302908ec117e3d
<ide><path>src/backend/ReactDebugHooks.js <ide> <ide> import ErrorStackParser from 'error-stack-parser'; <ide> <add>import type { ReactContext, ReactEventResponder } from './types'; <add> <ide> type Fiber = any; <ide> type Hook = any; <ide> <ide> type HookLogEntry = { <ide> value: mixed, <ide> }; <ide> <add>const emptyObject = {}; <add> <ide> let hookLog: Array<HookLogEntry> = []; <ide> <ide> // Primitives <ide> function getPrimitiveStackCache(): Map<string, Array<any>> { <ide> Dispatcher.useLayoutEffect(() => {}); <ide> Dispatcher.useEffect(() => {}); <ide> Dispatcher.useImperativeHandle(undefined, () => null); <add> Dispatcher.useDebugValue(null); <ide> Dispatcher.useCallback(() => {}); <ide> Dispatcher.useMemo(() => null); <del> Dispatcher.useDebugValue(null); <ide> } finally { <ide> readHookLog = hookLog; <ide> hookLog = []; <ide> function nextHook(): null | Hook { <ide> } <ide> <ide> function readContext<T>( <del> context: any, <add> context: ReactContext<T>, <ide> observedBits: void | number | boolean <ide> ): T { <ide> // For now we don't expose readContext usage in the hooks debugging info. <ide> return context._currentValue; <ide> } <ide> <del>function useContext<T>(context: any, observedBits: void | number | boolean): T { <add>function useContext<T>( <add> context: ReactContext<T>, <add> observedBits: void | number | boolean <add>): T { <ide> hookLog.push({ <ide> primitive: 'Context', <ide> stackError: new Error(), <ide> function useState<S>( <ide> return [state, (action: BasicStateAction<S>) => {}]; <ide> } <ide> <del>function useReducer<S, A>( <add>function useReducer<S, I, A>( <ide> reducer: (S, A) => S, <del> initialState: S, <del> initialAction: A | void | null <add> initialArg: I, <add> init?: I => S <ide> ): [S, Dispatch<A>] { <ide> const hook = nextHook(); <del> const state = hook !== null ? hook.memoizedState : initialState; <add> let state; <add> if (hook !== null) { <add> state = hook.memoizedState; <add> } else { <add> state = init !== undefined ? init(initialArg) : ((initialArg: any): S); <add> } <ide> hookLog.push({ <ide> primitive: 'Reducer', <ide> stackError: new Error(), <ide> function useRef<T>(initialValue: T): { current: T } { <ide> } <ide> <ide> function useLayoutEffect( <del> create: () => mixed, <add> create: () => (() => void) | void, <ide> inputs: Array<mixed> | void | null <ide> ): void { <ide> nextHook(); <ide> function useLayoutEffect( <ide> } <ide> <ide> function useEffect( <del> create: () => mixed, <add> create: () => (() => void) | void, <ide> inputs: Array<mixed> | void | null <ide> ): void { <ide> nextHook(); <ide> function useImperativeHandle<T>( <ide> }); <ide> } <ide> <del>function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T { <del> const hook = nextHook(); <add>function useDebugValue(value: any, formatterFn: ?(value: any) => any) { <ide> hookLog.push({ <del> primitive: 'Callback', <add> primitive: 'DebugValue', <ide> stackError: new Error(), <del> value: hook !== null ? hook.memoizedState[0] : callback, <add> value: typeof formatterFn === 'function' ? formatterFn(value) : value, <ide> }); <del> return callback; <ide> } <ide> <del>function useDebugValue(value: any, formatterFn: ?(value: any) => any) { <add>function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T { <add> const hook = nextHook(); <ide> hookLog.push({ <del> primitive: 'DebugValue', <add> primitive: 'Callback', <ide> stackError: new Error(), <del> value: typeof formatterFn === 'function' ? formatterFn(value) : value, <add> value: hook !== null ? hook.memoizedState[0] : callback, <ide> }); <add> return callback; <ide> } <ide> <ide> function useMemo<T>( <ide> function useMemo<T>( <ide> return value; <ide> } <ide> <add>function useListener( <add> responder: ReactEventResponder<any, any>, <add> hookProps: ?Object <add>): void { <add> const value = { <add> responder: responder.displayName || 'EventComponent', <add> props: hookProps || emptyObject, <add> }; <add> hookLog.push({ <add> primitive: 'Listener', <add> stackError: new Error(), <add> value, <add> }); <add>} <add> <ide> const Dispatcher = { <ide> readContext, <ide> useCallback, <ide> const Dispatcher = { <ide> useReducer, <ide> useRef, <ide> useState, <add> useListener, <ide> }; <ide> <ide> // Inspect <ide> function buildTree(rootStack, readHookLog): HooksTree { <ide> for (let j = stack.length - commonSteps - 1; j >= 1; j--) { <ide> const children = []; <ide> levelChildren.push({ <del> name: parseCustomHookName(stack[j - 1].functionName), <del> value: undefined, <ide> id: null, <ide> isStateEditable: false, <add> name: parseCustomHookName(stack[j - 1].functionName), <add> value: undefined, <ide> subHooks: children, <ide> }); <ide> stackOfChildren.push(levelChildren); <ide> function buildTree(rootStack, readHookLog): HooksTree { <ide> return rootChildren; <ide> } <ide> <del>// Custom hooks support user-configurable labels (via the useDebugValue() hook). <del>// That hook adds the user-provided values to the hooks tree. <del>// This method removes those values (so they don't appear in DevTools), <del>// and bubbles them up to the "value" attribute of their parent custom hook. <add>// Custom hooks support user-configurable labels (via the special useDebugValue() hook). <add>// That hook adds user-provided values to the hooks tree, <add>// but these values aren't intended to appear alongside of the other hooks. <add>// Instead they should be attributed to their parent custom hook. <add>// This method walks the tree and assigns debug values to their custom hook owners. <ide> function processDebugValues( <ide> hooksTree: HooksTree, <ide> parentHooksNode: HooksNode | null <ide> function processDebugValues( <ide> } <ide> } <ide> <del> // Bubble debug value labels to their parent custom hook. <del> // If there is no parent hook, just ignore them. <add> // Bubble debug value labels to their custom hook owner. <add> // If there is no parent hook, just ignore them for now. <ide> // (We may warn about this in the future.) <ide> if (parentHooksNode !== null) { <ide> if (debugValueHooksNodes.length === 1) { <ide> export function inspectHooks<Props>( <ide> props: Props, <ide> currentDispatcher: ReactCurrentDispatcher <ide> ): HooksTree { <add> // DevTools will pass the current renderer's injected dispatcher. <add> // Other apps might compile debug hooks as part of their app though. <add> //if (currentDispatcher == null) { <add> //currentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; <add> //} <add> <ide> const previousDispatcher = currentDispatcher.current; <ide> let readHookLog; <ide> currentDispatcher.current = Dispatcher; <ide> export function inspectHooksOfFiber( <ide> fiber: Fiber, <ide> currentDispatcher: ReactCurrentDispatcher <ide> ) { <add> // DevTools will pass the current renderer's injected dispatcher. <add> // Other apps might compile debug hooks as part of their app though. <add> //if (currentDispatcher == null) { <add> //currentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; <add> //} <add> <ide> if ( <ide> fiber.tag !== FunctionComponent && <ide> fiber.tag !== SimpleMemoComponent && <ide><path>src/backend/types.js <ide> export type GetFiberIDForNative = ( <ide> ) => number | null; <ide> export type FindNativeNodesForFiberID = (id: number) => ?Array<NativeType>; <ide> <add>export type ReactProviderType<T> = { <add> $$typeof: Symbol | number, <add> _context: ReactContext<T>, <add>}; <add> <add>export type ReactContext<T> = { <add> $$typeof: Symbol | number, <add> Consumer: ReactContext<T>, <add> Provider: ReactProviderType<T>, <add> <add> _calculateChangedBits: ((a: T, b: T) => number) | null, <add> <add> _currentValue: T, <add> _currentValue2: T, <add> _threadCount: number, <add> <add> // DEV only <add> _currentRenderer?: Object | null, <add> _currentRenderer2?: Object | null, <add>}; <add> <ide> export type ReactRenderer = { <ide> findFiberByHostInstance: (hostInstance: NativeType) => ?Fiber, <ide> version: string, <ide> export type HooksNode = { <ide> subHooks: Array<HooksNode>, <ide> }; <ide> export type HooksTree = Array<HooksNode>; <add> <add>export type ReactEventResponder<E, C> = { <add> $$typeof: Symbol | number, <add> displayName: string, <add> targetEventTypes: null | Array<string>, <add> rootEventTypes: null | Array<string>, <add> getInitialState: null | ((props: Object) => Object), <add> onEvent: <add> | null <add> | ((event: E, context: C, props: Object, state: Object) => void), <add> onRootEvent: <add> | null <add> | ((event: E, context: C, props: Object, state: Object) => void), <add> onMount: null | ((context: C, props: Object, state: Object) => void), <add> onUnmount: null | ((context: C, props: Object, state: Object) => void), <add> onOwnershipChange: <add> | null <add> | ((context: C, props: Object, state: Object) => void), <add>};
2
Java
Java
introduce eventbeatmanager and enable events
9e7d918365baa5bc7da769b555381d6f7f7f05a4
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricBinding.java <ide> /** <ide> * Copyright (c) Facebook, Inc. and its affiliates. <ide> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root <add> * directory of this source tree. <ide> */ <del> <ide> package com.facebook.react.fabric; <ide> <ide> import com.facebook.react.bridge.JavaScriptContextHolder; <ide> import com.facebook.react.bridge.NativeMap; <del>import com.facebook.react.bridge.UIManager; <ide> <ide> public interface FabricBinding { <ide> <del> void installFabric(JavaScriptContextHolder jsContext, FabricBinder fabricBinder); <add> // TODO: T31905686 change types of UIManager and EventBeatManager when moving to OSS <add> void installFabric( <add> JavaScriptContextHolder jsContext, FabricBinder fabricBinder, Object eventBeatManager); <ide> <ide> void releaseEventTarget(long jsContextNativePointer, long eventTargetPointer); <ide> <ide> void releaseEventHandler(long jsContextNativePointer, long eventHandlerPointer); <ide> <ide> void dispatchEventToEmptyTarget( <del> long jsContextNativePointer, <del> long eventHandlerPointer, <del> String type, <del> NativeMap payload <del> ); <add> long jsContextNativePointer, long eventHandlerPointer, String type, NativeMap payload); <ide> <ide> void dispatchEventToTarget( <del> long jsContextNativePointer, <del> long eventHandlerPointer, <del> long eventTargetPointer, <del> String type, <del> NativeMap payload <del> ); <del> <add> long jsContextNativePointer, <add> long eventHandlerPointer, <add> long eventTargetPointer, <add> String type, <add> NativeMap payload); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/BatchEventDispatchedListener.java <add>/** <add> * Copyright (c) 2014-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> */ <add>package com.facebook.react.uimanager.events; <add> <add>public interface BatchEventDispatchedListener { <add> <add> /** <add> * Called after a batch of low priority events has been dispatched. <add> */ <add> void onBatchEventDispatched(); <add> <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> import java.util.Comparator; <add>import java.util.List; <ide> import java.util.Map; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> import javax.annotation.Nullable; <ide> public int compare(Event lhs, Event rhs) { <ide> private final DispatchEventsRunnable mDispatchEventsRunnable = new DispatchEventsRunnable(); <ide> private final ArrayList<Event> mEventStaging = new ArrayList<>(); <ide> private final ArrayList<EventDispatcherListener> mListeners = new ArrayList<>(); <add> private final List<BatchEventDispatchedListener> mPostEventDispatchListeners = new ArrayList<>(); <ide> private final ScheduleDispatchFrameCallback mCurrentFrameCallback = <ide> new ScheduleDispatchFrameCallback(); <ide> private final AtomicInteger mHasDispatchScheduledCount = new AtomicInteger(); <ide> public void removeListener(EventDispatcherListener listener) { <ide> mListeners.remove(listener); <ide> } <ide> <add> public void addBatchEventDispatchedListener(BatchEventDispatchedListener listener) { <add> mPostEventDispatchListeners.add(listener); <add> } <add> <add> public void removeBatchEventDispatchedListener(BatchEventDispatchedListener listener) { <add> mPostEventDispatchListeners.remove(listener); <add> } <add> <ide> @Override <ide> public void onHostResume() { <ide> mCurrentFrameCallback.maybePostFromNonUI(); <ide> public void run() { <ide> event.dispatch(mReactEventEmitter); <ide> event.dispose(); <ide> } <add> for (BatchEventDispatchedListener listener : mPostEventDispatchListeners) { <add> listener.onBatchEventDispatched(); <add> } <ide> clearEventsToDispatch(); <ide> mEventCookieToLastEventIdx.clear(); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/ReactEventEmitter.java <ide> <ide> import static com.facebook.react.uimanager.events.TouchesHelper.TARGET_KEY; <ide> <del>import android.util.Log; <ide> import android.util.SparseArray; <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.bridge.WritableArray; <ide> import com.facebook.react.bridge.WritableMap; <ide> import com.facebook.react.uimanager.common.UIManagerType; <ide> import com.facebook.react.uimanager.common.ViewUtil; <del>import java.io.Closeable; <del>import java.io.IOException; <ide> import javax.annotation.Nullable; <ide> <ide> public class ReactEventEmitter implements RCTEventEmitter {
4
Ruby
Ruby
remove unnecessary initializers
94d81c3c39e3ddc441c3af3f874e53b197cf3f54
<ide><path>activerecord/lib/active_record/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> end <ide> end <ide> end <del> <del> initializer "active_record.use_yaml_unsafe_load" do |app| <del> config.after_initialize do <del> unless app.config.active_record.use_yaml_unsafe_load.nil? <del> ActiveRecord.use_yaml_unsafe_load = <del> app.config.active_record.use_yaml_unsafe_load <del> end <del> end <del> end <del> <del> initializer "active_record.yaml_column_permitted_classes" do |app| <del> config.after_initialize do <del> unless app.config.active_record.yaml_column_permitted_classes.nil? <del> ActiveRecord.yaml_column_permitted_classes = <del> app.config.active_record.yaml_column_permitted_classes <del> end <del> end <del> end <ide> end <ide> end
1
Ruby
Ruby
send cookies with request
ae29142142324545a328948e059e8b8118fd7a33
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def determine_default_controller_class(name) <ide> # Note that the request method is not verified. The different methods are <ide> # available to make the tests more expressive. <ide> def get(action, *args) <del> process_with_kwargs("GET", action, *args) <add> res = process_with_kwargs("GET", action, *args) <add> cookies.update res.cookies <add> res <ide> end <ide> <ide> # Simulate a POST request with the given parameters and set/volley the response. <ide> def process(action, *args) <ide> if cookies = @request.env['action_dispatch.cookies'] <ide> unless @response.committed? <ide> cookies.write(@response) <add> self.cookies.update(cookies.instance_variable_get(:@cookies)) <ide> end <ide> end <ide> @response.prepare! <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> def update(other_hash) <ide> self <ide> end <ide> <add> def to_header <add> @cookies.map { |k,v| "#{k}=#{v}" }.join ';' <add> end <add> <ide> def handle_options(options) #:nodoc: <ide> options[:path] ||= "/" <ide> <ide><path>actionpack/lib/action_dispatch/testing/test_process.rb <ide> def flash <ide> end <ide> <ide> def cookies <del> @request.cookie_jar <add> @cookie_jar ||= Cookies::CookieJar.build(@request.env, @request.host, @request.ssl?, @request.cookies) <ide> end <ide> <ide> def redirect_to_url
3
Ruby
Ruby
show line number for whitespace
af4aff8c13ffd952ce6217616fae02d9f27c0c89
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_text <ide> end <ide> end <ide> <del> def audit_line(line) <add> def audit_line(line, lineno) <ide> if line =~ /<(Formula|AmazonWebServicesFormula|ScriptFileFormula|GithubGistFormula)/ <ide> problem "Use a space in class inheritance: class Foo < #{$1}" <ide> end <ide> def audit_line(line) <ide> <ide> # No trailing whitespace, please <ide> if line =~ /[\t ]+$/ <del> problem "Trailing whitespace was found" <add> problem "#{lineno}: Trailing whitespace was found" <ide> end <ide> <ide> if line =~ /if\s+ARGV\.include\?\s+'--(HEAD|devel)'/ <ide> def audit <ide> audit_conflicts <ide> audit_patches <ide> audit_text <del> text.each_line { |line| audit_line(line) } <add> text.split("\n").each_with_index { |line, lineno| audit_line(line, lineno) } <ide> audit_installed <ide> end <ide>
1
Ruby
Ruby
reduce extra object creations in taggedlogging
ac93e7b5c192c39cfc224a1259a68c3b1e7bf0aa
<ide><path>activesupport/lib/active_support/tagged_logging.rb <ide> def current_tags <ide> <ide> def tags_text <ide> tags = current_tags <del> if tags.any? <add> if tags.one? <add> "[#{tags[0]}] " <add> elsif tags.any? <ide> tags.collect { |tag| "[#{tag}] " }.join <ide> end <ide> end
1
Ruby
Ruby
resolve conflict in diagnostic.rb
9a29a306cfd6b116a0cb696ce56bd7bc7679a8e3
<ide><path>Library/Homebrew/cmd/--env.rb <ide> <ide> require "extend/ENV" <ide> require "build_environment" <add>require "utils/shell" <ide> <ide> module Homebrew <ide> def __env <ide> def __env <ide> ENV.setup_build_environment <ide> ENV.universal_binary if ARGV.build_universal? <ide> <del> if $stdout.tty? <add> shell_value = ARGV.value("shell") <add> has_plain = ARGV.include?("--plain") <add> <add> if has_plain <add> shell = nil <add> elsif shell_value.nil? <add> # legacy behavior <add> shell = :bash unless $stdout.tty? <add> elsif shell_value == "auto" <add> shell = Utils::Shell.parent_shell || Utils::Shell.preferred_shell <add> elsif shell_value <add> shell = Utils::Shell.path_to_shell(shell_value) <add> end <add> <add> env_keys = build_env_keys(ENV) <add> if shell.nil? <ide> dump_build_env ENV <ide> else <del> build_env_keys(ENV).each do |key| <del> puts "export #{key}=\"#{ENV[key]}\"" <del> end <add> env_keys.each { |key| puts Utils::Shell.export_value(shell, key, ENV[key]) } <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/diagnostic.rb <ide> require "formula" <ide> require "version" <ide> require "development_tools" <add>require "utils/shell" <ide> <ide> module Homebrew <ide> module Diagnostic <ide> def check_user_path_1 <ide> <ide> Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin <ide> occurs before /usr/bin. Here is a one-liner: <del> echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile} <add> echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{Utils::Shell.shell_profile} <ide> EOS <ide> end <ide> end <ide> def check_user_path_2 <ide> <<-EOS.undent <ide> Homebrew's bin was not found in your PATH. <ide> Consider setting the PATH for example like so <del> echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile} <add> echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{Utils::Shell.shell_profile} <ide> EOS <ide> end <ide> <ide> def check_user_path_3 <ide> Homebrew's sbin was not found in your PATH but you have installed <ide> formulae that put executables in #{HOMEBREW_PREFIX}/sbin. <ide> Consider setting the PATH for example like so <del> echo 'export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH"' >> #{shell_profile} <add> echo 'export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH"' >> #{Utils::Shell.shell_profile} <ide> EOS <ide> end <ide> <ide><path>Library/Homebrew/extend/os/mac/diagnostic.rb <ide> def check_for_unsupported_curl_vars <ide> SSL_CERT_DIR support was removed from Apple's curl. <ide> If fetching formulae fails you should: <ide> unset SSL_CERT_DIR <del> and remove it from #{shell_profile} if present. <add> and remove it from #{Utils::Shell.shell_profile} if present. <ide> EOS <ide> end <ide> <ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> def test_env <ide> cmd("--env")) <ide> end <ide> <add> def test_env_bash <add> assert_match %r{export CMAKE_PREFIX_PATH="#{Regexp.quote(HOMEBREW_PREFIX.to_s)}"}, <add> cmd("--env", "--shell=bash") <add> end <add> <add> def test_env_fish <add> assert_match %r{set [-]gx CMAKE_PREFIX_PATH "#{Regexp.quote(HOMEBREW_PREFIX.to_s)}"}, <add> cmd("--env", "--shell=fish") <add> end <add> <add> def test_env_csh <add> assert_match %r{setenv CMAKE_PREFIX_PATH}, <add> cmd("--env", "--shell=tcsh") <add> end <add> <add> def test_env_plain <add> assert_match %r{CMAKE_PREFIX_PATH: #{Regexp.quote(HOMEBREW_PREFIX)}}, <add> cmd("--env", "--plain") <add> end <add> <ide> def test_prefix_formula <ide> assert_match "#{HOMEBREW_CELLAR}/testball", <ide> cmd("--prefix", testball) <ide><path>Library/Homebrew/test/test_shell.rb <add>require "testing_env" <add>require "utils/shell" <add> <add>class ShellSmokeTest < Homebrew::TestCase <add> def test_path_to_shell() <add> # raw command name <add> assert_equal :bash, Utils::Shell.path_to_shell("bash") <add> # full path <add> assert_equal :bash, Utils::Shell.path_to_shell("/bin/bash") <add> # versions <add> assert_equal :zsh, Utils::Shell.path_to_shell("zsh-5.2") <add> # strip newline too <add> assert_equal :zsh, Utils::Shell.path_to_shell("zsh-5.2\n") <add> end <add> <add> def test_path_to_shell_failure() <add> assert_equal nil, Utils::Shell.path_to_shell("") <add> assert_equal nil, Utils::Shell.path_to_shell("@@") <add> assert_equal nil, Utils::Shell.path_to_shell("invalid_shell-4.2") <add> end <add> <add> def test_sh_quote() <add> assert_equal "''", Utils::Shell.sh_quote("") <add> assert_equal "\\\\", Utils::Shell.sh_quote("\\") <add> assert_equal "'\n'", Utils::Shell.sh_quote("\n") <add> assert_equal "\\$", Utils::Shell.sh_quote("$") <add> assert_equal "word", Utils::Shell.sh_quote("word") <add> end <add> <add> def test_csh_quote() <add> assert_equal "''", Utils::Shell.csh_quote("") <add> assert_equal "\\\\", Utils::Shell.csh_quote("\\") <add> # note this test is different <add> assert_equal "'\\\n'", Utils::Shell.csh_quote("\n") <add> assert_equal "\\$", Utils::Shell.csh_quote("$") <add> assert_equal "word", Utils::Shell.csh_quote("word") <add> end <add>end <ide><path>Library/Homebrew/test/test_utils.rb <ide> require "testing_env" <ide> require "utils" <ide> require "tempfile" <add>require "utils/shell" <ide> <ide> class TtyTests < Homebrew::TestCase <ide> def test_strip_ansi <ide> def test_gzip <ide> <ide> def test_shell_profile <ide> ENV["SHELL"] = "/bin/sh" <del> assert_equal "~/.bash_profile", shell_profile <add> assert_equal "~/.bash_profile", Utils::Shell.shell_profile <ide> ENV["SHELL"] = "/bin/bash" <del> assert_equal "~/.bash_profile", shell_profile <add> assert_equal "~/.bash_profile", Utils::Shell.shell_profile <ide> ENV["SHELL"] = "/bin/another_shell" <del> assert_equal "~/.bash_profile", shell_profile <add> assert_equal "~/.bash_profile", Utils::Shell.shell_profile <ide> ENV["SHELL"] = "/bin/zsh" <del> assert_equal "~/.zshrc", shell_profile <add> assert_equal "~/.zshrc", Utils::Shell.shell_profile <ide> ENV["SHELL"] = "/bin/ksh" <del> assert_equal "~/.kshrc", shell_profile <add> assert_equal "~/.kshrc", Utils::Shell.shell_profile <ide> end <ide> <ide> def test_popen_read <ide><path>Library/Homebrew/utils/shell.rb <add>module Utils <add> SHELL_PROFILE_MAP = { <add> :bash => "~/.bash_profile", <add> :csh => "~/.cshrc", <add> :fish => "~/.config/fish/config.fish", <add> :ksh => "~/.kshrc", <add> :sh => "~/.bash_profile", <add> :tcsh => "~/.tcshrc", <add> :zsh => "~/.zshrc", <add> }.freeze <add> <add> module Shell <add> # take a path and heuristically convert it <add> # to a shell, return nil if there's no match <add> def self.path_to_shell(path) <add> # we only care about the basename <add> shell_name = File.basename(path) <add> # handle possible version suffix like `zsh-5.2` <add> shell_name.sub!(/-.*\z/m, "") <add> shell_name.to_sym if %w[bash csh fish ksh sh tcsh zsh].include?(shell_name) <add> end <add> <add> def self.preferred_shell <add> path_to_shell(ENV.fetch("SHELL", "")) <add> end <add> <add> def self.parent_shell <add> path_to_shell(`ps -p #{Process.ppid} -o ucomm=`.strip) <add> end <add> <add> def self.csh_quote(str) <add> # ruby's implementation of shell_escape <add> str = str.to_s <add> return "''" if str.empty? <add> str = str.dup <add> # anything that isn't a known safe character is padded <add> str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\" + "\\1") <add> str.gsub!(/\n/, "'\\\n'") <add> str <add> end <add> <add> def self.sh_quote(str) <add> # ruby's implementation of shell_escape <add> str = str.to_s <add> return "''" if str.empty? <add> str = str.dup <add> # anything that isn't a known safe character is padded <add> str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\" + "\\1") <add> str.gsub!(/\n/, "'\n'") <add> str <add> end <add> <add> # quote values. quoting keys is overkill <add> def self.export_value(shell, key, value) <add> case shell <add> when :bash, :ksh, :sh, :zsh <add> "export #{key}=\"#{sh_quote(value)}\"" <add> when :fish <add> # fish quoting is mostly Bourne compatible except that <add> # a single quote can be included in a single-quoted string via \' <add> # and a literal \ can be included via \\ <add> "set -gx #{key} \"#{sh_quote(value)}\"" <add> when :csh, :tcsh <add> "setenv #{key} #{csh_quote(value)}" <add> end <add> end <add> <add> # return the shell profile file based on users' preferred shell <add> def self.shell_profile <add> SHELL_PROFILE_MAP.fetch(preferred_shell, "~/.bash_profile") <add> end <add> end <add>end
7
Python
Python
replace assert with assert_(...) in some tests
bb959e1857c3ba2ad98ab87f13fdcc6b43740ffb
<ide><path>numpy/core/tests/test_datetime.py <ide> def test_setstate(self): <ide> "Verify that datetime dtype __setstate__ can handle bad arguments" <ide> dt = np.dtype('>M8[us]') <ide> assert_raises(ValueError, dt.__setstate__, (4, '>', None, None, None, -1, -1, 0, 1)) <del> assert (dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) <add> assert_(dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) <ide> assert_raises(TypeError, dt.__setstate__, (4, '>', None, None, None, -1, -1, 0, ({}, 'xxx'))) <del> assert (dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) <add> assert_(dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2]) <ide> <ide> def test_dtype_promotion(self): <ide> # datetime <op> datetime computes the metadata gcd <ide><path>numpy/core/tests/test_defchararray.py <ide> def test_slice(self): <ide> dtype='S4').view(np.chararray) <ide> sl1 = arr[:] <ide> assert_array_equal(sl1, arr) <del> assert sl1.base is arr <del> assert sl1.base.base is arr.base <add> assert_(sl1.base is arr) <add> assert_(sl1.base.base is arr.base) <ide> <ide> sl2 = arr[:, :] <ide> assert_array_equal(sl2, arr) <del> assert sl2.base is arr <del> assert sl2.base.base is arr.base <add> assert_(sl2.base is arr) <add> assert_(sl2.base.base is arr.base) <ide> <del> assert arr[0, 0] == asbytes('abc') <add> assert_(arr[0, 0] == asbytes('abc')) <ide> <ide> <ide> def test_empty_indexing(): <ide><path>numpy/core/tests/test_deprecations.py <ide> def test_array_richcompare_legacy_weirdness(self): <ide> with warnings.catch_warnings() as l: <ide> warnings.filterwarnings("always") <ide> assert_raises(TypeError, f, arg1, arg2) <del> assert not l <add> assert_(not l) <ide> else: <ide> # py2 <ide> assert_warns(DeprecationWarning, f, arg1, arg2) <ide><path>numpy/core/tests/test_mem_overlap.py <ide> def _check_assignment(srcidx, dstidx): <ide> cpy[dstidx] = arr[srcidx] <ide> arr[dstidx] = arr[srcidx] <ide> <del> assert np.all(arr == cpy), 'assigning arr[%s] = arr[%s]' % (dstidx, srcidx) <add> assert_(np.all(arr == cpy), <add> 'assigning arr[%s] = arr[%s]' % (dstidx, srcidx)) <ide> <ide> <ide> def test_overlapping_assignments(): <ide> def test_diophantine_fuzz(): <ide> if X is None: <ide> # Check the simplified decision problem agrees <ide> X_simplified = solve_diophantine(A, U, b, simplify=1) <del> assert X_simplified is None, (A, U, b, X_simplified) <add> assert_(X_simplified is None, (A, U, b, X_simplified)) <ide> <ide> # Check no solution exists (provided the problem is <ide> # small enough so that brute force checking doesn't <ide> def test_diophantine_fuzz(): <ide> else: <ide> # Check the simplified decision problem agrees <ide> X_simplified = solve_diophantine(A, U, b, simplify=1) <del> assert X_simplified is not None, (A, U, b, X_simplified) <add> assert_(X_simplified is not None, (A, U, b, X_simplified)) <ide> <ide> # Check validity <ide> assert_(sum(a*x for a, x in zip(A, X)) == b) <ide> def random_slice(n, step): <ide> s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps)) <ide> a = x[s1].transpose(t1) <ide> <del> assert not internal_overlap(a) <add> assert_(not internal_overlap(a)) <ide> cases += 1 <ide> <ide> <ide><path>numpy/core/tests/test_memmap.py <ide> def test_arithmetic_drops_references(self): <ide> shape=self.shape) <ide> tmp = (fp + 10) <ide> if isinstance(tmp, memmap): <del> assert tmp._mmap is not fp._mmap <add> assert_(tmp._mmap is not fp._mmap) <ide> <ide> def test_indexing_drops_references(self): <ide> fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', <ide> shape=self.shape) <ide> tmp = fp[[(1, 2), (2, 3)]] <ide> if isinstance(tmp, memmap): <del> assert tmp._mmap is not fp._mmap <add> assert_(tmp._mmap is not fp._mmap) <ide> <ide> def test_slicing_keeps_references(self): <ide> fp = memmap(self.tmpfp, dtype=self.dtype, mode='w+', <ide> shape=self.shape) <del> assert fp[:2, :2]._mmap is fp._mmap <add> assert_(fp[:2, :2]._mmap is fp._mmap) <ide> <ide> def test_view(self): <ide> fp = memmap(self.tmpfp, dtype=self.dtype, shape=self.shape) <ide> new1 = fp.view() <ide> new2 = new1.view() <del> assert(new1.base is fp) <del> assert(new2.base is fp) <add> assert_(new1.base is fp) <add> assert_(new2.base is fp) <ide> new_array = asarray(fp) <del> assert(new_array.base is fp) <add> assert_(new_array.base is fp) <ide> <ide> if __name__ == "__main__": <ide> run_module_suite() <ide><path>numpy/core/tests/test_multiarray.py <ide> def test_contiguous(self): <ide> self.a.flat[12] = 100.0 <ide> except ValueError: <ide> testpassed = True <del> assert testpassed <del> assert self.a.flat[12] == 12.0 <add> assert_(testpassed) <add> assert_(self.a.flat[12] == 12.0) <ide> <ide> def test_discontiguous(self): <ide> testpassed = False <ide> try: <ide> self.b.flat[4] = 100.0 <ide> except ValueError: <ide> testpassed = True <del> assert testpassed <del> assert self.b.flat[4] == 12.0 <add> assert_(testpassed) <add> assert_(self.b.flat[4] == 12.0) <ide> <ide> def test___array__(self): <ide> c = self.a.flat.__array__() <ide> d = self.b.flat.__array__() <ide> e = self.a0.flat.__array__() <ide> f = self.b0.flat.__array__() <ide> <del> assert c.flags.writeable is False <del> assert d.flags.writeable is False <del> assert e.flags.writeable is True <del> assert f.flags.writeable is True <add> assert_(c.flags.writeable is False) <add> assert_(d.flags.writeable is False) <add> assert_(e.flags.writeable is True) <add> assert_(f.flags.writeable is True) <ide> <del> assert c.flags.updateifcopy is False <del> assert d.flags.updateifcopy is False <del> assert e.flags.updateifcopy is False <del> assert f.flags.updateifcopy is True <del> assert f.base is self.b0 <add> assert_(c.flags.updateifcopy is False) <add> assert_(d.flags.updateifcopy is False) <add> assert_(e.flags.updateifcopy is False) <add> assert_(f.flags.updateifcopy is True) <add> assert_(f.base is self.b0) <ide> <ide> class TestResize(TestCase): <ide> def test_basic(self): <ide> def test_relaxed_strides(self): <ide> if np.ones((10, 1), order="C").flags.f_contiguous: <ide> c.strides = (-1, 80, 8) <ide> <del> assert memoryview(c).strides == (800, 80, 8) <add> assert_(memoryview(c).strides == (800, 80, 8)) <ide> <ide> # Writing C-contiguous data to a BytesIO buffer should work <ide> fd = io.BytesIO() <ide> fd.write(c.data) <ide> <ide> fortran = c.T <del> assert memoryview(fortran).strides == (8, 80, 800) <add> assert_(memoryview(fortran).strides == (8, 80, 800)) <ide> <ide> arr = np.ones((1, 10)) <ide> if arr.flags.f_contiguous: <ide><path>numpy/core/tests/test_numeric.py <ide> def test_errobj(self): <ide> def log_err(*args): <ide> self.called += 1 <ide> extobj_err = args <del> assert (len(extobj_err) == 2) <del> assert ("divide" in extobj_err[0]) <add> assert_(len(extobj_err) == 2) <add> assert_("divide" in extobj_err[0]) <ide> <ide> with np.errstate(divide='ignore'): <ide> np.seterrobj([20000, 3, log_err]) <ide><path>numpy/core/tests/test_scalarinherit.py <ide> from __future__ import division, absolute_import, print_function <ide> <ide> import numpy as np <del>from numpy.testing import TestCase, run_module_suite <add>from numpy.testing import TestCase, run_module_suite, assert_ <ide> <ide> <ide> class A(object): <ide> class C0(B0): <ide> class TestInherit(TestCase): <ide> def test_init(self): <ide> x = B(1.0) <del> assert str(x) == '1.0' <add> assert_(str(x) == '1.0') <ide> y = C(2.0) <del> assert str(y) == '2.0' <add> assert_(str(y) == '2.0') <ide> z = D(3.0) <del> assert str(z) == '3.0' <add> assert_(str(z) == '3.0') <ide> <ide> def test_init2(self): <ide> x = B0(1.0) <del> assert str(x) == '1.0' <add> assert_(str(x) == '1.0') <ide> y = C0(2.0) <del> assert str(y) == '2.0' <add> assert_(str(y) == '2.0') <ide> <ide> if __name__ == "__main__": <ide> run_module_suite() <ide><path>numpy/core/tests/test_shape_base.py <ide> def test_stack(): <ide> for axis, expected_shape in zip(axes, expected_shapes): <ide> assert_equal(np.stack(arrays, axis).shape, expected_shape) <ide> # empty arrays <del> assert stack([[], [], []]).shape == (3, 0) <del> assert stack([[], [], []], axis=1).shape == (0, 3) <add> assert_(stack([[], [], []]).shape == (3, 0)) <add> assert_(stack([[], [], []], axis=1).shape == (0, 3)) <ide> # edge cases <ide> assert_raises_regex(ValueError, 'need at least one array', stack, []) <ide> assert_raises_regex(ValueError, 'must have the same shape', <ide><path>numpy/core/tests/test_ufunc.py <ide> def test_sig_dtype(self): <ide> class TestUfunc(TestCase): <ide> def test_pickle(self): <ide> import pickle <del> assert pickle.loads(pickle.dumps(np.sin)) is np.sin <add> assert_(pickle.loads(pickle.dumps(np.sin)) is np.sin) <ide> <ide> # Check that ufunc not defined in the top level numpy namespace such as <ide> # numpy.core.test_rational.test_add can also be pickled <del> assert pickle.loads(pickle.dumps(test_add)) is test_add <add> assert_(pickle.loads(pickle.dumps(test_add)) is test_add) <ide> <ide> def test_pickle_withstring(self): <ide> import pickle <ide> astring = asbytes("cnumpy.core\n_ufunc_reconstruct\np0\n" <ide> "(S'numpy.core.umath'\np1\nS'cos'\np2\ntp3\nRp4\n.") <del> assert pickle.loads(astring) is np.cos <add> assert_(pickle.loads(astring) is np.cos) <ide> <ide> def test_reduceat_shifting_sum(self): <ide> L = 6 <ide><path>numpy/lib/tests/test_io.py <ide> def test_auto_dtype_largeint(self): <ide> <ide> assert_equal(test.dtype.names, ['f0', 'f1', 'f2']) <ide> <del> assert test.dtype['f0'] == np.float <del> assert test.dtype['f1'] == np.int64 <del> assert test.dtype['f2'] == np.integer <add> assert_(test.dtype['f0'] == np.float) <add> assert_(test.dtype['f1'] == np.int64) <add> assert_(test.dtype['f2'] == np.integer) <ide> <ide> assert_allclose(test['f0'], 73786976294838206464.) <ide> assert_equal(test['f1'], 17179869184) <ide><path>numpy/linalg/tests/test_linalg.py <ide> def get_rtol(dtype): <ide> class LinalgCase(object): <ide> <ide> def __init__(self, name, a, b, exception_cls=None): <del> assert isinstance(name, str) <add> assert_(isinstance(name, str)) <ide> self.name = name <ide> self.a = a <ide> self.b = b <ide> def _stride_comb_iter(x): <ide> xi = xi[slices] <ide> xi[...] = x <ide> xi = xi.view(x.__class__) <del> assert np.all(xi == x) <add> assert_(np.all(xi == x)) <ide> yield xi, "stride_" + "_".join(["%+d" % j for j in repeats]) <ide> <ide> # generate also zero strides if possible <ide><path>numpy/ma/tests/test_core.py <ide> def test_mvoid_multidim_print(self): <ide> mask = [([False, True, False],)], <ide> fill_value = ([999999, 999999, 999999],), <ide> dtype = [('a', '<i8', (3,))]) <del> assert str(t_ma[0]) == "([1, --, 3],)" <del> assert repr(t_ma[0]) == "([1, --, 3],)" <add> assert_(str(t_ma[0]) == "([1, --, 3],)") <add> assert_(repr(t_ma[0]) == "([1, --, 3],)") <ide> <ide> # additonal tests with structured arrays <ide> <ide> t_2d = masked_array(data = [([[1, 2], [3,4]],)], <ide> mask = [([[False, True], [True, False]],)], <ide> dtype = [('a', '<i8', (2,2))]) <del> assert str(t_2d[0]) == "([[1, --], [--, 4]],)" <del> assert repr(t_2d[0]) == "([[1, --], [--, 4]],)" <add> assert_(str(t_2d[0]) == "([[1, --], [--, 4]],)") <add> assert_(repr(t_2d[0]) == "([[1, --], [--, 4]],)") <ide> <ide> t_0d = masked_array(data = [(1,2)], <ide> mask = [(True,False)], <ide> dtype = [('a', '<i8'), ('b', '<i8')]) <del> assert str(t_0d[0]) == "(--, 2)" <del> assert repr(t_0d[0]) == "(--, 2)" <add> assert_(str(t_0d[0]) == "(--, 2)") <add> assert_(repr(t_0d[0]) == "(--, 2)") <ide> <ide> t_2d = masked_array(data = [([[1, 2], [3,4]], 1)], <ide> mask = [([[False, True], [True, False]], False)], <ide> dtype = [('a', '<i8', (2,2)), ('b', float)]) <del> assert str(t_2d[0]) == "([[1, --], [--, 4]], 1.0)" <del> assert repr(t_2d[0]) == "([[1, --], [--, 4]], 1.0)" <add> assert_(str(t_2d[0]) == "([[1, --], [--, 4]], 1.0)") <add> assert_(repr(t_2d[0]) == "([[1, --], [--, 4]], 1.0)") <ide> <ide> t_ne = masked_array(data=[(1, (1, 1))], <ide> mask=[(True, (True, False))], <ide> dtype = [('a', '<i8'), ('b', 'i4,i4')]) <del> assert str(t_ne[0]) == "(--, (--, 1))" <del> assert repr(t_ne[0]) == "(--, (--, 1))" <add> assert_(str(t_ne[0]) == "(--, (--, 1))") <add> assert_(repr(t_ne[0]) == "(--, (--, 1))") <ide> <ide> def test_object_with_array(self): <ide> mx1 = masked_array([1.], mask=[True]) <ide> mx2 = masked_array([1., 2.]) <ide> mx = masked_array([mx1, mx2], mask=[False, True]) <del> assert mx[0] is mx1 <del> assert mx[1] is not mx2 <del> assert np.all(mx[1].data == mx2.data) <del> assert np.all(mx[1].mask) <add> assert_(mx[0] is mx1) <add> assert_(mx[1] is not mx2) <add> assert_(np.all(mx[1].data == mx2.data)) <add> assert_(np.all(mx[1].mask)) <ide> # check that we return a view. <ide> mx[1].data[0] = 0. <del> assert mx2[0] == 0. <add> assert_(mx2[0] == 0.) <ide> <ide> <ide> class TestMaskedArrayArithmetic(TestCase): <ide> def test_append_masked_array_along_axis(): <ide> <ide> def test_default_fill_value_complex(): <ide> # regression test for Python 3, where 'unicode' was not defined <del> assert default_fill_value(1 + 1j) == 1.e20 + 0.0j <add> assert_(default_fill_value(1 + 1j) == 1.e20 + 0.0j) <ide> <ide> ############################################################################### <ide> if __name__ == "__main__":
13
Python
Python
fix a couple of `pytest` id labels
705c54c688bf1bdf5562624b8971c228faaed675
<ide><path>numpy/lib/tests/test_nanfunctions.py <ide> def test_result_values(self): <ide> @pytest.mark.parametrize("axis", [None, 0, 1]) <ide> @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"]) <ide> @pytest.mark.parametrize("array", [ <del> np.full((3, 3), np.nan), <ide> np.array(np.nan), <add> np.full((3, 3), np.nan), <ide> ], ids=["0d", "2d"]) <ide> def test_allnans(self, axis, dtype, array): <ide> if axis is not None and array.ndim == 0: <ide> def test_result_values(self): <ide> @pytest.mark.parametrize("axis", [None, 0, 1]) <ide> @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"]) <ide> @pytest.mark.parametrize("array", [ <del> np.full((3, 3), np.nan), <ide> np.array(np.nan), <add> np.full((3, 3), np.nan), <ide> ], ids=["0d", "2d"]) <ide> def test_allnans(self, axis, dtype, array): <ide> if axis is not None and array.ndim == 0: <ide> class TestNanFunctions_SumProd(SharedNanFunctionsTestsMixin): <ide> @pytest.mark.parametrize("axis", [None, 0, 1]) <ide> @pytest.mark.parametrize("dtype", np.typecodes["AllFloat"]) <ide> @pytest.mark.parametrize("array", [ <del> np.full((3, 3), np.nan), <ide> np.array(np.nan), <add> np.full((3, 3), np.nan), <ide> ], ids=["0d", "2d"]) <ide> def test_allnans(self, axis, dtype, array): <ide> if axis is not None and array.ndim == 0:
1
PHP
PHP
remove extra whitespace
8e5b9e347675d9f7d5d0d9d495e6e631202d7575
<ide><path>src/I18n/RelativeTimeFormatter.php <ide> public function timeAgoInWords(array $options = []) <ide> <ide> $relativeDate = []; <ide> if ($fNum >= 1 && $years > 0) { <del> $relativeDate[] = __dn('cake', '{0} year', '{0} years', $years, $years); <add> $relativeDate[] = __dn('cake', '{0} year', '{0} years', $years, $years); <ide> } <ide> if ($fNum >= 2 && $months > 0) { <ide> $relativeDate[] = __dn('cake', '{0} month', '{0} months', $months, $months); <ide> public function dateAgoInWords(array $options = []) <ide> $relativeDate[] = __dn('cake', '{0} week', '{0} weeks', $weeks, $weeks); <ide> } <ide> if ($fNum >= 4 && $days > 0) { <del> $relativeDate[] = __dn('cake', '{0} day', '{0} days', $days, $days); <add> $relativeDate[] = __dn('cake', '{0} day', '{0} days', $days, $days); <ide> } <ide> $relativeDate = implode(', ', $relativeDate); <ide>
1
Ruby
Ruby
fix inspect with non-primary key id attribute
65cd0fda2572ac9c78d8582496a9009d0c48df08
<ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def attributes <ide> # person.attribute_for_inspect(:tag_ids) <ide> # # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]" <ide> def attribute_for_inspect(attr_name) <del> value = read_attribute(attr_name) <add> value = _read_attribute(attr_name) <ide> format_for_inspect(value) <ide> end <ide> <ide><path>activerecord/lib/active_record/core.rb <ide> def inspect <ide> inspection = if defined?(@attributes) && @attributes <ide> self.class.attribute_names.collect do |name| <ide> if has_attribute?(name) <del> attr = read_attribute(name) <add> attr = _read_attribute(name) <ide> value = if attr.nil? <ide> attr.inspect <ide> else <ide> def pretty_print(pp) <ide> pp.text attr_name <ide> pp.text ":" <ide> pp.breakable <del> value = read_attribute(attr_name) <add> value = _read_attribute(attr_name) <ide> value = inspection_filter.filter_param(attr_name, value) unless value.nil? <ide> pp.pp value <ide> end <ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def setup <ide> assert_equal "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]", t.attribute_for_inspect(:content) <ide> end <ide> <add> test "attribute_for_inspect with a non-primary key id attribute" do <add> t = topics(:first).becomes(TitlePrimaryKeyTopic) <add> t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters" <add> <add> assert_equal "1", t.attribute_for_inspect(:id) <add> end <add> <ide> test "attribute_present" do <ide> t = Topic.new <ide> t.title = "hello there!" <ide><path>activerecord/test/cases/core_test.rb <ide> def test_inspect_limited_select_instance <ide> assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.all.merge!(select: "id, title", where: "id = 1").first.inspect <ide> end <ide> <add> def test_inspect_instance_with_non_primary_key_id_attribute <add> topic = topics(:first).becomes(TitlePrimaryKeyTopic) <add> assert_match(/id: 1/, topic.inspect) <add> end <add> <ide> def test_inspect_class_without_table <ide> assert_equal "NonExistentTable(Table doesn't exist)", NonExistentTable.inspect <ide> end <ide> def inspect <ide> PP.pp(subtopic.new, StringIO.new(actual)) <ide> assert_equal "inspecting topic\n", actual <ide> end <add> <add> def test_pretty_print_with_non_primary_key_id_attribute <add> topic = topics(:first).becomes(TitlePrimaryKeyTopic) <add> actual = +"" <add> PP.pp(topic, StringIO.new(actual)) <add> assert_match(/id: 1/, actual) <add> end <ide> end <ide><path>activerecord/test/models/topic.rb <ide> def blank? <ide> end <ide> end <ide> <add>class TitlePrimaryKeyTopic < Topic <add> self.primary_key = :title <add>end <add> <ide> module Web <ide> class Topic < ActiveRecord::Base <ide> has_many :replies, dependent: :destroy, foreign_key: "parent_id", class_name: "Web::Reply"
5
Javascript
Javascript
handle division by zero in partition
9579eedc3e57748a160e86373acd8dc90a50fde3
<ide><path>src/layout/partition.js <ide> d3.layout.partition = function() { <ide> n = children.length, <ide> c, <ide> d; <del> dx /= node.value; <add> dx = node.value === 0 <add> ? 0 : dx / node.value; <ide> while (++i < n) { <ide> position(c = children[i], x, d = c.value * dx, dy); <ide> x += d;
1
Ruby
Ruby
avoid two method calls
68a949bae7408dafdfdd28b6c1de25d5348e64c7
<ide><path>activerecord/lib/active_record/relation/spawn_methods.rb <ide> def merge(r) <ide> <ide> ((Relation::ASSOCIATION_METHODS + Relation::MULTI_VALUE_METHODS) - [:joins, :where]).each do |method| <ide> value = r.send(:"#{method}_values") <del> if value.present? <add> unless value.empty? <ide> if method == :includes <ide> merged_relation = merged_relation.includes(value) <ide> else
1
Python
Python
remove eagerloading when querying for ti
9eae83c1386523e5fc9e8f0e93840330d4d988d0
<ide><path>airflow/api_connexion/endpoints/log_endpoint.py <ide> from flask import Response, current_app, request <ide> from itsdangerous.exc import BadSignature <ide> from itsdangerous.url_safe import URLSafeSerializer <del>from sqlalchemy.orm import eagerload <ide> <ide> from airflow.api_connexion import security <ide> from airflow.api_connexion.exceptions import BadRequest, NotFound <ide> def get_log(session, dag_id, dag_run_id, task_id, task_try_number, full_content= <ide> session.query(TaskInstance) <ide> .filter(TaskInstance.task_id == task_id, TaskInstance.run_id == dag_run_id) <ide> .join(TaskInstance.dag_run) <del> .options(eagerload(TaskInstance.dag_run)) <ide> .one_or_none() <ide> ) <ide> if ti is None: <ide><path>airflow/api_connexion/endpoints/task_instance_endpoint.py <ide> from flask import current_app, request <ide> from marshmallow import ValidationError <ide> from sqlalchemy import and_, func <del>from sqlalchemy.orm import eagerload <ide> from sqlalchemy.orm.exc import NoResultFound <ide> <ide> from airflow.api_connexion import security <ide> def get_task_instance(dag_id: str, dag_run_id: str, task_id: str, session=None): <ide> session.query(TI) <ide> .filter(TI.dag_id == dag_id, DR.run_id == dag_run_id, TI.task_id == task_id) <ide> .join(TI.dag_run) <del> .options(eagerload(TI.dag_run)) <ide> .outerjoin( <ide> SlaMiss, <ide> and_( <ide> def get_task_instances( <ide> session=None, <ide> ): <ide> """Get list of task instances.""" <del> base_query = session.query(TI).join(TI.dag_run).options(eagerload(TI.dag_run)) <add> base_query = session.query(TI).join(TI.dag_run) <ide> <ide> if dag_id != "~": <ide> base_query = base_query.filter(TI.dag_id == dag_id) <ide> def get_task_instances_batch(session=None): <ide> data = task_instance_batch_form.load(body) <ide> except ValidationError as err: <ide> raise BadRequest(detail=str(err.messages)) <del> base_query = session.query(TI).join(TI.dag_run).options(eagerload(TI.dag_run)) <add> base_query = session.query(TI).join(TI.dag_run) <ide> <ide> base_query = _apply_array_filter(base_query, key=TI.dag_id, values=data["dag_ids"]) <ide> base_query = _apply_range_filter( <ide> def post_clear_task_instances(dag_id: str, session=None): <ide> clear_task_instances( <ide> task_instances.all(), session, dag=dag, dag_run_state=State.QUEUED if reset_dag_runs else False <ide> ) <del> task_instances = task_instances.join(TI.dag_run).options(eagerload(TI.dag_run)) <add> <ide> return task_instance_reference_collection_schema.dump( <ide> TaskInstanceReferenceCollection(task_instances=task_instances.all()) <ide> ) <ide><path>airflow/dag_processing/processor.py <ide> <ide> from setproctitle import setproctitle <ide> from sqlalchemy import func, or_ <del>from sqlalchemy.orm import eagerload <ide> from sqlalchemy.orm.session import Session <ide> <ide> from airflow import models, settings <ide> def manage_slas(self, dag: DAG, session: Session = None) -> None: <ide> <ide> max_tis: Iterator[TI] = ( <ide> session.query(TI) <del> .options(eagerload(TI.dag_run)) <ide> .join(TI.dag_run) <ide> .filter( <ide> TI.dag_id == dag.dag_id, <ide><path>airflow/jobs/backfill_job.py <ide> from typing import Optional, Set <ide> <ide> import pendulum <del>from sqlalchemy.orm import eagerload <ide> from sqlalchemy.orm.session import Session, make_transient <ide> from tabulate import tabulate <ide> <ide> def reset_state_for_orphaned_tasks(self, filter_by_dag_run=None, session=None): <ide> resettable_tis = ( <ide> session.query(TaskInstance) <ide> .join(TaskInstance.dag_run) <del> .options(eagerload(TaskInstance.dag_run)) <ide> .filter( <ide> DagRun.state == State.RUNNING, <ide> DagRun.run_type != DagRunType.BACKFILL_JOB, <ide><path>airflow/jobs/scheduler_job.py <ide> <ide> from sqlalchemy import and_, func, not_, or_, tuple_ <ide> from sqlalchemy.exc import OperationalError <del>from sqlalchemy.orm import eagerload, load_only, selectinload <add>from sqlalchemy.orm import load_only, selectinload <ide> from sqlalchemy.orm.session import Session, make_transient <ide> <ide> from airflow import models, settings <ide> def _executable_task_instances_to_queued(self, max_tis: int, session: Session = <ide> query = ( <ide> session.query(TI) <ide> .join(TI.dag_run) <del> .options(eagerload(TI.dag_run)) <ide> .filter(DR.run_type != DagRunType.BACKFILL_JOB, DR.state != DagRunState.QUEUED) <ide> .join(TI.dag_model) <ide> .filter(not_(DM.is_paused))
5
PHP
PHP
update main descrition
d492c86ddc7f9c072d286491d8eef729f645a37d
<ide><path>lib/Cake/Console/Command/TestShell.php <ide> public function getOptionParser() { <ide> $parser = new ConsoleOptionParser($this->name); <ide> $parser->description(array( <ide> __d('cake_console', 'The CakePHP Testsuite allows you to run test cases from the command line'), <del> ))->addArgument('category', array( <del> 'help' => __d('cake_console', 'app, core or name of a plugin.'), <del> 'required' => true <add> __d('cake_console', 'Accepts'), <add> __d('cake_console', ' - path to a file'), <add> __d('cake_console', ' - path to a test file'), <add> __d('cake_console', ' - <category> <test> (syntax used until 2.0)') <ide> ))->addArgument('file', array( <del> 'help' => __d('cake_console', 'file name with folder prefix and without the test.php suffix.'), <add> 'help' => __d('cake_console', 'The path to the file, or test file, to test.'), <ide> 'required' => false, <ide> ))->addOption('log-junit', array( <ide> 'help' => __d('cake_console', '<file> Log test execution in JUnit XML format to file.'),
1
PHP
PHP
fix bug in migration table builder
e943b3da84ab556f0176eea73387cd14fa07933e
<ide><path>src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php <ide> public function repositoryExists() <ide> { <ide> $schema = $this->getConnection()->getSchemaBuilder(); <ide> <del> $prefix = $this->getConnection()->getTablePrefix(); <del> <del> return $schema->hasTable($prefix.$this->table); <add> return $schema->hasTable($this->table); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add news link to nav (#261)
5024e69b69f53574457f884d2e95a3789bb3ca74
<ide><path>packages/learn/src/components/Header/index.js <ide> function Header() { <ide> return ( <ide> <header> <ide> <nav id='top-nav'> <del> <a className='home-link' href='https://freecodecamp.org'> <add> <a className='home-link' href='https://www.freecodecamp.org'> <ide> <NavLogo /> <ide> </a> <ide> <FCCSearch /> <ide> function Header() { <ide> Forum <ide> </a> <ide> </li> <add> <li className='nav-btn'> <add> <a href='https://www.freecodecamp.org/news' target='_blank'> <add> News <add> </a> <add> </li> <ide> <li className='sign-in-btn'> <add> <ide> <UserState /> <ide> </li> <ide> </ul>
1
Javascript
Javascript
add the type1 subrs into the cff local subrs index
7bc26ba12765742817c3ea810d90bd796230cce2
<ide><path>fonts.js <ide> CFF.prototype = { <ide> "hlineto": 6, <ide> "vlineto": 7, <ide> "rrcurveto": 8, <add> "callsubr": 10, <add> "return": 11, <ide> "endchar": 14, <ide> "rmoveto": 21, <ide> "hmoveto": 22, <ide> "vhcurveto": 30, <ide> "hvcurveto": 31, <ide> }, <ide> <del> flattenCharstring: function flattenCharstring(charstring, subrs) { <add> flattenCharstring: function flattenCharstring(charstring) { <ide> var i = 0; <ide> while (true) { <ide> var obj = charstring[i]; <ide> CFF.prototype = { <ide> <ide> if (obj.charAt) { <ide> switch (obj) { <del> case "callsubr": <del> var subr = subrs[charstring[i - 1]]; <del> if (subr.length > 1) { <del> subr = this.flattenCharstring(subr, subrs); <del> subr.pop(); <del> charstring.splice(i - 1, 2, subr); <del> } else { <del> charstring.splice(i - 1, 2); <del> } <del> i -= 1; <del> break; <del> <ide> case "callothersubr": <ide> var index = charstring[i - 1]; <ide> var count = charstring[i - 2]; <ide> var data = charstring[i - 3]; <ide> <del> // XXX The callothersubr needs to support at least the 3 defaults <del> // otherSubrs of the spec <del> if (index != 3) <del> error("callothersubr for index: " + index + " (" + charstring + ")"); <del> <del> if (!data) { <del> charstring.splice(i - 2, 4, "pop", 3); <del> i -= 3; <del> } else { <del> // 5 to remove the arguments, the callothersubr call and the pop command <del> charstring.splice(i - 3, 5, 3); <add> // If the flex mechanishm is not used in a font program, Adobe <add> // state that that entries 0, 1 and 2 can simply be replace by <add> // {}, which means that we can simply ignore them. <add> if (index < 3) { <ide> i -= 3; <add> continue; <add> } <add> <add> // This is the same things about hint replacment, if it is not used <add> // entry 3 can be replaced by {} <add> if (index == 3) { <add> if (!data) { <add> charstring.splice(i - 2, 4, "pop", 3); <add> i -= 3; <add> } else { <add> // 5 to remove the arguments, the callothersubr call and the pop command <add> charstring.splice(i - 3, 5, 3); <add> i -= 3; <add> } <ide> } <ide> break; <ide> <ide> CFF.prototype = { <ide> i -= 2; <ide> break; <ide> <del> case "pop": <del> if (i) <del> charstring.splice(i - 2, 2); <del> else <del> charstring.splice(i - 1, 1); <del> i -= 1; <del> break; <del> <del> <ide> case "hsbw": <ide> var charWidthVector = charstring[i - 1]; <ide> var leftSidebearing = charstring[i - 2]; <ide> CFF.prototype = { <ide> var glyphsCount = charstrings.length; <ide> for (var i = 0; i < glyphsCount; i++) { <ide> var charstring = charstrings[i].charstring; <del> glyphs.push(this.flattenCharstring(charstring.slice(), subrs)); <add> glyphs.push(this.flattenCharstring(charstring.slice())); <ide> } <ide> <ide> // Create a CFF font data <ide> CFF.prototype = { <ide> 247, 32, 11, <ide> 247, 10, 161, 147, 154, 150, 143, 12, 13, <ide> 139, 12, 14, <del> 28, 0, 55, 19 <add> 28, 0, 55, 19 // Subrs offset <ide> ]); <ide> cff.set(privateData, currentOffset); <ide> currentOffset += privateData.length; <ide> <del> // Dump shit at the end of the file <del> var shit = [ <del> 0x00, 0x01, 0x01, 0x01, <del> 0x13, 0x5D, 0x65, 0x64, <del> 0x5E, 0x5B, 0xAF, 0x66, <del> 0xBA, 0xBB, 0xB1, 0xB0, <del> 0xB9, 0xBA, 0x65, 0xB2, <del> 0x5C, 0x1F, 0x0B <del> ]; <del> cff.set(shit, currentOffset); <del> currentOffset += shit.length; <add> // Local Subrs <add> var flattenedSubrs = []; <add> <add> var bias = 0; <add> var subrsCount = subrs.length; <add> if (subrsCount < 1240) <add> bias = 107; <add> else if (subrsCount < 33900) <add> bias = 1131; <add> else <add> bias = 32768; <add> <add> // Add a bunch of empty subrs to deal with the Type2 bias <add> for (var i = 0; i < bias; i++) <add> flattenedSubrs.push([0x0B]); <add> <add> for (var i = 0; i < subrsCount; i++) { <add> var subr = subrs[i]; <add> flattenedSubrs.push(this.flattenCharstring(subr)); <add> } <add> <add> var subrsData = this.createCFFIndexHeader(flattenedSubrs, true); <add> cff.set(subrsData, currentOffset); <add> currentOffset += subrsData.length; <ide> <ide> var fontData = []; <ide> for (var i = 0; i < currentOffset; i++)
1
Javascript
Javascript
use a polyfill when math.log10 does not exist
29743e1d63353008d53276cce6db962c636d6c39
<ide><path>src/Chart.Core.js <ide> return x > 0 ? 1 : -1; <ide> } <ide> }, <add> log10 = helpers.log10 = function(x) { <add> if (Math.log10) { <add> return Math.log10(x) <add> } else { <add> return Math.log(x) / Math.LN10; <add> } <add> }, <ide> cap = helpers.cap = function(valueToCap, maxValue, minValue) { <ide> if (isNumber(maxValue)) { <ide> if (valueToCap > maxValue) { <ide> }, <ide> // Implementation of the nice number algorithm used in determining where axis labels will go <ide> niceNum = helpers.niceNum = function(range, round) { <del> var exponent = Math.floor(Math.log10(range)); <add> var exponent = Math.floor(helpers.log10(range)); <ide> var fraction = range / Math.pow(10, exponent); <ide> var niceFraction; <ide>
1
Text
Text
add oculus go/quest to supported platforms
19f2317e46ec56d971adae5793ae9518830f10b5
<ide><path>guide/english/game-development/unity/index.md <ide> For 3D games, Unity allows specification of texture compression and resolution s <ide> <ide> Unity also offers services to developers, these are: Unity Ads, Unity Analytics, Unity Certification, Unity Cloud Build, Unity Everyplay, Unity IAP, Unity Multiplayer, Unity Performance Reporting and Unity Collaborate. Besides this, Unity has an asset store where the developer community can download and upload both commercial and free third party resources such as textures, models, plugins, editor extensions and even entire game examples. <ide> <del>Unity is notable for its ability to target games for multiple platforms. The currently supported platforms are Android, Android TV, Facebook Gameroom, Fire OS, Gear VR, Google Cardboard, Google Daydream, HTC Vive, iOS, Linux, macOS, Microsoft HoloLens, Nintendo 3DS family, Nintendo Switch, Oculus Rift, PlayStation 4, PlayStation Vita, PlayStation VR, Samsung Smart TV, Tizen, tvOS, WebGL, Wii U, Windows, Windows Phone, Windows Store, and Xbox One. <add>Unity is notable for its ability to target games for multiple platforms. The currently supported platforms are Android, Android TV, Facebook Gameroom, Fire OS, Gear VR, Google Cardboard, Google Daydream, HTC Vive, iOS, Linux, macOS, Microsoft HoloLens, Nintendo 3DS family, Nintendo Switch, Oculus Rift, Oculus Go, Oculus Quest, PlayStation 4, PlayStation Vita, PlayStation VR, Samsung Smart TV, Tizen, tvOS, WebGL, Wii U, Windows, Windows Phone, Windows Store, and Xbox One. <ide> <ide> Unity is the default software development kit (SDK) for Nintendo's Wii U video game console platform, with a free copy included by Nintendo with each Wii U developer license. <ide> Unity Technologies calls this bundling of a third-party SDK an "industry first".
1
Ruby
Ruby
add stable checksum to the json api
cc78b155c6f1ced33b864f21613f29b235ca1c7a
<ide><path>Library/Homebrew/formula.rb <ide> def to_hash <ide> "url" => stable.url, <ide> "tag" => stable.specs[:tag], <ide> "revision" => stable.specs[:revision], <add> "checksum" => stable.checksum&.to_s, <ide> } <ide> <ide> hsh["bottle"]["stable"] = bottle_hash if bottle_defined? <ide><path>Library/Homebrew/formulary.rb <ide> def self.load_formula_from_api(name, flags:) <ide> stable do <ide> url urls_stable["url"] <ide> version json_formula["versions"]["stable"] <add> sha256 urls_stable["checksum"] if urls_stable["checksum"].present? <ide> end <ide> end <ide>
2
Python
Python
add regression test for fromstring
5af6ff3a240fa44e28a1630414ec69a0780aaa20
<ide><path>numpy/core/tests/test_regression.py <ide> def check_mem_scalar_indexing(self, level=rlevel): <ide> def check_binary_repr_0_width(self, level=rlevel): <ide> assert_equal(np.binary_repr(0,width=3),'000') <ide> <add> def check_fromstring(self, level=rlevel): <add> assert_equal(np.fromstring("12:09:09", dtype=int, sep=":"), <add> [12,9,9]) <add> <ide> if __name__ == "__main__": <ide> NumpyTest().run()
1
Javascript
Javascript
remove unused method
3cf2f45290dfb6529554c57a854cbf5bfd957eb0
<ide><path>lib/optimize/ConcatenatedModule.js <ide> ${defineGetters}` <ide> } <ide> } <ide> <del> /** <del> * @param {ChunkGraph} chunkGraph the chunk graph <del> * @param {DependencyTemplates} dependencyTemplates dependency templates <del> * @param {RuntimeSpec} runtime the runtime <del> * @returns {string} hash <del> */ <del> _getHashDigest(chunkGraph, dependencyTemplates, runtime) { <del> const hash = chunkGraph.getModuleHash(this, runtime); <del> const dtHash = dependencyTemplates.getHash(); <del> return `${hash}-${dtHash}`; <del> } <del> <ide> /** <ide> * @param {ModuleGraph} moduleGraph the module graph <ide> * @param {RuntimeSpec} runtime the runtime
1
Ruby
Ruby
add [email protected] to binary urls whitelist
79811537fbef39b2efad2036544e0bfdc33da278
<ide><path>Library/Homebrew/rubocops/urls.rb <ide> class Urls < FormulaCop <ide> [email protected] <ide> [email protected] <ide> [email protected] <add> [email protected] <ide> haskell-stack <ide> ldc <ide> mlton
1
Ruby
Ruby
remove unused use_sprockets config
cb85d70d61705381a57cb99d8dcd4d7083f0a143
<ide><path>actionpack/lib/abstract_controller/asset_paths.rb <ide> module AssetPaths <ide> extend ActiveSupport::Concern <ide> <ide> included do <del> config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir, :stylesheets_dir, :use_sprockets <add> config_accessor :asset_host, :asset_path, :assets_dir, :javascripts_dir, :stylesheets_dir <ide> end <ide> end <ide> end <ide><path>actionpack/lib/sprockets/railtie.rb <ide> class Railtie < ::Rails::Railtie <ide> load "sprockets/assets.rake" <ide> end <ide> <del> # Configure ActionController to use sprockets. <del> initializer "sprockets.set_configs", :after => "action_controller.set_configs" do |app| <del> ActiveSupport.on_load(:action_controller) do <del> self.use_sprockets = app.config.assets.enabled <del> end <del> end <del> <ide> # We need to configure this after initialization to ensure we collect <ide> # paths from all engines. This hook is invoked exactly before routes <ide> # are compiled, and so that other Railties have an opportunity to
2
Javascript
Javascript
prevent workers outliving parent
4d896c44f3a0b5f824a4d2971d96b29f3df69e23
<ide><path>test/sequential/test-child-process-pass-fd.js <ide> if (process.argv[2] !== 'child') { <ide> process.send('handle', socket); <ide> } <ide> <add> // As a side-effect, listening for the message event will ref the IPC channel, <add> // so the child process will stay alive as long as it has a parent process/IPC <add> // channel. Once this is done, we can unref our client and server sockets, and <add> // the only thing keeping this worker alive will be IPC. This is important, <add> // because it means a worker with no parent will have no referenced handles, <add> // thus no work to do, and will exit immediately, preventing process leaks. <add> process.on('message', function() {}); <add> <ide> const server = net.createServer((c) => { <ide> process.once('message', function(msg) { <ide> assert.strictEqual(msg, 'got'); <ide> c.end('hello'); <ide> }); <ide> socketConnected(); <del> }); <add> }).unref(); <ide> server.listen(0, common.localhostIPv4, () => { <ide> const port = server.address().port; <del> socket = net.connect(port, common.localhostIPv4, socketConnected); <add> socket = net.connect(port, common.localhostIPv4, socketConnected).unref(); <ide> }); <ide> }
1
Python
Python
clarify table contents in cond docstring
adea1d4fd4e1638f74bf1c8bc48b06992d569c7b
<ide><path>numpy/linalg/linalg.py <ide> def cond(x, p=None): <ide> x : (..., M, N) array_like <ide> The matrix whose condition number is sought. <ide> p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional <del> Order of the norm: <add> Order of the norm used in the condition number computation: <ide> <ide> ===== ============================ <ide> p norm for matrices <ide> def cond(x, p=None): <ide> -inf min(sum(abs(x), axis=1)) <ide> 1 max(sum(abs(x), axis=0)) <ide> -1 min(sum(abs(x), axis=0)) <del> 2 (largest sing. value)/(smallest sing. value) <del> -2 (smallest sing. value)/(largest sing. value) <add> 2 2-norm (largest sing. value) <add> -2 smallest singular value <ide> ===== ============================ <ide> <del> inf means the numpy.inf object, and the Frobenius norm is <add> inf means the `numpy.inf` object, and the Frobenius norm is <ide> the root-of-sum-of-squares norm. <ide> <ide> Returns
1
Python
Python
copy loss and metric to prevent side effect
5cc435810de326ee549c53e10ac014d676e37447
<ide><path>keras/engine/compile_utils.py <ide> def __init__(self, losses, loss_weights=None, output_names=None): <ide> self._user_losses = losses <ide> self._user_loss_weights = loss_weights <ide> <del> self._losses = losses <add> self._losses = copy.copy(losses) <ide> self._loss_weights = loss_weights <ide> self._per_output_metrics = None # Per-output losses become metrics. <ide> self._loss_metric = metrics_mod.Mean(name='loss') # Total loss. <ide> def __init__(self, metrics=None, weighted_metrics=None, output_names=None, <ide> self._user_metrics = metrics <ide> self._user_weighted_metrics = weighted_metrics <ide> <del> self._metrics = metrics <add> self._metrics = copy.copy(metrics) <ide> self._weighted_metrics = weighted_metrics <ide> self._built = False <ide> <ide><path>keras/engine/compile_utils_test.py <ide> def test_nested_structure(self): <ide> self.assertEqual(b_1_metric.name, 'b_1_loss') <ide> self.assertEqual(b_1_metric.result().numpy(), 0.5) <ide> <add> def test_no_input_mutation(self): <add> loss = {'a': 'mae'} <add> loss_container = compile_utils.LossesContainer(loss) <add> <add> y_t = {'a': tf.zeros((10, 1))} <add> y_p = {'a': tf.ones((10, 1)), 'b': tf.zeros((10, 1))} <add> sw = tf.convert_to_tensor([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) <add> <add> total_loss = loss_container(y_t, y_p, sample_weight=sw) <add> self.assertIsInstance(total_loss, tf.Tensor) <add> self.assertEqual(total_loss.numpy(), 0.5) <add> self.assertLen(loss, 1) <add> <ide> def test_broadcast_single_loss(self): <ide> loss_container = compile_utils.LossesContainer('mse') <ide> <ide> def test_nested_structure(self): <ide> self.assertEqual(b_1_mse_metric.name, 'b_1_mse') <ide> self.assertEqual(b_1_mse_metric.result().numpy(), 4.) <ide> <add> def test_no_input_mutation(self): <add> metric = {'a': 'mae'} <add> metric_container = compile_utils.MetricsContainer(metric) <add> <add> y_t = {'a': tf.zeros((10, 1))} <add> y_p = {'a': tf.ones((10, 1)), 'b': tf.zeros((10, 1))} <add> <add> metric_container.update_state(y_t, y_p) <add> self.assertLen(metric, 1) <add> mae_metric = metric_container.metrics[0] <add> self.assertEqual(mae_metric.result().numpy(), 1.) <add> <ide> def test_crossentropy(self): <ide> metric_container = compile_utils.MetricsContainer('crossentropy') <ide> y_t, y_p = tf.ones((10, 1)), tf.ones((10, 1))
2
Java
Java
fix user destination parsing in simp messaging
75c70fac3d77b4a9b81fb95b46309636ffdd3d76
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolver.java <ide> else if (SimpMessageType.MESSAGE.equals(messageType)) { <ide> subscribeDestination = this.destinationPrefix.substring(0, startIndex-1) + destinationWithoutPrefix; <ide> user = destination.substring(startIndex, endIndex); <ide> user = StringUtils.replace(user, "%2F", "/"); <del> user = user.equals(sessionId) ? null : user; <del> sessionIds = (sessionId != null ? <del> Collections.singleton(sessionId) : this.userSessionRegistry.getSessionIds(user)); <add> <add> if(user.equals(sessionId)) { <add> user = null; <add> sessionIds = Collections.singleton(sessionId); <add> } <add> else if (this.userSessionRegistry.getSessionIds(user).contains(sessionId)) { <add> sessionIds = Collections.singleton(sessionId); <add> } <add> else { <add> sessionIds = this.userSessionRegistry.getSessionIds(user); <add> } <ide> } <ide> else { <ide> return null; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolverTests.java <ide> public void handleMessage() { <ide> assertEquals(this.user.getName(), actual.getUser()); <ide> } <ide> <add> // SPR-12444 <add> @Test <add> public void handleMessageToOtherUser() { <add> final String OTHER_SESSION_ID = "456"; <add> final String OTHER_USER_NAME = "anna"; <add> <add> String sourceDestination = "/user/"+OTHER_USER_NAME+"/queue/foo"; <add> TestPrincipal otherUser = new TestPrincipal(OTHER_USER_NAME); <add> this.registry.registerSessionId(otherUser.getName(), OTHER_SESSION_ID); <add> Message<?> message = createMessage(SimpMessageType.MESSAGE, this.user, SESSION_ID, sourceDestination); <add> UserDestinationResult actual = this.resolver.resolveDestination(message); <add> <add> assertEquals(sourceDestination, actual.getSourceDestination()); <add> assertEquals(1, actual.getTargetDestinations().size()); <add> assertEquals("/queue/foo-user" + OTHER_SESSION_ID, actual.getTargetDestinations().iterator().next()); <add> assertEquals("/user/queue/foo", actual.getSubscribeDestination()); <add> assertEquals(otherUser.getName(), actual.getUser()); <add> } <add> <ide> @Test <ide> public void handleMessageEncodedUserName() { <ide>
2
Python
Python
add 1.8 support
8f25c0c53c24c88afc86d99bbb3ca4edc3a4e0a2
<ide><path>rest_framework/serializers.py <ide> """ <ide> from __future__ import unicode_literals <ide> from django.db import models <del>from django.db.models.fields import FieldDoesNotExist <add>from django.db.models.fields import FieldDoesNotExist, Field as DjangoModelField <ide> from django.utils.translation import ugettext_lazy as _ <ide> from rest_framework.compat import unicode_to_repr <ide> from rest_framework.utils import model_meta <ide> def _get_model_fields(self, field_names, declared_fields, extra_kwargs): <ide> continue <ide> <ide> try: <del> model_fields[source] = model._meta.get_field(source) <add> field = model._meta.get_field(source) <add> if isinstance(field, DjangoModelField): <add> model_fields[source] = field <ide> except FieldDoesNotExist: <ide> pass <ide>
1
Python
Python
remove leftover statement
087505280da48ced19435ec65630015bb31d2648
<ide><path>celery/concurrency/processes/pool.py <ide> def on_state_change(task): <ide> on_state_change(task) <ide> join_exited_workers() <ide> <del> job, i, obj = task <del> try: <del> cache[job]._set(i, obj) <del> except KeyError: <del> pass <del> <ide> if hasattr(outqueue, '_reader'): <ide> debug('ensuring that outqueue is not full') <ide> # If we don't make room available in outqueue then
1
PHP
PHP
fake() assertions
5783f4a741a537aaee9845fb725e9eb9941ce376
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php <ide> namespace Illuminate\Support\Testing\Fakes; <ide> <ide> use BadMethodCallException; <add>use Closure; <ide> use Illuminate\Contracts\Queue\Queue; <ide> use Illuminate\Queue\QueueManager; <add>use Illuminate\Support\Traits\ReflectsClosures; <ide> use PHPUnit\Framework\Assert as PHPUnit; <ide> <ide> class QueueFake extends QueueManager implements Queue <ide> { <add> use ReflectsClosures; <add> <ide> /** <ide> * All of the jobs that have been pushed. <ide> * <ide> class QueueFake extends QueueManager implements Queue <ide> */ <ide> public function assertPushed($job, $callback = null) <ide> { <add> if ($job instanceof Closure) { <add> [$job, $callback] = [$this->firstParameterType($job), $job]; <add> } <add> <ide> if (is_numeric($callback)) { <ide> return $this->assertPushedTimes($job, $callback); <ide> } <ide> protected function assertPushedTimes($job, $times = 1) <ide> */ <ide> public function assertPushedOn($queue, $job, $callback = null) <ide> { <add> if ($job instanceof Closure) { <add> [$job, $callback] = [$this->firstParameterType($job), $job]; <add> } <add> <ide> return $this->assertPushed($job, function ($job, $pushedQueue) use ($callback, $queue) { <ide> if ($pushedQueue !== $queue) { <ide> return false; <ide> protected function isChainOfObjects($chain) <ide> */ <ide> public function assertNotPushed($job, $callback = null) <ide> { <add> if ($job instanceof Closure) { <add> [$job, $callback] = [$this->firstParameterType($job), $job]; <add> } <add> <ide> PHPUnit::assertCount( <ide> 0, $this->pushed($job, $callback), <ide> "The unexpected [{$job}] job was pushed." <ide><path>tests/Support/SupportTestingQueueFakeTest.php <ide> public function testAssertPushed() <ide> $this->fake->assertPushed(JobStub::class); <ide> } <ide> <add> public function testAssertPushedWithClosure() <add> { <add> $this->fake->push($this->job); <add> <add> $this->fake->assertPushed(function (JobStub $job) { <add> return true; <add> }); <add> } <add> <ide> public function testQueueSize() <ide> { <ide> $this->assertEquals(0, $this->fake->size()); <ide> public function testQueueSize() <ide> } <ide> <ide> public function testAssertNotPushed() <add> { <add> $this->fake->push($this->job); <add> <add> try { <add> $this->fake->assertNotPushed(JobStub::class); <add> $this->fail(); <add> } catch (ExpectationFailedException $e) { <add> $this->assertThat($e, new ExceptionMessage('The unexpected [Illuminate\Tests\Support\JobStub] job was pushed.')); <add> } <add> } <add> <add> public function testAssertNotPushedWithClosure() <ide> { <ide> $this->fake->assertNotPushed(JobStub::class); <ide> <ide> $this->fake->push($this->job); <ide> <ide> try { <del> $this->fake->assertNotPushed(JobStub::class); <add> $this->fake->assertNotPushed(function (JobStub $job) { <add> return true; <add> }); <ide> $this->fail(); <ide> } catch (ExpectationFailedException $e) { <ide> $this->assertThat($e, new ExceptionMessage('The unexpected [Illuminate\Tests\Support\JobStub] job was pushed.')); <ide> public function testAssertPushedOn() <ide> $this->fake->assertPushedOn('foo', JobStub::class); <ide> } <ide> <add> public function testAssertPushedOnWithClosure() <add> { <add> $this->fake->push($this->job, '', 'foo'); <add> <add> try { <add> $this->fake->assertPushedOn('bar', function (JobStub $job) { <add> return true; <add> }); <add> $this->fail(); <add> } catch (ExpectationFailedException $e) { <add> $this->assertThat($e, new ExceptionMessage('The expected [Illuminate\Tests\Support\JobStub] job was not pushed.')); <add> } <add> <add> $this->fake->assertPushedOn('foo', function (JobStub $job) { <add> return true; <add> }); <add> } <add> <ide> public function testAssertPushedTimes() <ide> { <ide> $this->fake->push($this->job);
2
Text
Text
add michaël zasso to release team
55e597d30658d34388eaeb2248b87ad76b338dff
<ide><path>README.md <ide> Node.js releases are signed with one of the following GPG keys: <ide> `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1` <ide> * **Jeremiah Senkpiel** &lt;[email protected]&gt; <ide> `FD3A5288F042B6850C66B31F09FE44734EB7990E` <add>* **Michaël Zasso** &lt;[email protected]&gt; <add>`8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600` <ide> * **Myles Borins** &lt;[email protected]&gt; <ide> `C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8` <ide> * **Rod Vagg** &lt;[email protected]&gt; <ide> The full set of trusted release keys can be imported by running: <ide> <ide> ```shell <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5 <del>gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E <del>gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 <del>gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D <del>gpg --keyserver pool.sks-keyservers.net --recv-keys C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys B9AE9905FFD7803F25714661B63B535A4C206CA9 <del>gpg --keyserver pool.sks-keyservers.net --recv-keys 56730D5401028683275BD23C23EFEFE93C4CFFFE <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 77984A986EBC2AA786BC0F66B01FBB92821C587A <add>gpg --keyserver pool.sks-keyservers.net --recv-keys 56730D5401028683275BD23C23EFEFE93C4CFFFE <add>gpg --keyserver pool.sks-keyservers.net --recv-keys 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 <add>gpg --keyserver pool.sks-keyservers.net --recv-keys FD3A5288F042B6850C66B31F09FE44734EB7990E <add>gpg --keyserver pool.sks-keyservers.net --recv-keys 8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 <add>gpg --keyserver pool.sks-keyservers.net --recv-keys C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 <add>gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D <ide> ``` <ide> <ide> See the section above on [Verifying Binaries](#verifying-binaries) for details
1
Javascript
Javascript
add color support for mosh
70abb4ffe40c8526c5415c02c20b7b3a3cdbacd2
<ide><path>lib/internal/tty.js <ide> const TERM_ENVS = { <ide> 'konsole': COLORS_16, <ide> 'kterm': COLORS_16, <ide> 'mlterm': COLORS_16, <add> 'mosh': COLORS_16m, <ide> 'putty': COLORS_16, <ide> 'st': COLORS_16, <ide> // https://github.com/da-x/rxvt-unicode/tree/v9.22-with-24bit-color
1
Javascript
Javascript
log error in test-fs-realpath-pipe
8aea8861e926519e1571fbbe1f269e9cc7342286
<ide><path>test/parallel/test-fs-realpath-pipe.js <ide> const { spawnSync } = require('child_process'); <ide> for (const code of [ <ide> `require('fs').realpath('/dev/stdin', (err, resolvedPath) => { <ide> if (err) { <add> console.error(err); <ide> process.exit(1); <ide> } <ide> if (resolvedPath) { <ide> for (const code of [ <ide> if (require('fs').realpathSync('/dev/stdin')) { <ide> process.exit(2); <ide> } <del> } catch { <add> } catch (e) { <add> console.error(e); <ide> process.exit(1); <ide> }` <ide> ]) { <del> assert.strictEqual(spawnSync(process.execPath, ['-e', code], { <add> const child = spawnSync(process.execPath, ['-e', code], { <ide> stdio: 'pipe' <del> }).status, 2); <add> }); <add> if (child.status !== 2) { <add> console.log(code); <add> console.log(child.stderr.toString()); <add> } <add> assert.strictEqual(child.status, 2); <ide> }
1
Python
Python
fix force_download of files on windows
9384e5f6de150e7c7c9c8de27698a7de59a37a85
<ide><path>src/transformers/file_utils.py <ide> def _resumable_file_manager(): <ide> http_get(url, temp_file, proxies=proxies, resume_size=resume_size, user_agent=user_agent) <ide> <ide> logger.info("storing %s in cache at %s", url, cache_path) <del> os.rename(temp_file.name, cache_path) <add> os.replace(temp_file.name, cache_path) <ide> <ide> logger.info("creating metadata file for %s", cache_path) <ide> meta = {"url": url, "etag": etag}
1
Mixed
Javascript
create shared runbenchmark function
640b20616d2cdc46bc3df8703cdc1395578ff1b3
<ide><path>test/common/README.md <ide> This directory contains modules used to test the Node.js implementation. <ide> <ide> ## Table of Contents <ide> <add>* [Benchmark module](#benchmark-module) <ide> * [Common module API](#common-module-api) <ide> * [WPT module](#wpt-module) <ide> <add>## Benchmark Module <add> <add>The `benchmark` module is used by tests to run benchmarks. <add> <add>### runBenchmark(name, args, env) <add> <add>* `name` [&lt;String>] Name of benchmark suite to be run. <add>* `args` [&lt;Array>] Array of environment variable key/value pairs (ex: <add> `n=1`) to be applied via `--set`. <add>* `env` [&lt;Object>] Environment variables to be applied during the run. <add> <ide> ## Common Module API <ide> <ide> The `common` module is used by tests for consistency across repeated <ide><path>test/common/benchmark.js <add>/* eslint-disable required-modules */ <add> <add>'use strict'; <add> <add>const assert = require('assert'); <add>const fork = require('child_process').fork; <add>const path = require('path'); <add> <add>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <add> <add>function runBenchmark(name, args, env) { <add> const argv = []; <add> <add> for (let i = 0; i < args.length; i++) { <add> argv.push('--set'); <add> argv.push(args[i]); <add> } <add> <add> argv.push(name); <add> <add> const mergedEnv = Object.assign({}, process.env, env); <add> <add> const child = fork(runjs, argv, { env: mergedEnv }); <add> child.on('exit', (code, signal) => { <add> assert.strictEqual(code, 0); <add> assert.strictEqual(signal, null); <add> }); <add>} <add> <add>module.exports = runBenchmark; <ide><path>test/parallel/test-benchmark-arrays.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for arrays benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <add>const runBenchmark = require('../common/benchmark'); <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'n=1', <del> '--set', 'type=Array', <del> 'arrays']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('arrays', ['n=1', 'type=Array']); <ide><path>test/parallel/test-benchmark-cluster.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for cluster benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <add>const runBenchmark = require('../common/benchmark'); <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'n=1', <del> '--set', 'payload=string', <del> '--set', 'sendsPerBroadcast=1', <del> 'cluster']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('cluster', ['n=1', 'payload=string', 'sendsPerBroadcast=1']); <ide><path>test/parallel/test-benchmark-crypto.js <ide> if (!common.hasCrypto) <ide> if (common.hasFipsCrypto) <ide> common.skip('some benchmarks are FIPS-incompatible'); <ide> <del>// Minimal test for crypto benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'algo=sha256', <del> '--set', 'api=stream', <del> '--set', 'keylen=1024', <del> '--set', 'len=1', <del> '--set', 'n=1', <del> '--set', 'out=buffer', <del> '--set', 'type=buf', <del> '--set', 'v=crypto', <del> '--set', 'writes=1', <del> 'crypto']; <del> <del>const child = fork(runjs, argv, { env: Object.assign({}, process.env, { <del> NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }) }); <del> <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('crypto', <add> [ <add> 'n=1', <add> 'algo=sha256', <add> 'api=stream', <add> 'keylen=1024', <add> 'len=1', <add> 'out=buffer', <add> 'type=buf', <add> 'v=crypto', <add> 'writes=1' <add> ], <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <ide><path>test/parallel/test-benchmark-dns.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for dns benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <add>const runBenchmark = require('../common/benchmark'); <ide> <ide> const env = Object.assign({}, process.env, <ide> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <ide> <del>const child = fork(runjs, <del> ['--set', 'n=1', <del> '--set', 'all=false', <del> '--set', 'name=127.0.0.1', <del> 'dns'], <del> { env }); <del> <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('dns', ['n=1', 'all=false', 'name=127.0.0.1'], env); <ide><path>test/parallel/test-benchmark-domain.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for domain benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <add>const runBenchmark = require('../common/benchmark'); <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'arguments=0', <del> '--set', 'n=1', <del> 'domain']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('domain', ['n=1', 'arguments=0']); <ide><path>test/parallel/test-benchmark-events.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for events benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <add>const runBenchmark = require('../common/benchmark'); <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'n=1', <del> 'events']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('events', ['n=1']); <ide><path>test/parallel/test-benchmark-os.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for os benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <add>const runBenchmark = require('../common/benchmark'); <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'n=1', <del> 'os']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('os', ['n=1']); <ide><path>test/parallel/test-benchmark-path.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for path benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'n=1', <del> '--set', 'path=', <del> '--set', 'pathext=', <del> '--set', 'paths=', <del> '--set', 'props=', <del> 'path']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('path', <add> [ <add> 'n=1', <add> 'path=', <add> 'pathext=', <add> 'paths=', <add> 'props=' <add> ]); <ide><path>test/parallel/test-benchmark-process.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for process benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'millions=0.000001', <del> '--set', 'n=1', <del> '--set', 'type=raw', <del> 'process']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('process', <add> [ <add> 'millions=0.000001', <add> 'n=1', <add> 'type=raw' <add> ]); <ide><path>test/parallel/test-benchmark-timers.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for timers benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'type=depth', <del> '--set', 'millions=0.000001', <del> '--set', 'thousands=0.001', <del> 'timers']; <del> <del>const env = Object.assign({}, process.env, <del> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <del> <del>const child = fork(runjs, argv, { env }); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('timers', <add> [ <add> 'type=depth', <add> 'millions=0.000001', <add> 'thousands=0.001' <add> ], <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <ide><path>test/parallel/test-benchmark-zlib.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for zlib benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del>const argv = ['--set', 'method=deflate', <del> '--set', 'n=1', <del> '--set', 'options=true', <del> '--set', 'type=Deflate', <del> 'zlib']; <del> <del>const child = fork(runjs, argv); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('zlib', <add> [ <add> 'method=deflate', <add> 'n=1', <add> 'options=true', <add> 'type=Deflate' <add> ]); <ide><path>test/sequential/test-benchmark-child-process.js <ide> <ide> require('../common'); <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del> <del>const env = Object.assign({}, process.env, <del> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <del> <del>const child = fork( <del> runjs, <del> [ <del> '--set', 'dur=0', <del> '--set', 'n=1', <del> '--set', 'len=1', <del> '--set', 'params=1', <del> '--set', 'methodName=execSync', <del> 'child_process' <del> ], <del> { env } <del>); <del> <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('child_process', <add> [ <add> 'dur=0', <add> 'n=1', <add> 'len=1', <add> 'params=1', <add> 'methodName=execSync', <add> ], <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <ide><path>test/sequential/test-benchmark-http.js <ide> const common = require('../common'); <ide> if (!common.enoughTestMem) <ide> common.skip('Insufficient memory for HTTP benchmark test'); <ide> <del>// Minimal test for http benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <ide> // Because the http benchmarks use hardcoded ports, this should be in sequential <ide> // rather than parallel to make sure it does not conflict with tests that choose <ide> // random available ports. <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <del> <del>const env = Object.assign({}, process.env, <del> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <del> <del>const child = fork(runjs, ['--set', 'benchmarker=test-double', <del> '--set', 'c=1', <del> '--set', 'chunkedEnc=true', <del> '--set', 'chunks=0', <del> '--set', 'dur=0.1', <del> '--set', 'key=""', <del> '--set', 'len=1', <del> '--set', 'method=write', <del> '--set', 'n=1', <del> '--set', 'res=normal', <del> 'http'], <del> { env }); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('http', <add> [ <add> 'benchmarker=test-double', <add> 'c=1', <add> 'chunkedEnc=true', <add> 'chunks=0', <add> 'dur=0.1', <add> 'key=""', <add> 'len=1', <add> 'method=write', <add> 'n=1', <add> 'res=normal' <add> ], <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <ide><path>test/sequential/test-benchmark-net.js <ide> <ide> require('../common'); <ide> <del>// Minimal test for net benchmarks. This makes sure the benchmarks aren't <del>// horribly broken but nothing more than that. <del> <ide> // Because the net benchmarks use hardcoded ports, this should be in sequential <ide> // rather than parallel to make sure it does not conflict with tests that choose <ide> // random available ports. <ide> <del>const assert = require('assert'); <del>const fork = require('child_process').fork; <del>const path = require('path'); <del> <del>const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <add>const runBenchmark = require('../common/benchmark'); <ide> <del>const env = Object.assign({}, process.env, <del> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <del>const child = fork(runjs, <del> ['--set', 'dur=0', <del> '--set', 'len=1024', <del> '--set', 'type=buf', <del> 'net'], <del> { env }); <del>child.on('exit', (code, signal) => { <del> assert.strictEqual(code, 0); <del> assert.strictEqual(signal, null); <del>}); <add>runBenchmark('net', <add> [ <add> 'dur=0', <add> 'len=1024', <add> 'type=buf' <add> ], <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 });
16
PHP
PHP
reduce duplication in tests
ee010dd5eed8f7fec3b6be6958fc4a93e1f24f30
<ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testTruthy() <ide> $this->assertFalse(Validation::truthy('0')); <ide> $this->assertFalse(Validation::truthy('false')); <ide> <del> $this->assertTrue(Validation::truthy(1)); <del> $this->assertTrue(Validation::truthy(true)); <del> $this->assertTrue(Validation::truthy('1')); <del> <del> $this->assertFalse(Validation::truthy('true')); <del> $this->assertFalse(Validation::truthy('on')); <del> $this->assertFalse(Validation::truthy('yes')); <del> <del> $this->assertFalse(Validation::truthy(0)); <del> $this->assertFalse(Validation::truthy(false)); <del> $this->assertFalse(Validation::truthy('0')); <del> $this->assertFalse(Validation::truthy('false')); <del> <del> $this->assertFalse(Validation::truthy('on')); <del> $this->assertFalse(Validation::truthy('yes')); <del> <ide> $this->assertTrue(Validation::truthy('on', ['on', 'yes', 'true'])); <ide> $this->assertTrue(Validation::truthy('yes', ['on', 'yes', 'true'])); <ide> $this->assertTrue(Validation::truthy('true', ['on', 'yes', 'true'])); <ide> public function testFalsey() <ide> $this->assertFalse(Validation::falsey('1')); <ide> $this->assertFalse(Validation::falsey('true')); <ide> <del> $this->assertTrue(Validation::falsey(0)); <del> $this->assertTrue(Validation::falsey(false)); <del> $this->assertTrue(Validation::falsey('0')); <del> <del> $this->assertFalse(Validation::falsey('false')); <del> $this->assertFalse(Validation::falsey('off')); <del> $this->assertFalse(Validation::falsey('no')); <del> <del> $this->assertFalse(Validation::falsey(1)); <del> $this->assertFalse(Validation::falsey(true)); <del> $this->assertFalse(Validation::falsey('1')); <del> $this->assertFalse(Validation::falsey('true')); <del> <del> $this->assertFalse(Validation::falsey('off')); <del> $this->assertFalse(Validation::falsey('no')); <del> <ide> $this->assertTrue(Validation::falsey('off', ['off', 'no', 'false'])); <ide> $this->assertTrue(Validation::falsey('no', ['off', 'no', 'false'])); <ide> $this->assertTrue(Validation::falsey('false', ['off', 'no', 'false']));
1
Javascript
Javascript
show deprecation warning when using didinitattrs
3f7bc1523cf6723d0e2c88acd1f8952c945a3588
<ide><path>packages/ember-htmlbars/tests/integration/component_lifecycle_test.js <ide> styles.forEach(style => { <ide> twitter: '@tomdale' <ide> }).create(); <ide> <del> runAppend(view); <add> expectDeprecation(() => { <add> runAppend(view); <add> }, /\[DEPRECATED\] didInitAttrs called in <\(subclass of Ember.Component\)\:ember[\d+]+>\./); <ide> <ide> ok(component, 'The component was inserted'); <ide> equal(jQuery('#qunit-fixture').text(), 'Twitter: @tomdale Name: Tom Dale Website: tomdale.net'); <ide> styles.forEach(style => { <ide> twitter: '@tomdale' <ide> }).create(); <ide> <del> runAppend(view); <add> expectDeprecation(() => { <add> runAppend(view); <add> }, /\[DEPRECATED\] didInitAttrs called in <\(subclass of Ember.Component\)\:ember[\d+]+>\./); <ide> <ide> ok(component, 'The component was inserted'); <ide> equal(jQuery('#qunit-fixture').text(), 'Top: Middle: Bottom: @tomdale'); <ide> styles.forEach(style => { <ide> }); <ide> <ide> QUnit.test('changing a component\'s displayed properties inside didInsertElement() is deprecated', function(assert) { <del> let component = style.class.extend({ <add> let component; <add> <add> component = style.class.extend({ <ide> [OWNER]: owner, <ide> layout: compile('<div>{{handle}}</div>'), <ide> handle: '@wycats', <ide> styles.forEach(style => { <ide> }); <ide> }); <ide> <add> QUnit.test('DEPRECATED: didInitAttrs is deprecated', function(assert) { <add> let component; <add> <add> let componentClass = style.class.extend({ <add> [OWNER]: owner, <add> layout: compile('<div>{{handle}}</div>'), <add> handle: '@wycats', <add> <add> didInitAttrs() { <add> this._super(...arguments); <add> } <add> }); <add> <add> expectDeprecation(() => { <add> component = componentClass.create(); <add> }, /\[DEPRECATED\] didInitAttrs called in <\(subclass of Ember.Component\)\:ember[\d+]+>\./); <add> <add> run(() => { <add> component.destroy(); <add> }); <add> }); <add> <ide> QUnit.test('properties set during `init` are availabe in `didReceiveAttrs`', function(assert) { <ide> assert.expect(1); <ide> <ide><path>packages/ember-metal/lib/events.js <ide> import { <ide> applyStr <ide> } from 'ember-metal/utils'; <ide> import { meta as metaFor, peekMeta } from 'ember-metal/meta'; <add>import { deprecate } from 'ember-metal/debug'; <ide> <ide> import { ONCE, SUSPENDED } from 'ember-metal/meta_listeners'; <ide> <ide> export function accumulateListeners(obj, eventName, otherActions) { <ide> export function addListener(obj, eventName, target, method, once) { <ide> assert('You must pass at least an object and event name to Ember.addListener', !!obj && !!eventName); <ide> <add> if (eventName === 'didInitAttrs' && obj.isComponent) { <add> deprecate( <add> `[DEPRECATED] didInitAttrs called in ${obj.toString()}.`, <add> false, <add> { <add> id: 'ember-views.did-init-attrs', <add> until: '3.0.0', <add> url: 'http://emberjs.com/deprecations/v2.x#toc_ember-component-didinitattrs' <add> } <add> ); <add> } <add> <ide> if (!method && 'function' === typeof target) { <ide> method = target; <ide> target = null; <ide><path>packages/ember-metal/tests/events_test.js <ide> import { Mixin } from 'ember-metal/mixin'; <ide> import { meta } from 'ember-metal/meta'; <add>import Component from 'ember-views/components/component'; <ide> <ide> import { <ide> on, <ide> QUnit.test('a listener added as part of a mixin may be overridden', function() { <ide> sendEvent(obj, 'baz'); <ide> equal(triggered, 1, 'should invoke from subclass property'); <ide> }); <add> <add>QUnit.test('DEPRECATED: adding didInitAttrs as a listener is deprecated', function() { <add> var obj = Component.create(); <add> <add> expectDeprecation(() => { <add> addListener(obj, 'didInitAttrs'); <add> }, /\[DEPRECATED\] didInitAttrs called in <\Ember.Component\:ember[\d+]+>\./); <add>}); <ide><path>packages/ember-views/lib/mixins/view_support.js <ide> export default Mixin.create({ <ide> <ide> this[INIT_WAS_CALLED] = true; <ide> <add> if (typeof(this.didInitAttrs) === 'function') { <add> deprecate( <add> `[DEPRECATED] didInitAttrs called in ${this.toString()}.`, <add> false, <add> { <add> id: 'ember-views.did-init-attrs', <add> until: '3.0.0', <add> url: 'http://emberjs.com/deprecations/v2.x#toc_ember-component-didinitattrs' <add> } <add> ); <add> } <add> <ide> assert( <ide> 'Using a custom `.render` function is no longer supported.', <ide> !this.render
4
Ruby
Ruby
add system tests to generate scaffold
d502cd1a5024743b3891592c73538d4e446bbd98
<ide><path>railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb <ide> class ScaffoldGenerator < ResourceGenerator # :nodoc: <ide> def handle_skip <ide> @options = @options.merge(stylesheets: false) unless options[:assets] <ide> @options = @options.merge(stylesheet_engine: false) unless options[:stylesheets] && options[:scaffold_stylesheet] <del> @options = @options.merge(system_tests: false) if options[:api] <ide> end <ide> <ide> hook_for :scaffold_controller, required: true <ide> <del> hook_for :system_tests, as: :system <del> <ide> hook_for :assets do |assets| <ide> invoke assets, [controller_name] <ide> end <ide><path>railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb <ide> class ScaffoldGenerator < Base # :nodoc: <ide> class_option :api, type: :boolean, <ide> desc: "Generates API functional tests" <ide> <add> class_option :system_tests, type: :string, <add> desc: "Skip system test files" <add> <ide> argument :attributes, type: :array, default: [], banner: "field:type field:type" <ide> <ide> def create_test_files <ide> template_file = options.api? ? "api_functional_test.rb" : "functional_test.rb" <ide> template template_file, <ide> File.join("test/controllers", controller_class_path, "#{controller_file_name}_controller_test.rb") <add> <add> unless options.api? || options[:system_tests].nil? <add> template "system_test.rb", File.join("test/system", class_path, "#{file_name.pluralize}_test.rb") <add> end <ide> end <ide> <ide> def fixture_name <ide> def fixture_name <ide> <ide> private <ide> <add> def attributes_string <add> attributes_hash.map { |k, v| "#{k}: #{v}" }.join(", ") <add> end <add> <ide> def attributes_hash <del> return if attributes_names.empty? <add> return {} if attributes_names.empty? <ide> <ide> attributes_names.map do |name| <ide> if %w(password password_confirmation).include?(name) && attributes.any?(&:password_digest?) <del> "#{name}: 'secret'" <add> ["#{name}", "'secret'"] <ide> else <del> "#{name}: @#{singular_table_name}.#{name}" <add> ["#{name}", "@#{singular_table_name}.#{name}"] <ide> end <del> end.sort.join(", ") <add> end.sort.to_h <ide> end <ide> end <ide> end <ide><path>railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb <ide> class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe <ide> <ide> test "should create <%= singular_table_name %>" do <ide> assert_difference('<%= class_name %>.count') do <del> post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }, as: :json <add> post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_string} }" %> }, as: :json <ide> end <ide> <ide> assert_response 201 <ide> class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe <ide> end <ide> <ide> test "should update <%= singular_table_name %>" do <del> patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }, as: :json <add> patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_string} }" %> }, as: :json <ide> assert_response 200 <ide> end <ide> <ide><path>railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb <ide> class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe <ide> <ide> test "should create <%= singular_table_name %>" do <ide> assert_difference('<%= class_name %>.count') do <del> post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } <add> post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_string} }" %> } <ide> end <ide> <ide> assert_redirected_to <%= singular_table_name %>_url(<%= class_name %>.last) <ide> class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTe <ide> end <ide> <ide> test "should update <%= singular_table_name %>" do <del> patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } <add> patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_string} }" %> } <ide> assert_redirected_to <%= singular_table_name %>_url(<%= "@#{singular_table_name}" %>) <ide> end <ide> <ide><path>railties/lib/rails/generators/test_unit/scaffold/templates/system_test.rb <add>require "application_system_test_case" <add> <add><% module_namespacing do -%> <add>class <%= class_name.pluralize %>Test < ApplicationSystemTestCase <add> setup do <add> @<%= singular_table_name %> = <%= fixture_name %>(:one) <add> end <add> <add> test "visiting the index" do <add> visit <%= plural_table_name %>_url <add> assert_selector "h1", text: "<%= class_name.pluralize.titleize %>" <add> end <add> <add> test "creating a <%= human_name %>" do <add> visit <%= plural_table_name %>_url <add> click_on "New <%= class_name.titleize %>" <add> <add> <%- attributes_hash.each do |attr, value| -%> <add> fill_in "<%= attr.humanize.titleize %>", with: <%= value %> <add> <%- end -%> <add> click_on "Create <%= human_name %>" <add> <add> assert_text "<%= human_name %> was successfully created" <add> click_on "Back" <add> end <add> <add> test "updating a <%= human_name %>" do <add> visit <%= plural_table_name %>_url <add> click_on "Edit", match: :first <add> <add> <%- attributes_hash.each do |attr, value| -%> <add> fill_in "<%= attr.humanize.titleize %>", with: <%= value %> <add> <%- end -%> <add> click_on "Update <%= human_name %>" <add> <add> assert_text "<%= human_name %> was successfully updated" <add> click_on "Back" <add> end <add> <add> test "destroying a <%= human_name %>" do <add> visit <%= plural_table_name %>_url <add> page.accept_confirm do <add> click_on "Destroy", match: :first <add> end <add> <add> assert_text "<%= human_name %> was successfully destroyed" <add> end <add>end <add><% end -%> <ide><path>railties/test/generators/app_generator_test.rb <ide> def test_generator_if_skip_test_is_given <ide> end <ide> <ide> def test_generator_if_skip_system_test_is_given <del> run_generator [destination_root, "--skip_system_test"] <add> run_generator [destination_root, "--skip-system-test"] <ide> assert_file "Gemfile" do |content| <ide> assert_no_match(/capybara/, content) <ide> assert_no_match(/selenium-webdriver/, content) <ide> end <ide> end <ide> <ide> def test_does_not_generate_system_test_files_if_skip_system_test_is_given <del> run_generator [destination_root, "--skip_system_test"] <add> run_generator [destination_root, "--skip-system-test"] <ide> <ide> Dir.chdir(destination_root) do <ide> quietly { `./bin/rails g scaffold User` } <ide><path>railties/test/generators/scaffold_generator_test.rb <ide> def test_scaffold_on_invoke <ide> # System tests <ide> assert_file "test/system/product_lines_test.rb" do |test| <ide> assert_match(/class ProductLinesTest < ApplicationSystemTestCase/, test) <add> assert_match(/visit product_lines_url/, test) <add> assert_match(/fill_in "Title", with: @product_line\.title/, test) <add> assert_match(/assert_text "Product line was successfully updated"/, test) <ide> end <ide> <ide> # Views <ide> def test_api_scaffold_on_invoke <ide> assert_no_match(/assert_redirected_to/, test) <ide> end <ide> <add> # System tests <add> assert_no_file "test/system/product_lines_test.rb" <add> <ide> # Views <ide> assert_no_file "app/views/layouts/product_lines.html.erb" <ide> <ide> def test_functional_tests_without_attributes <ide> end <ide> end <ide> <add> def test_system_tests_without_attributes <add> run_generator ["product_line"] <add> <add> assert_file "test/system/product_lines_test.rb" do |content| <add> assert_match(/class ProductLinesTest < ApplicationSystemTestCase/, content) <add> assert_match(/test "visiting the index"/, content) <add> assert_no_match(/fill_in/, content) <add> end <add> end <add> <ide> def test_scaffold_on_revoke <ide> run_generator <ide> run_generator ["product_line"], behavior: :revoke <ide> def test_scaffold_on_revoke <ide> assert_no_file "app/controllers/product_lines_controller.rb" <ide> assert_no_file "test/controllers/product_lines_controller_test.rb" <ide> <add> # System tests <add> assert_no_file "test/system/product_lines_test.rb" <add> <ide> # Views <ide> assert_no_file "app/views/product_lines" <ide> assert_no_file "app/views/layouts/product_lines.html.erb" <ide> def test_scaffold_with_namespace_on_invoke <ide> assert_file "test/controllers/admin/roles_controller_test.rb", <ide> /class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/ <ide> <add> assert_file "test/system/admin/roles_test.rb", <add> /class Admin::RolesTest < ApplicationSystemTestCase/ <add> <ide> # Views <ide> %w(index edit new show _form).each do |view| <ide> assert_file "app/views/admin/roles/#{view}.html.erb" <ide> def test_scaffold_with_namespace_on_revoke <ide> assert_no_file "app/controllers/admin/roles_controller.rb" <ide> assert_no_file "test/controllers/admin/roles_controller_test.rb" <ide> <add> # System tests <add> assert_no_file "test/system/admin/roles_test.rb" <add> <ide> # Views <ide> assert_no_file "app/views/admin/roles" <ide> assert_no_file "app/views/layouts/admin/roles.html.erb" <ide> def test_scaffold_generator_password_digest <ide> assert_match(/password_confirmation: 'secret'/, content) <ide> end <ide> <add> assert_file "test/system/users_test.rb" do |content| <add> assert_match(/fill_in "Password", with: 'secret'/, content) <add> assert_match(/fill_in "Password Confirmation", with: 'secret'/, content) <add> end <add> <ide> assert_file "test/fixtures/users.yml" do |content| <ide> assert_match(/password_digest: <%= BCrypt::Password.create\('secret'\) %>/, content) <ide> end <ide> def test_scaffold_on_invoke_inside_mountable_engine <ide> assert File.exist?("app/controllers/bukkits/users_controller.rb") <ide> assert File.exist?("test/controllers/bukkits/users_controller_test.rb") <ide> <add> assert File.exist?("test/system/bukkits/users_test.rb") <add> <ide> assert File.exist?("app/views/bukkits/users/index.html.erb") <ide> assert File.exist?("app/views/bukkits/users/edit.html.erb") <ide> assert File.exist?("app/views/bukkits/users/show.html.erb") <ide> def test_scaffold_on_revoke_inside_mountable_engine <ide> assert_not File.exist?("app/controllers/bukkits/users_controller.rb") <ide> assert_not File.exist?("test/controllers/bukkits/users_controller_test.rb") <ide> <add> assert_not File.exist?("test/system/bukkits/users_test.rb") <add> <ide> assert_not File.exist?("app/views/bukkits/users/index.html.erb") <ide> assert_not File.exist?("app/views/bukkits/users/edit.html.erb") <ide> assert_not File.exist?("app/views/bukkits/users/show.html.erb")
7