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
Ruby
Ruby
fix typo in redirect test
6ce21af8aa97951b0a760f553421ba95caf3fdbb
<ide><path>actionpack/test/controller/redirect_test.rb <ide> def test_redirect_with_header_break <ide> end <ide> <ide> def test_redirect_with_null_bytes <del> get :redirect_with_header_break <add> get :redirect_with_null_bytes <ide> assert_response :redirect <ide> assert_equal "http://test.host/lolwat", redirect_to_url <ide> end
1
Ruby
Ruby
add #clear to mem_cache_store, flushes all caches
4c3077183b91e3972b07e5488ce12e5b8a6b68a5
<ide><path>activesupport/lib/active_support/cache/mem_cache_store.rb <ide> def delete_matched(matcher, options = nil) <ide> raise "Not supported by Memcache" <ide> end <ide> <add> def clear <add> @data.flush_all <add> end <add> <ide> private <ide> def expires_in(options) <ide> (options && options[:expires_in]) || 0
1
Text
Text
add tessian to list of companies using airflow
cff7d9194f549d801947f47dfce4b5d6870bfaaa
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Telia Company](https://www.teliacompany.com/en) <ide> 1. [Ternary Data](https://ternarydata.com/) [[@mhousley](https://github.com/mhousley), [@JoeReis](https://github.com/JoeReis)] <ide> 1. [Tesla](https://www.tesla.com/) [[@thoralf-gutierrez](https://github.com/thoralf-gutierrez)] <add>1. [Tessian](https://www.tessian.com/) [[@ChethanUK](https://github.com/ChethanUK)] <ide> 1. [TextNow](https://www.textnow.com/) <ide> 1. [The Climate Corporation](https://climate.com/) [[@jmelching](https://github.com/jmelching)] <ide> 1. [The Dyrt](https://thedyrt.com/)
1
Ruby
Ruby
swap misnamed variables of arel with terms
c81d961921a3ecd96e280387ac48ed5919de1c13
<ide><path>activerecord/test/cases/arel/select_manager_test.rb <ide> def test_join_sources <ide> replies = Table.new(:replies) <ide> replies_id = replies[:id] <ide> <del> recursive_term = Arel::SelectManager.new <del> recursive_term.from(comments).project(comments_id, comments_parent_id).where(comments_id.eq 42) <del> <ide> non_recursive_term = Arel::SelectManager.new <del> non_recursive_term.from(comments).project(comments_id, comments_parent_id).join(replies).on(comments_parent_id.eq replies_id) <add> non_recursive_term.from(comments).project(comments_id, comments_parent_id).where(comments_id.eq 42) <add> <add> recursive_term = Arel::SelectManager.new <add> recursive_term.from(comments).project(comments_id, comments_parent_id).join(replies).on(comments_parent_id.eq replies_id) <ide> <del> union = recursive_term.union(non_recursive_term) <add> union = non_recursive_term.union(recursive_term) <ide> <ide> as_statement = Arel::Nodes::As.new replies, union <ide>
1
Go
Go
move utils.testdirectory to pkg/testutil/tempfile
0ab9320ab28afbf62a8b81e5f151db908897df86
<ide><path>distribution/registry_unit_test.go <ide> package distribution <ide> <ide> import ( <add> "fmt" <add> "io/ioutil" <ide> "net/http" <ide> "net/http/httptest" <ide> "net/url" <ide> "os" <add> "runtime" <ide> "strings" <ide> "testing" <ide> <ide> "github.com/Sirupsen/logrus" <ide> "github.com/docker/docker/api/types" <ide> registrytypes "github.com/docker/docker/api/types/registry" <add> "github.com/docker/docker/pkg/archive" <add> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/reference" <ide> "github.com/docker/docker/registry" <del> "github.com/docker/docker/utils" <ide> "golang.org/x/net/context" <ide> ) <ide> <ide> func (h *tokenPassThruHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) <ide> } <ide> <ide> func testTokenPassThru(t *testing.T, ts *httptest.Server) { <del> tmp, err := utils.TestDirectory("") <add> tmp, err := testDirectory("") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestTokenPassThruDifferentHost(t *testing.T) { <ide> t.Fatal("Redirect should not forward Authorization header to another host") <ide> } <ide> } <add> <add>// TestDirectory creates a new temporary directory and returns its path. <add>// The contents of directory at path `templateDir` is copied into the <add>// new directory. <add>func testDirectory(templateDir string) (dir string, err error) { <add> testID := stringid.GenerateNonCryptoID()[:4] <add> prefix := fmt.Sprintf("docker-test%s-%s-", testID, getCallerName(2)) <add> if prefix == "" { <add> prefix = "docker-test-" <add> } <add> dir, err = ioutil.TempDir("", prefix) <add> if err = os.Remove(dir); err != nil { <add> return <add> } <add> if templateDir != "" { <add> if err = archive.CopyWithTar(templateDir, dir); err != nil { <add> return <add> } <add> } <add> return <add>} <add> <add>// getCallerName introspects the call stack and returns the name of the <add>// function `depth` levels down in the stack. <add>func getCallerName(depth int) string { <add> // Use the caller function name as a prefix. <add> // This helps trace temp directories back to their test. <add> pc, _, _, _ := runtime.Caller(depth + 1) <add> callerLongName := runtime.FuncForPC(pc).Name() <add> parts := strings.Split(callerLongName, ".") <add> callerShortName := parts[len(parts)-1] <add> return callerShortName <add>} <ide><path>pkg/testutil/tempfile/tempfile.go <ide> package tempfile <ide> <ide> import ( <add> "github.com/docker/docker/pkg/testutil/assert" <ide> "io/ioutil" <ide> "os" <del> <del> "github.com/docker/docker/pkg/testutil/assert" <ide> ) <ide> <ide> // TempFile is a temporary file that can be used with unit tests. TempFile <ide><path>utils/utils.go <ide> package utils <ide> <ide> import ( <del> "fmt" <del> "io/ioutil" <del> "os" <del> "runtime" <ide> "strings" <del> <del> "github.com/docker/docker/pkg/archive" <del> "github.com/docker/docker/pkg/stringid" <ide> ) <ide> <del>var globalTestID string <del> <del>// TestDirectory creates a new temporary directory and returns its path. <del>// The contents of directory at path `templateDir` is copied into the <del>// new directory. <del>func TestDirectory(templateDir string) (dir string, err error) { <del> if globalTestID == "" { <del> globalTestID = stringid.GenerateNonCryptoID()[:4] <del> } <del> prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2)) <del> if prefix == "" { <del> prefix = "docker-test-" <del> } <del> dir, err = ioutil.TempDir("", prefix) <del> if err = os.Remove(dir); err != nil { <del> return <del> } <del> if templateDir != "" { <del> if err = archive.CopyWithTar(templateDir, dir); err != nil { <del> return <del> } <del> } <del> return <del>} <del> <del>// GetCallerName introspects the call stack and returns the name of the <del>// function `depth` levels down in the stack. <del>func GetCallerName(depth int) string { <del> // Use the caller function name as a prefix. <del> // This helps trace temp directories back to their test. <del> pc, _, _, _ := runtime.Caller(depth + 1) <del> callerLongName := runtime.FuncForPC(pc).Name() <del> parts := strings.Split(callerLongName, ".") <del> callerShortName := parts[len(parts)-1] <del> return callerShortName <del>} <del> <ide> // ReplaceOrAppendEnvValues returns the defaults with the overrides either <ide> // replaced by env key or appended to the list <ide> func ReplaceOrAppendEnvValues(defaults, overrides []string) []string {
3
Javascript
Javascript
propagate nativeid in createanimatedcomponent
d1b695d343988b036137b50d4ceef8c0d0f8ba66
<ide><path>Libraries/Animated/createAnimatedComponent.js <ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>( <ide> style={mergedStyle} <ide> ref={this._setComponentRef} <ide> nativeID={ <del> this._isFabric() ? 'animatedComponent' : undefined <add> props.nativeID ?? <add> (this._isFabric() ? 'animatedComponent' : undefined) <ide> } /* TODO: T68258846. */ <ide> // The native driver updates views directly through the UI thread so we <ide> // have to make sure the view doesn't get optimized away because it cannot
1
Ruby
Ruby
remove useless duplication in include test
7aae4e5e667e9d38a8db81e452841319b7c89ace
<ide><path>activesupport/test/concern_test.rb <ide> def test_module_is_included_normally <ide> @klass.send(:include, Baz) <ide> assert_equal "baz", @klass.new.baz <ide> assert @klass.included_modules.include?(ConcernTest::Baz) <del> <del> @klass.send(:include, Baz) <del> assert_equal "baz", @klass.new.baz <del> assert @klass.included_modules.include?(ConcernTest::Baz) <ide> end <ide> <ide> def test_class_methods_are_extended
1
Javascript
Javascript
fix failure in test-icu-data-dir.js
a1ecdcfb154ec79db4da595ca85ce75f9f759c6a
<ide><path>test/parallel/test-icu-data-dir.js <ide> const assert = require('assert'); <ide> const { spawnSync } = require('child_process'); <ide> <ide> const expected = <del> 'could not initialize ICU ' + <del> '(check NODE_ICU_DATA or --icu-data-dir parameters)\n'; <add> 'could not initialize ICU (check NODE_ICU_DATA or ' + <add> '--icu-data-dir parameters)' + (common.isWindows ? '\r\n' : '\n'); <ide> <ide> { <ide> const child = spawnSync(process.execPath, ['--icu-data-dir=/', '-e', '0']);
1
Python
Python
use new evaluation loop in trainerqa
936b57158ad2641390422274fed6ee6c2a685e15
<ide><path>examples/pytorch/question-answering/trainer_qa.py <ide> def evaluate(self, eval_dataset=None, eval_examples=None, ignore_keys=None): <ide> # Temporarily disable metric computation, we will do it in the loop here. <ide> compute_metrics = self.compute_metrics <ide> self.compute_metrics = None <add> eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop <ide> try: <del> output = self.prediction_loop( <add> output = eval_loop( <ide> eval_dataloader, <ide> description="Evaluation", <ide> # No point gathering the predictions if there are no metrics, otherwise we defer to <ide> def predict(self, predict_dataset, predict_examples, ignore_keys=None): <ide> # Temporarily disable metric computation, we will do it in the loop here. <ide> compute_metrics = self.compute_metrics <ide> self.compute_metrics = None <add> eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop <ide> try: <del> output = self.prediction_loop( <add> output = eval_loop( <ide> predict_dataloader, <ide> description="Prediction", <ide> # No point gathering the predictions if there are no metrics, otherwise we defer to
1
Go
Go
fix login command
e6efbd659606386db4d0b83b98f9e189cf42595c
<ide><path>registry/service.go <ide> func (s *Service) Auth(job *engine.Job) engine.Status { <ide> authConfig.ServerAddress = endpoint.String() <ide> } <ide> <del> if _, err := Login(authConfig, HTTPRequestFactory(nil)); err != nil { <add> status, err := Login(authConfig, HTTPRequestFactory(nil)) <add> if err != nil { <ide> return job.Error(err) <ide> } <add> job.Printf("%s\n", status) <ide> <ide> return engine.StatusOK <ide> }
1
PHP
PHP
use strict typing for i18n/formatter classes
9efb0e03a910de5d2a56d3168e449e4d4da4c7bb
<ide><path>src/I18n/Formatter/IcuFormatter.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class IcuFormatter implements FormatterInterface <ide> * @throws \Aura\Intl\Exception\CannotFormat <ide> * @throws \Aura\Intl\Exception\CannotInstantiateFormatter <ide> */ <del> public function format($locale, $message, array $vars) <add> public function format($locale, $message, array $vars): string <ide> { <ide> unset($vars['_singular'], $vars['_count']); <ide> <ide> public function format($locale, $message, array $vars) <ide> * @throws \Aura\Intl\Exception\CannotFormat If any error related to the passed <ide> * variables is found <ide> */ <del> protected function _formatMessage($locale, $message, $vars) <add> protected function _formatMessage(string $locale, $message, array $vars): string <ide> { <ide> if ($message === '') { <ide> return $message; <ide><path>src/I18n/Formatter/SprintfFormatter.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class SprintfFormatter implements FormatterInterface <ide> * @param array $vars The list of values to interpolate in the message <ide> * @return string The formatted message <ide> */ <del> public function format($locale, $message, array $vars) <add> public function format($locale, $message, array $vars): string <ide> { <ide> unset($vars['_singular']); <ide> <ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/I18n/Formatter/SprintfFormatterTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
4
Javascript
Javascript
switch callsites over to update lane priority
431e76e2db39e74e25965027d67d69debdb7384a
<ide><path>packages/react-reconciler/src/ReactFiberCommitWork.new.js <ide> import type { <ide> } from './ReactFiberHostConfig'; <ide> import type {Fiber} from './ReactInternalTypes'; <ide> import type {FiberRoot} from './ReactInternalTypes'; <del>import type {Lanes} from './ReactFiberLane.new'; <add>import type {LanePriority, Lanes} from './ReactFiberLane.new'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; <ide> import type {UpdateQueue} from './ReactUpdateQueue.new'; <ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.new'; <ide> import type {Wakeable} from 'shared/ReactTypes'; <del>import type {ReactPriorityLevel} from './ReactInternalTypes'; <ide> import type {OffscreenState} from './ReactFiberOffscreenComponent'; <ide> import type {HookFlags} from './ReactHookEffectTags'; <ide> <ide> function commitUnmount( <ide> finishedRoot: FiberRoot, <ide> current: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> onCommitUnmount(current); <ide> <ide> function commitNestedUnmounts( <ide> finishedRoot: FiberRoot, <ide> root: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> // While we're inside a removed host node we don't want to call <ide> // removeChild on the inner nodes because they're removed by the top <ide> function unmountHostComponents( <ide> finishedRoot: FiberRoot, <ide> current: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> // We only have the top Fiber that was deleted but we need to recurse down its <ide> // children to find all the terminal nodes. <ide> function commitDeletion( <ide> finishedRoot: FiberRoot, <ide> current: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> if (supportsMutation) { <ide> // Recursively delete all host nodes from the parent. <ide> function commitResetTextContent(current: Fiber) { <ide> <ide> export function commitMutationEffects( <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> firstChild: Fiber, <ide> ) { <ide> nextEffect = firstChild; <ide> export function commitMutationEffects( <ide> <ide> function commitMutationEffects_begin( <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ) { <ide> while (nextEffect !== null) { <ide> const fiber = nextEffect; <ide> function commitMutationEffects_begin( <ide> <ide> function commitMutationEffects_complete( <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ) { <ide> while (nextEffect !== null) { <ide> const fiber = nextEffect; <ide> function commitMutationEffects_complete( <ide> function commitMutationEffectsOnFiber( <ide> finishedWork: Fiber, <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ) { <ide> const flags = finishedWork.flags; <ide> <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.old.js <ide> import type { <ide> } from './ReactFiberHostConfig'; <ide> import type {Fiber} from './ReactInternalTypes'; <ide> import type {FiberRoot} from './ReactInternalTypes'; <del>import type {Lanes} from './ReactFiberLane.old'; <add>import type {LanePriority, Lanes} from './ReactFiberLane.old'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.old'; <ide> import type {UpdateQueue} from './ReactUpdateQueue.old'; <ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks.old'; <ide> import type {Wakeable} from 'shared/ReactTypes'; <del>import type {ReactPriorityLevel} from './ReactInternalTypes'; <ide> import type {OffscreenState} from './ReactFiberOffscreenComponent'; <ide> import type {HookFlags} from './ReactHookEffectTags'; <ide> <ide> function commitUnmount( <ide> finishedRoot: FiberRoot, <ide> current: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> onCommitUnmount(current); <ide> <ide> function commitNestedUnmounts( <ide> finishedRoot: FiberRoot, <ide> root: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> // While we're inside a removed host node we don't want to call <ide> // removeChild on the inner nodes because they're removed by the top <ide> function unmountHostComponents( <ide> finishedRoot: FiberRoot, <ide> current: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> // We only have the top Fiber that was deleted but we need to recurse down its <ide> // children to find all the terminal nodes. <ide> function commitDeletion( <ide> finishedRoot: FiberRoot, <ide> current: Fiber, <ide> nearestMountedAncestor: Fiber, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ): void { <ide> if (supportsMutation) { <ide> // Recursively delete all host nodes from the parent. <ide> function commitResetTextContent(current: Fiber) { <ide> <ide> export function commitMutationEffects( <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> firstChild: Fiber, <ide> ) { <ide> nextEffect = firstChild; <ide> export function commitMutationEffects( <ide> <ide> function commitMutationEffects_begin( <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ) { <ide> while (nextEffect !== null) { <ide> const fiber = nextEffect; <ide> function commitMutationEffects_begin( <ide> <ide> function commitMutationEffects_complete( <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ) { <ide> while (nextEffect !== null) { <ide> const fiber = nextEffect; <ide> function commitMutationEffects_complete( <ide> function commitMutationEffectsOnFiber( <ide> finishedWork: Fiber, <ide> root: FiberRoot, <del> renderPriorityLevel: ReactPriorityLevel, <add> renderPriorityLevel: LanePriority, <ide> ) { <ide> const flags = finishedWork.flags; <ide> <ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.new.js <ide> <ide> import {enableProfilerTimer} from 'shared/ReactFeatureFlags'; <ide> <del>import type {Fiber, FiberRoot, ReactPriorityLevel} from './ReactInternalTypes'; <add>import type {Fiber, FiberRoot} from './ReactInternalTypes'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <add>import type {LanePriority} from './ReactFiberLane.new'; <ide> <ide> import {DidCapture} from './ReactFiberFlags'; <add>import { <add> lanePriorityToSchedulerPriority, <add> NoLanePriority, <add>} from './ReactFiberLane.new'; <add>import {NormalPriority} from './SchedulerWithReactIntegration.new'; <ide> <ide> declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; <ide> <ide> export function onScheduleRoot(root: FiberRoot, children: ReactNodeList) { <ide> } <ide> } <ide> <del>export function onCommitRoot( <del> root: FiberRoot, <del> priorityLevel: ReactPriorityLevel, <del>) { <add>export function onCommitRoot(root: FiberRoot, priorityLevel: LanePriority) { <ide> if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { <ide> try { <ide> const didError = (root.current.flags & DidCapture) === DidCapture; <ide> if (enableProfilerTimer) { <add> const schedulerPriority = <add> priorityLevel === NoLanePriority <add> ? NormalPriority <add> : lanePriorityToSchedulerPriority(priorityLevel); <ide> injectedHook.onCommitFiberRoot( <ide> rendererID, <ide> root, <del> priorityLevel, <add> schedulerPriority, <ide> didError, <ide> ); <ide> } else { <ide><path>packages/react-reconciler/src/ReactFiberDevToolsHook.old.js <ide> <ide> import {enableProfilerTimer} from 'shared/ReactFeatureFlags'; <ide> <del>import type {Fiber, FiberRoot, ReactPriorityLevel} from './ReactInternalTypes'; <add>import type {Fiber, FiberRoot} from './ReactInternalTypes'; <ide> import type {ReactNodeList} from 'shared/ReactTypes'; <add>import type {LanePriority} from './ReactFiberLane.old'; <ide> <ide> import {DidCapture} from './ReactFiberFlags'; <add>import { <add> lanePriorityToSchedulerPriority, <add> NoLanePriority, <add>} from './ReactFiberLane.old'; <add>import {NormalPriority} from './SchedulerWithReactIntegration.old'; <ide> <ide> declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: Object | void; <ide> <ide> export function onScheduleRoot(root: FiberRoot, children: ReactNodeList) { <ide> } <ide> } <ide> <del>export function onCommitRoot( <del> root: FiberRoot, <del> priorityLevel: ReactPriorityLevel, <del>) { <add>export function onCommitRoot(root: FiberRoot, priorityLevel: LanePriority) { <ide> if (injectedHook && typeof injectedHook.onCommitFiberRoot === 'function') { <ide> try { <ide> const didError = (root.current.flags & DidCapture) === DidCapture; <ide> if (enableProfilerTimer) { <add> const schedulerPriority = <add> priorityLevel === NoLanePriority <add> ? NormalPriority <add> : lanePriorityToSchedulerPriority(priorityLevel); <ide> injectedHook.onCommitFiberRoot( <ide> rendererID, <ide> root, <del> priorityLevel, <add> schedulerPriority, <ide> didError, <ide> ); <ide> } else { <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> <ide> import type {Thenable, Wakeable} from 'shared/ReactTypes'; <ide> import type {Fiber, FiberRoot} from './ReactInternalTypes'; <del>import type {Lanes, Lane} from './ReactFiberLane.new'; <del>import type {ReactPriorityLevel} from './ReactInternalTypes'; <add>import type {Lanes, Lane, LanePriority} from './ReactFiberLane.new'; <ide> import type {Interaction} from 'scheduler/src/Tracing'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.new'; <ide> import type {StackCursor} from './ReactFiberStack.new'; <ide> import { <ide> shouldYield, <ide> requestPaint, <ide> now, <del> NoPriority as NoSchedulerPriority, <ide> ImmediatePriority as ImmediateSchedulerPriority, <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> import { <ide> markRootFinished, <ide> schedulerPriorityToLanePriority, <ide> lanePriorityToSchedulerPriority, <add> higherLanePriority, <ide> } from './ReactFiberLane.new'; <ide> import {requestCurrentTransition, NoTransition} from './ReactFiberTransition'; <ide> import {beginWork as originalBeginWork} from './ReactFiberBeginWork.new'; <ide> let rootCommittingMutationOrLayoutEffects: FiberRoot | null = null; <ide> <ide> let rootDoesHavePassiveEffects: boolean = false; <ide> let rootWithPendingPassiveEffects: FiberRoot | null = null; <del>let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority; <add>let pendingPassiveEffectsRenderPriority: LanePriority = NoLanePriority; <ide> let pendingPassiveEffectsLanes: Lanes = NoLanes; <ide> let pendingPassiveProfilerEffects: Array<Fiber> = []; <ide> <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> if ((mode & BlockingMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <del> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <add> return getCurrentUpdateLanePriority() === SyncLanePriority <ide> ? (SyncLane: Lane) <ide> : (SyncBatchedLane: Lane); <ide> } else if ( <ide> function requestRetryLane(fiber: Fiber) { <ide> if ((mode & BlockingMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <del> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <add> return getCurrentUpdateLanePriority() === SyncLanePriority <ide> ? (SyncLane: Lane) <ide> : (SyncBatchedLane: Lane); <ide> } <ide> export function scheduleUpdateOnFiber( <ide> // Schedule a discrete update but only if it's not Sync. <ide> if ( <ide> (executionContext & DiscreteEventContext) !== NoContext && <del> // Only updates at user-blocking priority or greater are considered <del> // discrete, even inside a discrete event. <del> updateLanePriority === InputDiscreteLanePriority <add> // Only updates greater than default considered discrete, even inside a discrete event. <add> higherLanePriority(updateLanePriority, DefaultLanePriority) !== <add> DefaultLanePriority <ide> ) { <ide> // This is the result of a discrete event. Track the lowest priority <ide> // discrete update per root so we can flush them early, if needed. <ide> function completeUnitOfWork(unitOfWork: Fiber): void { <ide> } <ide> <ide> function commitRoot(root) { <del> const renderPriorityLevel = getCurrentPriorityLevel(); <del> runWithPriority( <del> ImmediateSchedulerPriority, <del> commitRootImpl.bind(null, root, renderPriorityLevel), <del> ); <add> const previousUpdateLanePriority = getCurrentUpdateLanePriority(); <add> try { <add> setCurrentUpdateLanePriority(SyncLanePriority); <add> runWithPriority( <add> ImmediateSchedulerPriority, <add> commitRootImpl.bind(null, root, previousUpdateLanePriority), <add> ); <add> } finally { <add> setCurrentUpdateLanePriority(previousUpdateLanePriority); <add> } <add> <ide> return null; <ide> } <ide> <ide> function commitRootImpl(root, renderPriorityLevel) { <ide> rootDoesHavePassiveEffects = false; <ide> rootWithPendingPassiveEffects = root; <ide> pendingPassiveEffectsLanes = lanes; <del> pendingPassiveEffectsRenderPriority = renderPriorityLevel; <add> pendingPassiveEffectsRenderPriority = <add> renderPriorityLevel === NoLanePriority <add> ? DefaultLanePriority <add> : renderPriorityLevel; <ide> } <ide> <ide> // Read this again, since an effect might have updated it <ide> function commitRootImpl(root, renderPriorityLevel) { <ide> <ide> export function flushPassiveEffects(): boolean { <ide> // Returns whether passive effects were flushed. <del> if (pendingPassiveEffectsRenderPriority !== NoSchedulerPriority) { <add> if (pendingPassiveEffectsRenderPriority !== NoLanePriority) { <ide> const priorityLevel = <del> pendingPassiveEffectsRenderPriority > NormalSchedulerPriority <del> ? NormalSchedulerPriority <add> pendingPassiveEffectsRenderPriority > DefaultLanePriority <add> ? DefaultLanePriority <ide> : pendingPassiveEffectsRenderPriority; <del> pendingPassiveEffectsRenderPriority = NoSchedulerPriority; <add> pendingPassiveEffectsRenderPriority = NoLanePriority; <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <del> setCurrentUpdateLanePriority( <del> schedulerPriorityToLanePriority(priorityLevel), <del> ); <del> return runWithPriority(priorityLevel, flushPassiveEffectsImpl); <add> setCurrentUpdateLanePriority(priorityLevel); <add> return flushPassiveEffectsImpl(); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> } <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> <ide> import type {Thenable, Wakeable} from 'shared/ReactTypes'; <ide> import type {Fiber, FiberRoot} from './ReactInternalTypes'; <del>import type {Lanes, Lane} from './ReactFiberLane.old'; <del>import type {ReactPriorityLevel} from './ReactInternalTypes'; <add>import type {Lanes, Lane, LanePriority} from './ReactFiberLane.old'; <ide> import type {Interaction} from 'scheduler/src/Tracing'; <ide> import type {SuspenseState} from './ReactFiberSuspenseComponent.old'; <ide> import type {StackCursor} from './ReactFiberStack.old'; <ide> import { <ide> shouldYield, <ide> requestPaint, <ide> now, <del> NoPriority as NoSchedulerPriority, <ide> ImmediatePriority as ImmediateSchedulerPriority, <ide> UserBlockingPriority as UserBlockingSchedulerPriority, <ide> NormalPriority as NormalSchedulerPriority, <ide> import { <ide> markRootFinished, <ide> schedulerPriorityToLanePriority, <ide> lanePriorityToSchedulerPriority, <add> higherLanePriority, <ide> } from './ReactFiberLane.old'; <ide> import {requestCurrentTransition, NoTransition} from './ReactFiberTransition'; <ide> import {beginWork as originalBeginWork} from './ReactFiberBeginWork.old'; <ide> let rootCommittingMutationOrLayoutEffects: FiberRoot | null = null; <ide> <ide> let rootDoesHavePassiveEffects: boolean = false; <ide> let rootWithPendingPassiveEffects: FiberRoot | null = null; <del>let pendingPassiveEffectsRenderPriority: ReactPriorityLevel = NoSchedulerPriority; <add>let pendingPassiveEffectsRenderPriority: LanePriority = NoLanePriority; <ide> let pendingPassiveEffectsLanes: Lanes = NoLanes; <ide> let pendingPassiveProfilerEffects: Array<Fiber> = []; <ide> <ide> export function requestUpdateLane(fiber: Fiber): Lane { <ide> if ((mode & BlockingMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <del> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <add> return getCurrentUpdateLanePriority() === SyncLanePriority <ide> ? (SyncLane: Lane) <ide> : (SyncBatchedLane: Lane); <ide> } else if ( <ide> function requestRetryLane(fiber: Fiber) { <ide> if ((mode & BlockingMode) === NoMode) { <ide> return (SyncLane: Lane); <ide> } else if ((mode & ConcurrentMode) === NoMode) { <del> return getCurrentPriorityLevel() === ImmediateSchedulerPriority <add> return getCurrentUpdateLanePriority() === SyncLanePriority <ide> ? (SyncLane: Lane) <ide> : (SyncBatchedLane: Lane); <ide> } <ide> export function scheduleUpdateOnFiber( <ide> // Schedule a discrete update but only if it's not Sync. <ide> if ( <ide> (executionContext & DiscreteEventContext) !== NoContext && <del> // Only updates at user-blocking priority or greater are considered <del> // discrete, even inside a discrete event. <del> updateLanePriority === InputDiscreteLanePriority <add> // Only updates greater than default considered discrete, even inside a discrete event. <add> higherLanePriority(updateLanePriority, DefaultLanePriority) !== <add> DefaultLanePriority <ide> ) { <ide> // This is the result of a discrete event. Track the lowest priority <ide> // discrete update per root so we can flush them early, if needed. <ide> function completeUnitOfWork(unitOfWork: Fiber): void { <ide> } <ide> <ide> function commitRoot(root) { <del> const renderPriorityLevel = getCurrentPriorityLevel(); <del> runWithPriority( <del> ImmediateSchedulerPriority, <del> commitRootImpl.bind(null, root, renderPriorityLevel), <del> ); <add> const previousUpdateLanePriority = getCurrentUpdateLanePriority(); <add> try { <add> setCurrentUpdateLanePriority(SyncLanePriority); <add> runWithPriority( <add> ImmediateSchedulerPriority, <add> commitRootImpl.bind(null, root, previousUpdateLanePriority), <add> ); <add> } finally { <add> setCurrentUpdateLanePriority(previousUpdateLanePriority); <add> } <add> <ide> return null; <ide> } <ide> <ide> function commitRootImpl(root, renderPriorityLevel) { <ide> rootDoesHavePassiveEffects = false; <ide> rootWithPendingPassiveEffects = root; <ide> pendingPassiveEffectsLanes = lanes; <del> pendingPassiveEffectsRenderPriority = renderPriorityLevel; <add> pendingPassiveEffectsRenderPriority = <add> renderPriorityLevel === NoLanePriority <add> ? DefaultLanePriority <add> : renderPriorityLevel; <ide> } <ide> <ide> // Read this again, since an effect might have updated it <ide> function commitRootImpl(root, renderPriorityLevel) { <ide> <ide> export function flushPassiveEffects(): boolean { <ide> // Returns whether passive effects were flushed. <del> if (pendingPassiveEffectsRenderPriority !== NoSchedulerPriority) { <add> if (pendingPassiveEffectsRenderPriority !== NoLanePriority) { <ide> const priorityLevel = <del> pendingPassiveEffectsRenderPriority > NormalSchedulerPriority <del> ? NormalSchedulerPriority <add> pendingPassiveEffectsRenderPriority > DefaultLanePriority <add> ? DefaultLanePriority <ide> : pendingPassiveEffectsRenderPriority; <del> pendingPassiveEffectsRenderPriority = NoSchedulerPriority; <add> pendingPassiveEffectsRenderPriority = NoLanePriority; <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <del> setCurrentUpdateLanePriority( <del> schedulerPriorityToLanePriority(priorityLevel), <del> ); <del> return runWithPriority(priorityLevel, flushPassiveEffectsImpl); <add> setCurrentUpdateLanePriority(priorityLevel); <add> return flushPassiveEffectsImpl(); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> } <ide><path>packages/react-reconciler/src/__tests__/ReactSchedulerIntegration-test.js <ide> describe('ReactSchedulerIntegration', () => { <ide> ]); <ide> }); <ide> <del> // TODO: Figure out what to do with these tests. I don't think most of them <del> // make sense once we decouple Scheduler from React. Perhaps need similar <del> // tests for React DOM. <del> // @gate !enableNativeEventPriorityInference <del> it('passive effects never have higher than normal priority', async () => { <del> const {useEffect} = React; <del> function ReadPriority({step}) { <del> Scheduler.unstable_yieldValue( <del> `Render priority: ${getCurrentPriorityAsString()}`, <del> ); <del> useEffect(() => { <del> Scheduler.unstable_yieldValue( <del> `Effect priority: ${getCurrentPriorityAsString()}`, <del> ); <del> return () => { <del> Scheduler.unstable_yieldValue( <del> `Effect clean-up priority: ${getCurrentPriorityAsString()}`, <del> ); <del> }; <del> }); <del> return null; <del> } <del> <del> // High priority renders spawn effects at normal priority <del> await ReactNoop.act(async () => { <del> Scheduler.unstable_runWithPriority(ImmediatePriority, () => { <del> ReactNoop.render(<ReadPriority />); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded([ <del> 'Render priority: Immediate', <del> 'Effect priority: Normal', <del> ]); <del> await ReactNoop.act(async () => { <del> Scheduler.unstable_runWithPriority(UserBlockingPriority, () => { <del> ReactNoop.render(<ReadPriority />); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded([ <del> 'Render priority: UserBlocking', <del> 'Effect clean-up priority: Normal', <del> 'Effect priority: Normal', <del> ]); <del> <del> // Renders lower than normal priority spawn effects at the same priority <del> await ReactNoop.act(async () => { <del> Scheduler.unstable_runWithPriority(IdlePriority, () => { <del> ReactNoop.render(<ReadPriority />); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded([ <del> 'Render priority: Idle', <del> 'Effect clean-up priority: Idle', <del> 'Effect priority: Idle', <del> ]); <del> }); <del> <del> // TODO: Figure out what to do with these tests. I don't think most of them <del> // make sense once we decouple Scheduler from React. Perhaps need similar <del> // tests for React DOM. <del> // @gate !enableNativeEventPriorityInference <del> it('passive effects have correct priority even if they are flushed early', async () => { <del> const {useEffect} = React; <del> function ReadPriority({step}) { <del> Scheduler.unstable_yieldValue( <del> `Render priority [step ${step}]: ${getCurrentPriorityAsString()}`, <del> ); <del> useEffect(() => { <del> Scheduler.unstable_yieldValue( <del> `Effect priority [step ${step}]: ${getCurrentPriorityAsString()}`, <del> ); <del> }); <del> return null; <del> } <del> await ReactNoop.act(async () => { <del> ReactNoop.render(<ReadPriority step={1} />); <del> Scheduler.unstable_flushUntilNextPaint(); <del> expect(Scheduler).toHaveYielded(['Render priority [step 1]: Normal']); <del> Scheduler.unstable_runWithPriority(UserBlockingPriority, () => { <del> ReactNoop.render(<ReadPriority step={2} />); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded([ <del> 'Effect priority [step 1]: Normal', <del> 'Render priority [step 2]: UserBlocking', <del> 'Effect priority [step 2]: Normal', <del> ]); <del> }); <del> <del> // TODO: Figure out what to do with these tests. I don't think most of them <del> // make sense once we decouple Scheduler from React. Perhaps need similar <del> // tests for React DOM. <del> // @gate !enableNativeEventPriorityInference <del> it('passive effect clean-up functions have correct priority even when component is deleted', async () => { <del> const {useEffect} = React; <del> function ReadPriority({step}) { <del> useEffect(() => { <del> return () => { <del> Scheduler.unstable_yieldValue( <del> `Effect clean-up priority: ${getCurrentPriorityAsString()}`, <del> ); <del> }; <del> }); <del> return null; <del> } <del> <del> await ReactNoop.act(async () => { <del> ReactNoop.render(<ReadPriority />); <del> }); <del> await ReactNoop.act(async () => { <del> Scheduler.unstable_runWithPriority(ImmediatePriority, () => { <del> ReactNoop.render(null); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded(['Effect clean-up priority: Normal']); <del> <del> await ReactNoop.act(async () => { <del> ReactNoop.render(<ReadPriority />); <del> }); <del> await ReactNoop.act(async () => { <del> Scheduler.unstable_runWithPriority(UserBlockingPriority, () => { <del> ReactNoop.render(null); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded(['Effect clean-up priority: Normal']); <del> <del> // Renders lower than normal priority spawn effects at the same priority <del> await ReactNoop.act(async () => { <del> ReactNoop.render(<ReadPriority />); <del> }); <del> await ReactNoop.act(async () => { <del> Scheduler.unstable_runWithPriority(IdlePriority, () => { <del> ReactNoop.render(null); <del> }); <del> }); <del> expect(Scheduler).toHaveYielded(['Effect clean-up priority: Idle']); <del> }); <del> <ide> it('passive effects are called before Normal-pri scheduled in layout effects', async () => { <ide> const {useEffect, useLayoutEffect} = React; <ide> function Effects({step}) {
7
Python
Python
remove duplicated code
197093bd7a455ce285b2415e45039cab83544269
<ide><path>numpy/linalg/linalg.py <ide> def _to_native_byte_order(*arrays): <ide> def _fastCopyAndTranspose(type, *arrays): <ide> cast_arrays = () <ide> for a in arrays: <del> if a.dtype.type is type: <del> cast_arrays = cast_arrays + (_fastCT(a),) <del> else: <del> cast_arrays = cast_arrays + (_fastCT(a.astype(type)),) <add> if a.dtype.type is not type: <add> a = a.astype(type) <add> cast_arrays = cast_arrays + (_fastCT(a),) <ide> if len(cast_arrays) == 1: <ide> return cast_arrays[0] <ide> else:
1
Python
Python
add unicode declaration
2df27db67190c799743266eede6d52471e1febe5
<ide><path>spacy/tests/regression/test_issue1518.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <ide> from ...vectors import Vectors <ide> <ide> def test_issue1518():
1
Ruby
Ruby
use string as keys
55f6c8c908fea2609cbc8503f8d87460fd1b16b4
<ide><path>activerecord/lib/active_record/enum.rb <ide> module Enum <ide> DEFINED_ENUMS = {} # :nodoc: <ide> <ide> def enum_mapping_for(attr_name) # :nodoc: <del> DEFINED_ENUMS[attr_name.to_sym] <add> DEFINED_ENUMS[attr_name.to_s] <ide> end <ide> <ide> def enum(definitions) <ide> def enum(definitions) <ide> define_method("#{value}!") { update! name => value } <ide> end <ide> <del> DEFINED_ENUMS[name] = enum_values <add> DEFINED_ENUMS[name.to_s] = enum_values <ide> end <ide> end <ide> end
1
Javascript
Javascript
skip the test with proper tap message
cd3c478f70dd71b8aeb02e041f686fa44742d81b
<ide><path>test/parallel/test-setproctitle.js <ide> const common = require('../common'); <ide> <ide> // FIXME add sunos support <ide> if (common.isSunOS) { <del> console.log(`1..0 # Skipped: Unsupported platform [${process.platform}]`); <del> return; <add> return common.skip(`Unsupported platform [${process.platform}]`); <ide> } <ide> <ide> const assert = require('assert'); <ide> process.title = title; <ide> assert.strictEqual(process.title, title); <ide> <ide> // Test setting the title but do not try to run `ps` on Windows. <del>if (common.isWindows) <del> return; <add>if (common.isWindows) { <add> return common.skip('Windows does not have "ps" utility'); <add>} <ide> <ide> exec(`ps -p ${process.pid} -o args=`, function callback(error, stdout, stderr) { <ide> assert.ifError(error);
1
Ruby
Ruby
use nameerror for missing association model class
336fa481787b7c2d9976a21064a4c75a3558dbe9
<ide><path>activerecord/lib/active_record/reflection.rb <ide> def compute_class(name) <ide> rescue NameError <ide> message = "Missing model class #{name} for the #{active_record}##{self.name} association." <ide> message += " You can specify a different model class with the :class_name option." unless options[:class_name] <del> raise ArgumentError, message <add> raise NameError, message <ide> end <ide> <ide> unless klass < ActiveRecord::Base <ide><path>activerecord/test/cases/associations_test.rb <ide> class ModelAssociatedToClassesThatDoNotExist < ActiveRecord::Base <ide> end <ide> <ide> def test_associations_raise_with_name_error_if_associated_to_classes_that_do_not_exist <del> assert_raises ArgumentError do <add> assert_raises NameError do <ide> ModelAssociatedToClassesThatDoNotExist.new.non_existent_has_one_class <ide> end <ide> <del> assert_raises ArgumentError do <add> assert_raises NameError do <ide> ModelAssociatedToClassesThatDoNotExist.new.non_existent_belongs_to_class <ide> end <ide> <del> assert_raises ArgumentError do <add> assert_raises NameError do <ide> ModelAssociatedToClassesThatDoNotExist.new.non_existent_has_many_classes <ide> end <ide> end <ide><path>activerecord/test/cases/finder_test.rb <ide> require "models/customer" <ide> require "models/toy" <ide> require "models/matey" <del>require "models/dog_lover" <ide> require "models/dog" <ide> require "models/car" <ide> require "models/tyre" <ide><path>activerecord/test/cases/fixtures_test.rb <ide> require "models/computer" <ide> require "models/course" <ide> require "models/developer" <del>require "models/dog_lover" <ide> require "models/dog" <ide> require "models/doubloon" <ide> require "models/essay" <ide><path>activerecord/test/cases/nested_attributes_test.rb <ide> <ide> require "cases/helper" <ide> require "models/pirate" <del>require "models/developer" <ide> require "models/ship" <ide> require "models/ship_part" <ide> require "models/bird" <ide><path>activerecord/test/cases/reflection_test.rb <ide> def test_irregular_reflection_class_name <ide> end <ide> <ide> def test_reflection_klass_not_found_with_no_class_name_option <del> error = assert_raise(ArgumentError) do <add> error = assert_raise(NameError) do <ide> UserWithInvalidRelation.reflect_on_association(:not_a_class).klass <ide> end <ide> <ide> def test_reflection_klass_not_found_with_no_class_name_option <ide> end <ide> <ide> def test_reflection_klass_not_found_with_pointer_to_non_existent_class_name <del> error = assert_raise(ArgumentError) do <add> error = assert_raise(NameError) do <ide> UserWithInvalidRelation.reflect_on_association(:class_name_provided_not_a_class).klass <ide> end <ide> <ide> def test_reflect_on_association_accepts_strings <ide> end <ide> end <ide> <add> def test_automatic_inverse_suppresses_name_error_for_association <add> reflection = UserWithInvalidRelation.reflect_on_association(:not_a_class) <add> assert_not reflection.dup.has_inverse? # dup to prevent global memoization <add> end <add> <ide> private <ide> def assert_reflection(klass, association, options) <ide> assert reflection = klass.reflect_on_association(association)
6
Python
Python
correct client.py complexity
ef1dbb3fefe48361ec320e4f91eee3d6f05b954d
<ide><path>glances/client.py <ide> def __init__(self, config=None, args=None, timeout=7, return_to_browser=False): <ide> <ide> # Build the URI <ide> if args.password != "": <del> uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password, <del> args.client, args.port) <add> self.uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password, <add> args.client, args.port) <ide> else: <del> uri = 'http://{0}:{1}'.format(args.client, args.port) <del> logger.debug("Try to connect to {0}".format(uri)) <add> self.uri = 'http://{0}:{1}'.format(args.client, args.port) <add> logger.debug("Try to connect to {0}".format(self.uri)) <ide> <ide> # Try to connect to the URI <ide> transport = GlancesClientTransport() <ide> # Configure the server timeout <ide> transport.set_timeout(timeout) <ide> try: <del> self.client = ServerProxy(uri, transport=transport) <add> self.client = ServerProxy(self.uri, transport=transport) <ide> except Exception as e: <del> self.log_and_exit("Client couldn't create socket {0}: {1}".format(uri, e)) <add> self.log_and_exit("Client couldn't create socket {0}: {1}".format(self.uri, e)) <ide> <ide> def log_and_exit(self, msg=''): <ide> """Log and exit.""" <ide> def client_mode(self, mode): <ide> """ <ide> self._client_mode = mode <ide> <del> def login(self): <del> """Logon to the server.""" <del> ret = True <add> def _login_glances(self): <add> """Login to a Glances server""" <add> client_version = None <add> try: <add> client_version = self.client.init() <add> except socket.error as err: <add> # Fallback to SNMP <add> self.client_mode = 'snmp' <add> logger.error("Connection to Glances server failed ({0} {1})".format(err.errno, err.strerror)) <add> fallbackmsg = 'No Glances server found on {}. Trying fallback to SNMP...'.format(self.uri) <add> if not self.return_to_browser: <add> print(fallbackmsg) <add> else: <add> logger.info(fallbackmsg) <add> except ProtocolError as err: <add> # Other errors <add> msg = "Connection to server {} failed".format(self.uri) <add> if err.errcode == 401: <add> msg += " (Bad username/password)" <add> else: <add> msg += " ({0} {1})".format(err.errcode, err.errmsg) <add> self.log_and_exit(msg) <add> return False <ide> <del> if not self.args.snmp_force: <del> # First of all, trying to connect to a Glances server <del> client_version = None <del> try: <del> client_version = self.client.init() <del> except socket.error as err: <del> # Fallback to SNMP <del> self.client_mode = 'snmp' <del> logger.error("Connection to Glances server failed ({0} {1})".format(err.errno, err.strerror)) <del> fallbackmsg = 'No Glances server found. Trying fallback to SNMP...' <del> if not self.return_to_browser: <del> print(fallbackmsg) <del> else: <del> logger.info(fallbackmsg) <del> except ProtocolError as err: <del> # Other errors <del> msg = "Connection to server failed" <del> if err.errcode == 401: <del> msg += " (Bad username/password)" <del> else: <del> msg += " ({0} {1})".format(err.errcode, err.errmsg) <del> self.log_and_exit(msg) <add> if self.client_mode == 'glances': <add> # Check that both client and server are in the same major version <add> if __version__.split('.')[0] == client_version.split('.')[0]: <add> # Init stats <add> self.stats = GlancesStatsClient(config=self.config, args=self.args) <add> self.stats.set_plugins(json.loads(self.client.getAllPlugins())) <add> logger.debug("Client version: {0} / Server version: {1}".format(__version__, client_version)) <add> else: <add> self.log_and_exit("Client and server not compatible: \ <add> Client version: {0} / Server version: {1}".format(__version__, client_version)) <ide> return False <ide> <del> if self.client_mode == 'glances': <del> # Check that both client and server are in the same major version <del> if __version__.split('.')[0] == client_version.split('.')[0]: <del> # Init stats <del> self.stats = GlancesStatsClient(config=self.config, args=self.args) <del> self.stats.set_plugins(json.loads(self.client.getAllPlugins())) <del> logger.debug("Client version: {0} / Server version: {1}".format(__version__, client_version)) <del> else: <del> self.log_and_exit("Client and server not compatible: \ <del> Client version: {0} / Server version: {1}".format(__version__, client_version)) <del> return False <add> return True <ide> <del> else: <del> self.client_mode = 'snmp' <add> def _login_snmp(self): <add> """Login to a SNMP server""" <add> logger.info("Trying to grab stats by SNMP...") <ide> <del> # SNMP mode <del> if self.client_mode == 'snmp': <del> logger.info("Trying to grab stats by SNMP...") <add> from glances.stats_client_snmp import GlancesStatsClientSNMP <add> <add> # Init stats <add> self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args) <ide> <del> from glances.stats_client_snmp import GlancesStatsClientSNMP <add> if not self.stats.check_snmp(): <add> self.log_and_exit("Connection to SNMP server failed") <add> return False <ide> <del> # Init stats <del> self.stats = GlancesStatsClientSNMP(config=self.config, args=self.args) <add> return True <ide> <del> if not self.stats.check_snmp(): <del> self.log_and_exit("Connection to SNMP server failed") <add> def login(self): <add> """Logon to the server.""" <add> <add> if self.args.snmp_force: <add> # Force SNMP instead of Glances server <add> self.client_mode = 'snmp' <add> else: <add> # First of all, trying to connect to a Glances server <add> if not self._login_glances(): <add> return False <add> <add> # Try SNMP mode <add> if self.client_mode == 'snmp': <add> if not self._login_snmp(): <ide> return False <ide> <del> if ret: <del> # Load limits from the configuration file <del> # Each client can choose its owns limits <del> logger.debug("Load limits from the client configuration file") <del> self.stats.load_limits(self.config) <add> # Load limits from the configuration file <add> # Each client can choose its owns limits <add> logger.debug("Load limits from the client configuration file") <add> self.stats.load_limits(self.config) <ide> <del> # Init screen <del> self.screen = GlancesCursesClient(config=self.config, args=self.args) <add> # Init screen <add> self.screen = GlancesCursesClient(config=self.config, args=self.args) <ide> <del> # Return result <del> return ret <add> # Return True: OK <add> return True <ide> <ide> def update(self): <ide> """Update stats from Glances/SNMP server."""
1
Mixed
Ruby
move default uuid generation to active_record
f0323288da939f57641b82041cb1a86a1e526746
<ide><path>activerecord/CHANGELOG.md <ide> <ide> * Add ability to default to `uuid` as primary key when generating database migrations <ide> <del> Set `Rails.application.config.active_record.primary_key = :uuid` <del> or `config.active_record.primary_key = :uuid` in config/application.rb <add> config.generators do |g| <add> g.orm :active_record, primary_key_type: :uuid <add> end <ide> <ide> *Jon McCartie* <ide> <ide><path>activerecord/lib/rails/generators/active_record.rb <ide> class Base < Rails::Generators::NamedBase # :nodoc: <ide> def self.base_root <ide> File.dirname(__FILE__) <ide> end <add> <add> private <add> def primary_key_type <add> key_type = Rails::Generators.options[:active_record][:primary_key_type] <add> ", id: :#{key_type}" if key_type <add> end <add> <add> <ide> end <ide> end <ide> end <ide><path>activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb <ide> class <%= migration_class_name %> < ActiveRecord::Migration <ide> def change <del> create_table :<%= table_name %><%= id_kind %> do |t| <add> create_table :<%= table_name %><%= primary_key_type %> do |t| <ide> <% attributes.each do |attribute| -%> <ide> <% if attribute.password_digest? -%> <ide> t.string :password_digest<%= attribute.inject_options %> <ide><path>railties/lib/rails/generators/migration.rb <ide> def next_migration_number(dirname) <ide> end <ide> end <ide> <del> def id_kind <del> kind = Rails.application.config.active_record.primary_key rescue nil <del> ", id: :#{kind}" if kind <del> end <del> <ide> def create_migration(destination, data, config = {}, &block) <ide> action Rails::Generators::Actions::CreateMigration.new(self, destination, block || data.to_s, config) <ide> end <ide><path>railties/test/generators/migration_generator_test.rb <ide> def test_create_table_migration <ide> end <ide> <ide> def test_add_uuid_to_create_table_migration <del> previous_value = Rails.application.config.active_record.primary_key <del> Rails.application.config.active_record.primary_key = :uuid <add> previous_value = Rails.application.config.generators.active_record[:primary_key_type] <add> Rails.application.config.generators.active_record[:primary_key_type] = :uuid <add> <ide> run_generator ["create_books"] <ide> assert_migration "db/migrate/create_books.rb" do |content| <ide> assert_method :change, content do |change| <ide> assert_match(/create_table :books, id: :uuid/, change) <ide> end <ide> end <ide> <del> Rails.application.config.active_record.primary_key = previous_value <add> Rails.application.config.generators.active_record[:primary_key_type] = previous_value <ide> end <ide> <ide> def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove_or_create
5
Ruby
Ruby
avoid rack security warning no secret provided
cb3181e81e3a0e9d03450c7065fcc226e2e1731c
<ide><path>actionpack/lib/action_dispatch/middleware/session/abstract_store.rb <ide> def initialize(const_error) <ide> module Compatibility <ide> def initialize(app, options = {}) <ide> options[:key] ||= '_session_id' <add> # FIXME Rack's secret is not being used <add> options[:secret] ||= SecureRandom.hex(30) <ide> super <ide> end <ide>
1
Go
Go
fix unmounting layer without merge dir
e1af6c8a5767e38957449a1d07e56104e317191b
<ide><path>daemon/graphdriver/overlay2/overlay.go <ide> import ( <ide> "github.com/docker/docker/pkg/mount" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/parsers/kernel" <del> "github.com/docker/go-units" <add> units "github.com/docker/go-units" <ide> <ide> "github.com/opencontainers/runc/libcontainer/label" <ide> ) <ide> func (d *Driver) Get(id string, mountLabel string) (s string, err error) { <ide> <ide> // Put unmounts the mount path created for the give id. <ide> func (d *Driver) Put(id string) error { <del> mountpoint := path.Join(d.dir(id), "merged") <add> dir := d.dir(id) <add> _, err := ioutil.ReadFile(path.Join(dir, lowerFile)) <add> if err != nil { <add> // If no lower, no mount happened and just return directly <add> if os.IsNotExist(err) { <add> return nil <add> } <add> return err <add> } <add> <add> mountpoint := path.Join(dir, "merged") <ide> if count := d.ctr.Decrement(mountpoint); count > 0 { <ide> return nil <ide> }
1
Python
Python
move ssd image to docker
17966c940aacf8a3a9edfae28bb9700a7f58bd1d
<ide><path>libnetwork/cmd/ssd/ssd.py <ide> def check_network(nw_name, ingress=False): <ide> <ide> if command == 'gossip-consistency': <ide> cspec = docker.types.ContainerSpec( <del> image='sanimej/ssd', <add> image='docker/ssd', <ide> args=[sys.argv[1], 'gossip-hash'], <ide> mounts=[docker.types.Mount('/var/run/docker.sock', '/var/run/docker.sock', type='bind')] <ide> )
1
Python
Python
remove unused import
b59be258c0597db0b11b807ec07c7a061462c0d3
<ide><path>celery/worker/controllers.py <ide> from multiprocessing import get_logger <ide> import traceback <ide> import threading <del>import socket <ide> import time <ide> <ide>
1
Text
Text
update the maintenance policy for the next release
e165f7fa6044926796c9d9a8bb9a81bc78431d4f
<ide><path>guides/source/maintenance_policy.md <ide> from. <ide> In special situations, where someone from the Core Team agrees to support more series, <ide> they are included in the list of supported series. <ide> <del>**Currently included series:** `4.2.Z`, `4.1.Z` (Supported by Rafael França). <add>**Currently included series:** `5.0.Z`. <ide> <ide> Security Issues <ide> --------------- <ide> be built from 1.2.2, and then added to the end of 1-2-stable. This means that <ide> security releases are easy to upgrade to if you're running the latest version <ide> of Rails. <ide> <del>**Currently included series:** `4.2.Z`, `4.1.Z`. <add>**Currently included series:** `5.0.Z`, `4.2.Z`. <ide> <ide> Severe Security Issues <ide> ---------------------- <ide> For severe security issues we will provide new versions as above, and also the <ide> last major release series will receive patches and new versions. The <ide> classification of the security issue is judged by the core team. <ide> <del>**Currently included series:** `4.2.Z`, `4.1.Z`, `3.2.Z`. <add>**Currently included series:** `5.0.Z`, `4.2.Z`. <ide> <ide> Unsupported Release Series <ide> --------------------------
1
Javascript
Javascript
add challenge head/tail to contents on execute
73b5fd5797d8a99457d87d659b5dc288307a635d
<ide><path>client/sagas/execute-challenge-saga.js <ide> function cacheLink({ link } = {}, crossDomain = true) { <ide> <ide> <ide> const htmlCatch = '\n<!--fcc-->'; <del>const jsCatch = '\n;/*fcc*/'; <add>const jsCatch = '\n;/*fcc*/\n'; <ide> <ide> export default function executeChallengeSaga(action$, getState) { <ide> const frameRunner$ = cacheScript( <ide> export default function executeChallengeSaga(action$, getState) { <ide> // createbuild <ide> .flatMap(file$ => file$.reduce((build, file) => { <ide> let finalFile; <add> const finalContents = [ <add> file.head, <add> file.contents, <add> file.tail <add> ]; <ide> if (file.ext === 'js') { <ide> finalFile = setExt('html', updateContents( <del> `<script>${file.contents}${jsCatch}</script>`, <add> `<script>${finalContents.join(jsCatch)}${jsCatch}</script>`, <ide> file <ide> )); <ide> } else if (file.ext === 'css') { <ide> finalFile = setExt('html', updateContents( <del> `<style>${file.contents}</style>`, <add> `<style>${finalContents.join(htmlCatch)}</style>`, <ide> file <ide> )); <ide> } else {
1
Javascript
Javascript
fix excessive toggles on the switch component
b782934f3f2a80ae7e3872cc7d7a610aa6680ec4
<ide><path>Libraries/Components/Switch/Switch.js <ide> class Switch extends React.Component<Props> { <ide> _nativeSwitchRef: ?React.ElementRef< <ide> typeof SwitchNativeComponent | typeof AndroidSwitchNativeComponent, <ide> >; <add> _lastNativeValue: ?boolean; <ide> <ide> render(): React.Node { <ide> const { <ide> class Switch extends React.Component<Props> { <ide> ); <ide> } <ide> <del> _handleChange = (event: SwitchChangeEvent) => { <del> if (this._nativeSwitchRef == null) { <del> return; <add> componentDidUpdate() { <add> // This is necessary in case native updates the switch and JS decides <add> // that the update should be ignored and we should stick with the value <add> // that we have in JS. <add> const nativeProps = {}; <add> const value = this.props.value === true; <add> <add> if (this._lastNativeValue !== value && typeof value === 'boolean') { <add> nativeProps.value = value; <ide> } <ide> <del> // Force value of native switch in order to control it. <del> const value = this.props.value === true; <del> if (Platform.OS === 'android') { <del> this._nativeSwitchRef.setNativeProps({on: value}); <del> } else { <del> this._nativeSwitchRef.setNativeProps({value}); <add> if ( <add> Object.keys(nativeProps).length > 0 && <add> this._nativeSwitchRef && <add> this._nativeSwitchRef.setNativeProps <add> ) { <add> this._nativeSwitchRef.setNativeProps(nativeProps); <ide> } <add> } <ide> <add> _handleChange = (event: SwitchChangeEvent) => { <ide> if (this.props.onChange != null) { <ide> this.props.onChange(event); <ide> } <ide> <ide> if (this.props.onValueChange != null) { <ide> this.props.onValueChange(event.nativeEvent.value); <ide> } <add> <add> this._lastNativeValue = event.nativeEvent.value; <add> this.forceUpdate(); <ide> }; <ide> <ide> _handleSwitchNativeComponentRef = (
1
PHP
PHP
add throttlelogin localization support
bd583fedd73d5c5f3cd6308439c48e9cbca47433
<ide><path>resources/lang/en/passwords.php <ide> 'token' => 'This password reset token is invalid.', <ide> 'sent' => 'We have e-mailed your password reset link!', <ide> 'reset' => 'Your password has been reset!', <add> 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', <ide> <ide> ];
1
Go
Go
refine error message when save non-exist image
ed231d409501d1e496fbe2b2e31a279eb2998cf2
<ide><path>image/store.go <ide> func (is *store) Search(term string) (ID, error) { <ide> <ide> dgst, err := is.digestSet.Lookup(term) <ide> if err != nil { <add> if err == digest.ErrDigestNotFound { <add> err = fmt.Errorf("No such image: %s", term) <add> } <ide> return "", err <ide> } <ide> return ID(dgst), nil <ide><path>integration-cli/docker_cli_save_load_test.go <ide> func (s *DockerSuite) TestSaveAndLoadRepoFlags(c *check.C) { <ide> c.Assert(before, checker.Equals, after, check.Commentf("inspect is not the same after a save / load")) <ide> } <ide> <add>func (s *DockerSuite) TestSaveWithNoExistImage(c *check.C) { <add> testRequires(c, DaemonIsLinux) <add> <add> imgName := "foobar-non-existing-image" <add> <add> out, _, err := dockerCmdWithError("save", "-o", "test-img.tar", imgName) <add> c.Assert(err, checker.NotNil, check.Commentf("save image should fail for non-existing image")) <add> c.Assert(out, checker.Contains, fmt.Sprintf("No such image: %s", imgName)) <add>} <add> <ide> func (s *DockerSuite) TestSaveMultipleNames(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <ide> repoName := "foobar-save-multi-name-test"
2
PHP
PHP
fix issue with url parsing and /?
b7f6645cec8fddea9318a53c99b138b55b5fb23a
<ide><path>lib/Cake/Network/CakeRequest.php <ide> protected function _url() { <ide> $uri = substr($uri, strlen($base)); <ide> } <ide> if (strpos($uri, '?') !== false) { <del> $uri = parse_url($uri, PHP_URL_PATH); <add> list($uri) = explode('?', $uri, 2); <ide> } <ide> if (empty($uri) || $uri == '/' || $uri == '//') { <ide> return '/'; <ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php <ide> public function testQueryStringParsingFromInputUrl() { <ide> $_GET = array(); <ide> $request = new CakeRequest('some/path?one=something&two=else'); <ide> $expected = array('one' => 'something', 'two' => 'else'); <del> $this->assertEquals($request->query, $expected); <add> $this->assertEquals($expected, $request->query); <ide> $this->assertEquals('some/path?one=something&two=else', $request->url); <ide> <ide> } <ide> <add>/** <add> * Test that named arguments + querystrings are handled correctly. <add> * <add> * @return void <add> */ <add> public function testQueryStringAndNamedParams() { <add> $_SERVER['REQUEST_URI'] = '/tasks/index/page:1?ts=123456'; <add> $request = new CakeRequest(); <add> $this->assertEquals('tasks/index/page:1', $request->url); <add> <add> $_SERVER['REQUEST_URI'] = '/tasks/index/page:1/?ts=123456'; <add> $request = new CakeRequest(); <add> $this->assertEquals('tasks/index/page:1/', $request->url); <add> } <add> <ide> /** <ide> * test addParams() method <ide> * <ide> public function testInputDecodeExtraParams() { <ide> ); <ide> } <ide> <add> <ide> /** <ide> * loadEnvironment method <ide> *
2
Python
Python
fix indentation issue
caf3746678111e906182416603e8f26d7eab1094
<ide><path>src/transformers/benchmark/benchmark.py <ide> def compute_loss_and_backprob_encoder_decoder(): <ide> ) <ide> torch.cuda.reset_max_memory_cached() <ide> <del> # calculate loss and do backpropagation <del> _train() <add> # calculate loss and do backpropagation <add> _train() <ide> elif not self.args.no_tpu and is_torch_tpu_available(): <ide> # tpu <ide> raise NotImplementedError( <ide> def compute_loss_and_backprob_encoder_decoder(): <ide> logger.info( <ide> "Please consider updating PyTorch to version 1.4 to get more accuracy on GPU memory usage" <ide> ) <del> memory = Memory(torch.cuda.max_memory_cached()) <del> memory = Memory(torch.cuda.max_memory_reserved()) <add> memory = Memory(torch.cuda.max_memory_reserved()) <ide> <ide> return memory, summary <ide> else: <ide> def encoder_forward(): <ide> ) <ide> torch.cuda.reset_max_memory_cached() <ide> <del> # run forward <del> _forward() <add> # run forward <add> _forward() <ide> elif not self.args.no_tpu and is_torch_tpu_available(): <ide> # tpu <ide> raise NotImplementedError(
1
Ruby
Ruby
use the -u switch for the `rails server` banner
bcc1207a8ebb730f6a86d1451e6c9089e5bfc89f
<ide><path>railties/lib/rails/commands/server/server_command.rb <ide> def pid <ide> end <ide> <ide> def self.banner(*) <del> "rails server [thin/puma/webrick] [options]" <add> "rails server -u [thin/puma/webrick] [options]" <ide> end <ide> <ide> def prepare_restart
1
Python
Python
fix url to lstm paper
767846e642dc73e421ac426380485fc3348c4f69
<ide><path>keras/layers/recurrent.py <ide> class LSTM(Recurrent): <ide> the linear transformation of the recurrent state. <ide> <ide> # References <del> - [Long short-term memory](http://deeplearning.cs.cmu.edu/pdfs/Hochreiter97_lstm.pdf) (original 1997 paper) <add> - [Long short-term memory](http://www.bioinf.jku.at/publications/older/2604.pdf) (original 1997 paper) <ide> - [Learning to forget: Continual prediction with LSTM](http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015) <ide> - [Supervised sequence labeling with recurrent neural networks](http://www.cs.toronto.edu/~graves/preprint.pdf) <ide> - [A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](http://arxiv.org/abs/1512.05287)
1
Javascript
Javascript
serve worker.js from its actual relative path
8205c681eb214dd8155d4ab05c4189d55a6a9737
<ide><path>src/environment/__tests__/ReactWebWorker-test.js <ide> describe('ReactWebWorker', function() { <ide> var done = false; <ide> var error; <ide> <del> var worker = new Worker('/worker.js'); <add> var worker = new Worker(window.ReactWebWorker_URL || '/src/test/worker.js?_=' + Date.now().toString(36)); <ide> worker.addEventListener('message', function(e) { <ide> var data = JSON.parse(e.data); <ide> if (data.type == 'error') { <ide><path>src/test/worker.js <ide> var global = {}; <ide> importScripts("phantomjs-shims.js"); <ide> <ide> try { <del> importScripts("react.js"); <add> importScripts("../../build/react.js"); <ide> } catch (e) { <ide> postMessage(JSON.stringify({ <ide> type: 'error', <ide><path>test/browser-runner.js <ide> <ide> var cacheBust = '?_=' + Date.now().toString(36); <ide> <add> window.ReactWebWorker_URL = __dirname + '/../src/test/worker.js' + cacheBust; <add> <ide> document.write('<script src="' + __dirname + '/../build/jasmine.js' + cacheBust + '"><\/script>'); <ide> document.write('<script src="' + __dirname + '/../build/react.js' + cacheBust + '"><\/script>'); <ide> document.write('<script src="' + __dirname + '/../build/react-test.js' + cacheBust + '"><\/script>'); <ide><path>test/phantom-harness.js <ide> server.listen(port, function(req, res) { <ide> file = "../build/" + file; <ide> break; <ide> <add> case "src/test/worker.js": <add> file = file.replace('src/test/', ''); <ide> case "phantomjs-shims.js": <ide> case "worker.js": <ide> file = "../src/test/" + file;
4
Ruby
Ruby
add additional test
3bdab156c298572cd540f81e4b2efad1dbcdbdd2
<ide><path>Library/Homebrew/test/cask/artifact/shared_examples/uninstall_zap.rb <ide> }; <ide> EOS <ide> end <add> let(:launchctl_list) do <add> <<~EOS <add> PID Status Label <add> 1111 0 my.fancy.package.service.12345 <add> - 0 com.apple.SafariHistoryServiceAgent <add> - 0 com.apple.progressd <add> 555 0 my.fancy.package.service.test <add> EOS <add> end <ide> <ide> it "searches installed launchctl items" do <ide> expect(subject).to receive(:find_launchctl_with_wildcard) <ide> <ide> subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command) <ide> end <add> <add> it "returns the matching launchctl services" do <add> expect(subject).to receive(:system_command!) <add> .with("/bin/launchctl", args: ["list"]) <add> .and_return(instance_double(SystemCommand::Result, stdout: launchctl_list)) <add> <add> expect(subject.send(:find_launchctl_with_wildcard, <add> "my.fancy.package.service.*")).to eq(["my.fancy.package.service.12345", <add> "my.fancy.package.service.test"]) <add> end <ide> end <ide> <ide> context "using :pkgutil" do
1
Python
Python
fix loss computation in tfbertforpretraining
0094565fc5cbf468d45e0e3cb8a3a4db99fef7be
<ide><path>src/transformers/models/bert/modeling_tf_bert.py <ide> def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor: <ide> loss_fn = tf.keras.losses.SparseCategoricalCrossentropy( <ide> from_logits=True, reduction=tf.keras.losses.Reduction.NONE <ide> ) <add> unmasked_lm_losses = loss_fn(y_true=labels["labels"], y_pred=logits[0]) <ide> # make sure only labels that are not equal to -100 <del> # are taken into account as loss <del> masked_lm_active_loss = tf.not_equal(tf.reshape(tensor=labels["labels"], shape=(-1,)), -100) <del> masked_lm_reduced_logits = tf.boolean_mask( <del> tensor=tf.reshape(tensor=logits[0], shape=(-1, shape_list(logits[0])[2])), <del> mask=masked_lm_active_loss, <del> ) <del> masked_lm_labels = tf.boolean_mask( <del> tensor=tf.reshape(tensor=labels["labels"], shape=(-1,)), mask=masked_lm_active_loss <del> ) <del> next_sentence_active_loss = tf.not_equal(tf.reshape(tensor=labels["next_sentence_label"], shape=(-1,)), -100) <del> next_sentence_reduced_logits = tf.boolean_mask( <del> tensor=tf.reshape(tensor=logits[1], shape=(-1, 2)), mask=next_sentence_active_loss <del> ) <del> next_sentence_label = tf.boolean_mask( <del> tensor=tf.reshape(tensor=labels["next_sentence_label"], shape=(-1,)), mask=next_sentence_active_loss <del> ) <del> masked_lm_loss = loss_fn(y_true=masked_lm_labels, y_pred=masked_lm_reduced_logits) <del> next_sentence_loss = loss_fn(y_true=next_sentence_label, y_pred=next_sentence_reduced_logits) <del> masked_lm_loss = tf.reshape(tensor=masked_lm_loss, shape=(-1, shape_list(next_sentence_loss)[0])) <del> masked_lm_loss = tf.reduce_mean(input_tensor=masked_lm_loss, axis=0) <del> <del> return masked_lm_loss + next_sentence_loss <add> # are taken into account for the loss computation <add> lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype) <add> lm_loss_denominator = tf.reduce_sum(lm_loss_mask, axis=1) <add> masked_lm_losses = tf.math.multiply_no_nan(unmasked_lm_losses, lm_loss_mask) <add> reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses, axis=1) / lm_loss_denominator <add> <add> unmasked_ns_loss = loss_fn(y_true=labels["next_sentence_label"], y_pred=logits[1]) <add> ns_loss_mask = tf.cast(labels["next_sentence_label"] != -100, dtype=unmasked_ns_loss.dtype) <add> # Just zero out samples where label is -100, no reduction <add> masked_ns_loss = tf.math.multiply_no_nan(unmasked_ns_loss, ns_loss_mask) <add> <add> return reduced_masked_lm_loss + masked_ns_loss <ide> <ide> <ide> class TFBertEmbeddings(tf.keras.layers.Layer):
1
Ruby
Ruby
remove gist link from the code
adbe8b18b8eb7b50a2eb5ca925c39b6a3c100cf9
<ide><path>activesupport/lib/active_support/cache/memory_store.rb <ide> def synchronize(&block) # :nodoc: <ide> <ide> protected <ide> <del> # See https://gist.github.com/ssimeonov/6047200 <ide> PER_ENTRY_OVERHEAD = 240 <ide> <ide> def cached_size(key, entry)
1
Python
Python
set version to 2.1.0a3.dev0
c9f6acc564f52687b416189081990bfba157a819
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy-nightly' <del>__version__ = '2.1.0a2' <add>__version__ = '2.1.0a3.dev0' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI' <ide> __email__ = 'contact@explosion.ai' <ide> __license__ = 'MIT' <del>__release__ = True <add>__release__ = False <ide> <ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download' <ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
1
Ruby
Ruby
prioritize tapdependency in parse_string_spec
ac16822a16bc1fb33ca020f26b74e81ff85028e9
<ide><path>Library/Homebrew/dependency_collector.rb <ide> def parse_spec(spec, tags) <ide> end <ide> <ide> def parse_string_spec(spec, tags) <del> if tags.empty? <add> if HOMEBREW_TAP_FORMULA_REGEX === spec <add> TapDependency.new(spec, tags) <add> elsif tags.empty? <ide> Dependency.new(spec, tags) <ide> elsif (tag = tags.first) && LANGUAGE_MODULES.include?(tag) <ide> LanguageModuleDependency.new(tag, spec, tags[1]) <del> elsif HOMEBREW_TAP_FORMULA_REGEX === spec <del> TapDependency.new(spec, tags) <ide> else <ide> Dependency.new(spec, tags) <ide> end
1
Python
Python
move logic seperation as its not longer repetitive
abbb88886bb1cd6013432c70586fbc118d378e27
<ide><path>django/db/models/deletion.py <ide> def sort(self): <ide> self.data = SortedDict([(model, self.data[model]) <ide> for model in sorted_models]) <ide> <del> def send_post_delete_signals(self, model, instances): <del> if model._meta.auto_created: <del> return <del> for obj in instances: <del> signals.post_delete.send( <del> sender=model, instance=obj, using=self.using <del> ) <del> <ide> @force_managed <ide> def delete(self): <ide> # sort instance collections <ide> def delete(self): <ide> query = sql.DeleteQuery(model) <ide> pk_list = [obj.pk for obj in instances] <ide> query.delete_batch(pk_list, self.using) <del> self.send_post_delete_signals(model, instances) <add> <add> if not model._meta.auto_created: <add> for obj in instances: <add> signals.post_delete.send( <add> sender=model, instance=obj, using=self.using <add> ) <ide> <ide> # update collected instances <ide> for model, instances_for_fieldvalues in six.iteritems(self.field_updates):
1
Java
Java
adjust activemq settings in integration tests
b727cdb120dcf08e76b8fd505cb63b37a7220935
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java <ide> public String getSessionId() { <ide> <ide> @Override <ide> public void afterConnected(TcpConnection<byte[]> connection) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Established TCP connection to broker in session=" + this.sessionId); <add> } <ide> this.tcpConnection = connection; <ide> connection.send(MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(this.connectHeaders).build()); <ide> } <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java <ide> import java.util.concurrent.TimeUnit; <ide> <ide> import org.apache.activemq.broker.BrokerService; <add>import org.apache.activemq.store.memory.MemoryPersistenceAdapter; <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.junit.After; <ide> private void startActiveMqBroker() throws Exception { <ide> this.activeMQBroker = new BrokerService(); <ide> this.activeMQBroker.addConnector("stomp://localhost:" + this.port); <ide> this.activeMQBroker.setStartAsync(false); <del> this.activeMQBroker.setDeleteAllMessagesOnStartup(true); <add> this.activeMQBroker.setPersistent(false); <add> this.activeMQBroker.getSystemUsage().getMemoryUsage().setLimit(1024 * 1024 * 5); <add> this.activeMQBroker.getSystemUsage().getTempUsage().setLimit(1024 * 1024 * 5); <ide> this.activeMQBroker.start(); <ide> } <ide>
2
Ruby
Ruby
simplify internal representation of patches
a55e196f5f72ef0b1c829007c9b4a68de5c06ef0
<ide><path>Library/Homebrew/formula.rb <ide> def option name, description=nil <ide> specs.each { |spec| spec.option(name, description) } <ide> end <ide> <del> def patch strip=:p1, io=nil, &block <del> specs.each { |spec| spec.patch(strip, io, &block) } <add> def patch strip=:p1, src=nil, &block <add> specs.each { |spec| spec.patch(strip, src, &block) } <ide> end <ide> <ide> def plist_options options <ide><path>Library/Homebrew/patch.rb <ide> require 'resource' <del>require 'stringio' <ide> require 'erb' <ide> <ide> module Patch <del> def self.create(strip, io, &block) <add> def self.create(strip, src, &block) <ide> case strip <ide> when :DATA <ide> DATAPatch.new(:p1) <del> when IO, StringIO <del> IOPatch.new(strip, :p1) <ide> when String <del> IOPatch.new(StringIO.new(strip), :p1) <add> StringPatch.new(:p1, strip) <ide> when Symbol <del> case io <add> case src <ide> when :DATA <ide> DATAPatch.new(strip) <del> when IO, StringIO <del> IOPatch.new(io, strip) <ide> when String <del> IOPatch.new(StringIO.new(io), strip) <add> StringPatch.new(strip, src) <ide> else <ide> ExternalPatch.new(strip, &block) <ide> end <ide> def self.normalize_legacy_patches(list) <ide> end <ide> end <ide> <del>class IOPatch <add>class EmbeddedPatch <ide> attr_writer :owner <ide> attr_reader :strip <ide> <add> def initialize(strip) <add> @strip = strip <add> end <add> <ide> def external? <ide> false <ide> end <ide> <del> def initialize(io, strip) <del> @io = io <del> @strip = strip <add> def contents <add> raise NotImplementedError <ide> end <ide> <ide> def apply <ide> data = contents.gsub("HOMEBREW_PREFIX", HOMEBREW_PREFIX) <ide> IO.popen("/usr/bin/patch -g 0 -f -#{strip}", "w") { |p| p.write(data) } <ide> raise ErrorDuringExecution, "Applying DATA patch failed" unless $?.success? <del> ensure <del> # IO and StringIO cannot be marshaled, so remove the reference <del> # in case we are indirectly referenced by an exception later. <del> @io = nil <del> end <del> <del> def contents <del> @io.read <ide> end <ide> <ide> def inspect <ide> "#<#{self.class.name}: #{strip.inspect}>" <ide> end <ide> end <ide> <del>class DATAPatch < IOPatch <add>class DATAPatch < EmbeddedPatch <ide> attr_accessor :path <ide> <ide> def initialize(strip) <del> @strip = strip <add> super <ide> @path = nil <ide> end <ide> <ide> def contents <ide> end <ide> end <ide> <add>class StringPatch < EmbeddedPatch <add> def initialize(strip, str) <add> super(strip) <add> @str = str <add> end <add> <add> def contents <add> @str <add> end <add>end <add> <ide> class ExternalPatch <ide> attr_reader :resource, :strip <ide> <ide><path>Library/Homebrew/software_spec.rb <ide> def requirements <ide> dependency_collector.requirements <ide> end <ide> <del> def patch strip=:p1, io=nil, &block <del> patches << Patch.create(strip, io, &block) <add> def patch strip=:p1, src=nil, &block <add> patches << Patch.create(strip, src, &block) <ide> end <ide> <ide> def add_legacy_patches(list) <ide><path>Library/Homebrew/test/test_patch.rb <ide> def test_create_simple <ide> assert_equal :p2, patch.strip <ide> end <ide> <del> def test_create_io <del> patch = Patch.create(:p0, StringIO.new("foo")) <del> assert_kind_of IOPatch, patch <del> refute_predicate patch, :external? <del> assert_equal :p0, patch.strip <del> end <del> <del> def test_create_io_without_strip <del> patch = Patch.create(StringIO.new("foo"), nil) <del> assert_kind_of IOPatch, patch <del> assert_equal :p1, patch.strip <del> end <del> <ide> def test_create_string <ide> patch = Patch.create(:p0, "foo") <del> assert_kind_of IOPatch, patch <add> assert_kind_of StringPatch, patch <ide> assert_equal :p0, patch.strip <ide> end <ide> <ide> def test_create_string_without_strip <ide> patch = Patch.create("foo", nil) <del> assert_kind_of IOPatch, patch <add> assert_kind_of StringPatch, patch <ide> assert_equal :p1, patch.strip <ide> end <ide>
4
Mixed
Python
update language docs [ci skip]
625ce2db8e6edf132f5db2cf28a0737c1bdb8917
<ide><path>spacy/language.py <ide> def pipe_names(self): <ide> <ide> @property <ide> def pipe_labels(self): <del> """Get the labels set by the pipeline components, if available. <add> """Get the labels set by the pipeline components, if available (if <add> the component exposes a labels property). <ide> <ide> RETURNS (dict): Labels keyed by component name. <ide> """ <ide><path>website/docs/api/language.md <ide> per component. <ide> | --------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------- | <ide> | `vocab` | `Vocab` | A container for the lexical types. | <ide> | `tokenizer` | `Tokenizer` | The tokenizer. | <del>| `make_doc` | `lambda text: Doc` | Create a `Doc` object from unicode text. | <add>| `make_doc` | `callable` | Callable that takes a unicode text and returns a `Doc`. | <ide> | `pipeline` | list | List of `(name, component)` tuples describing the current processing pipeline, in order. | <ide> | `pipe_names` <Tag variant="new">2</Tag> | list | List of pipeline component names, in order. | <add>| `pipe_labels` <Tag variant="new">2.2</Tag> | dict | List of labels set by the pipeline components, if available, keyed by component name. | <ide> | `meta` | dict | Custom meta data for the Language class. If a model is loaded, contains meta data of the model. | <ide> | `path` <Tag variant="new">2</Tag> | `Path` | Path to the model data directory, if a model is loaded. Otherwise `None`. | <ide>
2
Text
Text
update nlp.vectors to nlp.vocab.vectors
90c754024f079e0b7842acb826cc253db17c3cb3
<ide><path>website/docs/api/vectors.md <ide> Check whether a key has been mapped to a vector entry in the table. <ide> > <ide> > ```python <ide> > cat_id = nlp.vocab.strings["cat"] <del>> nlp.vectors.add(cat_id, numpy.random.uniform(-1, 1, (300,))) <add>> nlp.vocab.vectors.add(cat_id, numpy.random.uniform(-1, 1, (300,))) <ide> > assert cat_id in vectors <ide> > ``` <ide> <ide> performed in chunks, to avoid consuming too much memory. You can set the <ide> > <ide> > ```python <ide> > queries = numpy.asarray([numpy.random.uniform(-1, 1, (300,))]) <del>> most_similar = nlp.vectors.most_similar(queries, n=10) <add>> most_similar = nlp.vocab.vectors.most_similar(queries, n=10) <ide> > ``` <ide> <ide> | Name | Type | Description |
1
Javascript
Javascript
remove -o- prefix css
58198fc113c9dc30c88b56dd8fc44a30a4c58fee
<ide><path>examples/js/renderers/CSS3DRenderer.js <ide> THREE.CSS3DRenderer = function () { <ide> <ide> cameraElement.style.WebkitTransformStyle = 'preserve-3d'; <ide> cameraElement.style.MozTransformStyle = 'preserve-3d'; <del> cameraElement.style.oTransformStyle = 'preserve-3d'; <ide> cameraElement.style.transformStyle = 'preserve-3d'; <ide> <ide> domElement.appendChild( cameraElement ); <ide> THREE.CSS3DRenderer = function () { <ide> <ide> element.style.WebkitTransform = style; <ide> element.style.MozTransform = style; <del> element.style.oTransform = style; <ide> element.style.transform = style; <ide> <ide> cache.objects[ object.id ] = { style: style }; <ide> THREE.CSS3DRenderer = function () { <ide> <ide> domElement.style.WebkitPerspective = fov + 'px'; <ide> domElement.style.MozPerspective = fov + 'px'; <del> domElement.style.oPerspective = fov + 'px'; <ide> domElement.style.perspective = fov + 'px'; <ide> <ide> cache.camera.fov = fov; <ide> THREE.CSS3DRenderer = function () { <ide> var style = cameraCSSMatrix + <ide> 'translate(' + _widthHalf + 'px,' + _heightHalf + 'px)'; <ide> <del> if ( !isFlatTransform && cache.camera.style !== style ) { <add> if ( ! isFlatTransform && cache.camera.style !== style ) { <ide> <ide> cameraElement.style.WebkitTransform = style; <ide> cameraElement.style.MozTransform = style; <del> cameraElement.style.oTransform = style; <ide> cameraElement.style.transform = style; <ide> <ide> cache.camera.style = style;
1
Java
Java
fix decoding issue in reactor tcpclient
ea274ebc0a355ffb499791a9abf1618b829c5edd
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompReactorNettyCodec.java <ide> */ <ide> package org.springframework.messaging.simp.stomp; <ide> <del>import org.springframework.messaging.tcp.reactor.ReactorNettyCodec; <add>import java.nio.ByteBuffer; <add>import java.util.List; <add> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.tcp.reactor.AbstractNioBufferReactorNettyCodec; <ide> <ide> /** <del> * {@code ReactorNettyCodec} that delegates to {@link StompDecoder} and <del> * {@link StompEncoder}. <add> * Simple delegation to StompDecoder and StompEncoder. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <del>class StompReactorNettyCodec extends ReactorNettyCodec<byte[]> { <add>class StompReactorNettyCodec extends AbstractNioBufferReactorNettyCodec<byte[]> { <add> <add> private final StompDecoder decoder; <add> <add> private final StompEncoder encoder; <add> <ide> <ide> public StompReactorNettyCodec() { <del> this(new StompDecoder(), new StompEncoder()); <add> this(new StompDecoder()); <ide> } <ide> <ide> public StompReactorNettyCodec(StompDecoder decoder) { <ide> this(decoder, new StompEncoder()); <ide> } <ide> <ide> public StompReactorNettyCodec(StompDecoder decoder, StompEncoder encoder) { <del> super(byteBuf -> decoder.decode(byteBuf.nioBuffer()), <del> (byteBuf, message) -> byteBuf.writeBytes(encoder.encode(message))); <add> this.decoder = decoder; <add> this.encoder = encoder; <add> } <add> <add> <add> @Override <add> protected List<Message<byte[]>> decodeInternal(ByteBuffer nioBuffer) { <add> return this.decoder.decode(nioBuffer); <add> } <add> <add> protected ByteBuffer encodeInternal(Message<byte[]> message) { <add> return ByteBuffer.wrap(this.encoder.encode(message)); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/AbstractNioBufferReactorNettyCodec.java <add>/* <add> * Copyright 2002-2016 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.messaging.tcp.reactor; <add> <add>import java.nio.ByteBuffer; <add>import java.util.Collection; <add>import java.util.List; <add> <add>import io.netty.buffer.ByteBuf; <add> <add>import org.springframework.messaging.Message; <add> <add>/** <add> * Convenient base class for {@link ReactorNettyCodec} implementations that need <add> * to work with NIO {@link ByteBuffer}s. <add> * <add> * @author Rossen Stoyanchev <add> * @since 5.0 <add> */ <add>public abstract class AbstractNioBufferReactorNettyCodec<P> implements ReactorNettyCodec<P> { <add> <add> @Override <add> public Collection<Message<P>> decode(ByteBuf inputBuffer) { <add> ByteBuffer nioBuffer = inputBuffer.nioBuffer(); <add> int start = nioBuffer.position(); <add> List<Message<P>> messages = decodeInternal(nioBuffer); <add> inputBuffer.skipBytes(nioBuffer.position() - start); <add> return messages; <add> } <add> <add> protected abstract List<Message<P>> decodeInternal(ByteBuffer nioBuffer); <add> <add> @Override <add> public void encode(Message<P> message, ByteBuf outputBuffer) { <add> outputBuffer.writeBytes(encodeInternal(message)); <add> } <add> <add> protected abstract ByteBuffer encodeInternal(Message<P> message); <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyCodec.java <ide> import io.netty.buffer.ByteBuf; <ide> <ide> import org.springframework.messaging.Message; <del>import org.springframework.util.Assert; <ide> <ide> /** <ide> * Simple holder for a decoding {@link Function} and an encoding <ide> * @author Rossen Stoyanchev <ide> * @since 5.0 <ide> */ <del>public class ReactorNettyCodec<P> { <del> <del> private final Function<? super ByteBuf, ? extends Collection<Message<P>>> decoder; <del> <del> private final BiConsumer<? super ByteBuf, ? super Message<P>> encoder; <del> <del> <del> public ReactorNettyCodec(Function<? super ByteBuf, ? extends Collection<Message<P>>> decoder, <del> BiConsumer<? super ByteBuf, ? super Message<P>> encoder) { <del> <del> Assert.notNull(decoder, "'decoder' is required"); <del> Assert.notNull(encoder, "'encoder' is required"); <del> this.decoder = decoder; <del> this.encoder = encoder; <del> } <del> <del> public Function<? super ByteBuf, ? extends Collection<Message<P>>> getDecoder() { <del> return this.decoder; <del> } <del> <del> public BiConsumer<? super ByteBuf, ? super Message<P>> getEncoder() { <del> return this.encoder; <del> } <add>public interface ReactorNettyCodec<P> { <add> <add> /** <add> * Decode the input {@link ByteBuf} into one or more {@link Message}s. <add> * @param inputBuffer the input buffer to decode from <add> * @return 0 or more decoded messages <add> */ <add> Collection<Message<P>> decode(ByteBuf inputBuffer); <add> <add> /** <add> * Encode the given {@link Message} to the output {@link ByteBuf}. <add> * @param message the message the encode <add> * @param outputBuffer the buffer to write to <add> */ <add> void encode(Message<P> message, ByteBuf outputBuffer); <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyTcpClient.java <ide> <ide> package org.springframework.messaging.tcp.reactor; <ide> <add>import java.util.Collection; <add>import java.util.List; <ide> import java.util.function.BiFunction; <ide> import java.util.function.Consumer; <ide> import java.util.function.Function; <ide> <add>import io.netty.buffer.ByteBuf; <add>import io.netty.channel.ChannelHandlerContext; <ide> import io.netty.channel.group.ChannelGroup; <ide> import io.netty.channel.group.ChannelGroupFuture; <ide> import io.netty.channel.group.DefaultChannelGroup; <add>import io.netty.handler.codec.ByteToMessageDecoder; <ide> import io.netty.util.concurrent.ImmediateEventExecutor; <ide> import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.DirectProcessor; <ide> import reactor.ipc.netty.tcp.TcpClient; <ide> import reactor.util.concurrent.QueueSupplier; <ide> <add>import org.springframework.messaging.Message; <ide> import org.springframework.messaging.tcp.ReconnectStrategy; <ide> import org.springframework.messaging.tcp.TcpConnection; <ide> import org.springframework.messaging.tcp.TcpConnectionHandler; <ide> private class ReactorNettyHandler implements BiFunction<NettyInbound, NettyOutbo <ide> this.connectionHandler = handler; <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> @Override <ide> public Publisher<Void> apply(NettyInbound inbound, NettyOutbound outbound) { <ide> <ide> DirectProcessor<Void> completion = DirectProcessor.create(); <ide> TcpConnection<P> connection = new ReactorNettyTcpConnection<>(inbound, outbound, codec, completion); <ide> scheduler.schedule(() -> connectionHandler.afterConnected(connection)); <ide> <del> inbound.receive() <del> .map(codec.getDecoder()) <add> inbound.context().addDecoder(new StompMessageDecoder<>(codec)); <add> <add> inbound.receiveObject() <add> .cast(Message.class) <ide> .publishOn(scheduler, QueueSupplier.SMALL_BUFFER_SIZE) <del> .flatMapIterable(Function.identity()) <ide> .subscribe( <ide> connectionHandler::handleMessage, <ide> connectionHandler::handleFailure, <ide> public Publisher<Void> apply(NettyInbound inbound, NettyOutbound outbound) { <ide> } <ide> } <ide> <add> private static class StompMessageDecoder<P> extends ByteToMessageDecoder { <add> <add> private final ReactorNettyCodec<P> codec; <add> <add> public StompMessageDecoder(ReactorNettyCodec<P> codec) { <add> this.codec = codec; <add> } <add> <add> @Override <add> protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { <add> Collection<Message<P>> messages = codec.decode(in); <add> out.addAll(messages); <add> } <add> } <add> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyTcpConnection.java <ide> public ReactorNettyTcpConnection(NettyInbound inbound, NettyOutbound outbound, <ide> @Override <ide> public ListenableFuture<Void> send(Message<P> message) { <ide> ByteBuf byteBuf = this.outbound.alloc().buffer(); <del> this.codec.getEncoder().accept(byteBuf, message); <add> this.codec.encode(message, byteBuf); <ide> Mono<Void> sendCompletion = this.outbound.send(Mono.just(byteBuf)).then(); <ide> return new MonoToListenableFutureAdapter<>(sendCompletion); <ide> }
5
Text
Text
recommend queuemicrotask over process.nexttick
ee6c467c8a7b451b4d785f0068f4e130de48ecc1
<ide><path>doc/api/process.md <ide> function definitelyAsync(arg, cb) { <ide> } <ide> ``` <ide> <add>### When to use `queueMicrotask()` vs. `process.nextTick()` <add> <add>The [`queueMicrotask()`][] API is an alternative to `process.nextTick()` that <add>also defers execution of a function using the same microtask queue used to <add>execute the then, catch, and finally handlers of resolved promises. Within <add>Node.js, every time the "next tick queue" is drained, the microtask queue <add>is drained immediately after. <add> <add>```js <add>Promise.resolve().then(() => console.log(2)); <add>queueMicrotask(() => console.log(3)); <add>process.nextTick(() => console.log(1)); <add>// Output: <add>// 1 <add>// 2 <add>// 3 <add>``` <add> <add>For *most* userland use cases, the `queueMicrotask()` API provides a portable <add>and reliable mechanism for deferring execution that works across multiple <add>JavaScript platform environments and should be favored over `process.nextTick()`. <add>In simple scenarios, `queueMicrotask()` can be a drop-in replacement for <add>`process.nextTick()`. <add> <add>```js <add>console.log('start'); <add>queueMicrotask(() => { <add> console.log('microtask callback'); <add>}); <add>console.log('scheduled'); <add>// Output: <add>// start <add>// scheduled <add>// microtask callback <add>``` <add> <add>One note-worthy difference between the two APIs is that `process.nextTick()` <add>allows specifying additional values that will be passed as arguments to the <add>deferred function when it is called. Achieving the same result with <add>`queueMicrotask()` requires using either a closure or a bound function: <add> <add>```js <add>function deferred(a, b) { <add> console.log('microtask', a + b); <add>} <add> <add>console.log('start'); <add>queueMicrotask(deferred.bind(undefined, 1, 2)); <add>console.log('scheduled'); <add>// Output: <add>// start <add>// scheduled <add>// microtask 3 <add>``` <add> <add>There are minor differences in the way errors raised from within the next tick <add>queue and microtask queue are handled. Errors thrown within a queued microtask <add>callback should be handled within the queued callback when possible. If they are <add>not, the `process.on('uncaughtException')` event handler can be used to capture <add>and handle the errors. <add> <add>When in doubt, unless the specific capabilities of `process.nextTick()` are <add>needed, use `queueMicrotask()`. <add> <ide> ## `process.noDeprecation` <ide> <!-- YAML <ide> added: v0.8.0 <ide> cases: <ide> [`process.kill()`]: #process_process_kill_pid_signal <ide> [`process.setUncaughtExceptionCaptureCallback()`]: process.md#process_process_setuncaughtexceptioncapturecallback_fn <ide> [`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch <add>[`queueMicrotask()`]: globals.md#globals_queuemicrotask_callback <ide> [`readable.read()`]: stream.md#stream_readable_read_size <ide> [`require()`]: globals.md#globals_require <ide> [`require.main`]: modules.md#modules_accessing_the_main_module
1
Python
Python
manage unicode decode error on windows os
7ce0383eae384957eb97032179d6da9f51c0f230
<ide><path>glances/plugins/glances_fs.py <ide> def __update__(self): <ide> # Grab the stats using the PsUtil disk_partitions <ide> # If 'all'=False return physical devices only (e.g. hard disks, cd-rom drives, USB keys) <ide> # and ignore all others (e.g. memory partitions such as /dev/shm) <del> fs_stat = psutil.disk_partitions(all=False) <add> try: <add> fs_stat = psutil.disk_partitions(all=False) <add> except UnicodeDecodeError: <add> return [] <add> <add> # Loop over fs <ide> for fs in range(len(fs_stat)): <ide> fs_current = {} <ide> fs_current['device_name'] = fs_stat[fs].device <ide><path>glances/plugins/glances_network.py <ide> def update(self): <ide> """ <ide> <ide> # Grab network interface stat using the PsUtil net_io_counter method <del> netiocounters = psutil.net_io_counters(pernic=True) <add> try: <add> netiocounters = psutil.net_io_counters(pernic=True) <add> except UnicodeDecodeError: <add> return [] <ide> <ide> # Previous network interface stats are stored in the network_old variable <ide> network = []
2
PHP
PHP
move tests to the class they belong with
5489813a20ead867654397b2b37474f66c8e727d
<ide><path>src/ORM/ResultSet.php <ide> protected function _groupResult($row) { <ide> } <ide> <ide> if (!$hasData) { <del> continue; <add> $results[$alias] = null; <ide> } <ide> } <ide> <del> if ($this->_hydrate && $assoc['canBeJoined']) { <add> if ($this->_hydrate && $results[$alias] !== null && $assoc['canBeJoined']) { <ide> $entity = new $assoc['entityClass']($results[$alias], $options); <ide> $entity->clean(); <ide> $results[$alias] = $entity; <ide><path>tests/TestCase/ORM/Association/BelongsToTest.php <ide> public function testAttachToBeforeFindExtraOptions() { <ide> }]); <ide> } <ide> <del>/** <del> * Test that eagerLoader leaves empty associations unpopulated. <del> * <del> * @return void <del> */ <del> public function testEagerLoaderLeavesEmptyAssocation() { <del> $this->loadFixtures('Article', 'Comment'); <del> $comments = TableRegistry::get('Comments'); <del> $comments->belongsTo('Articles'); <del> <del> // Clear the articles table so we can trigger an empty belongsTo <del> $articles = TableRegistry::get('Articles'); <del> $articles->deleteAll([]); <del> <del> $comment = $comments->get(1, ['contain' => ['Articles']]); <del> $this->assertNull($comment->article); <del> } <del> <ide> } <ide><path>tests/TestCase/ORM/Association/HasOneTest.php <ide> */ <ide> class HasOneTest extends \Cake\TestSuite\TestCase { <ide> <del>/** <del> * Fixtures to use. <del> * <del> * @var array <del> */ <del> public $fixtures = ['core.article', 'core.comment']; <del> <del>/** <del> * Don't autoload fixtures as most tests uses mocks. <del> * <del> * @var bool <del> */ <del> public $autoFixture = false; <del> <ide> /** <ide> * Set up <ide> * <ide> public function testAttachToBeforeFindExtraOptions() { <ide> }]); <ide> } <ide> <del>/** <del> * Test that eagerLoader leaves empty associations unpopulated. <del> * <del> * @return void <del> */ <del> public function testEagerLoaderLeavesEmptyAssocation() { <del> $this->loadFixtures('Article', 'Comment'); <del> $articles = TableRegistry::get('Articles'); <del> $articles->hasOne('Comments'); <del> <del> // Clear the comments table so we can trigger an empty hasOne. <del> $comments = TableRegistry::get('Comments'); <del> $comments->deleteAll([]); <del> <del> $article = $articles->get(1, ['contain' => ['Comments']]); <del> $this->assertNull($article->comment); <del> } <del> <ide> } <ide><path>tests/TestCase/ORM/ResultSetTest.php <ide> use Cake\ORM\Query; <ide> use Cake\ORM\ResultSet; <ide> use Cake\ORM\Table; <add>use Cake\ORM\TableRegistry; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> * ResultSet test case. <ide> */ <ide> class ResultSetTest extends TestCase { <ide> <del> public $fixtures = ['core.article']; <add> public $fixtures = ['core.article', 'core.comment']; <ide> <ide> /** <ide> * setup <ide> public function testDebugInfo() { <ide> $this->assertSame($expected, $results->__debugInfo()); <ide> } <ide> <add>/** <add> * Test that eagerLoader leaves empty associations unpopulated. <add> * <add> * @return void <add> */ <add> public function testBelongsToEagerLoaderLeavesEmptyAssocation() { <add> $comments = TableRegistry::get('Comments'); <add> $comments->belongsTo('Articles'); <add> <add> // Clear the articles table so we can trigger an empty belongsTo <add> $this->table->deleteAll([]); <add> <add> $comment = $comments->find()->where(['Comments.id' => 1]) <add> ->contain(['Articles']) <add> ->hydrate(false) <add> ->first(); <add> $this->assertEquals(1, $comment['id']); <add> $this->assertNotEmpty($comment['comment']); <add> $this->assertNull($comment['article']); <add> <add> $comment = $comments->get(1, ['contain' => ['Articles']]); <add> $this->assertNull($comment->article); <add> $this->assertEquals(1, $comment->id); <add> $this->assertNotEmpty($comment->comment); <add> } <add> <add>/** <add> * Test that eagerLoader leaves empty associations unpopulated. <add> * <add> * @return void <add> */ <add> public function testHasOneEagerLoaderLeavesEmptyAssocation() { <add> $this->table->hasOne('Comments'); <add> <add> // Clear the comments table so we can trigger an empty hasOne. <add> $comments = TableRegistry::get('Comments'); <add> $comments->deleteAll([]); <add> <add> $article = $this->table->get(1, ['contain' => ['Comments']]); <add> $this->assertNull($article->comment); <add> $this->assertEquals(1, $article->id); <add> $this->assertNotEmpty($article->title); <add> <add> $article = $this->table->find()->where(['Articles.id' => 1]) <add> ->contain(['Comments']) <add> ->hydrate(false) <add> ->first(); <add> $this->assertNull($article['comment']); <add> $this->assertEquals(1, $article['id']); <add> $this->assertNotEmpty($article['title']); <add> } <add> <ide> }
4
Javascript
Javascript
add option to exclude error params from url
03a4782a35e036a6b1b4fc8137fae58f73f3bb6f
<ide><path>src/minErr.js <ide> */ <ide> <ide> var minErrConfig = { <del> objectMaxDepth: 5 <add> objectMaxDepth: 5, <add> urlErrorParamsEnabled: true <ide> }; <ide> <ide> /** <ide> var minErrConfig = { <ide> * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a <ide> * non-positive or non-numeric value, removes the max depth limit. <ide> * Default: 5 <add> * <add> * * `urlErrorParamsEnabled` **{Boolean}** - Specifies wether the generated error url will <add> * contain the parameters of the thrown error. Disabling the parameters can be useful if the <add> * generated error url is very long. <add> * <add> * Default: true. When used without argument, it returns the current value. <ide> */ <ide> function errorHandlingConfig(config) { <ide> if (isObject(config)) { <ide> if (isDefined(config.objectMaxDepth)) { <ide> minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN; <ide> } <add> if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) { <add> minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled; <add> } <ide> } else { <ide> return minErrConfig; <ide> } <ide> function isValidObjectMaxDepth(maxDepth) { <ide> return isNumber(maxDepth) && maxDepth > 0; <ide> } <ide> <add> <ide> /** <ide> * @description <ide> * <ide> function minErr(module, ErrorConstructor) { <ide> <ide> message += '\n' + url + (module ? module + '/' : '') + code; <ide> <del> for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { <del> message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]); <add> if (minErrConfig.urlErrorParamsEnabled) { <add> for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { <add> message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]); <add> } <ide> } <ide> <ide> return new ErrorConstructor(message); <ide><path>test/minErrSpec.js <ide> <ide> describe('errors', function() { <ide> var originalObjectMaxDepthInErrorMessage = minErrConfig.objectMaxDepth; <add> var originalUrlErrorParamsEnabled = minErrConfig.urlErrorParamsEnabled; <ide> <ide> afterEach(function() { <ide> minErrConfig.objectMaxDepth = originalObjectMaxDepthInErrorMessage; <add> minErrConfig.urlErrorParamsEnabled = originalUrlErrorParamsEnabled; <ide> }); <ide> <ide> describe('errorHandlingConfig', function() { <del> it('should get default objectMaxDepth', function() { <del> expect(errorHandlingConfig().objectMaxDepth).toBe(5); <del> }); <add> describe('objectMaxDepth',function() { <add> it('should get default objectMaxDepth', function() { <add> expect(errorHandlingConfig().objectMaxDepth).toBe(5); <add> }); <add> <add> it('should set objectMaxDepth', function() { <add> errorHandlingConfig({objectMaxDepth: 3}); <add> expect(errorHandlingConfig().objectMaxDepth).toBe(3); <add> }); <ide> <del> it('should set objectMaxDepth', function() { <del> errorHandlingConfig({objectMaxDepth: 3}); <del> expect(errorHandlingConfig().objectMaxDepth).toBe(3); <add> it('should not change objectMaxDepth when undefined is supplied', function() { <add> errorHandlingConfig({objectMaxDepth: undefined}); <add> expect(errorHandlingConfig().objectMaxDepth).toBe(originalObjectMaxDepthInErrorMessage); <add> }); <add> <add> they('should set objectMaxDepth to NaN when $prop is supplied', <add> [NaN, null, true, false, -1, 0], function(maxDepth) { <add> errorHandlingConfig({objectMaxDepth: maxDepth}); <add> expect(errorHandlingConfig().objectMaxDepth).toBeNaN(); <add> } <add> ); <ide> }); <ide> <del> it('should not change objectMaxDepth when undefined is supplied', function() { <del> errorHandlingConfig({objectMaxDepth: undefined}); <del> expect(errorHandlingConfig().objectMaxDepth).toBe(originalObjectMaxDepthInErrorMessage); <add> <add> describe('urlErrorParamsEnabled',function() { <add> <add> it('should get default urlErrorParamsEnabled', function() { <add> expect(errorHandlingConfig().urlErrorParamsEnabled).toBe(true); <add> }); <add> <add> it('should set urlErrorParamsEnabled', function() { <add> errorHandlingConfig({urlErrorParamsEnabled: false}); <add> expect(errorHandlingConfig().urlErrorParamsEnabled).toBe(false); <add> errorHandlingConfig({urlErrorParamsEnabled: true}); <add> expect(errorHandlingConfig().urlErrorParamsEnabled).toBe(true); <add> }); <add> <add> it('should not change its value when non-boolean is supplied', function() { <add> errorHandlingConfig({urlErrorParamsEnabled: 123}); <add> expect(errorHandlingConfig().urlErrorParamsEnabled).toBe(originalUrlErrorParamsEnabled); <add> }); <ide> }); <ide> <del> they('should set objectMaxDepth to NaN when $prop is supplied', <del> [NaN, null, true, false, -1, 0], function(maxDepth) { <del> errorHandlingConfig({objectMaxDepth: maxDepth}); <del> expect(errorHandlingConfig().objectMaxDepth).toBeNaN(); <del> } <del> ); <ide> }); <ide> <ide> describe('minErr', function() { <ide> describe('errors', function() { <ide> .toMatch(/^[\s\S]*\?p0=a&p1=b&p2=value%20with%20space$/); <ide> }); <ide> <del> <ide> it('should strip error reference urls from the error message parameters', function() { <ide> var firstError = testError('firstcode', 'longer string and so on'); <ide> <ide> describe('errors', function() { <ide> '%3A%2F%2Ferrors.angularjs.org%2F%22NG_VERSION_FULL%22%2Ftest%2Ffirstcode'); <ide> }); <ide> <add> it('should not generate URL query parameters when urlErrorParamsEnabled is false', function() { <add> <add> errorHandlingConfig({urlErrorParamsEnabled: false}); <add> <add> expect(testError('acode', 'aproblem', 'a', 'b', 'c').message).toBe('[test:acode] aproblem\n' + <add> 'https://errors.angularjs.org/"NG_VERSION_FULL"/test/acode'); <add> }); <add> <ide> }); <ide> });
2
PHP
PHP
apply fixes from styleci
391d7d755c3678ab67c196c7a225176d4f0d8d41
<ide><path>src/Illuminate/Database/Schema/Grammars/RenameColumn.php <ide> protected static function getRenamedDiff($grammar, Blueprint $blueprint, Fluent <ide> protected static function setRenamedColumns(TableDiff $tableDiff, Fluent $command, Column $column) <ide> { <ide> $tableDiff->renamedColumns = [ <del> $command->from => new Column($command->to, $column->getType(), $column->toArray()) <add> $command->from => new Column($command->to, $column->getType(), $column->toArray()), <ide> ]; <ide> <ide> return $tableDiff;
1
Python
Python
remove doc prefix for version switcher
180d56b00481e99ab62d175a50c73e7bb8f77f1b
<ide><path>doc/source/conf.py <ide> def setup(app): <ide> elif ".dev" in version: <ide> switcher_version = "devdocs" <ide> else: <del> switcher_version = f"doc/{version}" <add> switcher_version = f"{version}" <ide> <ide> html_theme_options = { <ide> "github_url": "https://github.com/numpy/numpy",
1
Javascript
Javascript
execute backend challenges
d2618df4f3f030b45002472af253623299421acd
<ide><path>client/src/templates/Challenges/redux/execute-challenge-epic.js <ide> import { <ide> createMainFramer <ide> } from '../utils/frame.js'; <ide> <del>import { backend } from '../../../../utils/challengeTypes'; <add>import { challengeTypes } from '../../../../utils/challengeTypes'; <ide> <ide> const executeDebounceTimeout = 750; <ide> <ide> function executeChallengeEpic(action$, state$, { document }) { <ide> const state = state$.value; <ide> const { challengeType } = challengeMetaSelector(state); <ide> const build = <del> challengeType === backend ? buildBackendChallenge : buildFromFiles; <add> challengeType === challengeTypes.backend <add> ? buildBackendChallenge <add> : buildFromFiles; <ide> return build(state).pipe( <ide> tap(frameTests), <ide> ignoreElements(),
1
PHP
PHP
fix session handling of booleans
aa9d374c8451576356b792c193eceefc8d0a96fa
<ide><path>src/Illuminate/Session/Store.php <ide> protected function ageFlashData() <ide> */ <ide> public function get($name, $default = null) <ide> { <del> return parent::get($name) ?: value($default); <add> $value = parent::get($name); <add> <add> return is_null($value) ? value($default) : $value; <ide> } <ide> <ide> /**
1
Text
Text
improve best practices in onboarding-extras
536190f1747a1085c2dd208d0eed090f5ee32da0
<ide><path>doc/onboarding-extras.md <ide> to update from nodejs/node: <ide> * `git remote update -p` OR `git fetch --all` (I prefer the former) <ide> * `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`) <ide> <del>## best practices <add>## Best practices <ide> <del>* commit often, out to your github fork (origin), open a PR <del>* when making PRs make sure to spend time on the description: <del> * every moment you spend writing a good description quarters the amount of <del> time it takes to understand your code. <del>* usually prefer to only squash at the *end* of your work, depends on the change <add>* When making PRs, spend time writing a thorough description. <add>* Usually only squash at the end of your work.
1
Ruby
Ruby
add test for type aliases
a87690b02c0d1b4387974114625696e7e113080f
<ide><path>actionpack/test/dispatch/mime_type_test.rb <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> end <ide> end <ide> <add> test "custom type with type aliases" do <add> begin <add> Mime::Type.register "text/foobar", :foobar, ["text/foo", "text/bar"] <add> %w[text/foobar text/foo text/bar].each do |type| <add> assert_equal Mime::FOOBAR, type <add> end <add> ensure <add> Mime::Type.unregister(:FOOBAR) <add> end <add> end <add> <ide> test "custom type with extension aliases" do <ide> begin <ide> Mime::Type.register "text/foobar", :foobar, [], [:foo, "bar"]
1
Go
Go
implement marshal/unmarshall for minversion
4539e7f0eb60720ab506500bf0829182ec183d28
<ide><path>profiles/seccomp/default_linux.go <ide> func DefaultProfile() *Seccomp { <ide> Names: []string{"ptrace"}, <ide> Action: specs.ActAllow, <ide> Includes: Filter{ <del> MinKernel: "4.8", <add> MinKernel: &KernelVersion{4, 8}, <ide> }, <ide> }, <ide> { <ide><path>profiles/seccomp/kernel_linux.go <ide> import ( <ide> "golang.org/x/sys/unix" <ide> ) <ide> <del>// kernelVersion holds information about the kernel. <del>type kernelVersion struct { <del> kernel uint // Version of the kernel (i.e., the "4" in "4.1.2-generic") <del> major uint // Major revision of the kernel (i.e., the "1" in "4.1.2-generic") <del>} <del> <ide> var ( <del> currentKernelVersion *kernelVersion <add> currentKernelVersion *KernelVersion <ide> kernelVersionError error <ide> once sync.Once <ide> ) <ide> <ide> // getKernelVersion gets the current kernel version. <del>func getKernelVersion() (*kernelVersion, error) { <add>func getKernelVersion() (*KernelVersion, error) { <ide> once.Do(func() { <ide> var uts unix.Utsname <ide> if err := unix.Uname(&uts); err != nil { <ide> func getKernelVersion() (*kernelVersion, error) { <ide> return currentKernelVersion, kernelVersionError <ide> } <ide> <del>// parseRelease parses a string and creates a kernelVersion based on it. <del>func parseRelease(release string) (*kernelVersion, error) { <del> var version = kernelVersion{} <add>// parseRelease parses a string and creates a KernelVersion based on it. <add>func parseRelease(release string) (*KernelVersion, error) { <add> var version = KernelVersion{} <ide> <ide> // We're only make sure we get the "kernel" and "major revision". Sometimes we have <ide> // 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64. <del> _, err := fmt.Sscanf(release, "%d.%d", &version.kernel, &version.major) <add> _, err := fmt.Sscanf(release, "%d.%d", &version.Kernel, &version.Major) <ide> if err != nil { <ide> return nil, fmt.Errorf("failed to parse kernel version %q: %w", release, err) <ide> } <ide> func parseRelease(release string) (*kernelVersion, error) { <ide> // equal to the given kernel version v. Only "kernel version" and "major revision" <ide> // can be specified (e.g., "3.12") and will be taken into account, which means <ide> // that 3.12.25-gentoo and 3.12-1-amd64 are considered equal (kernel: 3, major: 12). <del>func kernelGreaterEqualThan(v string) (bool, error) { <del> minVersion, err := parseRelease(v) <del> if err != nil { <del> return false, err <del> } <add>func kernelGreaterEqualThan(minVersion KernelVersion) (bool, error) { <ide> kv, err := getKernelVersion() <ide> if err != nil { <ide> return false, err <ide> } <del> if kv.kernel > minVersion.kernel { <add> if kv.Kernel > minVersion.Kernel { <ide> return true, nil <ide> } <del> if kv.kernel == minVersion.kernel && kv.major >= minVersion.major { <add> if kv.Kernel == minVersion.Kernel && kv.Major >= minVersion.Major { <ide> return true, nil <ide> } <ide> return false, nil <ide><path>profiles/seccomp/kernel_linux_test.go <ide> func TestGetKernelVersion(t *testing.T) { <ide> if version == nil { <ide> t.Fatal("version is nil") <ide> } <del> if version.kernel == 0 { <add> if version.Kernel == 0 { <ide> t.Fatal("no kernel version") <ide> } <ide> } <ide> func TestGetKernelVersion(t *testing.T) { <ide> func TestParseRelease(t *testing.T) { <ide> tests := []struct { <ide> in string <del> out kernelVersion <add> out KernelVersion <ide> expectedErr error <ide> }{ <del> {in: "3.8", out: kernelVersion{kernel: 3, major: 8}}, <del> {in: "3.8.0", out: kernelVersion{kernel: 3, major: 8}}, <del> {in: "3.8.0-19-generic", out: kernelVersion{kernel: 3, major: 8}}, <del> {in: "3.4.54.longterm-1", out: kernelVersion{kernel: 3, major: 4}}, <del> {in: "3.10.0-862.2.3.el7.x86_64", out: kernelVersion{kernel: 3, major: 10}}, <del> {in: "3.12.8tag", out: kernelVersion{kernel: 3, major: 12}}, <del> {in: "3.12-1-amd64", out: kernelVersion{kernel: 3, major: 12}}, <del> {in: "3.12foobar", out: kernelVersion{kernel: 3, major: 12}}, <del> {in: "99.999.999-19-generic", out: kernelVersion{kernel: 99, major: 999}}, <add> {in: "3.8", out: KernelVersion{Kernel: 3, Major: 8}}, <add> {in: "3.8.0", out: KernelVersion{Kernel: 3, Major: 8}}, <add> {in: "3.8.0-19-generic", out: KernelVersion{Kernel: 3, Major: 8}}, <add> {in: "3.4.54.longterm-1", out: KernelVersion{Kernel: 3, Major: 4}}, <add> {in: "3.10.0-862.2.3.el7.x86_64", out: KernelVersion{Kernel: 3, Major: 10}}, <add> {in: "3.12.8tag", out: KernelVersion{Kernel: 3, Major: 12}}, <add> {in: "3.12-1-amd64", out: KernelVersion{Kernel: 3, Major: 12}}, <add> {in: "3.12foobar", out: KernelVersion{Kernel: 3, Major: 12}}, <add> {in: "99.999.999-19-generic", out: KernelVersion{Kernel: 99, Major: 999}}, <add> {in: "", expectedErr: fmt.Errorf(`failed to parse kernel version "": EOF`)}, <ide> {in: "3", expectedErr: fmt.Errorf(`failed to parse kernel version "3": unexpected EOF`)}, <ide> {in: "3.", expectedErr: fmt.Errorf(`failed to parse kernel version "3.": EOF`)}, <ide> {in: "3a", expectedErr: fmt.Errorf(`failed to parse kernel version "3a": input does not match format`)}, <ide> func TestParseRelease(t *testing.T) { <ide> if version == nil { <ide> t.Fatal("version is nil") <ide> } <del> if version.kernel != tc.out.kernel || version.major != tc.out.major { <del> t.Fatalf("expected: %d.%d, got: %d.%d", tc.out.kernel, tc.out.major, version.kernel, version.major) <add> if version.Kernel != tc.out.Kernel || version.Major != tc.out.Major { <add> t.Fatalf("expected: %d.%d, got: %d.%d", tc.out.Kernel, tc.out.Major, version.Kernel, version.Major) <ide> } <ide> }) <ide> } <ide> func TestKernelGreaterEqualThan(t *testing.T) { <ide> <ide> tests := []struct { <ide> doc string <del> in string <add> in KernelVersion <ide> expected bool <ide> }{ <ide> { <ide> doc: "same version", <del> in: fmt.Sprintf("%d.%d", v.kernel, v.major), <add> in: KernelVersion{v.Kernel, v.Major}, <ide> expected: true, <ide> }, <ide> { <ide> doc: "kernel minus one", <del> in: fmt.Sprintf("%d.%d", v.kernel-1, v.major), <add> in: KernelVersion{v.Kernel - 1, v.Major}, <ide> expected: true, <ide> }, <ide> { <ide> doc: "kernel plus one", <del> in: fmt.Sprintf("%d.%d", v.kernel+1, v.major), <add> in: KernelVersion{v.Kernel + 1, v.Major}, <ide> expected: false, <ide> }, <ide> { <ide> doc: "major plus one", <del> in: fmt.Sprintf("%d.%d", v.kernel, v.major+1), <add> in: KernelVersion{v.Kernel, v.Major + 1}, <ide> expected: false, <ide> }, <ide> } <ide> for _, tc := range tests { <ide> tc := tc <del> t.Run(tc.doc+": "+tc.in, func(t *testing.T) { <add> t.Run(tc.doc+": "+tc.in.String(), func(t *testing.T) { <ide> ok, err := kernelGreaterEqualThan(tc.in) <ide> if err != nil { <ide> t.Fatal("unexpected error:", err) <ide><path>profiles/seccomp/seccomp.go <ide> package seccomp // import "github.com/docker/docker/profiles/seccomp" <ide> <del>import "github.com/opencontainers/runtime-spec/specs-go" <add>import ( <add> "encoding/json" <add> "fmt" <add> "strconv" <add> "strings" <add> <add> "github.com/opencontainers/runtime-spec/specs-go" <add>) <ide> <ide> // Seccomp represents the config for a seccomp profile for syscall restriction. <ide> type Seccomp struct { <ide> type Filter struct { <ide> // When matching the kernel version of the host, minor revisions, and distro- <ide> // specific suffixes are ignored, which means that "3.12.25-gentoo", "3.12-1-amd64", <ide> // "3.12", and "3.12-rc5" are considered equal (kernel 3, major revision 12). <del> MinKernel string `json:"minKernel,omitempty"` <add> MinKernel *KernelVersion `json:"minKernel,omitempty"` <ide> } <ide> <ide> // Syscall is used to match a group of syscalls in Seccomp <ide> type Syscall struct { <ide> Includes Filter `json:"includes"` <ide> Excludes Filter `json:"excludes"` <ide> } <add> <add>// KernelVersion holds information about the kernel. <add>type KernelVersion struct { <add> Kernel uint64 // Version of the Kernel (i.e., the "4" in "4.1.2-generic") <add> Major uint64 // Major revision of the Kernel (i.e., the "1" in "4.1.2-generic") <add>} <add> <add>// String implements fmt.Stringer for KernelVersion <add>func (k *KernelVersion) String() string { <add> if k.Kernel > 0 || k.Major > 0 { <add> return fmt.Sprintf("%d.%d", k.Kernel, k.Major) <add> } <add> return "" <add>} <add> <add>// MarshalJSON implements json.Unmarshaler for KernelVersion <add>func (k *KernelVersion) MarshalJSON() ([]byte, error) { <add> return json.Marshal(k.String()) <add>} <add> <add>// UnmarshalJSON implements json.Marshaler for KernelVersion <add>func (k *KernelVersion) UnmarshalJSON(version []byte) error { <add> var ( <add> ver string <add> err error <add> ) <add> <add> // make sure we have a string <add> if err = json.Unmarshal(version, &ver); err != nil { <add> return fmt.Errorf(`invalid kernel version: %s, expected "<kernel>.<major>": %v`, string(version), err) <add> } <add> if ver == "" { <add> return nil <add> } <add> parts := strings.SplitN(ver, ".", 3) <add> if len(parts) != 2 { <add> return fmt.Errorf(`invalid kernel version: %s, expected "<kernel>.<major>"`, string(version)) <add> } <add> if k.Kernel, err = strconv.ParseUint(parts[0], 10, 8); err != nil { <add> return fmt.Errorf(`invalid kernel version: %s, expected "<kernel>.<major>": %v`, string(version), err) <add> } <add> if k.Major, err = strconv.ParseUint(parts[1], 10, 8); err != nil { <add> return fmt.Errorf(`invalid kernel version: %s, expected "<kernel>.<major>": %v`, string(version), err) <add> } <add> if k.Kernel == 0 && k.Major == 0 { <add> return fmt.Errorf(`invalid kernel version: %s, expected "<kernel>.<major>": version cannot be 0.0`, string(version)) <add> } <add> return nil <add>} <ide><path>profiles/seccomp/seccomp_linux.go <ide> Loop: <ide> } <ide> } <ide> } <del> if call.Excludes.MinKernel != "" { <del> if ok, err := kernelGreaterEqualThan(call.Excludes.MinKernel); err != nil { <add> if call.Excludes.MinKernel != nil { <add> if ok, err := kernelGreaterEqualThan(*call.Excludes.MinKernel); err != nil { <ide> return nil, err <ide> } else if ok { <ide> continue Loop <ide> Loop: <ide> } <ide> } <ide> } <del> if call.Includes.MinKernel != "" { <del> if ok, err := kernelGreaterEqualThan(call.Includes.MinKernel); err != nil { <add> if call.Includes.MinKernel != nil { <add> if ok, err := kernelGreaterEqualThan(*call.Includes.MinKernel); err != nil { <ide> return nil, err <ide> } else if !ok { <ide> continue Loop <ide><path>profiles/seccomp/seccomp_test.go <ide> package seccomp // import "github.com/docker/docker/profiles/seccomp" <ide> import ( <ide> "encoding/json" <ide> "io/ioutil" <add> "strings" <ide> "testing" <ide> <ide> "github.com/opencontainers/runtime-spec/specs-go" <ide> func TestUnmarshalDefaultProfile(t *testing.T) { <ide> assert.DeepEqual(t, expected.Syscalls, profile.Syscalls) <ide> } <ide> <add>func TestMarshalUnmarshalFilter(t *testing.T) { <add> t.Parallel() <add> tests := []struct { <add> in string <add> out string <add> error bool <add> }{ <add> {in: `{"arches":["s390x"],"minKernel":3}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":3.12}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":true}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":"0.0"}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":"3"}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":".3"}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":"3."}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":"true"}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":"3.12.1\""}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":"4.15abc"}`, error: true}, <add> {in: `{"arches":["s390x"],"minKernel":null}`, out: `{"arches":["s390x"]}`}, <add> {in: `{"arches":["s390x"],"minKernel":""}`, out: `{"arches":["s390x"],"minKernel":""}`}, // FIXME: try to fix omitempty for this <add> {in: `{"arches":["s390x"],"minKernel":"0.5"}`, out: `{"arches":["s390x"],"minKernel":"0.5"}`}, <add> {in: `{"arches":["s390x"],"minKernel":"0.50"}`, out: `{"arches":["s390x"],"minKernel":"0.50"}`}, <add> {in: `{"arches":["s390x"],"minKernel":"5.0"}`, out: `{"arches":["s390x"],"minKernel":"5.0"}`}, <add> {in: `{"arches":["s390x"],"minKernel":"50.0"}`, out: `{"arches":["s390x"],"minKernel":"50.0"}`}, <add> {in: `{"arches":["s390x"],"minKernel":"4.15"}`, out: `{"arches":["s390x"],"minKernel":"4.15"}`}, <add> } <add> for _, tc := range tests { <add> tc := tc <add> t.Run(tc.in, func(t *testing.T) { <add> var filter Filter <add> err := json.Unmarshal([]byte(tc.in), &filter) <add> if tc.error { <add> if err == nil { <add> t.Fatal("expected an error") <add> } else if !strings.Contains(err.Error(), "invalid kernel version") { <add> t.Fatal("unexpected error:", err) <add> } <add> return <add> } <add> if err != nil { <add> t.Fatal(err) <add> } <add> out, err := json.Marshal(filter) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if string(out) != tc.out { <add> t.Fatalf("expected %s, got %s", tc.out, string(out)) <add> } <add> }) <add> } <add>} <add> <ide> func TestLoadConditional(t *testing.T) { <ide> f, err := ioutil.ReadFile("fixtures/conditional_include.json") <ide> if err != nil {
6
PHP
PHP
apply fixes from styleci
9c96b4636848a80ca81831b3672b06e3451486aa
<ide><path>src/Illuminate/Collections/EnumeratesValues.php <ide> use Exception; <ide> use Illuminate\Contracts\Support\Arrayable; <ide> use Illuminate\Contracts\Support\Jsonable; <del>use Illuminate\Collections\Arr; <del>use Illuminate\Collections\Enumerable; <del>use Illuminate\Collections\HigherOrderCollectionProxy; <ide> use JsonSerializable; <ide> use Symfony\Component\VarDumper\VarDumper; <ide> use Traversable; <ide><path>src/Illuminate/Support/Collection.php <ide> class Collection extends BaseCollection <ide> */ <ide> public function collect() <ide> { <del> return new Collection($this->all()); <add> return new self($this->all()); <ide> } <ide> <ide> /**
2
Python
Python
skip this test on windows
cb47d58ce8d49a1cad4d31b2554aea62728e7cc4
<ide><path>libcloud/test/test_utils.py <ide> def test_is_public_and_is_private_subnet(self): <ide> self.assertFalse(is_public) <ide> self.assertTrue(is_private) <ide> <add> @unittest.skipIf(platform.platform().lower() == 'windows', 'Unsupported on Windows') <ide> def test_is_valid_ip_address(self): <ide> valid_ipv4_addresses = [ <ide> '192.168.1.100',
1
Ruby
Ruby
fix actionmailer tests broken by a69
da1a9203b42a67bb81d39319c7ecb99be48b20a3
<ide><path>actionmailer/test/base_test.rb <ide> def notify <ide> end <ide> end <ide> <del> assert_equal ["notify"], FooMailer.action_methods <add> assert_equal Set.new(["notify"]), FooMailer.action_methods <ide> end <ide> <ide> protected
1
Ruby
Ruby
handle unreadable bottle formula
83e2049636d023f8181badf844171fe4f9e5a29f
<ide><path>Library/Homebrew/formulary.rb <ide> def initialize(bottle_name) <ide> <ide> def get_formula(spec, **) <ide> contents = Utils::Bottles.formula_contents @bottle_filename, name: name <del> formula = Formulary.from_contents name, @bottle_filename, contents, spec <add> formula = begin <add> Formulary.from_contents name, @bottle_filename, contents, spec <add> rescue FormulaUnreadableError => e <add> opoo <<-EOS.undent <add> Unreadable formula in #{@bottle_filename}: <add> #{e} <add> EOS <add> super <add> end <ide> formula.local_bottle_path = @bottle_filename <ide> formula <ide> end
1
Javascript
Javascript
use url constructor for combineurl
e362c3b8fcbd738578dc8f6f3d2050edbb26330d
<ide><path>src/shared/util.js <ide> function combineUrl(baseUrl, url) { <ide> if (!url) { <ide> return baseUrl; <ide> } <del> if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) { <del> return url; <del> } <del> var i; <del> if (url.charAt(0) === '/') { <del> // absolute path <del> i = baseUrl.indexOf('://'); <del> if (url.charAt(1) === '/') { <del> ++i; <del> } else { <del> i = baseUrl.indexOf('/', i + 3); <del> } <del> return baseUrl.substring(0, i) + url; <del> } else { <del> // relative path <del> var pathLength = baseUrl.length; <del> i = baseUrl.lastIndexOf('#'); <del> pathLength = i >= 0 ? i : pathLength; <del> i = baseUrl.lastIndexOf('?', pathLength); <del> pathLength = i >= 0 ? i : pathLength; <del> var prefixLength = baseUrl.lastIndexOf('/', pathLength); <del> return baseUrl.substring(0, prefixLength + 1) + url; <del> } <add> return new URL(url, baseUrl).href; <ide> } <ide> <ide> // Validates if URL is safe and allowed, e.g. to avoid XSS. <ide> function loadJpegStream(id, imageUrl, objs) { <ide> img.src = imageUrl; <ide> } <ide> <add>//#if !(MOZCENTRAL) <add>// Polyfill from https://github.com/Polymer/URL <add>/* Any copyright is dedicated to the Public Domain. <add> * http://creativecommons.org/publicdomain/zero/1.0/ */ <add>(function checkURLConstructor(scope) { <add> /* jshint ignore:start */ <add> <add> // feature detect for URL constructor <add> var hasWorkingUrl = false; <add> if (typeof URL === 'function' && ('origin' in URL.prototype)) { <add> try { <add> var u = new URL('b', 'http://a'); <add> u.pathname = 'c%20d'; <add> hasWorkingUrl = u.href === 'http://a/c%20d'; <add> } catch(e) {} <add> } <add> <add> if (hasWorkingUrl) <add> return; <add> <add> var relative = Object.create(null); <add> relative['ftp'] = 21; <add> relative['file'] = 0; <add> relative['gopher'] = 70; <add> relative['http'] = 80; <add> relative['https'] = 443; <add> relative['ws'] = 80; <add> relative['wss'] = 443; <add> <add> var relativePathDotMapping = Object.create(null); <add> relativePathDotMapping['%2e'] = '.'; <add> relativePathDotMapping['.%2e'] = '..'; <add> relativePathDotMapping['%2e.'] = '..'; <add> relativePathDotMapping['%2e%2e'] = '..'; <add> <add> function isRelativeScheme(scheme) { <add> return relative[scheme] !== undefined; <add> } <add> <add> function invalid() { <add> clear.call(this); <add> this._isInvalid = true; <add> } <add> <add> function IDNAToASCII(h) { <add> if ('' == h) { <add> invalid.call(this) <add> } <add> // XXX <add> return h.toLowerCase() <add> } <add> <add> function percentEscape(c) { <add> var unicode = c.charCodeAt(0); <add> if (unicode > 0x20 && <add> unicode < 0x7F && <add> // " # < > ? ` <add> [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1 <add> ) { <add> return c; <add> } <add> return encodeURIComponent(c); <add> } <add> <add> function percentEscapeQuery(c) { <add> // XXX This actually needs to encode c using encoding and then <add> // convert the bytes one-by-one. <add> <add> var unicode = c.charCodeAt(0); <add> if (unicode > 0x20 && <add> unicode < 0x7F && <add> // " # < > ` (do not escape '?') <add> [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1 <add> ) { <add> return c; <add> } <add> return encodeURIComponent(c); <add> } <add> <add> var EOF = undefined, <add> ALPHA = /[a-zA-Z]/, <add> ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; <add> <add> function parse(input, stateOverride, base) { <add> function err(message) { <add> errors.push(message) <add> } <add> <add> var state = stateOverride || 'scheme start', <add> cursor = 0, <add> buffer = '', <add> seenAt = false, <add> seenBracket = false, <add> errors = []; <add> <add> loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { <add> var c = input[cursor]; <add> switch (state) { <add> case 'scheme start': <add> if (c && ALPHA.test(c)) { <add> buffer += c.toLowerCase(); // ASCII-safe <add> state = 'scheme'; <add> } else if (!stateOverride) { <add> buffer = ''; <add> state = 'no scheme'; <add> continue; <add> } else { <add> err('Invalid scheme.'); <add> break loop; <add> } <add> break; <add> <add> case 'scheme': <add> if (c && ALPHANUMERIC.test(c)) { <add> buffer += c.toLowerCase(); // ASCII-safe <add> } else if (':' == c) { <add> this._scheme = buffer; <add> buffer = ''; <add> if (stateOverride) { <add> break loop; <add> } <add> if (isRelativeScheme(this._scheme)) { <add> this._isRelative = true; <add> } <add> if ('file' == this._scheme) { <add> state = 'relative'; <add> } else if (this._isRelative && base && base._scheme == this._scheme) { <add> state = 'relative or authority'; <add> } else if (this._isRelative) { <add> state = 'authority first slash'; <add> } else { <add> state = 'scheme data'; <add> } <add> } else if (!stateOverride) { <add> buffer = ''; <add> cursor = 0; <add> state = 'no scheme'; <add> continue; <add> } else if (EOF == c) { <add> break loop; <add> } else { <add> err('Code point not allowed in scheme: ' + c) <add> break loop; <add> } <add> break; <add> <add> case 'scheme data': <add> if ('?' == c) { <add> this._query = '?'; <add> state = 'query'; <add> } else if ('#' == c) { <add> this._fragment = '#'; <add> state = 'fragment'; <add> } else { <add> // XXX error handling <add> if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { <add> this._schemeData += percentEscape(c); <add> } <add> } <add> break; <add> <add> case 'no scheme': <add> if (!base || !(isRelativeScheme(base._scheme))) { <add> err('Missing scheme.'); <add> invalid.call(this); <add> } else { <add> state = 'relative'; <add> continue; <add> } <add> break; <add> <add> case 'relative or authority': <add> if ('/' == c && '/' == input[cursor+1]) { <add> state = 'authority ignore slashes'; <add> } else { <add> err('Expected /, got: ' + c); <add> state = 'relative'; <add> continue <add> } <add> break; <add> <add> case 'relative': <add> this._isRelative = true; <add> if ('file' != this._scheme) <add> this._scheme = base._scheme; <add> if (EOF == c) { <add> this._host = base._host; <add> this._port = base._port; <add> this._path = base._path.slice(); <add> this._query = base._query; <add> this._username = base._username; <add> this._password = base._password; <add> break loop; <add> } else if ('/' == c || '\\' == c) { <add> if ('\\' == c) <add> err('\\ is an invalid code point.'); <add> state = 'relative slash'; <add> } else if ('?' == c) { <add> this._host = base._host; <add> this._port = base._port; <add> this._path = base._path.slice(); <add> this._query = '?'; <add> this._username = base._username; <add> this._password = base._password; <add> state = 'query'; <add> } else if ('#' == c) { <add> this._host = base._host; <add> this._port = base._port; <add> this._path = base._path.slice(); <add> this._query = base._query; <add> this._fragment = '#'; <add> this._username = base._username; <add> this._password = base._password; <add> state = 'fragment'; <add> } else { <add> var nextC = input[cursor+1] <add> var nextNextC = input[cursor+2] <add> if ( <add> 'file' != this._scheme || !ALPHA.test(c) || <add> (nextC != ':' && nextC != '|') || <add> (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) { <add> this._host = base._host; <add> this._port = base._port; <add> this._username = base._username; <add> this._password = base._password; <add> this._path = base._path.slice(); <add> this._path.pop(); <add> } <add> state = 'relative path'; <add> continue; <add> } <add> break; <add> <add> case 'relative slash': <add> if ('/' == c || '\\' == c) { <add> if ('\\' == c) { <add> err('\\ is an invalid code point.'); <add> } <add> if ('file' == this._scheme) { <add> state = 'file host'; <add> } else { <add> state = 'authority ignore slashes'; <add> } <add> } else { <add> if ('file' != this._scheme) { <add> this._host = base._host; <add> this._port = base._port; <add> this._username = base._username; <add> this._password = base._password; <add> } <add> state = 'relative path'; <add> continue; <add> } <add> break; <add> <add> case 'authority first slash': <add> if ('/' == c) { <add> state = 'authority second slash'; <add> } else { <add> err("Expected '/', got: " + c); <add> state = 'authority ignore slashes'; <add> continue; <add> } <add> break; <add> <add> case 'authority second slash': <add> state = 'authority ignore slashes'; <add> if ('/' != c) { <add> err("Expected '/', got: " + c); <add> continue; <add> } <add> break; <add> <add> case 'authority ignore slashes': <add> if ('/' != c && '\\' != c) { <add> state = 'authority'; <add> continue; <add> } else { <add> err('Expected authority, got: ' + c); <add> } <add> break; <add> <add> case 'authority': <add> if ('@' == c) { <add> if (seenAt) { <add> err('@ already seen.'); <add> buffer += '%40'; <add> } <add> seenAt = true; <add> for (var i = 0; i < buffer.length; i++) { <add> var cp = buffer[i]; <add> if ('\t' == cp || '\n' == cp || '\r' == cp) { <add> err('Invalid whitespace in authority.'); <add> continue; <add> } <add> // XXX check URL code points <add> if (':' == cp && null === this._password) { <add> this._password = ''; <add> continue; <add> } <add> var tempC = percentEscape(cp); <add> (null !== this._password) ? this._password += tempC : this._username += tempC; <add> } <add> buffer = ''; <add> } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { <add> cursor -= buffer.length; <add> buffer = ''; <add> state = 'host'; <add> continue; <add> } else { <add> buffer += c; <add> } <add> break; <add> <add> case 'file host': <add> if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { <add> if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { <add> state = 'relative path'; <add> } else if (buffer.length == 0) { <add> state = 'relative path start'; <add> } else { <add> this._host = IDNAToASCII.call(this, buffer); <add> buffer = ''; <add> state = 'relative path start'; <add> } <add> continue; <add> } else if ('\t' == c || '\n' == c || '\r' == c) { <add> err('Invalid whitespace in file host.'); <add> } else { <add> buffer += c; <add> } <add> break; <add> <add> case 'host': <add> case 'hostname': <add> if (':' == c && !seenBracket) { <add> // XXX host parsing <add> this._host = IDNAToASCII.call(this, buffer); <add> buffer = ''; <add> state = 'port'; <add> if ('hostname' == stateOverride) { <add> break loop; <add> } <add> } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { <add> this._host = IDNAToASCII.call(this, buffer); <add> buffer = ''; <add> state = 'relative path start'; <add> if (stateOverride) { <add> break loop; <add> } <add> continue; <add> } else if ('\t' != c && '\n' != c && '\r' != c) { <add> if ('[' == c) { <add> seenBracket = true; <add> } else if (']' == c) { <add> seenBracket = false; <add> } <add> buffer += c; <add> } else { <add> err('Invalid code point in host/hostname: ' + c); <add> } <add> break; <add> <add> case 'port': <add> if (/[0-9]/.test(c)) { <add> buffer += c; <add> } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { <add> if ('' != buffer) { <add> var temp = parseInt(buffer, 10); <add> if (temp != relative[this._scheme]) { <add> this._port = temp + ''; <add> } <add> buffer = ''; <add> } <add> if (stateOverride) { <add> break loop; <add> } <add> state = 'relative path start'; <add> continue; <add> } else if ('\t' == c || '\n' == c || '\r' == c) { <add> err('Invalid code point in port: ' + c); <add> } else { <add> invalid.call(this); <add> } <add> break; <add> <add> case 'relative path start': <add> if ('\\' == c) <add> err("'\\' not allowed in path."); <add> state = 'relative path'; <add> if ('/' != c && '\\' != c) { <add> continue; <add> } <add> break; <add> <add> case 'relative path': <add> if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) { <add> if ('\\' == c) { <add> err('\\ not allowed in relative path.'); <add> } <add> var tmp; <add> if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { <add> buffer = tmp; <add> } <add> if ('..' == buffer) { <add> this._path.pop(); <add> if ('/' != c && '\\' != c) { <add> this._path.push(''); <add> } <add> } else if ('.' == buffer && '/' != c && '\\' != c) { <add> this._path.push(''); <add> } else if ('.' != buffer) { <add> if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { <add> buffer = buffer[0] + ':'; <add> } <add> this._path.push(buffer); <add> } <add> buffer = ''; <add> if ('?' == c) { <add> this._query = '?'; <add> state = 'query'; <add> } else if ('#' == c) { <add> this._fragment = '#'; <add> state = 'fragment'; <add> } <add> } else if ('\t' != c && '\n' != c && '\r' != c) { <add> buffer += percentEscape(c); <add> } <add> break; <add> <add> case 'query': <add> if (!stateOverride && '#' == c) { <add> this._fragment = '#'; <add> state = 'fragment'; <add> } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { <add> this._query += percentEscapeQuery(c); <add> } <add> break; <add> <add> case 'fragment': <add> if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { <add> this._fragment += c; <add> } <add> break; <add> } <add> <add> cursor++; <add> } <add> } <add> <add> function clear() { <add> this._scheme = ''; <add> this._schemeData = ''; <add> this._username = ''; <add> this._password = null; <add> this._host = ''; <add> this._port = ''; <add> this._path = []; <add> this._query = ''; <add> this._fragment = ''; <add> this._isInvalid = false; <add> this._isRelative = false; <add> } <add> <add> // Does not process domain names or IP addresses. <add> // Does not handle encoding for the query parameter. <add> function jURL(url, base /* , encoding */) { <add> if (base !== undefined && !(base instanceof jURL)) <add> base = new jURL(String(base)); <add> <add> this._url = url; <add> clear.call(this); <add> <add> var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); <add> // encoding = encoding || 'utf-8' <add> <add> parse.call(this, input, null, base); <add> } <add> <add> jURL.prototype = { <add> toString: function() { <add> return this.href; <add> }, <add> get href() { <add> if (this._isInvalid) <add> return this._url; <add> <add> var authority = ''; <add> if ('' != this._username || null != this._password) { <add> authority = this._username + <add> (null != this._password ? ':' + this._password : '') + '@'; <add> } <add> <add> return this.protocol + <add> (this._isRelative ? '//' + authority + this.host : '') + <add> this.pathname + this._query + this._fragment; <add> }, <add> set href(href) { <add> clear.call(this); <add> parse.call(this, href); <add> }, <add> <add> get protocol() { <add> return this._scheme + ':'; <add> }, <add> set protocol(protocol) { <add> if (this._isInvalid) <add> return; <add> parse.call(this, protocol + ':', 'scheme start'); <add> }, <add> <add> get host() { <add> return this._isInvalid ? '' : this._port ? <add> this._host + ':' + this._port : this._host; <add> }, <add> set host(host) { <add> if (this._isInvalid || !this._isRelative) <add> return; <add> parse.call(this, host, 'host'); <add> }, <add> <add> get hostname() { <add> return this._host; <add> }, <add> set hostname(hostname) { <add> if (this._isInvalid || !this._isRelative) <add> return; <add> parse.call(this, hostname, 'hostname'); <add> }, <add> <add> get port() { <add> return this._port; <add> }, <add> set port(port) { <add> if (this._isInvalid || !this._isRelative) <add> return; <add> parse.call(this, port, 'port'); <add> }, <add> <add> get pathname() { <add> return this._isInvalid ? '' : this._isRelative ? <add> '/' + this._path.join('/') : this._schemeData; <add> }, <add> set pathname(pathname) { <add> if (this._isInvalid || !this._isRelative) <add> return; <add> this._path = []; <add> parse.call(this, pathname, 'relative path start'); <add> }, <add> <add> get search() { <add> return this._isInvalid || !this._query || '?' == this._query ? <add> '' : this._query; <add> }, <add> set search(search) { <add> if (this._isInvalid || !this._isRelative) <add> return; <add> this._query = '?'; <add> if ('?' == search[0]) <add> search = search.slice(1); <add> parse.call(this, search, 'query'); <add> }, <add> <add> get hash() { <add> return this._isInvalid || !this._fragment || '#' == this._fragment ? <add> '' : this._fragment; <add> }, <add> set hash(hash) { <add> if (this._isInvalid) <add> return; <add> this._fragment = '#'; <add> if ('#' == hash[0]) <add> hash = hash.slice(1); <add> parse.call(this, hash, 'fragment'); <add> }, <add> <add> get origin() { <add> var host; <add> if (this._isInvalid || !this._scheme) { <add> return ''; <add> } <add> // javascript: Gecko returns String(""), WebKit/Blink String("null") <add> // Gecko throws error for "data://" <add> // data: Gecko returns "", Blink returns "data://", WebKit returns "null" <add> // Gecko returns String("") for file: mailto: <add> // WebKit/Blink returns String("SCHEME://") for file: mailto: <add> switch (this._scheme) { <add> case 'data': <add> case 'file': <add> case 'javascript': <add> case 'mailto': <add> return 'null'; <add> } <add> host = this.host; <add> if (!host) { <add> return ''; <add> } <add> return this._scheme + '://' + host; <add> } <add> }; <add> <add> // Copy over the static methods <add> var OriginalURL = scope.URL; <add> if (OriginalURL) { <add> jURL.createObjectURL = function(blob) { <add> // IE extension allows a second optional options argument. <add> // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx <add> return OriginalURL.createObjectURL.apply(OriginalURL, arguments); <add> }; <add> jURL.revokeObjectURL = function(url) { <add> OriginalURL.revokeObjectURL(url); <add> }; <add> } <add> <add> scope.URL = jURL; <add> /* jshint ignore:end */ <add>})(globalScope); <add>//#endif <add> <ide> exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; <ide> exports.IDENTITY_MATRIX = IDENTITY_MATRIX; <ide> exports.OPS = OPS;
1
Python
Python
remove unsupported version [ci skip]
80d554f2e2813aea41b0889b39d8f30f648af1ad
<ide><path>setup.py <ide> def setup_package(): <ide> "Programming Language :: Python :: 2", <ide> "Programming Language :: Python :: 2.7", <ide> "Programming Language :: Python :: 3", <del> "Programming Language :: Python :: 3.4", <ide> "Programming Language :: Python :: 3.5", <ide> "Programming Language :: Python :: 3.6", <ide> "Programming Language :: Python :: 3.7",
1
Javascript
Javascript
make `syncwritestream` inherit from `writable`
a60f6078a17b92cd944635ce19cdd6710a04b1a4
<ide><path>lib/internal/fs.js <ide> 'use strict'; <ide> <ide> const Buffer = require('buffer').Buffer; <del>const Stream = require('stream').Stream; <add>const Writable = require('stream').Writable; <ide> const fs = require('fs'); <ide> const util = require('util'); <ide> const constants = process.binding('constants').fs; <ide> exports.stringToFlags = stringToFlags; <ide> <ide> // Temporary hack for process.stdout and process.stderr when piped to files. <ide> function SyncWriteStream(fd, options) { <del> Stream.call(this); <add> Writable.call(this); <ide> <ide> options = options || {}; <ide> <ide> this.fd = fd; <del> this.writable = true; <ide> this.readable = false; <ide> this.autoClose = options.autoClose === undefined ? true : options.autoClose; <del>} <del> <del>util.inherits(SyncWriteStream, Stream); <del> <del>SyncWriteStream.prototype.write = function(data, arg1, arg2) { <del> var encoding, cb; <del> <del> // parse arguments <del> if (arg1) { <del> if (typeof arg1 === 'string') { <del> encoding = arg1; <del> cb = arg2; <del> } else if (typeof arg1 === 'function') { <del> cb = arg1; <del> } else { <del> throw new Error('Bad arguments'); <del> } <del> } <del> assertEncoding(encoding); <del> <del> // Change strings to buffers. SLOW <del> if (typeof data === 'string') { <del> data = Buffer.from(data, encoding); <del> } <ide> <del> fs.writeSync(this.fd, data, 0, data.length); <add> this.on('end', () => this._destroy()); <add>} <ide> <del> if (cb) { <del> process.nextTick(cb); <del> } <add>util.inherits(SyncWriteStream, Writable); <ide> <add>SyncWriteStream.prototype._write = function(chunk, encoding, cb) { <add> fs.writeSync(this.fd, chunk, 0, chunk.length); <add> cb(); <ide> return true; <ide> }; <ide> <add>SyncWriteStream.prototype._destroy = function() { <add> if (this.fd === null) // already destroy()ed <add> return; <ide> <del>SyncWriteStream.prototype.end = function(data, arg1, arg2) { <del> if (data) { <del> this.write(data, arg1, arg2); <del> } <del> this.destroy(); <del>}; <del> <del> <del>SyncWriteStream.prototype.destroy = function() { <ide> if (this.autoClose) <ide> fs.closeSync(this.fd); <add> <ide> this.fd = null; <del> this.emit('close'); <ide> return true; <ide> }; <ide> <del>SyncWriteStream.prototype.destroySoon = SyncWriteStream.prototype.destroy; <add>SyncWriteStream.prototype.destroySoon = <add>SyncWriteStream.prototype.destroy = function() { <add> this._destroy(); <add> this.emit('close'); <add> return true; <add>}; <ide> <ide> exports.SyncWriteStream = SyncWriteStream; <ide><path>test/parallel/test-fs-syncwritestream.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const spawn = require('child_process').spawn; <add>const stream = require('stream'); <add>const fs = require('fs'); <add>const path = require('path'); <add> <add>// require('internal/fs').SyncWriteStream is used as a stdio implementation <add>// when stdout/stderr point to files. <add> <add>if (process.argv[2] === 'child') { <add> // Note: Calling console.log() is part of this test as it exercises the <add> // SyncWriteStream#_write() code path. <add> console.log(JSON.stringify([process.stdout, process.stderr].map((stdio) => ({ <add> instance: stdio instanceof stream.Writable, <add> readable: stdio.readable, <add> writable: stdio.writable, <add> })))); <add> <add> return; <add>} <add> <add>common.refreshTmpDir(); <add> <add>const filename = path.join(common.tmpDir, 'stdout'); <add>const stdoutFd = fs.openSync(filename, 'w'); <add> <add>const proc = spawn(process.execPath, [__filename, 'child'], { <add> stdio: ['inherit', stdoutFd, stdoutFd ] <add>}); <add> <add>proc.on('close', common.mustCall(() => { <add> fs.closeSync(stdoutFd); <add> <add> assert.deepStrictEqual(JSON.parse(fs.readFileSync(filename, 'utf8')), [ <add> { instance: true, readable: false, writable: true }, <add> { instance: true, readable: false, writable: true } <add> ]); <add>}));
2
Text
Text
update changelog with null_store default
732111b05faec567f4dec7d3dad5e9fc81b4efe8
<ide><path>railties/CHANGELOG.md <add>* Make :null_store the default store in the test environment. <add> <add> *Michael C. Nelson* <add> <ide> * Emit warning for unknown inflection rule when generating model. <ide> <ide> *Yoshiyuki Kinjo*
1
Ruby
Ruby
use reader method
b96411052ea23a6085788c18f7d19a24fa1c5b29
<ide><path>Library/Homebrew/formula.rb <ide> def patch <ide> # Explicitly request changing C++ standard library compatibility check <ide> # settings. Use with caution! <ide> def cxxstdlib_check check_type <del> @cxxstdlib << check_type <add> cxxstdlib << check_type <ide> end <ide> <ide> def self.method_added method
1
Python
Python
add 2.x version of mnist model to model garden
37c1202686338872f0df13e0393cb6ce3656e19d
<ide><path>official/vision/image_classification/mnist_main.py <add># Copyright 2018 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Runs a simple model on the MNIST dataset.""" <add>from __future__ import absolute_import <add>from __future__ import division <add>from __future__ import print_function <add> <add>import os <add> <add>from absl import app <add>from absl import flags <add>from absl import logging <add>import tensorflow as tf <add>import tensorflow_datasets as tfds <add> <add>from official.utils.flags import core as flags_core <add>from official.utils.misc import distribution_utils <add>from official.utils.misc import model_helpers <add>from official.vision.image_classification import common <add> <add>FLAGS = flags.FLAGS <add> <add> <add>def build_model(): <add> """Constructs the ML model used to predict handwritten digits.""" <add> <add> image = tf.keras.layers.Input(shape=(28, 28, 1)) <add> <add> y = tf.keras.layers.Conv2D(filters=32, <add> kernel_size=5, <add> padding='same', <add> activation='relu')(image) <add> y = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), <add> strides=(2, 2), <add> padding='same')(y) <add> y = tf.keras.layers.Conv2D(filters=32, <add> kernel_size=5, <add> padding='same', <add> activation='relu')(y) <add> y = tf.keras.layers.MaxPooling2D(pool_size=(2, 2), <add> strides=(2, 2), <add> padding='same')(y) <add> y = tf.keras.layers.Flatten()(y) <add> y = tf.keras.layers.Dense(1024, activation='relu')(y) <add> y = tf.keras.layers.Dropout(0.4)(y) <add> <add> probs = tf.keras.layers.Dense(10, activation='softmax')(y) <add> <add> model = tf.keras.models.Model(image, probs, name='mnist') <add> <add> return model <add> <add> <add>@tfds.decode.make_decoder(output_dtype=tf.float32) <add>def decode_image(example, feature): <add> """Convert image to float32 and normalize from [0, 255] to [0.0, 1.0].""" <add> return tf.cast(feature.decode_example(example), dtype=tf.float32) / 255 <add> <add> <add>def run(flags_obj, strategy_override=None): <add> """Run MNIST model training and eval loop using native Keras APIs. <add> <add> Args: <add> flags_obj: An object containing parsed flag values. <add> strategy_override: A `tf.distribute.Strategy` object to use for model. <add> <add> Returns: <add> Dictionary of training and eval stats. <add> """ <add> strategy = strategy_override or distribution_utils.get_distribution_strategy( <add> distribution_strategy=flags_obj.distribution_strategy, <add> num_gpus=flags_obj.num_gpus, <add> tpu_address=flags_obj.tpu) <add> <add> strategy_scope = distribution_utils.get_strategy_scope(strategy) <add> <add> mnist = tfds.builder('mnist', data_dir=flags_obj.data_dir) <add> if flags_obj.download: <add> mnist.download_and_prepare() <add> <add> mnist_train, mnist_test = mnist.as_dataset( <add> split=['train', 'test'], <add> decoders={'image': decode_image()}, # pylint: disable=no-value-for-parameter <add> as_supervised=True) <add> train_input_dataset = mnist_train.cache().repeat().shuffle( <add> buffer_size=50000).batch(flags_obj.batch_size) <add> eval_input_dataset = mnist_test.cache().repeat().batch(flags_obj.batch_size) <add> <add> with strategy_scope: <add> lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( <add> 0.05, decay_steps=100000, decay_rate=0.96) <add> optimizer = tf.keras.optimizers.SGD(learning_rate=lr_schedule) <add> <add> model = build_model() <add> model.compile( <add> optimizer=optimizer, <add> loss='sparse_categorical_crossentropy', <add> metrics=['sparse_categorical_accuracy']) <add> <add> num_train_examples = mnist.info.splits['train'].num_examples <add> train_steps = num_train_examples // flags_obj.batch_size <add> train_epochs = flags_obj.train_epochs <add> <add> ckpt_full_path = os.path.join(flags_obj.model_dir, 'model.ckpt-{epoch:04d}') <add> callbacks = [ <add> tf.keras.callbacks.ModelCheckpoint( <add> ckpt_full_path, save_weights_only=True), <add> tf.keras.callbacks.TensorBoard(log_dir=flags_obj.model_dir), <add> ] <add> <add> num_eval_examples = mnist.info.splits['test'].num_examples <add> num_eval_steps = num_eval_examples // flags_obj.batch_size <add> <add> history = model.fit( <add> train_input_dataset, <add> epochs=train_epochs, <add> steps_per_epoch=train_steps, <add> callbacks=callbacks, <add> validation_steps=num_eval_steps, <add> validation_data=eval_input_dataset, <add> validation_freq=flags_obj.epochs_between_evals) <add> <add> export_path = os.path.join(flags_obj.model_dir, 'saved_model') <add> model.save(export_path, include_optimizer=False) <add> <add> eval_output = model.evaluate( <add> eval_input_dataset, steps=num_eval_steps, verbose=2) <add> <add> stats = common.build_stats(history, eval_output, callbacks) <add> return stats <add> <add> <add>def define_mnist_flags(): <add> """Define command line flags for MNIST model.""" <add> flags_core.define_base( <add> clean=True, <add> num_gpu=True, <add> train_epochs=True, <add> epochs_between_evals=True, <add> distribution_strategy=True) <add> flags_core.define_device() <add> flags_core.define_distribution() <add> flags.DEFINE_bool('download', False, <add> 'Whether to download data to `--data_dir`.') <add> FLAGS.set_default('batch_size', 1024) <add> <add> <add>def main(_): <add> model_helpers.apply_clean(FLAGS) <add> stats = run(flags.FLAGS) <add> logging.info('Run stats:\n%s', stats) <add> <add> <add>if __name__ == '__main__': <add> logging.set_verbosity(logging.INFO) <add> define_mnist_flags() <add> app.run(main) <ide><path>official/vision/image_classification/mnist_test.py <add># Copyright 2017 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""Test the Keras MNIST model on GPU.""" <add> <add>from __future__ import absolute_import <add>from __future__ import division <add>from __future__ import print_function <add> <add>import functools <add> <add>from absl.testing import parameterized <add>import tensorflow as tf <add>import tensorflow_datasets as tfds <add> <add>from tensorflow.python.distribute import combinations <add>from tensorflow.python.distribute import strategy_combinations <add>from official.utils.misc import keras_utils <add>from official.utils.testing import integration <add>from official.vision.image_classification import mnist_main <add> <add> <add>def eager_strategy_combinations(): <add> return combinations.combine( <add> distribution=[ <add> strategy_combinations.default_strategy, <add> strategy_combinations.tpu_strategy, <add> strategy_combinations.one_device_strategy_gpu, <add> ], <add> mode="eager", <add> ) <add> <add> <add>class KerasMnistTest(tf.test.TestCase, parameterized.TestCase): <add> """Unit tests for sample Keras MNIST model.""" <add> _tempdir = None <add> <add> @classmethod <add> def setUpClass(cls): # pylint: disable=invalid-name <add> super(KerasMnistTest, cls).setUpClass() <add> mnist_main.define_mnist_flags() <add> <add> def tearDown(self): <add> super(KerasMnistTest, self).tearDown() <add> tf.io.gfile.rmtree(self.get_temp_dir()) <add> <add> @combinations.generate(eager_strategy_combinations()) <add> def test_end_to_end(self, distribution): <add> """Test Keras MNIST model with `strategy`.""" <add> config = keras_utils.get_config_proto_v1() <add> tf.compat.v1.enable_eager_execution(config=config) <add> <add> extra_flags = [ <add> "-train_epochs", "1", <add> # Let TFDS find the metadata folder automatically <add> "--data_dir=" <add> ] <add> <add> def _mock_dataset(self, *args, **kwargs): # pylint: disable=unused-argument <add> """Generate mock dataset with TPU-compatible dtype (instead of uint8).""" <add> return tf.data.Dataset.from_tensor_slices({ <add> "image": tf.ones(shape=(10, 28, 28, 1), dtype=tf.int32), <add> "label": tf.range(10), <add> }) <add> <add> run = functools.partial(mnist_main.run, strategy_override=distribution) <add> <add> with tfds.testing.mock_data(as_dataset_fn=_mock_dataset): <add> integration.run_synthetic( <add> main=run, <add> synth=False, <add> tmp_root=self.get_temp_dir(), <add> extra_flags=extra_flags) <add> <add> <add>if __name__ == "__main__": <add> tf.compat.v1.enable_v2_behavior() <add> tf.test.main()
2
PHP
PHP
remove tests for deprecated code
e46714bda7f35cf7504a8b5381e69b4f50e7b8e7
<ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testSelectOrderByString() <ide> $result->closeCursor(); <ide> } <ide> <del> /** <del> * Test that order() works with an associative array which contains extra values. <del> * <del> * @return void <del> */ <del> public function testSelectOrderByAssociativeArrayContainingExtraExpressions() <del> { <del> $this->deprecated(function () { <del> $this->loadFixtures('Articles'); <del> $query = new Query($this->connection); <del> $query->select(['id']) <del> ->from('articles') <del> ->order([ <del> 'id' => 'desc -- Comment', <del> ]); <del> $result = $query->execute(); <del> $this->assertEquals(['id' => 3], $result->fetch('assoc')); <del> $this->assertEquals(['id' => 2], $result->fetch('assoc')); <del> $this->assertEquals(['id' => 1], $result->fetch('assoc')); <del> $result->closeCursor(); <del> }); <del> } <del> <ide> /** <ide> * Tests that order() works with closures. <ide> * <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function assertLineLengths($message) <ide> ); <ide> } <ide> } <del> <del> /** <del> * Test deprecated methods <del> * <del> * @return void <del> */ <del> public function testDeprecatedMethods() <del> { <del> $this->deprecated(function () { <del> $this->Email <del> ->setTemplate('foo') <del> ->setLayout('bar') <del> ->setTheme('baz') <del> ->setHelpers(['A', 'B']); <del> <del> $this->assertSame('foo', $this->Email->getTemplate()); <del> $this->assertSame('bar', $this->Email->getLayout()); <del> $this->assertSame('baz', $this->Email->getTheme()); <del> $this->assertSame(['A', 'B'], $this->Email->getHelpers()); <del> <del> $this->Email->setLayout(''); <del> $this->assertFalse($this->Email->getLayout()); <del> }); <del> } <ide> }
2
Java
Java
consolidate txmgr lookup tests in the tcf
a42944d3644e7b3100445b463574b2a52e37aa1e
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java <del>/* <del> * Copyright 2002-2019 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * https://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.test.context.junit4.spr9645; <del> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <del> <del>import org.springframework.context.annotation.Bean; <del>import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <del>import org.springframework.test.context.transaction.AfterTransaction; <del>import org.springframework.test.context.transaction.BeforeTransaction; <del>import org.springframework.transaction.PlatformTransactionManager; <del>import org.springframework.transaction.annotation.Transactional; <del>import org.springframework.transaction.testfixture.CallCountingTransactionManager; <del> <del>import static org.assertj.core.api.Assertions.assertThat; <del> <del>/** <del> * Integration tests that verify the behavior requested in <del> * <a href="https://jira.spring.io/browse/SPR-9645">SPR-9645</a>. <del> * <del> * @author Sam Brannen <del> * @since 3.2 <del> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <del>@Transactional <del>public class LookUpTxMgrByTypeAndDefaultNameTests { <del> <del> private static final CallCountingTransactionManager txManager1 = new CallCountingTransactionManager(); <del> private static final CallCountingTransactionManager txManager2 = new CallCountingTransactionManager(); <del> <del> @Configuration <del> static class Config { <del> <del> @Bean <del> public PlatformTransactionManager transactionManager() { <del> return txManager1; <del> } <del> <del> @Bean <del> public PlatformTransactionManager txManager2() { <del> return txManager2; <del> } <del> } <del> <del> @BeforeTransaction <del> public void beforeTransaction() { <del> txManager1.clear(); <del> txManager2.clear(); <del> } <del> <del> @Test <del> public void transactionalTest() { <del> assertThat(txManager1.begun).isEqualTo(1); <del> assertThat(txManager1.inflight).isEqualTo(1); <del> assertThat(txManager1.commits).isEqualTo(0); <del> assertThat(txManager1.rollbacks).isEqualTo(0); <del> } <del> <del> @AfterTransaction <del> public void afterTransaction() { <del> assertThat(txManager1.begun).isEqualTo(1); <del> assertThat(txManager1.inflight).isEqualTo(0); <del> assertThat(txManager1.commits).isEqualTo(0); <del> assertThat(txManager1.rollbacks).isEqualTo(1); <del> } <del> <del>} <ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java <del>/* <del> * Copyright 2002-2019 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * https://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.test.context.junit4.spr9645; <del> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <del> <del>import org.springframework.context.annotation.Bean; <del>import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <del>import org.springframework.test.context.transaction.AfterTransaction; <del>import org.springframework.test.context.transaction.BeforeTransaction; <del>import org.springframework.transaction.PlatformTransactionManager; <del>import org.springframework.transaction.annotation.Transactional; <del>import org.springframework.transaction.testfixture.CallCountingTransactionManager; <del> <del>import static org.assertj.core.api.Assertions.assertThat; <del> <del>/** <del> * Integration tests that verify the behavior requested in <del> * <a href="https://jira.spring.io/browse/SPR-9645">SPR-9645</a>. <del> * <del> * @author Sam Brannen <del> * @since 3.2 <del> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <del>@Transactional("txManager1") <del>public class LookUpTxMgrByTypeAndNameTests { <del> <del> private static final CallCountingTransactionManager txManager1 = new CallCountingTransactionManager(); <del> private static final CallCountingTransactionManager txManager2 = new CallCountingTransactionManager(); <del> <del> @Configuration <del> static class Config { <del> <del> @Bean <del> public PlatformTransactionManager txManager1() { <del> return txManager1; <del> } <del> <del> @Bean <del> public PlatformTransactionManager txManager2() { <del> return txManager2; <del> } <del> } <del> <del> @BeforeTransaction <del> public void beforeTransaction() { <del> txManager1.clear(); <del> txManager2.clear(); <del> } <del> <del> @Test <del> public void transactionalTest() { <del> assertThat(txManager1.begun).isEqualTo(1); <del> assertThat(txManager1.inflight).isEqualTo(1); <del> assertThat(txManager1.commits).isEqualTo(0); <del> assertThat(txManager1.rollbacks).isEqualTo(0); <del> } <del> <del> @AfterTransaction <del> public void afterTransaction() { <del> assertThat(txManager1.begun).isEqualTo(1); <del> assertThat(txManager1.inflight).isEqualTo(0); <del> assertThat(txManager1.commits).isEqualTo(0); <del> assertThat(txManager1.rollbacks).isEqualTo(1); <del> } <del> <del>} <ide><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrByTypeAndDefaultNameTests.java <add>/* <add> * Copyright 2002-2020 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.context.transaction.manager; <add> <add>import org.junit.jupiter.api.Test; <add> <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.context.annotation.Bean; <add>import org.springframework.context.annotation.Configuration; <add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <add>import org.springframework.test.context.transaction.AfterTransaction; <add>import org.springframework.transaction.PlatformTransactionManager; <add>import org.springframework.transaction.annotation.Transactional; <add>import org.springframework.transaction.testfixture.CallCountingTransactionManager; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add>/** <add> * Integration tests that verify the behavior requested in <add> * <a href="https://jira.spring.io/browse/SPR-9645">SPR-9645</a>. <add> * <add> * @author Sam Brannen <add> * @since 3.2 <add> */ <add>@SpringJUnitConfig <add>@Transactional <add>class LookUpTxMgrByTypeAndDefaultNameTests { <add> <add> @Autowired <add> CallCountingTransactionManager transactionManager; <add> <add> @Autowired <add> CallCountingTransactionManager txManager2; <add> <add> <add> @Test <add> void transactionalTest() { <add> assertThat(transactionManager.begun).isEqualTo(1); <add> assertThat(transactionManager.inflight).isEqualTo(1); <add> assertThat(transactionManager.commits).isEqualTo(0); <add> assertThat(transactionManager.rollbacks).isEqualTo(0); <add> <add> assertThat(txManager2.begun).isEqualTo(0); <add> assertThat(txManager2.inflight).isEqualTo(0); <add> assertThat(txManager2.commits).isEqualTo(0); <add> assertThat(txManager2.rollbacks).isEqualTo(0); <add> } <add> <add> @AfterTransaction <add> void afterTransaction() { <add> assertThat(transactionManager.begun).isEqualTo(1); <add> assertThat(transactionManager.inflight).isEqualTo(0); <add> assertThat(transactionManager.commits).isEqualTo(0); <add> assertThat(transactionManager.rollbacks).isEqualTo(1); <add> <add> assertThat(txManager2.begun).isEqualTo(0); <add> assertThat(txManager2.inflight).isEqualTo(0); <add> assertThat(txManager2.commits).isEqualTo(0); <add> assertThat(txManager2.rollbacks).isEqualTo(0); <add> } <add> <add> <add> @Configuration <add> static class Config { <add> <add> @Bean <add> PlatformTransactionManager transactionManager() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> @Bean <add> PlatformTransactionManager txManager2() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> } <add> <add>} <add><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java <del><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.test.context.junit4.spr9645; <add>package org.springframework.test.context.transaction.manager; <ide> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <add>import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <ide> import org.springframework.test.context.transaction.AfterTransaction; <del>import org.springframework.test.context.transaction.BeforeTransaction; <ide> import org.springframework.transaction.PlatformTransactionManager; <ide> import org.springframework.transaction.annotation.Transactional; <ide> import org.springframework.transaction.testfixture.CallCountingTransactionManager; <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <add>@SpringJUnitConfig <ide> @Transactional("txManager1") <del>public class LookUpTxMgrByTypeAndQualifierAtClassLevelTests { <add>class LookUpTxMgrByTypeAndQualifierAtClassLevelTests { <ide> <del> private static final CallCountingTransactionManager txManager1 = new CallCountingTransactionManager(); <del> private static final CallCountingTransactionManager txManager2 = new CallCountingTransactionManager(); <add> @Autowired <add> CallCountingTransactionManager txManager1; <ide> <del> @Configuration <del> static class Config { <del> <del> @Bean <del> public PlatformTransactionManager txManager1() { <del> return txManager1; <del> } <del> <del> @Bean <del> public PlatformTransactionManager txManager2() { <del> return txManager2; <del> } <del> } <add> @Autowired <add> CallCountingTransactionManager txManager2; <ide> <del> @BeforeTransaction <del> public void beforeTransaction() { <del> txManager1.clear(); <del> txManager2.clear(); <del> } <ide> <ide> @Test <del> public void transactionalTest() { <add> void transactionalTest() { <ide> assertThat(txManager1.begun).isEqualTo(1); <ide> assertThat(txManager1.inflight).isEqualTo(1); <ide> assertThat(txManager1.commits).isEqualTo(0); <ide> assertThat(txManager1.rollbacks).isEqualTo(0); <add> <add> assertThat(txManager2.begun).isEqualTo(0); <add> assertThat(txManager2.inflight).isEqualTo(0); <add> assertThat(txManager2.commits).isEqualTo(0); <add> assertThat(txManager2.rollbacks).isEqualTo(0); <ide> } <ide> <ide> @AfterTransaction <del> public void afterTransaction() { <add> void afterTransaction() { <ide> assertThat(txManager1.begun).isEqualTo(1); <ide> assertThat(txManager1.inflight).isEqualTo(0); <ide> assertThat(txManager1.commits).isEqualTo(0); <ide> assertThat(txManager1.rollbacks).isEqualTo(1); <add> <add> assertThat(txManager2.begun).isEqualTo(0); <add> assertThat(txManager2.inflight).isEqualTo(0); <add> assertThat(txManager2.commits).isEqualTo(0); <add> assertThat(txManager2.rollbacks).isEqualTo(0); <add> } <add> <add> <add> @Configuration <add> static class Config { <add> <add> @Bean <add> PlatformTransactionManager txManager1() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> @Bean <add> PlatformTransactionManager txManager2() { <add> return new CallCountingTransactionManager(); <add> } <add> <ide> } <ide> <ide> } <add><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java <del><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.test.context.junit4.spr9645; <add>package org.springframework.test.context.transaction.manager; <ide> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <add>import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <ide> import org.springframework.test.context.transaction.AfterTransaction; <del>import org.springframework.test.context.transaction.BeforeTransaction; <ide> import org.springframework.transaction.PlatformTransactionManager; <ide> import org.springframework.transaction.annotation.Transactional; <ide> import org.springframework.transaction.testfixture.CallCountingTransactionManager; <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <del>public class LookUpTxMgrByTypeAndQualifierAtMethodLevelTests { <add>@SpringJUnitConfig <add>class LookUpTxMgrByTypeAndQualifierAtMethodLevelTests { <ide> <del> private static final CallCountingTransactionManager txManager1 = new CallCountingTransactionManager(); <del> private static final CallCountingTransactionManager txManager2 = new CallCountingTransactionManager(); <add> @Autowired <add> CallCountingTransactionManager txManager1; <ide> <del> @Configuration <del> static class Config { <del> <del> @Bean <del> public PlatformTransactionManager txManager1() { <del> return txManager1; <del> } <del> <del> @Bean <del> public PlatformTransactionManager txManager2() { <del> return txManager2; <del> } <del> } <add> @Autowired <add> CallCountingTransactionManager txManager2; <ide> <del> @BeforeTransaction <del> public void beforeTransaction() { <del> txManager1.clear(); <del> txManager2.clear(); <del> } <ide> <ide> @Transactional("txManager1") <ide> @Test <del> public void transactionalTest() { <add> void transactionalTest() { <ide> assertThat(txManager1.begun).isEqualTo(1); <ide> assertThat(txManager1.inflight).isEqualTo(1); <ide> assertThat(txManager1.commits).isEqualTo(0); <ide> assertThat(txManager1.rollbacks).isEqualTo(0); <add> <add> assertThat(txManager2.begun).isEqualTo(0); <add> assertThat(txManager2.inflight).isEqualTo(0); <add> assertThat(txManager2.commits).isEqualTo(0); <add> assertThat(txManager2.rollbacks).isEqualTo(0); <ide> } <ide> <ide> @AfterTransaction <del> public void afterTransaction() { <add> void afterTransaction() { <ide> assertThat(txManager1.begun).isEqualTo(1); <ide> assertThat(txManager1.inflight).isEqualTo(0); <ide> assertThat(txManager1.commits).isEqualTo(0); <ide> assertThat(txManager1.rollbacks).isEqualTo(1); <add> <add> assertThat(txManager2.begun).isEqualTo(0); <add> assertThat(txManager2.inflight).isEqualTo(0); <add> assertThat(txManager2.commits).isEqualTo(0); <add> assertThat(txManager2.rollbacks).isEqualTo(0); <add> } <add> <add> <add> @Configuration <add> static class Config { <add> <add> @Bean <add> PlatformTransactionManager txManager1() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> @Bean <add> PlatformTransactionManager txManager2() { <add> return new CallCountingTransactionManager(); <add> } <add> <ide> } <ide> <ide> } <add><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrByTypeTests.java <del><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.test.context.junit4.spr9645; <add>package org.springframework.test.context.transaction.manager; <ide> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <add>import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <ide> import org.springframework.test.context.transaction.AfterTransaction; <del>import org.springframework.test.context.transaction.BeforeTransaction; <ide> import org.springframework.transaction.PlatformTransactionManager; <ide> import org.springframework.transaction.annotation.Transactional; <ide> import org.springframework.transaction.testfixture.CallCountingTransactionManager; <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <add>@SpringJUnitConfig <ide> @Transactional <del>public class LookUpTxMgrByTypeTests { <add>class LookUpTxMgrByTypeTests { <ide> <del> private static final CallCountingTransactionManager txManager = new CallCountingTransactionManager(); <add> @Autowired <add> CallCountingTransactionManager txManager; <ide> <del> @Configuration <del> static class Config { <del> <del> @Bean <del> public PlatformTransactionManager txManager() { <del> return txManager; <del> } <del> } <del> <del> @BeforeTransaction <del> public void beforeTransaction() { <del> txManager.clear(); <del> } <ide> <ide> @Test <del> public void transactionalTest() { <add> void transactionalTest() { <ide> assertThat(txManager.begun).isEqualTo(1); <ide> assertThat(txManager.inflight).isEqualTo(1); <ide> assertThat(txManager.commits).isEqualTo(0); <ide> assertThat(txManager.rollbacks).isEqualTo(0); <ide> } <ide> <ide> @AfterTransaction <del> public void afterTransaction() { <add> void afterTransaction() { <ide> assertThat(txManager.begun).isEqualTo(1); <ide> assertThat(txManager.inflight).isEqualTo(0); <ide> assertThat(txManager.commits).isEqualTo(0); <ide> assertThat(txManager.rollbacks).isEqualTo(1); <ide> } <ide> <add> <add> @Configuration <add> static class Config { <add> <add> @Bean <add> PlatformTransactionManager txManager() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> } <add> <ide> } <add><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrNonTransactionalTests.java <del><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.test.context.junit4.spr9645; <add>package org.springframework.test.context.transaction.manager; <ide> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <add>import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <ide> import org.springframework.transaction.PlatformTransactionManager; <ide> import org.springframework.transaction.testfixture.CallCountingTransactionManager; <ide> <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <del>public class LookUpNonexistentTxMgrTests { <add>@SpringJUnitConfig <add>class LookUpTxMgrNonTransactionalTests { <ide> <del> private static final CallCountingTransactionManager txManager = new CallCountingTransactionManager(); <add> @Autowired <add> CallCountingTransactionManager txManager; <ide> <del> @Configuration <del> static class Config { <del> <del> @Bean <del> public PlatformTransactionManager transactionManager() { <del> return txManager; <del> } <del> } <ide> <ide> @Test <del> public void nonTransactionalTest() { <add> void nonTransactionalTest() { <ide> assertThat(txManager.begun).isEqualTo(0); <ide> assertThat(txManager.inflight).isEqualTo(0); <ide> assertThat(txManager.commits).isEqualTo(0); <ide> assertThat(txManager.rollbacks).isEqualTo(0); <ide> } <add> <add> <add> @Configuration <add> static class Config { <add> <add> @Bean <add> PlatformTransactionManager transactionManager() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> } <add> <ide> } <add><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrViaTransactionManagementConfigurerTests.java <del><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.test.context.junit4.spr9604; <add>package org.springframework.test.context.transaction.manager; <ide> <del>import org.junit.Test; <del>import org.junit.runner.RunWith; <add>import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <del>import org.springframework.test.context.ContextConfiguration; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <ide> import org.springframework.test.context.transaction.AfterTransaction; <del>import org.springframework.test.context.transaction.BeforeTransaction; <ide> import org.springframework.transaction.PlatformTransactionManager; <ide> import org.springframework.transaction.annotation.TransactionManagementConfigurer; <ide> import org.springframework.transaction.annotation.Transactional; <ide> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <del>@RunWith(SpringJUnit4ClassRunner.class) <del>@ContextConfiguration <add>@SpringJUnitConfig <ide> @Transactional <del>public class LookUpTxMgrViaTransactionManagementConfigurerTests { <add>class LookUpTxMgrViaTransactionManagementConfigurerTests { <ide> <del> private static final CallCountingTransactionManager txManager1 = new CallCountingTransactionManager(); <del> private static final CallCountingTransactionManager txManager2 = new CallCountingTransactionManager(); <add> @Autowired <add> CallCountingTransactionManager txManager1; <ide> <add> @Autowired <add> CallCountingTransactionManager txManager2; <ide> <del> @Configuration <del> static class Config implements TransactionManagementConfigurer { <del> <del> @Override <del> public PlatformTransactionManager annotationDrivenTransactionManager() { <del> return txManager1(); <del> } <del> <del> @Bean <del> public PlatformTransactionManager txManager1() { <del> return txManager1; <del> } <del> <del> @Bean <del> public PlatformTransactionManager txManager2() { <del> return txManager2; <del> } <del> } <del> <del> <del> @BeforeTransaction <del> public void beforeTransaction() { <del> txManager1.clear(); <del> txManager2.clear(); <del> } <ide> <ide> @Test <del> public void transactionalTest() { <add> void transactionalTest() { <ide> assertThat(txManager1.begun).isEqualTo(1); <ide> assertThat(txManager1.inflight).isEqualTo(1); <ide> assertThat(txManager1.commits).isEqualTo(0); <ide> public void transactionalTest() { <ide> } <ide> <ide> @AfterTransaction <del> public void afterTransaction() { <add> void afterTransaction() { <ide> assertThat(txManager1.begun).isEqualTo(1); <ide> assertThat(txManager1.inflight).isEqualTo(0); <ide> assertThat(txManager1.commits).isEqualTo(0); <ide> public void afterTransaction() { <ide> assertThat(txManager2.rollbacks).isEqualTo(0); <ide> } <ide> <add> <add> @Configuration <add> static class Config implements TransactionManagementConfigurer { <add> <add> @Override <add> public PlatformTransactionManager annotationDrivenTransactionManager() { <add> return txManager1(); <add> } <add> <add> @Bean <add> PlatformTransactionManager txManager1() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> @Bean <add> PlatformTransactionManager txManager2() { <add> return new CallCountingTransactionManager(); <add> } <add> <add> } <add> <ide> } <add><path>spring-test/src/test/java/org/springframework/test/context/transaction/manager/PrimaryTransactionManagerTests.java <del><path>spring-test/src/test/java/org/springframework/test/context/transaction/PrimaryTransactionManagerTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.test.context.transaction; <add>package org.springframework.test.context.transaction.manager; <ide> <ide> import javax.sql.DataSource; <ide> <ide> import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; <ide> import org.springframework.test.annotation.DirtiesContext; <ide> import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; <add>import org.springframework.test.context.transaction.AfterTransaction; <add>import org.springframework.test.context.transaction.BeforeTransaction; <ide> import org.springframework.test.jdbc.JdbcTestUtils; <ide> import org.springframework.transaction.PlatformTransactionManager; <ide> import org.springframework.transaction.annotation.EnableTransactionManagement; <ide> */ <ide> @SpringJUnitConfig <ide> @DirtiesContext <del>final class PrimaryTransactionManagerTests { <del> <del> private JdbcTemplate jdbcTemplate; <add>final /* Intentionally FINAL */ class PrimaryTransactionManagerTests { <ide> <add> private final JdbcTemplate jdbcTemplate; <ide> <ide> @Autowired <del> void setDataSource(DataSource dataSource1) { <add> PrimaryTransactionManagerTests(DataSource dataSource1) { <ide> this.jdbcTemplate = new JdbcTemplate(dataSource1); <ide> } <ide> <add> <ide> @BeforeTransaction <ide> void beforeTransaction() { <ide> assertNumUsers(0); <ide> DataSource dataSource1() { <ide> DataSource dataSource2() { <ide> return new EmbeddedDatabaseBuilder().generateUniqueName(true).build(); <ide> } <add> <ide> } <ide> <ide> }
9
PHP
PHP
fix failing tests
7b0138aa7fcd81caf86981a1ae39748494424264
<ide><path>tests/TestCase/View/Helper/SessionHelperTest.php <ide> public function testFlash() <ide> <ide> $result = $this->Session->flash('notification'); <ide> $result = str_replace("\r\n", "\n", $result); <del> $expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>This is a test of the emergency broadcasting system</p>\n</div>"; <add> $expected = "<div id=\"notificationLayout\">\n <h1>Alert!</h1>\n <h3>Notice!</h3>\n <p>This is a test of the emergency broadcasting system</p>\n</div>\n"; <ide> $this->assertEquals($expected, $result); <ide> $this->assertFalse($this->Session->check('Message.notification')); <ide> } <ide> public function testFlashElementInAttrs() <ide> 'element' => 'session_helper', <ide> 'params' => array('title' => 'Notice!', 'name' => 'Alert!') <ide> )); <del> $expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>This is a calling</p>\n</div>"; <add> $expected = "<div id=\"notificationLayout\">\n <h1>Alert!</h1>\n <h3>Notice!</h3>\n <p>This is a calling</p>\n</div>\n"; <ide> $this->assertTextEquals($expected, $result); <ide> } <ide>
1
Python
Python
try a hack to avoid warnings from docstrings
68b6c2d5d8553ead2ad278d0ce16d794c4a3776c
<ide><path>docs/conf.py <ide> # All configuration values have a default; values that are commented out <ide> # serve to show the default. <ide> <del>import sys, os <add>import os <add>import sys <ide> import subprocess <ide> <add>from sphinx.environment import BuildEnvironment <add> <add>from sphinx.ext.autodoc import AutoDirective <add>from sphinx.ext.autodoc import AutodocReporter <add> <ide> # Detect if we are running on read the docs <ide> on_rtd = os.environ.get('READTHEDOCS', None) == 'True' <ide> <ide> intersphinx_mapping = {'http://docs.python.org/': None} <ide> <ide> autoclass_content = 'both' <add> <add> <add># Note: For now we ignore sphinx-autodoc warnings since there are too many <add># and we want at least documentation (not docstring) related warnings to be <add># reported, treated as errors and fixed. <add>def noop(*args, **kwargs): <add> pass <add> <add>def mock_warning(self, *args, **kwargs): <add> # We re-write warning as info (level 1) <add> return self.system_message(1, *args, **kwargs) <add> <add>original_warn_node = BuildEnvironment.warn_node <add> <add>def ignore_more_than_one_target_found_errors(self, msg, node): <add> if "more than one target found" in msg: <add> return None <add> <add> return original_warn_node(self, msg, node) <add> <add> <add># Monkey patch the original methods <add>AutoDirective.warn = noop <add>AutodocReporter.warning = mock_warning <add> <add>BuildEnvironment.warn_node = ignore_more_than_one_target_found_errors
1
Python
Python
test previous commit
a79343f5b03407bba225a40e1383f515faee473d
<ide><path>tests/auto/test_loss_masking.py <add>import numpy as np <add>from keras.models import Sequential <add>from keras.layers.core import TimeDistributedDense, Masking <add> <add> <add>def test_cost_masking(): <add> X = np.array( <add> [[[1, 1], [2, 1], [3, 1], [5, 5]], <add> [[1, 5], [5, 0], [0, 0], [0, 0]]], dtype=np.int32) <add> <add> model = Sequential() <add> model.add(Masking(mask_value=0)) <add> model.add(TimeDistributedDense(2, 1, init='one')) <add> model.compile(loss='mse', optimizer='sgd') <add> y = model.predict(X) <add> <add> loss = model.fit(X, 4*y, nb_epoch=1, batch_size=2, verbose=1).history['loss'][0] <add> assert loss == 213.75 <add> <add> model = Sequential() <add> model.add(Masking(mask_value=0)) <add> model.add(TimeDistributedDense(2, 1, init='one')) <add> model.compile(loss='mse', optimizer='sgd', mask_cost=True) <add> loss = model.fit(X, 4*y, nb_epoch=1, batch_size=2, verbose=1).history['loss'][0] <add> assert loss == 285.0
1
PHP
PHP
fix errors in mysqltest
2def930c7d25af73833c95da5d476b73c585dd15
<ide><path>tests/TestCase/Database/Driver/MysqlTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Database\Driver; <ide> <add>use Cake\Database\Connection; <ide> use Cake\Database\Driver\Mysql; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\TestCase; <ide> public function testConnectionConfigDefault() <ide> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, <ide> ]; <ide> $connection = $this->getMockBuilder('StdClass') <del> ->onlyMethods(['exec']) <add> ->addMethods(['exec']) <ide> ->getMock(); <ide> <ide> $driver->expects($this->once())->method('_connect') <ide> public function testConnectionConfigCustom() <ide> ]; <ide> <ide> $connection = $this->getMockBuilder('StdClass') <del> ->onlyMethods(['exec']) <add> ->addMethods(['exec']) <ide> ->getMock(); <ide> $connection->expects($this->at(0))->method('exec')->with('Execute this'); <ide> $connection->expects($this->at(1))->method('exec')->with('this too'); <ide> public function testVersion($dbVersion, $expectedVersion) <ide> { <ide> /** @var \PHPUnit\Framework\MockObject\MockObject&\Cake\Database\Connection $connection */ <ide> $connection = $this->getMockBuilder(Connection::class) <del> ->onlyMethods(['getAttribute']) <add> ->disableOriginalConstructor() <add> ->addMethods(['getAttribute']) <ide> ->getMock(); <ide> $connection->expects($this->once()) <ide> ->method('getAttribute')
1
Java
Java
use system.nanotime() in stopwatch
a532afb15d298f2114d6072f0d29138c89bda04f
<ide><path>spring-core/src/main/java/org/springframework/util/StopWatch.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.text.NumberFormat; <ide> import java.util.LinkedList; <ide> import java.util.List; <add>import java.util.concurrent.TimeUnit; <ide> <ide> import org.springframework.lang.Nullable; <ide> <ide> /** <del> * Simple stop watch, allowing for timing of a number of tasks, <del> * exposing total running time and running time for each named task. <add> * Simple stop watch, allowing for timing of a number of tasks, exposing total <add> * running time and running time for each named task. <ide> * <del> * <p>Conceals use of {@code System.currentTimeMillis()}, improving the <del> * readability of application code and reducing the likelihood of calculation errors. <add> * <p>Conceals use of {@link System#nanoTime()}, improving the readability of <add> * application code and reducing the likelihood of calculation errors. <ide> * <del> * <p>Note that this object is not designed to be thread-safe and does not <del> * use synchronization. <add> * <p>Note that this object is not designed to be thread-safe and does not use <add> * synchronization. <ide> * <del> * <p>This class is normally used to verify performance during proof-of-concepts <del> * and in development, rather than as part of production applications. <add> * <p>This class is normally used to verify performance during proof-of-concept <add> * work and in development, rather than as part of production applications. <add> * <add> * <p>As of Spring Framework 5.2, running time is tracked and reported in <add> * nanoseconds. <ide> * <ide> * @author Rod Johnson <ide> * @author Juergen Hoeller <ide> public class StopWatch { <ide> <ide> /** <del> * Identifier of this stop watch. <del> * Handy when we have output from multiple stop watches <del> * and need to distinguish between them in log or console output. <add> * Identifier of this {@code StopWatch}. <add> * <p>Handy when we have output from multiple stop watches and need to <add> * distinguish between them in log or console output. <ide> */ <ide> private final String id; <ide> <ide> public class StopWatch { <ide> private final List<TaskInfo> taskList = new LinkedList<>(); <ide> <ide> /** Start time of the current task. */ <del> private long startTimeMillis; <add> private long startTimeNanos; <ide> <ide> /** Name of the current task. */ <ide> @Nullable <ide> public class StopWatch { <ide> private int taskCount; <ide> <ide> /** Total running time. */ <del> private long totalTimeMillis; <add> private long totalTimeNanos; <ide> <ide> <ide> /** <del> * Construct a new stop watch. Does not start any task. <add> * Construct a new {@code StopWatch}. <add> * <p>Does not start any task. <ide> */ <ide> public StopWatch() { <ide> this(""); <ide> } <ide> <ide> /** <del> * Construct a new stop watch with the given id. <del> * Does not start any task. <del> * @param id identifier for this stop watch. <del> * Handy when we have output from multiple stop watches <del> * and need to distinguish between them. <add> * Construct a new {@code StopWatch} with the given ID. <add> * <p>The ID is handy when we have output from multiple stop watches and need <add> * to distinguish between them. <add> * <p>Does not start any task. <add> * @param id identifier for this stop watch <ide> */ <ide> public StopWatch(String id) { <ide> this.id = id; <ide> } <ide> <ide> <ide> /** <del> * Return the id of this stop watch, as specified on construction. <del> * @return the id (empty String by default) <add> * Get the ID of this {@code StopWatch}, as specified on construction. <add> * @return the ID (empty String by default) <ide> * @since 4.2.2 <ide> * @see #StopWatch(String) <ide> */ <ide> public String getId() { <ide> } <ide> <ide> /** <del> * Determine whether the TaskInfo array is built over time. Set this to <del> * "false" when using a StopWatch for millions of intervals, or the task <del> * info structure will consume excessive memory. Default is "true". <add> * Configure whether the {@link TaskInfo} array is built over time. <add> * <p>Set this to {@code false} when using a {@code StopWatch} for millions <add> * of intervals; otherwise, the {@code TaskInfo} structure will consume <add> * excessive memory. <add> * <p>Default is {@code true}. <ide> */ <ide> public void setKeepTaskList(boolean keepTaskList) { <ide> this.keepTaskList = keepTaskList; <ide> } <ide> <ide> <ide> /** <del> * Start an unnamed task. The results are undefined if {@link #stop()} <del> * or timing methods are called without invoking this method. <add> * Start an unnamed task. <add> * <p>The results are undefined if {@link #stop()} or timing methods are <add> * called without invoking this method first. <add> * @see #start(String) <ide> * @see #stop() <ide> */ <ide> public void start() throws IllegalStateException { <ide> start(""); <ide> } <ide> <ide> /** <del> * Start a named task. The results are undefined if {@link #stop()} <del> * or timing methods are called without invoking this method. <add> * Start a named task. <add> * <p>The results are undefined if {@link #stop()} or timing methods are <add> * called without invoking this method first. <ide> * @param taskName the name of the task to start <add> * @see #start() <ide> * @see #stop() <ide> */ <ide> public void start(String taskName) throws IllegalStateException { <ide> if (this.currentTaskName != null) { <ide> throw new IllegalStateException("Can't start StopWatch: it's already running"); <ide> } <ide> this.currentTaskName = taskName; <del> this.startTimeMillis = System.currentTimeMillis(); <add> this.startTimeNanos = System.nanoTime(); <ide> } <ide> <ide> /** <del> * Stop the current task. The results are undefined if timing <del> * methods are called without invoking at least one pair <del> * {@code start()} / {@code stop()} methods. <add> * Stop the current task. <add> * <p>The results are undefined if timing methods are called without invoking <add> * at least one pair of {@code start()} / {@code stop()} methods. <ide> * @see #start() <add> * @see #start(String) <ide> */ <ide> public void stop() throws IllegalStateException { <ide> if (this.currentTaskName == null) { <ide> throw new IllegalStateException("Can't stop StopWatch: it's not running"); <ide> } <del> long lastTime = System.currentTimeMillis() - this.startTimeMillis; <del> this.totalTimeMillis += lastTime; <add> long lastTime = System.nanoTime() - this.startTimeNanos; <add> this.totalTimeNanos += lastTime; <ide> this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime); <ide> if (this.keepTaskList) { <ide> this.taskList.add(this.lastTaskInfo); <ide> public void stop() throws IllegalStateException { <ide> } <ide> <ide> /** <del> * Return whether the stop watch is currently running. <add> * Determine whether this {@code StopWatch} is currently running. <ide> * @see #currentTaskName() <ide> */ <ide> public boolean isRunning() { <ide> return (this.currentTaskName != null); <ide> } <ide> <ide> /** <del> * Return the name of the currently running task, if any. <add> * Get the name of the currently running task, if any. <ide> * @since 4.2.2 <ide> * @see #isRunning() <ide> */ <ide> public String currentTaskName() { <ide> return this.currentTaskName; <ide> } <ide> <add> /** <add> * Get the time taken by the last task in nanoseconds. <add> * @since 5.2 <add> * @see #getLastTaskTimeMillis() <add> */ <add> public long getLastTaskTimeNanos() throws IllegalStateException { <add> if (this.lastTaskInfo == null) { <add> throw new IllegalStateException("No tasks run: can't get last task interval"); <add> } <add> return this.lastTaskInfo.getTimeNanos(); <add> } <ide> <ide> /** <del> * Return the time taken by the last task. <add> * Get the time taken by the last task in milliseconds. <add> * @see #getLastTaskTimeNanos() <ide> */ <ide> public long getLastTaskTimeMillis() throws IllegalStateException { <ide> if (this.lastTaskInfo == null) { <ide> public long getLastTaskTimeMillis() throws IllegalStateException { <ide> } <ide> <ide> /** <del> * Return the name of the last task. <add> * Get the name of the last task. <ide> */ <ide> public String getLastTaskName() throws IllegalStateException { <ide> if (this.lastTaskInfo == null) { <ide> public String getLastTaskName() throws IllegalStateException { <ide> } <ide> <ide> /** <del> * Return the last task as a TaskInfo object. <add> * Get the last task as a {@link TaskInfo} object. <ide> */ <ide> public TaskInfo getLastTaskInfo() throws IllegalStateException { <ide> if (this.lastTaskInfo == null) { <ide> public TaskInfo getLastTaskInfo() throws IllegalStateException { <ide> <ide> <ide> /** <del> * Return the total time in milliseconds for all tasks. <add> * Get the total time in nanoseconds for all tasks. <add> * @since 5.2 <add> * @see #getTotalTimeMillis() <add> * @see #getTotalTimeSeconds() <add> */ <add> public long getTotalTimeNanos() { <add> return this.totalTimeNanos; <add> } <add> <add> /** <add> * Get the total time in milliseconds for all tasks. <add> * @see #getTotalTimeNanos() <add> * @see #getTotalTimeSeconds() <ide> */ <ide> public long getTotalTimeMillis() { <del> return this.totalTimeMillis; <add> return nanosToMillis(this.totalTimeNanos); <ide> } <ide> <ide> /** <del> * Return the total time in seconds for all tasks. <add> * Get the total time in seconds for all tasks. <add> * @see #getTotalTimeNanos() <add> * @see #getTotalTimeMillis() <ide> */ <ide> public double getTotalTimeSeconds() { <del> return this.totalTimeMillis / 1000.0; <add> return nanosToSeconds(this.totalTimeNanos); <ide> } <ide> <ide> /** <del> * Return the number of tasks timed. <add> * Get the number of tasks timed. <ide> */ <ide> public int getTaskCount() { <ide> return this.taskCount; <ide> } <ide> <ide> /** <del> * Return an array of the data for tasks performed. <add> * Get an array of the data for tasks performed. <ide> */ <ide> public TaskInfo[] getTaskInfo() { <ide> if (!this.keepTaskList) { <ide> public TaskInfo[] getTaskInfo() { <ide> <ide> <ide> /** <del> * Return a short description of the total running time. <add> * Get a short description of the total running time. <ide> */ <ide> public String shortSummary() { <del> return "StopWatch '" + getId() + "': running time (millis) = " + getTotalTimeMillis(); <add> return "StopWatch '" + getId() + "': running time = " + getTotalTimeNanos() + " ns"; <ide> } <ide> <ide> /** <del> * Return a string with a table describing all tasks performed. <del> * For custom reporting, call getTaskInfo() and use the task info directly. <add> * Generate a string with a table describing all tasks performed. <add> * <p>For custom reporting, call {@link #getTaskInfo()} and use the task info <add> * directly. <ide> */ <ide> public String prettyPrint() { <ide> StringBuilder sb = new StringBuilder(shortSummary()); <ide> public String prettyPrint() { <ide> sb.append("No task info kept"); <ide> } <ide> else { <del> sb.append("-----------------------------------------\n"); <del> sb.append("ms % Task name\n"); <del> sb.append("-----------------------------------------\n"); <add> sb.append("---------------------------------------------\n"); <add> sb.append("ns % Task name\n"); <add> sb.append("---------------------------------------------\n"); <ide> NumberFormat nf = NumberFormat.getNumberInstance(); <del> nf.setMinimumIntegerDigits(5); <add> nf.setMinimumIntegerDigits(9); <ide> nf.setGroupingUsed(false); <ide> NumberFormat pf = NumberFormat.getPercentInstance(); <ide> pf.setMinimumIntegerDigits(3); <ide> pf.setGroupingUsed(false); <ide> for (TaskInfo task : getTaskInfo()) { <del> sb.append(nf.format(task.getTimeMillis())).append(" "); <del> sb.append(pf.format(task.getTimeSeconds() / getTotalTimeSeconds())).append(" "); <add> sb.append(nf.format(task.getTimeNanos())).append(" "); <add> sb.append(pf.format((double) task.getTimeNanos() / getTotalTimeNanos())).append(" "); <ide> sb.append(task.getTaskName()).append("\n"); <ide> } <ide> } <ide> return sb.toString(); <ide> } <ide> <ide> /** <del> * Return an informative string describing all tasks performed <del> * For custom reporting, call {@code getTaskInfo()} and use the task info directly. <add> * Generate an informative string describing all tasks performed <add> * <p>For custom reporting, call {@link #getTaskInfo()} and use the task info <add> * directly. <ide> */ <ide> @Override <ide> public String toString() { <ide> StringBuilder sb = new StringBuilder(shortSummary()); <ide> if (this.keepTaskList) { <ide> for (TaskInfo task : getTaskInfo()) { <del> sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeMillis()); <del> long percent = Math.round((100.0 * task.getTimeSeconds()) / getTotalTimeSeconds()); <add> sb.append("; [").append(task.getTaskName()).append("] took ").append(task.getTimeNanos()).append(" ns"); <add> long percent = Math.round(100.0 * task.getTimeNanos() / getTotalTimeNanos()); <ide> sb.append(" = ").append(percent).append("%"); <ide> } <ide> } <ide> public String toString() { <ide> } <ide> <ide> <add> private static long nanosToMillis(long duration) { <add> return TimeUnit.NANOSECONDS.toMillis(duration); <add> } <add> <add> private static double nanosToSeconds(long duration) { <add> return duration / 1_000_000_000.0; <add> } <add> <add> <ide> /** <del> * Inner class to hold data about one task executed within the stop watch. <add> * Nested class to hold data about one task executed within the {@code StopWatch}. <ide> */ <ide> public static final class TaskInfo { <ide> <ide> private final String taskName; <ide> <del> private final long timeMillis; <add> private final long timeNanos; <ide> <del> TaskInfo(String taskName, long timeMillis) { <add> TaskInfo(String taskName, long timeNanos) { <ide> this.taskName = taskName; <del> this.timeMillis = timeMillis; <add> this.timeNanos = timeNanos; <ide> } <ide> <ide> /** <del> * Return the name of this task. <add> * Get the name of this task. <ide> */ <ide> public String getTaskName() { <ide> return this.taskName; <ide> } <ide> <ide> /** <del> * Return the time in milliseconds this task took. <add> * Get the time in nanoseconds this task took. <add> * @since 5.2 <add> * @see #getTimeMillis() <add> * @see #getTimeSeconds() <add> */ <add> public long getTimeNanos() { <add> return this.timeNanos; <add> } <add> <add> /** <add> * Get the time in milliseconds this task took. <add> * @see #getTimeNanos() <add> * @see #getTimeSeconds() <ide> */ <ide> public long getTimeMillis() { <del> return this.timeMillis; <add> return nanosToMillis(this.timeNanos); <ide> } <ide> <ide> /** <del> * Return the time in seconds this task took. <add> * Get the time in seconds this task took. <add> * @see #getTimeMillis() <add> * @see #getTimeNanos() <ide> */ <ide> public double getTimeSeconds() { <del> return (this.timeMillis / 1000.0); <add> return nanosToSeconds(this.timeNanos); <ide> } <add> <ide> } <ide> <ide> } <ide><path>spring-core/src/test/java/org/springframework/util/StopWatchTests.java <ide> <ide> package org.springframework.util; <ide> <add>import java.util.concurrent.TimeUnit; <add> <ide> import org.junit.Test; <ide> <ide> import org.springframework.util.StopWatch.TaskInfo; <ide> public class StopWatchTests { <ide> private static final String name2 = "Task 2"; <ide> <ide> private static final long duration1 = 200; <del> private static final long duration2 = 50; <del> private static final long fudgeFactor = 20; <add> private static final long duration2 = 100; <add> private static final long fudgeFactor = 50; <ide> <ide> private final StopWatch stopWatch = new StopWatch(ID); <ide> <ide> public void rejectsStartTwice() { <ide> @Test <ide> public void validUsage() throws Exception { <ide> assertThat(stopWatch.isRunning()).isFalse(); <add> <ide> stopWatch.start(name1); <ide> Thread.sleep(duration1); <ide> assertThat(stopWatch.isRunning()).isTrue(); <ide> assertThat(stopWatch.currentTaskName()).isEqualTo(name1); <ide> stopWatch.stop(); <ide> assertThat(stopWatch.isRunning()).isFalse(); <del> <add> assertThat(stopWatch.getLastTaskTimeNanos()) <add> .as("last task time in nanoseconds for task #1") <add> .isGreaterThanOrEqualTo(millisToNanos(duration1)) <add> .isLessThanOrEqualTo(millisToNanos(duration1 + fudgeFactor)); <ide> assertThat(stopWatch.getTotalTimeMillis()) <del> .as("Unexpected timing " + stopWatch.getTotalTimeMillis()) <del> .isGreaterThanOrEqualTo(duration1); <del> assertThat(stopWatch.getTotalTimeMillis()) <del> .as("Unexpected timing " + stopWatch.getTotalTimeMillis()) <add> .as("total time in milliseconds for task #1") <add> .isGreaterThanOrEqualTo(duration1) <ide> .isLessThanOrEqualTo(duration1 + fudgeFactor); <add> assertThat(stopWatch.getTotalTimeSeconds()) <add> .as("total time in seconds for task #1") <add> .isGreaterThanOrEqualTo(duration1 / 1000.0) <add> .isLessThanOrEqualTo((duration1 + fudgeFactor) / 1000.0); <ide> <ide> stopWatch.start(name2); <ide> Thread.sleep(duration2); <add> assertThat(stopWatch.isRunning()).isTrue(); <add> assertThat(stopWatch.currentTaskName()).isEqualTo(name2); <ide> stopWatch.stop(); <del> <del> assertThat(stopWatch.getTotalTimeMillis()) <del> .as("Unexpected timing " + stopWatch.getTotalTimeMillis()) <del> .isGreaterThanOrEqualTo(duration1 + duration2); <add> assertThat(stopWatch.isRunning()).isFalse(); <add> assertThat(stopWatch.getLastTaskTimeNanos()) <add> .as("last task time in nanoseconds for task #2") <add> .isGreaterThanOrEqualTo(millisToNanos(duration2)) <add> .isLessThanOrEqualTo(millisToNanos(duration2 + fudgeFactor)); <ide> assertThat(stopWatch.getTotalTimeMillis()) <del> .as("Unexpected timing " + stopWatch.getTotalTimeMillis()) <add> .as("total time in milliseconds for tasks #1 and #2") <add> .isGreaterThanOrEqualTo(duration1 + duration2) <ide> .isLessThanOrEqualTo(duration1 + duration2 + fudgeFactor); <add> assertThat(stopWatch.getTotalTimeSeconds()) <add> .as("total time in seconds for task #2") <add> .isGreaterThanOrEqualTo((duration1 + duration2) / 1000.0) <add> .isLessThanOrEqualTo((duration1 + duration2 + fudgeFactor) / 1000.0); <ide> <ide> assertThat(stopWatch.getTaskCount()).isEqualTo(2); <ide> assertThat(stopWatch.prettyPrint()).contains(name1, name2); <ide> public void validUsage() throws Exception { <ide> public void validUsageDoesNotKeepTaskList() throws Exception { <ide> stopWatch.setKeepTaskList(false); <ide> <del> assertThat(stopWatch.isRunning()).isFalse(); <del> <ide> stopWatch.start(name1); <ide> Thread.sleep(duration1); <del> assertThat(stopWatch.isRunning()).isTrue(); <add> assertThat(stopWatch.currentTaskName()).isEqualTo(name1); <ide> stopWatch.stop(); <del> assertThat(stopWatch.isRunning()).isFalse(); <ide> <ide> stopWatch.start(name2); <ide> Thread.sleep(duration2); <del> assertThat(stopWatch.isRunning()).isTrue(); <add> assertThat(stopWatch.currentTaskName()).isEqualTo(name2); <ide> stopWatch.stop(); <del> assertThat(stopWatch.isRunning()).isFalse(); <ide> <ide> assertThat(stopWatch.getTaskCount()).isEqualTo(2); <ide> assertThat(stopWatch.prettyPrint()).contains("No task info kept"); <ide> assertThat(stopWatch.toString()).doesNotContain(name1, name2); <del> assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(stopWatch::getTaskInfo); <add> assertThatExceptionOfType(UnsupportedOperationException.class) <add> .isThrownBy(stopWatch::getTaskInfo) <add> .withMessage("Task info is not being kept!"); <add> } <add> <add> private static long millisToNanos(long duration) { <add> return TimeUnit.NANOSECONDS.convert(duration, TimeUnit.MILLISECONDS); <ide> } <ide> <ide> }
2
Python
Python
fix deprecation warning for return_all_scores
22d37a9d2c685cc0d1ca33903fa9f00ca53a56a1
<ide><path>src/transformers/pipelines/text_classification.py <ide> def _sanitize_parameters(self, return_all_scores=None, function_to_apply=None, t <ide> postprocess_params["_legacy"] = False <ide> elif return_all_scores is not None: <ide> warnings.warn( <del> "`return_all_scores` is now deprecated, use `top_k=1` if you want similar functionnality", UserWarning <add> "`return_all_scores` is now deprecated, if want a similar funcionality use `top_k=None` instead of" <add> " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.", <add> UserWarning, <ide> ) <ide> if return_all_scores: <ide> postprocess_params["top_k"] = None
1
Ruby
Ruby
recommend interactive usage of `fish_add_path`
00f209e16ed0698f10c8b8d03204f3d7e9850ce8
<ide><path>Library/Homebrew/test/utils/shell_spec.rb <ide> ENV["SHELL"] = "/usr/local/bin/fish" <ide> ENV["fish_user_paths"] = "/some/path" <ide> expect(described_class.prepend_path_in_profile(path)) <del> .to eq("echo 'fish_add_path #{path}' >> #{shell_profile}") <add> .to eq("fish_add_path #{path}") <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/utils/shell.rb <ide> def prepend_path_in_profile(path) <ide> when :csh, :tcsh <ide> "echo 'setenv PATH #{csh_quote(path)}:$PATH' >> #{profile}" <ide> when :fish <del> "echo 'fish_add_path #{sh_quote(path)}' >> #{profile}" <add> "fish_add_path #{sh_quote(path)}" <ide> end <ide> end <ide>
2
Ruby
Ruby
return fetched content in match_data
eedd108acec7e94724b226c85e7c651d9b9623ae
<ide><path>Library/Homebrew/livecheck/strategy/page_match.rb <ide> def self.find_versions(url, regex, provided_content = nil, &block) <ide> provided_content <ide> else <ide> match_data.merge!(Strategy.page_content(url)) <del> match_data.delete(:content) <add> match_data[:content] <ide> end <ide> return match_data if content.blank? <ide>
1
PHP
PHP
add semi-colon onto padding to be safe
4f5cc0cd97676e5064b176cee7b0432df31ba975
<ide><path>laravel/response.php <ide> public static function jsonp($callback, $data, $status = 200, $headers = array() <ide> { <ide> $headers['Content-Type'] = 'application/javascript; charset=utf-8'; <ide> <del> return new static($callback.'('.json_encode($data).')', $status, $headers); <add> return new static($callback.'('.json_encode($data).');', $status, $headers); <ide> } <ide> <ide> /**
1
Javascript
Javascript
fix failing assertion
8c0290e0543af85ac82c243987d5996c00a16cc6
<ide><path>test/parallel/test-assert.js <ide> const circular = { y: 1 }; <ide> circular.x = circular; <ide> <ide> function testAssertionMessage(actual, expected, msg) { <del> try { <del> assert.strictEqual(actual, ''); <del> } catch (e) { <del> assert.strictEqual( <del> e.message, <del> msg || strictEqualMessageStart + <del> `+ actual - expected\n\n+ ${expected}\n- ''` <del> ); <del> assert.ok(e.generatedMessage, 'Message not marked as generated'); <del> } <add> assert.throws( <add> () => assert.strictEqual(actual, ''), <add> { <add> generatedMessage: true, <add> message: msg || strictEqualMessageStart + <add> `+ actual - expected\n\n+ ${expected}\n- ''` <add> } <add> ); <ide> } <ide> <ide> function testShortAssertionMessage(actual, expected) { <ide> testShortAssertionMessage(false, 'false'); <ide> testShortAssertionMessage(100, '100'); <ide> testShortAssertionMessage(NaN, 'NaN'); <ide> testShortAssertionMessage(Infinity, 'Infinity'); <del>testShortAssertionMessage('', '""'); <add>testShortAssertionMessage('a', '"a"'); <ide> testShortAssertionMessage('foo', '\'foo\''); <ide> testShortAssertionMessage(0, '0'); <ide> testShortAssertionMessage(Symbol(), 'Symbol()');
1
Python
Python
add torch.no_grad when in eval mode
bdd690a74da5283cbc893dfd79e1c7c72ec1bcfa
<ide><path>examples/pytorch/image-classification/run_image_classification_no_trainer.py <ide> def collate_fn(examples): <ide> model.eval() <ide> samples_seen = 0 <ide> for step, batch in enumerate(eval_dataloader): <del> outputs = model(**batch) <add> with torch.no_grad(): <add> outputs = model(**batch) <ide> predictions = outputs.logits.argmax(dim=-1) <ide> predictions, references = accelerator.gather((predictions, batch["labels"])) <ide> # If we are in a multiprocess environment, the last batch has duplicates <ide><path>examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py <ide> def preprocess_val(example_batch): <ide> model.eval() <ide> samples_seen = 0 <ide> for step, batch in enumerate(tqdm(eval_dataloader, disable=not accelerator.is_local_main_process)): <del> outputs = model(**batch) <add> with torch.no_grad(): <add> outputs = model(**batch) <ide> <ide> upsampled_logits = torch.nn.functional.interpolate( <ide> outputs.logits, size=batch["labels"].shape[-2:], mode="bilinear", align_corners=False <ide><path>examples/pytorch/text-classification/run_glue_no_trainer.py <ide> from pathlib import Path <ide> <ide> import datasets <add>import torch <ide> from datasets import load_dataset, load_metric <ide> from torch.utils.data import DataLoader <ide> from tqdm.auto import tqdm <ide> def preprocess_function(examples): <ide> model.eval() <ide> samples_seen = 0 <ide> for step, batch in enumerate(eval_dataloader): <del> outputs = model(**batch) <add> with torch.no_grad(): <add> outputs = model(**batch) <ide> predictions = outputs.logits.argmax(dim=-1) if not is_regression else outputs.logits.squeeze() <ide> predictions, references = accelerator.gather((predictions, batch["labels"])) <ide> # If we are in a multiprocess environment, the last batch has duplicates <ide><path>templates/adding_a_new_example_script/{{cookiecutter.directory_name}}/run_{{cookiecutter.example_shortcut}}.py <ide> from typing import Optional, List <ide> <ide> import datasets <add>import torch <ide> from datasets import load_dataset <ide> <ide> import transformers <ide> def tokenize_function(examples): <ide> <ide> model.eval() <ide> for step, batch in enumerate(eval_dataloader): <del> outputs = model(**batch) <add> with torch.no_grad(): <add> outputs = model(**batch) <ide> predictions = outputs.logits.argmax(dim=-1) <ide> metric.add_batch( <ide> predictions=accelerator.gather(predictions),
4
Javascript
Javascript
fix template only components
8ef863f10275318241bc6cc33a7ff1517b052ce7
<ide><path>packages/ember/tests/component_registration_test.js <ide> import Controller from '@ember/controller'; <ide> import { Component } from 'ember-glimmer'; <ide> import { compile } from 'ember-template-compiler'; <ide> import { moduleFor, ApplicationTestCase } from 'internal-test-helpers'; <add>import { ENV } from 'ember-environment'; <ide> <ide> moduleFor( <ide> 'Application Lifecycle - Component Registration', <ide> moduleFor( <ide> return super.createApplication(options, Application.extend()); <ide> } <ide> <del> ['@feature(!ember-glimmer-template-only-components) The helper becomes the body of the component']() { <add> ['@test The helper becomes the body of the component']() { <ide> this.addTemplate('components/expand-it', '<p>hello {{yield}}</p>'); <ide> this.addTemplate('application', 'Hello world {{#expand-it}}world{{/expand-it}}'); <ide> <ide> moduleFor( <ide> }); <ide> } <ide> <del> ['@feature(ember-glimmer-template-only-components) The helper becomes the body of the component']() { <add> ['@test The helper becomes the body of the component (ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS = true;)']() { <add> ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS = true; <ide> this.addTemplate('components/expand-it', '<p>hello {{yield}}</p>'); <ide> this.addTemplate('application', 'Hello world {{#expand-it}}world{{/expand-it}}'); <ide> <ide> return this.visit('/').then(() => { <ide> this.assertInnerHTML('Hello world <p>hello world</p>'); <add> ENV._TEMPLATE_ONLY_GLIMMER_COMPONENTS = false; <ide> }); <ide> } <ide>
1
Javascript
Javascript
add support for custom @usage metadata
e05a97c6f5bcef1ae300c7d4181fcf2a34f0aab1
<ide><path>docs/src/ngdoc.js <ide> Doc.prototype = { <ide> dom.h('Usage', function() { <ide> dom.h('In HTML Template Binding', function() { <ide> dom.tag('code', function() { <del> dom.text('{{ '); <del> dom.text(self.shortName); <del> dom.text('_expression | '); <del> dom.text(self.shortName); <del> self.parameters(dom, ':', true); <del> dom.text(' }}'); <add> if (self.usage) { <add> dom.text(self.usage); <add> } else { <add> dom.text('{{ '); <add> dom.text(self.shortName); <add> dom.text('_expression | '); <add> dom.text(self.shortName); <add> self.parameters(dom, ':', true); <add> dom.text(' }}'); <add> } <ide> }); <ide> }); <ide>
1
Ruby
Ruby
rename it to datastreaming
7a152ab0127877eea6f2cef8ff6d1975a3fc16d4
<ide><path>actionpack/lib/action_controller.rb <ide> module ActionController <ide> autoload :Compatibility <ide> autoload :ConditionalGet <ide> autoload :Cookies <add> autoload :DataStreaming <ide> autoload :Flash <ide> autoload :ForceSSL <ide> autoload :Head <ide> module ActionController <ide> autoload :Rescue <ide> autoload :Responder <ide> autoload :SessionManagement <del> autoload :Streaming <ide> autoload :Testing <ide> autoload :UrlFor <ide> end <ide><path>actionpack/lib/action_controller/base.rb <ide> def self.without_modules(*modules) <ide> Flash, <ide> RequestForgeryProtection, <ide> ForceSSL, <del> Streaming, <add> DataStreaming, <ide> RecordIdentifier, <ide> HttpAuthentication::Basic::ControllerMethods, <ide> HttpAuthentication::Digest::ControllerMethods, <add><path>actionpack/lib/action_controller/metal/data_streaming.rb <del><path>actionpack/lib/action_controller/metal/streaming.rb <ide> module ActionController #:nodoc: <ide> # Methods for sending arbitrary data and for streaming files to the browser, <ide> # instead of rendering. <del> module Streaming <add> module DataStreaming <ide> extend ActiveSupport::Concern <ide> <ide> include ActionController::Rendering
3
Javascript
Javascript
switch htmlvideoelement to constructor reference
f86e073f03aa504c11e272d40daf4ab6a6728483
<ide><path>src/js/media/html5.js <ide> vjs.Html5.canControlVolume = function(){ <ide> // Android 4.0 and above can play HLS to some extent but it reports being unable to do so <ide> if (vjs.ANDROID_VERSION >= 4.0) { <ide> if (!canPlayType) { <del> canPlayType = HTMLVideoElement.prototype.canPlayType; <add> canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; <ide> } <ide> <del> HTMLVideoElement.prototype.canPlayType = function(type) { <add> vjs.TEST_VID.constructor.prototype.canPlayType = function(type) { <ide> if (type && mpegurlRE.test(type)) { <ide> return "maybe"; <ide> } <ide> vjs.Html5.canControlVolume = function(){ <ide> // Override Android 2.2 and less canPlayType method which is broken <ide> if (vjs.IS_OLD_ANDROID) { <ide> if (!canPlayType) { <del> canPlayType = HTMLVideoElement.prototype.canPlayType; <add> canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; <ide> } <ide> <del> HTMLVideoElement.prototype.canPlayType = function(type){ <add> vjs.TEST_VID.constructor.prototype.canPlayType = function(type){ <ide> if (type && mp4RE.test(type)) { <ide> return "maybe"; <ide> } <ide> vjs.Html5.canControlVolume = function(){ <ide> vjs.Html5.unpatchCanPlayType = function() { <ide> var r = canPlayType; <ide> if (canPlayType) { <del> HTMLVideoElement.prototype.canPlayType = canPlayType; <add> vjs.TEST_VID.constructor.prototype.canPlayType = canPlayType; <ide> canPlayType = null; <ide> return r; <ide> }
1
Javascript
Javascript
raise hangup error on destroyed socket write
c9dcf5718cf47322b00f2994797aebb68d7ed0fb
<ide><path>lib/http.js <ide> OutgoingMessage.prototype._writeRaw = function(data, encoding) { <ide> <ide> if (this.connection && <ide> this.connection._httpMessage === this && <del> this.connection.writable) { <add> this.connection.writable && <add> !this.connection.destroyed) { <ide> // There might be pending data in the this.output buffer. <ide> while (this.output.length) { <ide> if (!this.connection.writable) { <ide> OutgoingMessage.prototype._writeRaw = function(data, encoding) { <ide> <ide> // Directly write to socket. <ide> return this.connection.write(data, encoding); <add> } else if (this.connection && this.connection.destroyed) { <add> // The socket was destroyed. If we're still trying to write to it, <add> // then something bad happened. <add> // If we've already raised an error on this message, then just ignore. <add> if (!this._hadError) { <add> this.emit('error', createHangUpError()); <add> this._hadError = true; <add> } <ide> } else { <add> // buffer, as long as we're not destroyed. <ide> this._buffer(data, encoding); <ide> return false; <ide> } <ide> function socketCloseListener() { <ide> // receive a response. The error needs to <ide> // fire on the request. <ide> req.emit('error', createHangUpError()); <add> req._hadError = true; <ide> } <ide> <add> // Too bad. That output wasn't getting written. <add> // This is pretty terrible that it doesn't raise an error. <add> // Fixed better in v0.10 <add> if (req.output) <add> req.output.length = 0; <add> if (req.outputEncodings) <add> req.outputEncodings.length = 0; <add> <ide> if (parser) { <ide> parser.finish(); <ide> freeParser(parser, req); <ide><path>test/simple/test-http-destroyed-socket-write.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>// Fix the memory explosion that happens when writing to a http request <add>// where the server has destroyed the socket on us between a successful <add>// first request, and a subsequent request that reuses the socket. <add>// <add>// This test should not be ported to v0.10 and higher, because the <add>// problem is fixed by not ignoring ECONNRESET in the first place. <add> <add>var http = require('http'); <add>var net = require('net'); <add>var server = http.createServer(function(req, res) { <add> // simulate a server that is in the process of crashing or something <add> // it only crashes after the first request, but before the second, <add> // which reuses the connection. <add> res.end('hallo wereld\n', function() { <add> setTimeout(function() { <add> req.connection.destroy(); <add> }, 100); <add> }); <add>}); <add> <add>var gotFirstResponse = false; <add>var gotFirstData = false; <add>var gotFirstEnd = false; <add>server.listen(common.PORT, function() { <add> <add> var gotFirstResponse = false; <add> var first = http.request({ <add> port: common.PORT, <add> path: '/' <add> }); <add> first.on('response', function(res) { <add> gotFirstResponse = true; <add> res.on('data', function(chunk) { <add> gotFirstData = true; <add> }); <add> res.on('end', function() { <add> gotFirstEnd = true; <add> }) <add> }); <add> first.end(); <add> second(); <add> <add> function second() { <add> var sec = http.request({ <add> port: common.PORT, <add> path: '/', <add> method: 'POST' <add> }); <add> <add> var timer = setTimeout(write, 200); <add> var writes = 0; <add> var sawFalseWrite; <add> <add> var gotError = false; <add> sec.on('error', function(er) { <add> assert.equal(gotError, false); <add> gotError = true; <add> assert(er.code === 'ECONNRESET'); <add> clearTimeout(timer); <add> test(); <add> }); <add> <add> function write() { <add> if (++writes === 64) { <add> clearTimeout(timer); <add> sec.end(); <add> test(); <add> } else { <add> timer = setTimeout(write); <add> var writeRet = sec.write(new Buffer('hello')); <add> <add> // Once we find out that the connection is destroyed, every <add> // write() returns false <add> if (sawFalseWrite) <add> assert.equal(writeRet, false); <add> else <add> sawFalseWrite = writeRet === false; <add> } <add> } <add> <add> assert.equal(first.connection, sec.connection, <add> 'should reuse connection'); <add> <add> sec.on('response', function(res) { <add> res.on('data', function(chunk) { <add> console.error('second saw data: ' + chunk); <add> }); <add> res.on('end', function() { <add> console.error('second saw end'); <add> }); <add> }); <add> <add> function test() { <add> server.close(); <add> assert(sec.connection.destroyed); <add> if (sec.output.length || sec.outputEncodings.length) <add> console.error('bad happened', sec.output, sec.outputEncodings); <add> assert.equal(sec.output.length, 0); <add> assert.equal(sec.outputEncodings, 0); <add> assert(gotError); <add> assert(gotFirstResponse); <add> assert(gotFirstData); <add> assert(gotFirstEnd); <add> console.log('ok'); <add> } <add> } <add>});
2
Javascript
Javascript
accept classname in reactdomfiber
51f1205fb4fd6402b155202263ee12571ca4c3a6
<ide><path>src/renderers/dom/fiber/ReactDOMFiber.js <ide> var warning = require('warning'); <ide> type DOMContainerElement = Element & { _reactRootContainer: ?Object }; <ide> <ide> type Container = Element; <del>type Props = { }; <add>type Props = { className ?: string }; <ide> type Instance = Element; <ide> type TextInstance = Text; <ide> <ide> var DOMRenderer = ReactFiberReconciler({ <ide> createInstance(type : string, props : Props, children : HostChildren<Instance | TextInstance>) : Instance { <ide> const domElement = document.createElement(type); <ide> recursivelyAppendChildren(domElement, children); <add> if (typeof props.className !== 'undefined') { <add> domElement.className = props.className; <add> } <ide> if (typeof props.children === 'string') { <ide> domElement.textContent = props.children; <ide> } else if (typeof props.children === 'number') { <ide> var DOMRenderer = ReactFiberReconciler({ <ide> }, <ide> <ide> commitUpdate(domElement : Instance, oldProps : Props, newProps : Props) : void { <add> if (typeof newProps.className !== 'undefined') { <add> domElement.className = newProps.className; <add> } <ide> if (typeof newProps.children === 'string') { <ide> domElement.textContent = newProps.children; <ide> } else if (typeof newProps.children === 'number') {
1
Javascript
Javascript
expose promise instead of only $then
05772e15fbecfdc63d4977e2e8839d8b95d6a92d
<ide><path>src/ngResource/resource.js <ide> * requests with credentials} for more information. <ide> * - **`responseType`** - `{string}` - see {@link <ide> * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. <add> * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - <add> * `response` and `responseError`. Both `response` and `responseError` interceptors get called <add> * with `http response` object. See {@link ng.$http $http interceptors}. <ide> * <ide> * @returns {Object} A resource "class" object with methods for the default set of resource actions <ide> * optionally extended with custom `actions`. The default set contains these actions: <ide> * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` <ide> * - non-GET instance actions: `instance.$action([parameters], [success], [error])` <ide> * <add> * Success callback is called with (value, responseHeaders) arguments. Error callback is called <add> * with (httpResponse) argument. <ide> * <del> * The Resource instances and collection have these additional properties: <add> * Class actions return empty instance (with additional properties below). <add> * Instance actions return promise of the action. <ide> * <del> * - `$then`: the `then` method of a {@link ng.$q promise} derived from the underlying <del> * {@link ng.$http $http} call. <add> * The Resource instances and collection have these additional properties: <ide> * <del> * The success callback for the `$then` method will be resolved if the underlying `$http` requests <del> * succeeds. <add> * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this <add> * instance or collection. <ide> * <del> * The success callback is called with a single object which is the {@link ng.$http http response} <del> * object extended with a new property `resource`. This `resource` property is a reference to the <del> * result of the resource action — resource object or array of resources. <add> * On success, the promise is resolved with the same resource instance or collection object, <add> * updated with data from server. This makes it easy to use in <add> * {@link ng.$routeProvider resolve section of $routeProvider.when()} to defer view rendering <add> * until the resource(s) are loaded. <ide> * <del> * The error callback is called with the {@link ng.$http http response} object when an http <del> * error occurs. <add> * On failure, the promise is resolved with the {@link ng.$http http response} object, <add> * without the `resource` property. <ide> * <del> * - `$resolved`: true if the promise has been resolved (either with success or rejection); <del> * Knowing if the Resource has been resolved is useful in data-binding. <add> * - `$resolved`: `true` after first server interaction is completed (either with success or rejection), <add> * `false` before that. Knowing if the Resource has been resolved is useful in data-binding. <ide> * <ide> * @example <ide> * <ide> </doc:example> <ide> */ <ide> angular.module('ngResource', ['ng']). <del> factory('$resource', ['$http', '$parse', function($http, $parse) { <add> factory('$resource', ['$http', '$parse', '$q', function($http, $parse, $q) { <ide> var DEFAULT_ACTIONS = { <ide> 'get': {method:'GET'}, <ide> 'save': {method:'POST'}, <ide> angular.module('ngResource', ['ng']). <ide> return ids; <ide> } <ide> <add> function defaultResponseInterceptor(response) { <add> return response.resource; <add> } <add> <ide> function Resource(value){ <ide> copy(value || {}, this); <ide> } <ide> <ide> forEach(actions, function(action, name) { <del> action.method = angular.uppercase(action.method); <del> var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; <add> var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); <add> <ide> Resource[name] = function(a1, a2, a3, a4) { <del> var params = {}; <del> var data; <del> var success = noop; <del> var error = null; <del> var promise; <add> var params = {}, data, success, error; <ide> <ide> switch(arguments.length) { <ide> case 4: <ide> angular.module('ngResource', ['ng']). <ide> break; <ide> case 0: break; <ide> default: <del> throw "Expected between 0-4 arguments [params, data, success, error], got " + <add> throw "Expected up to 4 arguments [params, data, success, error], got " + <ide> arguments.length + " arguments."; <ide> } <ide> <del> var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); <del> var httpConfig = {}, <del> promise; <add> var isInstanceCall = data instanceof Resource; <add> var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); <add> var httpConfig = {}; <add> var responseInterceptor = action.interceptor && action.interceptor.response || defaultResponseInterceptor; <add> var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || undefined; <ide> <ide> forEach(action, function(value, key) { <del> if (key != 'params' && key != 'isArray' ) { <add> if (key != 'params' && key != 'isArray' && key != 'interceptor') { <ide> httpConfig[key] = copy(value); <ide> } <ide> }); <add> <ide> httpConfig.data = data; <ide> route.setUrlParams(httpConfig, extend({}, extractParams(data, action.params || {}), params), action.url); <ide> <del> function markResolved() { value.$resolved = true; } <del> <del> promise = $http(httpConfig); <del> value.$resolved = false; <del> <del> promise.then(markResolved, markResolved); <del> value.$then = promise.then(function(response) { <del> var data = response.data; <del> var then = value.$then, resolved = value.$resolved; <add> var promise = $http(httpConfig).then(function(response) { <add> var data = response.data, <add> promise = value.$promise; <ide> <ide> if (data) { <ide> if (action.isArray) { <ide> angular.module('ngResource', ['ng']). <ide> }); <ide> } else { <ide> copy(data, value); <del> value.$then = then; <del> value.$resolved = resolved; <add> value.$promise = promise; <ide> } <ide> } <ide> <add> value.$resolved = true; <add> <ide> (success||noop)(value, response.headers); <ide> <ide> response.resource = value; <add> <ide> return response; <del> }, error).then; <add> }, function(response) { <add> value.$resolved = true; <ide> <del> return value; <del> }; <add> (error||noop)(response); <ide> <add> return $q.reject(response); <add> }).then(responseInterceptor, responseErrorInterceptor); <ide> <del> Resource.prototype['$' + name] = function(a1, a2, a3) { <del> var params = extractParams(this), <del> success = noop, <del> error; <ide> <del> switch(arguments.length) { <del> case 3: params = a1; success = a2; error = a3; break; <del> case 2: <del> case 1: <del> if (isFunction(a1)) { <del> success = a1; <del> error = a2; <del> } else { <del> params = a1; <del> success = a2 || noop; <del> } <del> case 0: break; <del> default: <del> throw "Expected between 1-3 arguments [params, success, error], got " + <del> arguments.length + " arguments."; <add> if (!isInstanceCall) { <add> // we are creating instance / collection <add> // - set the initial promise <add> // - return the instance / collection <add> value.$promise = promise; <add> value.$resolved = false; <add> <add> return value; <add> } <add> <add> // instance call <add> return promise; <add> }; <add> <add> <add> Resource.prototype['$' + name] = function(params, success, error) { <add> if (isFunction(params)) { <add> error = success; success = params; params = {}; <ide> } <del> var data = hasBody ? this : undefined; <del> Resource[name].call(this, params, data, success, error); <add> var result = Resource[name](params, this, success, error); <add> return result.$promise || result; <ide> }; <ide> }); <ide> <ide><path>test/ngResource/resourceSpec.js <ide> describe("resource", function() { <ide> <ide> describe('single resource', function() { <ide> <del> it('should add promise $then method to the result object', function() { <add> it('should add $promise to the result object', function() { <ide> $httpBackend.expect('GET', '/CreditCard/123').respond({id: 123, number: '9876'}); <ide> var cc = CreditCard.get({id: 123}); <ide> <del> cc.$then(callback); <add> cc.$promise.then(callback); <ide> expect(callback).not.toHaveBeenCalled(); <ide> <ide> $httpBackend.flush(); <ide> <del> var response = callback.mostRecentCall.args[0]; <del> <del> expect(response.data).toEqual({id: 123, number: '9876'}); <del> expect(response.status).toEqual(200); <del> expect(response.resource).toEqualData({id: 123, number: '9876', $resolved: true}); <del> expect(typeof response.resource.$save).toBe('function'); <add> expect(callback).toHaveBeenCalledOnce(); <add> expect(callback.mostRecentCall.args[0]).toBe(cc); <ide> }); <ide> <ide> <del> it('should keep $then around after promise resolution', function() { <add> it('should keep $promise around after resolution', function() { <ide> $httpBackend.expect('GET', '/CreditCard/123').respond({id: 123, number: '9876'}); <ide> var cc = CreditCard.get({id: 123}); <ide> <del> cc.$then(callback); <add> cc.$promise.then(callback); <ide> $httpBackend.flush(); <ide> <del> var response = callback.mostRecentCall.args[0]; <del> <ide> callback.reset(); <ide> <del> cc.$then(callback); <add> cc.$promise.then(callback); <ide> $rootScope.$apply(); //flush async queue <ide> <del> expect(callback).toHaveBeenCalledOnceWith(response); <add> expect(callback).toHaveBeenCalledOnce(); <add> }); <add> <add> <add> it('should keep the original promise after instance action', function() { <add> $httpBackend.expect('GET', '/CreditCard/123').respond({id: 123, number: '9876'}); <add> $httpBackend.expect('POST', '/CreditCard/123').respond({id: 123, number: '9876'}); <add> <add> var cc = CreditCard.get({id: 123}); <add> var originalPromise = cc.$promise; <add> <add> cc.number = '666'; <add> cc.$save({id: 123}); <add> <add> expect(cc.$promise).toBe(originalPromise); <ide> }); <ide> <ide> <del> it('should allow promise chaining via $then method', function() { <add> it('should allow promise chaining', function() { <ide> $httpBackend.expect('GET', '/CreditCard/123').respond({id: 123, number: '9876'}); <ide> var cc = CreditCard.get({id: 123}); <ide> <del> cc.$then(function(response) { return 'new value'; }).then(callback); <add> cc.$promise.then(function(value) { return 'new value'; }).then(callback); <ide> $httpBackend.flush(); <ide> <ide> expect(callback).toHaveBeenCalledOnceWith('new value'); <ide> }); <ide> <ide> <del> it('should allow error callback registration via $then method', function() { <add> it('should allow $promise error callback registration', function() { <ide> $httpBackend.expect('GET', '/CreditCard/123').respond(404, 'resource not found'); <ide> var cc = CreditCard.get({id: 123}); <ide> <del> cc.$then(null, callback); <add> cc.$promise.then(null, callback); <ide> $httpBackend.flush(); <ide> <ide> var response = callback.mostRecentCall.args[0]; <ide> describe("resource", function() { <ide> <ide> expect(cc.$resolved).toBe(false); <ide> <del> cc.$then(callback); <add> cc.$promise.then(callback); <ide> expect(cc.$resolved).toBe(false); <ide> <ide> $httpBackend.flush(); <ide> describe("resource", function() { <ide> $httpBackend.expect('GET', '/CreditCard/123').respond(404, 'resource not found'); <ide> var cc = CreditCard.get({id: 123}); <ide> <del> cc.$then(null, callback); <add> cc.$promise.then(null, callback); <ide> $httpBackend.flush(); <ide> expect(callback).toHaveBeenCalledOnce(); <ide> expect(cc.$resolved).toBe(true); <ide> }); <add> <add> <add> it('should keep $resolved true in all subsequent interactions', function() { <add> $httpBackend.expect('GET', '/CreditCard/123').respond({id: 123, number: '9876'}); <add> var cc = CreditCard.get({id: 123}); <add> $httpBackend.flush(); <add> expect(cc.$resolved).toBe(true); <add> <add> $httpBackend.expect('POST', '/CreditCard/123').respond(); <add> cc.$save({id: 123}); <add> expect(cc.$resolved).toBe(true); <add> $httpBackend.flush(); <add> expect(cc.$resolved).toBe(true); <add> }); <add> <add> <add> it('should return promise from action method calls', function() { <add> $httpBackend.expect('GET', '/CreditCard/123').respond({id: 123, number: '9876'}); <add> var cc = new CreditCard({name: 'Mojo'}); <add> <add> expect(cc).toEqualData({name: 'Mojo'}); <add> <add> cc.$get({id:123}).then(callback); <add> <add> $httpBackend.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <add> expect(cc).toEqualData({id: 123, number: '9876'}); <add> callback.reset(); <add> <add> $httpBackend.expect('POST', '/CreditCard').respond({id: 1, number: '9'}); <add> <add> cc.$save().then(callback); <add> <add> $httpBackend.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <add> expect(cc).toEqualData({id: 1, number: '9'}); <add> }); <add> <add> <add> it('should allow parsing a value from headers', function() { <add> // https://github.com/angular/angular.js/pull/2607#issuecomment-17759933 <add> $httpBackend.expect('POST', '/CreditCard').respond(201, '', {'Location': '/new-id'}); <add> <add> var parseUrlFromHeaders = function(response) { <add> var resource = response.resource; <add> resource.url = response.headers('Location'); <add> return resource; <add> }; <add> <add> var CreditCard = $resource('/CreditCard', {}, { <add> save: { <add> method: 'post', <add> interceptor: {response: parseUrlFromHeaders} <add> } <add> }); <add> <add> var cc = new CreditCard({name: 'Me'}); <add> <add> cc.$save(); <add> $httpBackend.flush(); <add> <add> expect(cc.url).toBe('/new-id'); <add> }); <ide> }); <ide> <ide> <ide> describe('resource collection', function() { <ide> <del> it('should add promise $then method to the result object', function() { <add> it('should add $promise to the result object', function() { <ide> $httpBackend.expect('GET', '/CreditCard?key=value').respond([{id: 1}, {id: 2}]); <ide> var ccs = CreditCard.query({key: 'value'}); <ide> <del> ccs.$then(callback); <add> ccs.$promise.then(callback); <ide> expect(callback).not.toHaveBeenCalled(); <ide> <ide> $httpBackend.flush(); <ide> <del> var response = callback.mostRecentCall.args[0]; <del> <del> expect(response.data).toEqual([{id: 1}, {id :2}]); <del> expect(response.status).toEqual(200); <del> expect(response.resource).toEqualData([ { id : 1 }, { id : 2 } ]); <del> expect(typeof response.resource[0].$save).toBe('function'); <del> expect(typeof response.resource[1].$save).toBe('function'); <add> expect(callback).toHaveBeenCalledOnce(); <add> expect(callback.mostRecentCall.args[0]).toBe(ccs); <ide> }); <ide> <ide> <del> it('should keep $then around after promise resolution', function() { <add> it('should keep $promise around after resolution', function() { <ide> $httpBackend.expect('GET', '/CreditCard?key=value').respond([{id: 1}, {id: 2}]); <ide> var ccs = CreditCard.query({key: 'value'}); <ide> <del> ccs.$then(callback); <add> ccs.$promise.then(callback); <ide> $httpBackend.flush(); <ide> <del> var response = callback.mostRecentCall.args[0]; <del> <ide> callback.reset(); <ide> <del> ccs.$then(callback); <add> ccs.$promise.then(callback); <ide> $rootScope.$apply(); //flush async queue <ide> <del> expect(callback).toHaveBeenCalledOnceWith(response); <add> expect(callback).toHaveBeenCalledOnce(); <ide> }); <ide> <ide> <del> it('should allow promise chaining via $then method', function() { <add> it('should allow promise chaining', function() { <ide> $httpBackend.expect('GET', '/CreditCard?key=value').respond([{id: 1}, {id: 2}]); <ide> var ccs = CreditCard.query({key: 'value'}); <ide> <del> ccs.$then(function(response) { return 'new value'; }).then(callback); <add> ccs.$promise.then(function(value) { return 'new value'; }).then(callback); <ide> $httpBackend.flush(); <ide> <ide> expect(callback).toHaveBeenCalledOnceWith('new value'); <ide> }); <ide> <ide> <del> it('should allow error callback registration via $then method', function() { <add> it('should allow $promise error callback registration', function() { <ide> $httpBackend.expect('GET', '/CreditCard?key=value').respond(404, 'resource not found'); <ide> var ccs = CreditCard.query({key: 'value'}); <ide> <del> ccs.$then(null, callback); <add> ccs.$promise.then(null, callback); <ide> $httpBackend.flush(); <ide> <ide> var response = callback.mostRecentCall.args[0]; <ide> describe("resource", function() { <ide> <ide> expect(ccs.$resolved).toBe(false); <ide> <del> ccs.$then(callback); <add> ccs.$promise.then(callback); <ide> expect(ccs.$resolved).toBe(false); <ide> <ide> $httpBackend.flush(); <ide> describe("resource", function() { <ide> $httpBackend.expect('GET', '/CreditCard?key=value').respond(404, 'resource not found'); <ide> var ccs = CreditCard.query({key: 'value'}); <ide> <del> ccs.$then(null, callback); <add> ccs.$promise.then(null, callback); <ide> $httpBackend.flush(); <ide> expect(callback).toHaveBeenCalledOnce(); <ide> expect(ccs.$resolved).toBe(true); <ide> }); <ide> }); <add> <add> it('should allow per action response interceptor that gets full response', function() { <add> CreditCard = $resource('/CreditCard', {}, { <add> query: { <add> method: 'get', <add> isArray: true, <add> interceptor: { <add> response: function(response) { <add> return response; <add> } <add> } <add> } <add> }); <add> <add> $httpBackend.expect('GET', '/CreditCard').respond([{id: 1}]); <add> <add> var ccs = CreditCard.query(); <add> <add> ccs.$promise.then(callback); <add> <add> $httpBackend.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <add> <add> var response = callback.mostRecentCall.args[0]; <add> expect(response.resource).toBe(ccs); <add> expect(response.status).toBe(200); <add> expect(response.config).toBeDefined(); <add> }); <add> <add> <add> it('should allow per action responseError interceptor that gets full response', function() { <add> CreditCard = $resource('/CreditCard', {}, { <add> query: { <add> method: 'get', <add> isArray: true, <add> interceptor: { <add> responseError: function(response) { <add> return response; <add> } <add> } <add> } <add> }); <add> <add> $httpBackend.expect('GET', '/CreditCard').respond(404); <add> <add> var ccs = CreditCard.query(); <add> <add> ccs.$promise.then(callback); <add> <add> $httpBackend.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <add> <add> var response = callback.mostRecentCall.args[0]; <add> expect(response.status).toBe(404); <add> expect(response.config).toBeDefined(); <add> }); <ide> }); <ide> <ide>
2
Text
Text
fix description of createdecipheriv
4927d94f4db8c5d8041f00e23b6e391151aba56d
<ide><path>doc/api/crypto.md <ide> recent OpenSSL releases, `openssl list-cipher-algorithms` will display the <ide> available cipher algorithms. <ide> <ide> The `key` is the raw key used by the `algorithm` and `iv` is an <del>[initialization vector][]. Both arguments must be `'utf8'` encoded strings or <del>[buffers][`Buffer`]. <add>[initialization vector][]. Both arguments must be `'utf8'` encoded strings, <add>[Buffers][`Buffer`], `TypedArray`, or `DataView`s. <ide> <ide> ### crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding]) <ide> <!-- YAML
1
Python
Python
add project_urls to setup
0486b6d7692798dabd3bcafa20aa87ce28ae0b90
<ide><path>setup.py <ide> def setup_package(): <ide> url = "https://www.numpy.org", <ide> author = "Travis E. Oliphant et al.", <ide> download_url = "https://pypi.python.org/pypi/numpy", <add> project_urls={ <add> "Bug Tracker": "https://github.com/numpy/numpy/issues", <add> "Documentation": "https://docs.scipy.org/doc/numpy/", <add> "Source Code": "https://github.com/numpy/numpy", <add> }, <ide> license = 'BSD', <ide> classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f], <ide> platforms = ["Windows", "Linux", "Solaris", "Mac OS-X", "Unix"],
1
Ruby
Ruby
pull the action methods directly onto the adapter
2815db356977b506f63d155aecf71ee010a64c62
<ide><path>actioncable/lib/action_cable/channel/streams.rb <ide> def stream_from(broadcasting, callback = nil) <ide> streams << [ broadcasting, callback ] <ide> <ide> EM.next_tick do <del> pubsub.subscribe(broadcasting, &callback).callback do |reply| <add> adapter.subscribe(broadcasting, callback, lambda do |reply| <ide> transmit_subscription_confirmation <ide> logger.info "#{self.class.name} is streaming from #{broadcasting}" <del> end <add> end) <ide> end <ide> end <ide> <ide> def stream_for(model, callback = nil) <ide> <ide> def stop_all_streams <ide> streams.each do |broadcasting, callback| <del> pubsub.unsubscribe_proc broadcasting, callback <add> adapter.unsubscribe broadcasting, callback <ide> logger.info "#{self.class.name} stopped streaming from #{broadcasting}" <ide> end.clear <ide> end <ide> <ide> private <del> delegate :pubsub, to: :connection <add> delegate :adapter, to: :connection <ide> <ide> def streams <ide> @_streams ||= [] <ide><path>actioncable/lib/action_cable/connection/base.rb <ide> class Base <ide> include Authorization <ide> <ide> attr_reader :server, :env, :subscriptions, :logger <del> delegate :worker_pool, :pubsub, to: :server <add> delegate :worker_pool, :adapter, to: :server <ide> <ide> def initialize(server, env) <ide> @server, @env = server, env <ide><path>actioncable/lib/action_cable/connection/internal_channel.rb <ide> def subscribe_to_internal_channel <ide> @_internal_subscriptions ||= [] <ide> @_internal_subscriptions << [ internal_channel, callback ] <ide> <del> EM.next_tick { pubsub.subscribe(internal_channel, &callback) } <add> EM.next_tick { adapter.subscribe(internal_channel, callback) } <ide> logger.info "Registered connection (#{connection_identifier})" <ide> end <ide> end <ide> <ide> def unsubscribe_from_internal_channel <ide> if @_internal_subscriptions.present? <del> @_internal_subscriptions.each { |channel, callback| EM.next_tick { pubsub.unsubscribe_proc(channel, callback) } } <add> @_internal_subscriptions.each { |channel, callback| EM.next_tick { adapter.unsubscribe(channel, callback) } } <ide> end <ide> end <ide> <ide><path>actioncable/lib/action_cable/server/base.rb <ide> def channel_classes <ide> end <ide> <ide> # The pubsub adapter used for all streams/broadcasting. <del> def pubsub <del> @pubsub ||= config.storage_adapter.new(self).pubsub <add> def adapter <add> @adapter ||= config.storage_adapter.new(self) <ide> end <ide> <ide> # All the identifiers applied to the connection class associated with this server. <ide><path>actioncable/lib/action_cable/server/broadcasting.rb <ide> def initialize(server, broadcasting) <ide> <ide> def broadcast(message) <ide> server.logger.info "[ActionCable] Broadcasting to #{broadcasting}: #{message}" <del> broadcast_storage_adapter = server.config.storage_adapter.new(server).broadcast <del> broadcast_storage_adapter.publish broadcasting, ActiveSupport::JSON.encode(message) <add> server.adapter.broadcast broadcasting, ActiveSupport::JSON.encode(message) <ide> end <ide> end <ide> end <ide><path>actioncable/lib/action_cable/storage_adapter/base.rb <ide> def initialize(server) <ide> @logger = @server.logger <ide> end <ide> <del> # Storage connection instance used for broadcasting. Not intended for direct user use. <del> def broadcast <add> def broadcast(channel, payload) <ide> raise NotImplementedError <ide> end <ide> <del> # Storage connection instance used for pubsub. <del> def pubsub <add> def subscribe(channel, message_callback, success_callback = nil) <add> raise NotImplementedError <add> end <add> <add> def unsubscribe(channel, message_callback) <ide> raise NotImplementedError <ide> end <ide> end <ide><path>actioncable/lib/action_cable/storage_adapter/postgres.rb <ide> module ActionCable <ide> module StorageAdapter <ide> class Postgres < Base <ide> # The storage instance used for broadcasting. Not intended for direct user use. <del> def broadcast <del> @broadcast ||= PostgresWrapper.new <add> def broadcast(channel, payload) <add> ActiveRecord::Base.connection_pool.with_connection do |ar_conn| <add> pg_conn = ar_conn.raw_connection <add> <add> unless pg_conn.is_a?(PG::Connection) <add> raise 'ActiveRecord database must be Postgres in order to use the Postgres ActionCable storage adapter' <add> end <add> <add> pg_conn.exec("NOTIFY #{channel}, '#{payload}'") <add> end <add> end <add> <add> def subscribe(channel, message_callback, success_callback = nil) <add> Listener.instance.subscribe_to(channel, message_callback, success_callback) <ide> end <ide> <del> def pubsub <del> PostgresWrapper.new <add> def unsubscribe(channel, message_callback) <add> Listener.instance.unsubscribe_to(channel, message_callback) <ide> end <ide> <ide> class Listener <ide> def listen <ide> value = @queue.pop(true) <ide> if value.first == :listen <ide> pg_conn.exec("LISTEN #{value[1]}") <add> ::EM.next_tick(&value[2]) if value[2] <ide> elsif value.first == :unlisten <ide> pg_conn.exec("UNLISTEN #{value[1]}") <ide> end <ide> def listen <ide> end <ide> end <ide> <del> def subscribe_to(channel, callback) <add> def subscribe_to(channel, callback, success_callback) <ide> @sync.synchronize do <ide> if @subscribers[channel].empty? <del> @queue.push([:listen, channel]) <add> @queue.push([:listen, channel, success_callback]) <ide> end <ide> <ide> @subscribers[channel] << callback <ide> def unsubscribe_to(channel, callback = nil) <ide> end <ide> end <ide> end <del> <del> class PostgresWrapper <del> def publish(channel, message) <del> ActiveRecord::Base.connection_pool.with_connection do |ar_conn| <del> pg_conn = ar_conn.raw_connection <del> <del> unless pg_conn.is_a?(PG::Connection) <del> raise 'ActiveRecord database must be Postgres in order to use the Postgres ActionCable storage adapter' <del> end <del> <del> pg_conn.exec("NOTIFY #{channel}, '#{message}'") <del> end <del> end <del> <del> def subscribe(channel, &callback) <del> Listener.instance.subscribe_to(channel, callback) <del> # Needed for channel/streams.rb#L79 <del> ::EM::DefaultDeferrable.new <del> end <del> <del> def unsubscribe(channel) <del> Listener.instance.unsubscribe_to(channel) <del> end <del> <del> def unsubscribe_proc(channel, block) <del> Listener.instance.unsubscribe_to(channel, block) <del> end <del> end <del> <ide> end <ide> end <ide> end <ide><path>actioncable/lib/action_cable/storage_adapter/redis.rb <ide> module ActionCable <ide> module StorageAdapter <ide> class Redis < Base <del> # The redis instance used for broadcasting. Not intended for direct user use. <del> def broadcast <del> @broadcast ||= ::Redis.new(@server.config.config_opts) <add> def broadcast(channel, payload) <add> redis_conn.publish(channel, payload) <add> end <add> <add> def subscribe(channel, message_callback, success_callback = nil) <add> hi_redis_conn.pubsub.subscribe(channel, &message_callback).tap do |result| <add> result.callback(&success_callback) if success_callback <add> end <ide> end <ide> <del> def pubsub <del> redis.pubsub <add> def unsubscribe(channel, message_callback) <add> hi_redis_conn.pubsub.unsubscribe_proc(channel, message_callback) <ide> end <ide> <ide> private <ide> <add> # The redis instance used for broadcasting. Not intended for direct user use. <add> def redis_conn <add> @broadcast ||= ::Redis.new(@server.config.config_opts) <add> end <add> <ide> # The EventMachine Redis instance used by the pubsub adapter. <del> def redis <add> def hi_redis_conn <ide> @redis ||= EM::Hiredis.connect(@server.config.config_opts[:url]).tap do |redis| <ide> redis.on(:reconnect_failed) do <ide> @logger.info "[ActionCable] Redis reconnect failed."
8
Ruby
Ruby
add tests for rubocop methods in line_cop.rb
b582ed513b3b28197369cb3cf808e9c4025ee581
<ide><path>Library/Homebrew/rubocops/extend/formula_cop.rb <ide> def find_method_with_args(node, method_name, *args) <ide> # Matches a method with a receiver, <ide> # EX: to match `Formula.factory(name)` <ide> # call `find_instance_method_call(node, "Formula", :factory)` <add> # EX: to match `build.head?` <add> # call `find_instance_method_call(node, :build, :head?)` <ide> # yields to a block with matching method node <ide> def find_instance_method_call(node, instance, method_name) <ide> methods = find_every_method_call_by_name(node, method_name) <ide><path>Library/Homebrew/rubocops/lines_cop.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> end <ide> <ide> # Node Pattern search for Language::Node <del> def_node_search :languageNodeModule?, <<-EOS.undent <add> def_node_search :languageNodeModule?, <<-EOS.undent <ide> (const (const nil :Language) :Node) <ide> EOS <ide> end <ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb <ide> class Foo < Formula <ide> expect_offense(expected, actual) <ide> end <ide> end <add> <add> it "with invalid rebuild" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> bottle do <add> rebuild 0 <add> sha256 "fe0679b932dd43a87fd415b609a7fbac7a069d117642ae8ebaac46ae1fb9f0b3" => :sierra <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "'rebuild 0' should be removed", <add> severity: :convention, <add> line: 5, <add> column: 4, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with OS.linux? check" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> bottle do <add> if OS.linux? <add> nil <add> end <add> sha256 "fe0679b932dd43a87fd415b609a7fbac7a069d117642ae8ebaac46ae1fb9f0b3" => :sierra <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "Don't use OS.linux?; Homebrew/core only supports macOS", <add> severity: :convention, <add> line: 5, <add> column: 7, <add> source: source }] <add> <add> inspect_source(cop, source, "/homebrew-core/") <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with fails_with :llvm" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> bottle do <add> sha256 "fe0679b932dd43a87fd415b609a7fbac7a069d117642ae8ebaac46ae1fb9f0b3" => :sierra <add> end <add> fails_with :llvm do <add> build 2335 <add> cause "foo" <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "'fails_with :llvm' is now a no-op so should be removed", <add> severity: :convention, <add> line: 7, <add> column: 2, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with def test" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> <add> def test <add> assert_equals "1", "1" <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "Use new-style test definitions (test do)", <add> severity: :convention, <add> line: 5, <add> column: 2, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with def options" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> <add> def options <add> [["--bar", "desc"]] <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "Use new-style option definitions", <add> severity: :convention, <add> line: 5, <add> column: 2, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with deprecated skip_clean call" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> skip_clean :all <add> end <add> EOS <add> <add> expected_offenses = [{ message: <<-EOS.undent.chomp, <add> `skip_clean :all` is deprecated; brew no longer strips symbols <add> Pass explicit paths to prevent Homebrew from removing empty folders. <add> EOS <add> severity: :convention, <add> line: 4, <add> column: 2, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with build.universal?" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> if build.universal? <add> "foo" <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "macOS has been 64-bit only since 10.6 so build.universal? is deprecated.", <add> severity: :convention, <add> line: 4, <add> column: 5, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with ENV.universal_binary" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> if build? <add> ENV.universal_binary <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "macOS has been 64-bit only since 10.6 so ENV.universal_binary is deprecated.", <add> severity: :convention, <add> line: 5, <add> column: 5, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with ENV.universal_binary" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> if build? <add> ENV.x11 <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: 'Use "depends_on :x11" instead of "ENV.x11"', <add> severity: :convention, <add> line: 5, <add> column: 5, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with ruby-macho alternatives" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> system "install_name_tool", "-id" <add> end <add> EOS <add> <add> expected_offenses = [{ message: 'Use ruby-macho instead of calling "install_name_tool"', <add> severity: :convention, <add> line: 4, <add> column: 10, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <add> <add> it "with npm install without language::Node args" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> system "npm", "install" <add> end <add> EOS <add> <add> expected_offenses = [{ message: "Use Language::Node for npm install args", <add> severity: :convention, <add> line: 4, <add> column: 2, <add> source: source }] <add> <add> inspect_source(cop, source) <add> <add> expected_offenses.zip(cop.offenses).each do |expected, actual| <add> expect_offense(expected, actual) <add> end <add> end <ide> end <ide> end
3
Go
Go
add error to docekr build --rm
a895c7238d3f32b22989c409a5a3b09aa3463054
<ide><path>buildfile.go <ide> type buildFile struct { <ide> func (b *buildFile) clearTmp(containers map[string]struct{}) { <ide> for c := range containers { <ide> tmp := b.runtime.Get(c) <del> b.runtime.Destroy(tmp) <del> fmt.Fprintf(b.outStream, "Removing intermediate container %s\n", utils.TruncateID(c)) <add> if err := b.runtime.Destroy(tmp); err != nil { <add> fmt.Fprintf(b.outStream, "Error removing intermediate container %s: %s\n", utils.TruncateID(c), err.Error()) <add> } else { <add> fmt.Fprintf(b.outStream, "Removing intermediate container %s\n", utils.TruncateID(c)) <add> } <ide> } <ide> } <ide>
1
Go
Go
promote overlay above vfs
2c72ff1dbfa83aa8f797bdfebaacb8a919677326
<ide><path>daemon/graphdriver/driver.go <ide> var ( <ide> "aufs", <ide> "btrfs", <ide> "devicemapper", <del> "vfs", <del> // experimental, has to be enabled manually for now <ide> "overlay", <add> "vfs", <ide> } <ide> <ide> ErrNotSupported = errors.New("driver not supported")
1
Ruby
Ruby
use rbconfig.ruby if it's available
83f2ee5aeabc55bc0806a7be168eaa272dc84ca5
<ide><path>Library/Homebrew/global.rb <ide> def mkpath <ide> <ide> HOMEBREW_TEMP = Pathname.new(ENV.fetch('HOMEBREW_TEMP', '/tmp')) <ide> <del>RUBY_BIN = Pathname.new(RbConfig::CONFIG['bindir']) <del>RUBY_PATH = RUBY_BIN + RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'] <add>if RbConfig.respond_to?(:ruby) <add> RUBY_PATH = Pathname.new(RbConfig.ruby) <add>else <add> RUBY_PATH = Pathname.new(RbConfig::CONFIG["bindir"]).join( <add> RbConfig::CONFIG["ruby_install_name"] + RbConfig::CONFIG["EXEEXT"] <add> ) <add>end <add>RUBY_BIN = RUBY_PATH.dirname <ide> <ide> if RUBY_PLATFORM =~ /darwin/ <ide> MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp <ide><path>Library/Homebrew/test/testing_env.rb <ide> <ide> require 'tap_constants' <ide> <del>RUBY_BIN = Pathname.new(RbConfig::CONFIG['bindir']) <del>RUBY_PATH = RUBY_BIN + RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'] <add>if RbConfig.respond_to?(:ruby) <add> RUBY_PATH = Pathname.new(RbConfig.ruby) <add>else <add> RUBY_PATH = Pathname.new(RbConfig::CONFIG["bindir"]).join( <add> RbConfig::CONFIG["ruby_install_name"] + RbConfig::CONFIG["EXEEXT"] <add> ) <add>end <add>RUBY_BIN = RUBY_PATH.dirname <ide> <ide> MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp <ide> MACOS_VERSION = ENV.fetch('MACOS_VERSION') { MACOS_FULL_VERSION[/10\.\d+/] }
2
Python
Python
fix bad usage of namespace alias change
a2dc78f54f65fa67d6d02e9fcc563752efd67509
<ide><path>numpy/numarray/util.py <ide> class NumOverflowError(OverflowError, ArithmeticError): <ide> def handleError(errorStatus, sourcemsg): <ide> """Take error status and use error mode to handle it.""" <ide> modes = np.geterr() <del> if errorStatus & numpy.FPE_INVALID: <add> if errorStatus & np.FPE_INVALID: <ide> if modes['invalid'] == "warn": <ide> print "Warning: Encountered invalid numeric result(s)", sourcemsg <ide> if modes['invalid'] == "raise": <ide> raise MathDomainError(sourcemsg) <del> if errorStatus & numpy.FPE_DIVIDEBYZERO: <add> if errorStatus & np.FPE_DIVIDEBYZERO: <ide> if modes['dividebyzero'] == "warn": <ide> print "Warning: Encountered divide by zero(s)", sourcemsg <ide> if modes['dividebyzero'] == "raise": <ide> raise ZeroDivisionError(sourcemsg) <del> if errorStatus & numpy.FPE_OVERFLOW: <add> if errorStatus & np.FPE_OVERFLOW: <ide> if modes['overflow'] == "warn": <ide> print "Warning: Encountered overflow(s)", sourcemsg <ide> if modes['overflow'] == "raise": <ide> raise NumOverflowError(sourcemsg) <del> if errorStatus & numpy.FPE_UNDERFLOW: <add> if errorStatus & np.FPE_UNDERFLOW: <ide> if modes['underflow'] == "warn": <ide> print "Warning: Encountered underflow(s)", sourcemsg <ide> if modes['underflow'] == "raise": <ide> raise UnderflowError(sourcemsg) <ide> <ide> <ide> def get_numarray_include_dirs(): <del> base = os.path.dirname(numpy.__file__) <add> base = os.path.dirname(np.__file__) <ide> newdirs = [os.path.join(base, 'numarray', 'include')] <ide> return newdirs
1
Python
Python
avoid obscure error on certain non-image textures
504bdabe074d89e2c8dbd2dbcc2e020d17af7084
<ide><path>utils/exporters/blender/addons/io_three/exporter/api/texture.py <ide> def textures(): <ide> if mat.users == 0: <ide> continue <ide> for slot in mat.texture_slots: <del> if slot and slot.use and slot.texture.type == IMAGE: <add> if (slot and slot.use and <add> slot.texture and slot.texture.type == IMAGE): <ide> yield slot.texture.name
1
PHP
PHP
add functions for testing option requests
b8eda4b3270ed69b00db3f93209fa12563443f1b
<ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php <ide> public function deleteJson($uri, array $data = [], array $headers = []) <ide> return $this->json('DELETE', $uri, $data, $headers); <ide> } <ide> <add> /** <add> * Visit the given URI with a OPTION request. <add> * <add> * @param string $uri <add> * @param array $data <add> * @param array $headers <add> * @return \Illuminate\Foundation\Testing\TestResponse <add> */ <add> public function option($uri, array $data = [], array $headers = []) <add> { <add> $server = $this->transformHeadersToServerVars($headers); <add> <add> return $this->call('OPTION', $uri, $data, [], [], $server); <add> } <add> <add> /** <add> * Visit the given URI with a OPTION request, expecting a JSON response. <add> * <add> * @param string $uri <add> * @param array $data <add> * @param array $headers <add> * @return \Illuminate\Foundation\Testing\TestResponse <add> */ <add> public function optionJson($uri, array $data = [], array $headers = []) <add> { <add> return $this->json('OPTION', $uri, $data, $headers); <add> } <add> <ide> /** <ide> * Call the given URI with a JSON request. <ide> *
1
Ruby
Ruby
use session= writer methods
f7d7dc5aa8a5facc357ed291819db23e3f3df9b6
<ide><path>actionpack/lib/action_controller/testing/process.rb <ide> def initialize(env = {}) <ide> super(Rack::MockRequest.env_for("/").merge(env)) <ide> <ide> @query_parameters = {} <del> @env['rack.session'] = TestSession.new <del> @env['rack.session.options'] = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16)) <add> self.session = TestSession.new <add> self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => ActiveSupport::SecureRandom.hex(16)) <ide> <ide> initialize_default_values <ide> initialize_containers
1
Javascript
Javascript
update chunk to files mapping when deleting assets
63ba54c10946ce8b016e5c8d8eb69cb5e6852fb5
<ide><path>lib/Compilation.js <ide> This prevents using hashes of each other and should be avoided.` <ide> } <ide> } <ide> } <add> // TODO If this becomes a performance problem <add> // store a reverse mapping from asset to chunk <add> for (const chunk of this.chunks) { <add> chunk.files.delete(file); <add> chunk.auxiliaryFiles.delete(file); <add> } <ide> } <ide> <ide> getAssets() { <ide><path>test/configCases/assets/delete-asset/chunk2.js <add>/**! Chunk */ <add> <add>console.log("Fail"); <ide><path>test/configCases/assets/delete-asset/index.js <ide> it("should fail loading a deleted asset", async () => { <ide> code: "ENOENT" <ide> }) <ide> ); <add> await expect(import("./chunk2.js")).rejects.toEqual( <add> expect.objectContaining({ <add> code: "ENOENT" <add> }) <add> ); <ide> }); <ide><path>test/configCases/assets/delete-asset/webpack.config.js <del>const { Compilation } = require("../../../../"); <add>const { Compilation, BannerPlugin } = require("../../../../"); <ide> const TerserPlugin = require("terser-webpack-plugin"); <ide> <ide> /** @type {import("../../../../").Configuration} */ <ide> module.exports = { <ide> }, <ide> devtool: "source-map", <ide> plugins: [ <add> new BannerPlugin({ <add> banner: "Test" <add> }), <ide> compiler => { <ide> compiler.hooks.compilation.tap("Test", compilation => { <add> compilation.hooks.processAssets.tap( <add> { <add> name: "Test", <add> stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL <add> }, <add> () => { <add> compilation.deleteAsset("chunk2_js.bundle0.js"); <add> } <add> ); <ide> compilation.hooks.processAssets.tap( <ide> { <ide> name: "Test", <ide> module.exports = { <ide> expect(compilation.getAsset("chunk_js.bundle0.js.map")).toBe( <ide> undefined <ide> ); <add> expect(compilation.getAsset("chunk2_js.bundle0.js")).toBe( <add> undefined <add> ); <add> expect(compilation.getAsset("chunk2_js.bundle0.js.map")).toBe( <add> undefined <add> ); <ide> expect(compilation.getAsset("LICENSES.txt")).not.toBe(undefined); <ide> } <ide> );
4
Ruby
Ruby
move pg float quoting to the correct location
d74e716b48b19a608a0445996cfcf17d304f289f
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb <ide> def unescape_bytea(value) <ide> @connection.unescape_bytea(value) if value <ide> end <ide> <del> # Quotes PostgreSQL-specific data types for SQL input. <del> def quote(value, column = nil) #:nodoc: <del> return super unless column <del> <del> case value <del> when Float <del> if value.infinite? || value.nan? <del> "'#{value}'" <del> else <del> super <del> end <del> else <del> super <del> end <del> end <del> <ide> # Quotes strings for use in SQL input. <ide> def quote_string(s) #:nodoc: <ide> @connection.escape(s) <ide> def _quote(value) <ide> elsif value.hex? <ide> "X'#{value}'" <ide> end <add> when Float <add> if value.infinite? || value.nan? <add> "'#{value}'" <add> else <add> super <add> end <ide> else <ide> super <ide> end
1
Ruby
Ruby
pass connection rather than alias_tracker
80099618e44bdfdd3be2e104d006753b0ed809a4
<ide><path>activerecord/lib/active_record/associations/association_scope.rb <ide> def initialize(block) <ide> @block = block <ide> end <ide> <del> def bind_value(scope, column, value, alias_tracker) <del> substitute = alias_tracker.connection.substitute_at(column) <add> def bind_value(scope, column, value, connection) <add> substitute = connection.substitute_at(column) <ide> scope.bind_values += [[column, @block.call(value)]] <ide> substitute <ide> end <ide> def join(table, constraint) <ide> table.create_join(table, table.create_on(constraint), join_type) <ide> end <ide> <del> def column_for(table_name, column_name, alias_tracker) <del> columns = alias_tracker.connection.schema_cache.columns_hash(table_name) <add> def column_for(table_name, column_name, connection) <add> columns = connection.schema_cache.columns_hash(table_name) <ide> columns[column_name] <ide> end <ide> <del> def bind_value(scope, column, value, alias_tracker) <del> @bind_substitution.bind_value scope, column, value, alias_tracker <add> def bind_value(scope, column, value, connection) <add> @bind_substitution.bind_value scope, column, value, connection <ide> end <ide> <del> def bind(scope, table_name, column_name, value, tracker) <del> column = column_for table_name, column_name, tracker <del> bind_value scope, column, value, tracker <add> def bind(scope, table_name, column_name, value, connection) <add> column = column_for table_name, column_name, connection <add> bind_value scope, column, value, connection <ide> end <ide> <del> def last_chain_scope(scope, table, reflection, owner, tracker, assoc_klass) <add> def last_chain_scope(scope, table, reflection, owner, connection, assoc_klass) <ide> join_keys = reflection.join_keys(assoc_klass) <ide> key = join_keys.key <ide> foreign_key = join_keys.foreign_key <ide> <del> bind_val = bind scope, table.table_name, key.to_s, owner[foreign_key], tracker <add> bind_val = bind scope, table.table_name, key.to_s, owner[foreign_key], connection <ide> scope = scope.where(table[key].eq(bind_val)) <ide> <ide> if reflection.type <ide> value = owner.class.base_class.name <del> bind_val = bind scope, table.table_name, reflection.type, value, tracker <add> bind_val = bind scope, table.table_name, reflection.type, value, connection <ide> scope = scope.where(table[reflection.type].eq(bind_val)) <ide> else <ide> scope <ide> end <ide> end <ide> <del> def next_chain_scope(scope, table, reflection, tracker, assoc_klass, foreign_table, next_reflection) <add> def next_chain_scope(scope, table, reflection, connection, assoc_klass, foreign_table, next_reflection) <ide> join_keys = reflection.join_keys(assoc_klass) <ide> key = join_keys.key <ide> foreign_key = join_keys.foreign_key <ide> def next_chain_scope(scope, table, reflection, tracker, assoc_klass, foreign_tab <ide> <ide> if reflection.type <ide> value = next_reflection.klass.base_class.name <del> bind_val = bind scope, table.table_name, reflection.type, value, tracker <add> bind_val = bind scope, table.table_name, reflection.type, value, connection <ide> scope = scope.where(table[reflection.type].eq(bind_val)) <ide> end <ide> <ide> def next_chain_scope(scope, table, reflection, tracker, assoc_klass, foreign_tab <ide> def add_constraints(scope, owner, assoc_klass, refl, tracker) <ide> chain = refl.chain <ide> scope_chain = refl.scope_chain <add> connection = tracker.connection <ide> <ide> tables = construct_tables(chain, assoc_klass, refl, tracker) <ide> <ide> owner_reflection = chain.last <ide> table = tables.last <del> scope = last_chain_scope(scope, table, owner_reflection, owner, tracker, assoc_klass) <add> scope = last_chain_scope(scope, table, owner_reflection, owner, connection, assoc_klass) <ide> <ide> chain.each_with_index do |reflection, i| <ide> table, foreign_table = tables.shift, tables.first <ide> <ide> unless reflection == chain.last <ide> next_reflection = chain[i + 1] <del> scope = next_chain_scope(scope, table, reflection, tracker, assoc_klass, foreign_table, next_reflection) <add> scope = next_chain_scope(scope, table, reflection, connection, assoc_klass, foreign_table, next_reflection) <ide> end <ide> <ide> is_first_chain = i == 0
1