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
|
add check for stray pre-4.3 xcode files
|
0329307770678a125bfe4e61d42fc30f9f3d1e04
|
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_latest_xcode
<ide> end
<ide> end
<ide>
<add>def check_for_stray_developer_directory
<add> if MacOS::Xcode.version >= "4.3" and File.exist? "/Developer/Library"
<add> return <<-EOS.undent
<add> You have leftover files from an older version of Xcode.
<add> You should delete them using:
<add> /Developer/Library/uninstall-developer-folder
<add> EOS
<add> end
<add>end
<add>
<ide> def check_cc
<ide> unless MacOS::CLT.installed?
<ide> if MacOS::Xcode.version >= "4.3"
| 1
|
Javascript
|
Javascript
|
add missing comma
|
1172e6478f86c1766ee1cb64f4b9b487853c9d13
|
<ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/a2/61/58/a261584d-a4cd-cbfa-cf9d-b5f1f15a7139/icon175x175.jpeg',
<ide> link: 'https://itunes.apple.com/app/id1031729525?mt=8&at=11l7ss&ct=reactnativeshowcase',
<ide> author: 'Josh Buchea',
<del> }
<add> },
<ide> {
<ide> name: 'MyPED',
<ide> icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/88/1f/fb/881ffb3b-7986-d427-7fcf-eb5920a883af/icon175x175.png',
| 1
|
Go
|
Go
|
fix some issues with locking on the container
|
972cb4978795029131697bd3b3746e321eec5c13
|
<ide><path>daemon/kill.go
<ide> func (daemon *Daemon) killWithSignal(container *containerpkg.Container, sig int)
<ide> container.Lock()
<ide> defer container.Unlock()
<ide>
<add> daemon.stopHealthchecks(container)
<add>
<ide> if !container.Running {
<ide> return errNotRunning(container.ID)
<ide> }
<ide><path>daemon/monitor.go
<ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerd.EventType, ei libc
<ide> if runtime.GOOS == "windows" {
<ide> return errors.New("received StateOOM from libcontainerd on Windows. This should never happen")
<ide> }
<add>
<add> c.Lock()
<add> defer c.Unlock()
<ide> daemon.updateHealthMonitor(c)
<ide> if err := c.CheckpointTo(daemon.containersReplica); err != nil {
<ide> return err
<ide> }
<add>
<ide> daemon.LogContainerEvent(c, "oom")
<ide> case libcontainerd.EventExit:
<ide> if int(ei.Pid) == c.Pid {
<ide><path>daemon/stop.go
<ide> func (daemon *Daemon) containerStop(container *containerpkg.Container, seconds i
<ide> return nil
<ide> }
<ide>
<del> daemon.stopHealthchecks(container)
<del>
<ide> stopSignal := container.StopSignal()
<ide> // 1. Send a stop signal
<ide> if err := daemon.killPossiblyDeadProcess(container, stopSignal); err != nil {
| 3
|
Go
|
Go
|
fix backingfs assignment
|
18c22f5bc1a30d325ed7a14d118c8fcf20f2f509
|
<ide><path>daemon/graphdriver/overlay/overlay.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> return nil, graphdriver.ErrNotSupported
<ide> }
<ide>
<add> fsMagic, err := graphdriver.GetFSMagic(testdir)
<add> if err != nil {
<add> return nil, err
<add> }
<add> if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
<add> backingFs = fsName
<add> }
<add>
<ide> supportsDType, err := fsutils.SupportsDType(testdir)
<ide> if err != nil {
<ide> return nil, err
<ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> return nil, graphdriver.ErrNotSupported
<ide> }
<ide>
<add> fsMagic, err := graphdriver.GetFSMagic(testdir)
<add> if err != nil {
<add> return nil, err
<add> }
<add> if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
<add> backingFs = fsName
<add> }
<add>
<ide> supportsDType, err := fsutils.SupportsDType(testdir)
<ide> if err != nil {
<ide> return nil, err
| 2
|
Go
|
Go
|
update drain test
|
b38408fd0287a5d6eda4f8083b83806faf5d5cbd
|
<ide><path>integration-cli/docker_api_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestApiSwarmNodeDrainPause(c *check.C) {
<ide> n.Spec.Availability = swarm.NodeAvailabilityActive
<ide> })
<ide>
<del> // change environment variable, resulting balanced rescheduling
<del> d1.updateService(c, d1.getService(c, id), func(s *swarm.Service) {
<del> s.Spec.TaskTemplate.ContainerSpec.Env = []string{"FOO=BAR"}
<del> s.Spec.UpdateConfig = &swarm.UpdateConfig{
<del> Parallelism: 2,
<del> Delay: 250 * time.Millisecond,
<del> }
<del> })
<add> instances = 1
<add> d1.updateService(c, d1.getService(c, id), setInstances(instances))
<add>
<add> waitAndAssert(c, defaultReconciliationTimeout*2, reducedCheck(sumAsIntegers, d1.checkActiveContainerCount, d2.checkActiveContainerCount), checker.Equals, instances)
<add>
<add> instances = 8
<add> d1.updateService(c, d1.getService(c, id), setInstances(instances))
<ide>
<ide> // drained node first so we don't get any old containers
<ide> waitAndAssert(c, defaultReconciliationTimeout, d2.checkActiveContainerCount, checker.GreaterThan, 0)
<ide> func (s *DockerSwarmSuite) TestApiSwarmNodeDrainPause(c *check.C) {
<ide> n.Spec.Availability = swarm.NodeAvailabilityPause
<ide> })
<ide>
<del> c.Skip("known flakiness with scaling up from this state")
<del>
<ide> instances = 14
<ide> d1.updateService(c, d1.getService(c, id), setInstances(instances))
<ide>
| 1
|
Text
|
Text
|
update korean translation to 9484d0f
|
ee38a36f50b2b3b5e877b7ffeea0f45ec213c58a
|
<ide><path>docs/docs/ref-04-tags-and-attributes.ko-KR.md
<ide> thead time title tr track u ul var video wbr
<ide> 다음의 SVG 엘리먼트가 지원됩니다.
<ide>
<ide> ```
<del>circle defs ellipse g line linearGradient mask path pattern polygon polyline
<add>circle clipPath defs ellipse g line linearGradient mask path pattern polygon polyline
<ide> radialGradient rect stop svg text tspan
<ide> ```
<ide>
<ide> srcSet start step style tabIndex target title type useMap value width wmode
<ide> ### SVG 어트리뷰트
<ide>
<ide> ```
<del>cx cy d dx dy fill fillOpacity fontFamily fontSize fx fy gradientTransform
<add>clip-path cx cy d dx dy fill fillOpacity fontFamily fontSize fx fy gradientTransform
<ide> gradientUnits markerEnd markerMid markerStart offset opacity
<ide> patternContentUnits patternUnits points preserveAspectRatio r rx ry
<ide> spreadMethod stopColor stopOpacity stroke strokeDasharray strokeLinecap
<ide><path>docs/docs/thinking-in-react.ko-KR.md
<ide> React 에는 두가지 타입의 자료 "모델"이 있습니다: props 와 stat
<ide>
<ide> ## 3단계: UI state 의 표현을 작지만 완전하도록 확인하세요.
<ide>
<del>상호적인 UI를 만들기 위해서는 자료 모델 변화에 반응할 수 있어야 합니다. React는 **state**로 이걸 쉽게 만들어주죠.
<add>상호적인 UI를 만들기 위해서는, 자료 모델 변화에 반응할 수 있어야 합니다. React는 **state**로 이걸 쉽게 만들어주죠.
<ide>
<del>올바르게 애플리케이션을 만들기 위해서는 첫째로 애플리케이션에 필요한 변할 수 있는 state 들의 최소한의 집합에 대해서 생각해볼 필요가 있습니다. 여기 방법이 있습니다: *스스로 반복하지 마세요* (DRY). 애플리케이션의 상태를 나타낼 수 있는 가장 최소한의 표현 방식을 찾고, 그 밖의 것은 필요할 때 계산합니다. 예를들어 TODO 목록를 만든다고 칩시다. TODO 아이템들의 배열만 유지하세요; 갯수를 표현하기 위한 state 변수를 분리하지 마세요. 대신 TODO 아이템들 배열의 길이를 이용하세요.
<add>올바르게 애플리케이션을 만들기 위해서는, 첫째로 애플리케이션에 필요한 변할 수 있는 state 들의 최소한의 집합에 대해서 생각해볼 필요가 있습니다. 여기 방법이 있습니다: *스스로 반복하지 마세요* (DRY). 애플리케이션의 상태를 나타낼 수 있는 가장 최소한의 표현 방식을 찾고, 그 밖의 것은 필요할 때 계산합니다. 예를들어 TODO 목록를 만든다고 칩시다. TODO 아이템들의 배열만 유지하세요; 갯수를 표현하기 위한 state 변수를 분리하지 마세요. 대신 TODO 아이템들 배열의 길이를 이용하세요.
<ide>
<ide> 예제 애플리케이션에서의 모든 자료유형에 대해 생각해 봅시다:
<ide>
<ide> product 들의 원본 목록은 props를 통해서 전달되기 때문에, state
<ide>
<ide> React는 어떻게 이 프로그램이 동작하는지 이해하기 쉽게 이 자료의 흐름을 명시적으로 만들어주지만 전통적인 두 방향의 자료 바인딩보다 다소 입력할 것이 많습니다. React는 이러한 패턴을 양방향 바인딩처럼 편하게 사용할 수 있도록 ReactLink를 제공하지만, 이 글의 목적상 명시적인 방식만 사용했습니다.
<ide>
<del>지금 예제에 문자열을 입력하거나 체크박스를 체크하더라도 React가 입력을 무시하는것을 볼 수 있습니다. 의도적으로 `input`의 prop에 `value`를 세팅하면 항상 `state`가 `FilterableProductTable`로부터 전달되어야 합니다.
<add>지금 예제에 문자열을 입력하거나 체크박스를 체크하더라도, React가 입력을 무시하는것을 볼 수 있습니다. 의도적으로 `input`의 prop에 `value`를 세팅하면 항상 `state`가 `FilterableProductTable`로부터 전달되어야 합니다.
<ide>
<del>우리가 원하는 것이 무엇인지 생각해 봅시다. 사용자가 form을 바꿀때마다 사용자 입력을 반영하기 위해 업데이트 하기를 원하죠. 컴포넌트들이 오직 자기 자신의 state만 업데이트 하더라도 `FilterableProductTable`은 state가 변할때마다 반영되어야할 `SearchBar`에 콜백을 전달할 것입니다. 이 알림을 위해서 `onChange`이벤트를 사용할 수 있습니다. 그리고 `FilterableProductTable`으로부터 전달된 콜백은 `setState()`를 호출할 것이고, 애플리케이션은 업데이트될 것입니다.
<add>우리가 원하는 것이 무엇인지 생각해 봅시다. 사용자 입력을 반영하기 위해, 사용자가 form을 바꿀때마다 업데이트 하기를 원하죠. 컴포넌트들이 오직 자기 자신의 state만 업데이트 하더라도 `FilterableProductTable`은 state가 변할때마다 반영되어야할 `SearchBar`에 콜백을 전달할 것입니다. 이 알림을 위해서 `onChange`이벤트를 사용할 수 있습니다. 그리고 `FilterableProductTable`으로부터 전달된 콜백은 `setState()`를 호출할 것이고, 애플리케이션은 업데이트될 것입니다.
<ide>
<ide> 많은 코드가 필요한 것 같이 들릴 수 있지만 실제로는 몇 줄 되지 않습니다. 그리고 애플리케이션의 구석구석에서 데이터가 어떻게 흐르는지 매우 명확해집니다.
<ide>
<ide> ## 그리고
<ide>
<del>이 글이 컴포넌트와 React로 애플리케이션을 어떻게 만들지에 대한 아이디어가 되길 바랍니다. 원래 하던 방식보다 조금 타이핑을 더 해야할지도 모르지만, 코드는 쓰는 경우보다 읽히는 경우가 많다는 점, 매우 읽기 편하고 명시적인 코드를 썼다는 점을 기억하세요. 컴포넌트로 큰 라이브러리를 만들기 시작할 때, 이 명시성과 모듈성에 감사하게 될 것이며 재사용함에 따라 코드의 양도 줄어들 것입니다. :)
<add>이 글이 컴포넌트와 React로 애플리케이션을 어떻게 만들지에 대한 아이디어가 되길 바랍니다. 원래 하던 방식보다 조금 타이핑을 더 해야할지도 모르지만, 코드는 쓰는 경우보다 읽히는 경우가 많다는 점, 매우 읽기 편하고 명시적인 코드를 썼다는 점을 기억하세요. 컴포넌트로 큰 라이브러리를 만들기 시작할 때, 이 명시성과 모듈성에 감사하게 될 것이며, 재사용함에 따라 코드의 양도 줄어들 것입니다. :)
<ide><path>docs/docs/tutorial.ko-KR.md
<ide> var CommentBox = React.createClass({
<ide>
<ide> ### props 사용하기
<ide>
<del>부모로 부터 받은 데이터에 의존하는 `Comment` 컴포넌트를 만들어 봅시다. 부모 컴포넌트로 부터 받은 데이터는 자식 컴포넌트에서 '프로퍼티'로 사용가능 합니다. 이 '프로퍼티들'은 `this.props`를 통해 접근합니다. props를 사용해 `CommentList`에서 전달받은 데이터를 읽어들이고, 마크업을 렌더할 수 있을 것입니다.
<add>부모로 부터 받은 데이터에 의존하는 `Comment` 컴포넌트를 만들어 봅시다. 부모 컴포넌트로 부터 받은 데이터는 자식 컴포넌트에서 '프로퍼티'로 사용가능 합니다. 이 '프로퍼티들'은 `this.props`를 통해 접근합니다. props를 사용해, `CommentList`에서 전달받은 데이터를 읽어들이고, 마크업을 렌더할 수 있을 것입니다.
<ide>
<ide>
<ide> ```javascript
<ide> Markdown은 텍스트를 포맷팅하는 간단한 방식입니다. 예를 들
<ide> <title>Hello React</title>
<ide> <script src="https://fb.me/react-{{site.react_version}}.js"></script>
<ide> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script>
<del> <script src="https://code.jquery.com/jquery-1.10.0.min.js"></script>
<add> <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
<ide> </head>
<ide> ```
| 3
|
Javascript
|
Javascript
|
remove unneeded escaping of /
|
7ef16eee2f0b69a2e5004f249cb4ebeb7000733e
|
<ide><path>lib/fs.js
<ide> fs.unwatchFile = function(filename, listener) {
<ide> // Regexp that finds the next portion of a (partial) path
<ide> // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
<ide> const nextPartRe = isWindows ?
<del> /(.*?)(?:[\/\\]+|$)/g :
<del> /(.*?)(?:[\/]+|$)/g;
<add> /(.*?)(?:[/\\]+|$)/g :
<add> /(.*?)(?:[/]+|$)/g;
<ide>
<ide> // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
<ide> const splitRootRe = isWindows ?
<del> /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/ :
<del> /^[\/]*/;
<add> /^(?:[a-zA-Z]:|[\\/]{2}[^\\/]+[\\/][^\\/]+)?[\\/]*/ :
<add> /^[/]*/;
<ide>
<ide> function encodeRealpathResult(result, options, err) {
<ide> if (!options || !options.encoding || options.encoding === 'utf8' || err)
<ide><path>lib/url.js
<ide> Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
<ide> // user@server is *always* interpreted as a hostname, and url
<ide> // resolution will treat //foo/bar as host=foo,path=bar because that's
<ide> // how the browser resolves relative URLs.
<del> if (slashesDenoteHost || proto || /^\/\/[^@\/]+@[^@\/]+/.test(rest)) {
<add> if (slashesDenoteHost || proto || /^\/\/[^@/]+@[^@/]+/.test(rest)) {
<ide> var slashes = rest.charCodeAt(0) === 47/*/*/ &&
<ide> rest.charCodeAt(1) === 47/*/*/;
<ide> if (slashes && !(proto && hostlessProtocol[proto])) {
<ide><path>test/debugger/test-debugger-repl-break-in-module.js
<ide> repl.addTest('sb(")^$*+?}{|][(.js\\\\", 1)', [
<ide>
<ide> // continue - the breakpoint should be triggered
<ide> repl.addTest('c', [
<del> /break in .*[\\\/]mod\.js:2/,
<add> /break in .*[\\/]mod\.js:2/,
<ide> /1/, /2/, /3/, /4/
<ide> ]);
<ide>
<ide> repl.addTest('restart', [].concat(
<ide>
<ide> // continue - the breakpoint should be triggered
<ide> repl.addTest('c', [
<del> /break in .*[\\\/]mod\.js:2/,
<add> /break in .*[\\/]mod\.js:2/,
<ide> /1/, /2/, /3/, /4/
<ide> ]);
<ide>
<ide> repl.addTest('cb("mod.js", 2)', [
<ide> ]);
<ide>
<ide> repl.addTest('c', [
<del> /break in .*[\\\/]main\.js:4/,
<add> /break in .*[\\/]main\.js:4/,
<ide> /2/, /3/, /4/, /5/, /6/
<ide> ]);
<ide>
<ide><path>test/parallel/test-require-json.js
<ide> var assert = require('assert');
<ide> try {
<ide> require(path.join(common.fixturesDir, 'invalid.json'));
<ide> } catch (err) {
<del> var re = /test[\/\\]fixtures[\/\\]invalid.json: Unexpected string/;
<add> var re = /test[/\\]fixtures[/\\]invalid.json: Unexpected string/;
<ide> var i = err.message.match(re);
<ide> assert.notStrictEqual(null, i, 'require() json error should include path');
<ide> }
| 4
|
PHP
|
PHP
|
do strict check on mac
|
7836868e0125e29ed6255f27727c2933105991ec
|
<ide><path>src/Illuminate/Encryption/Encrypter.php
<ide> protected function getJsonPayload($payload)
<ide> */
<ide> protected function validMac(array $payload)
<ide> {
<del> return ($payload['mac'] == $this->hash($payload['iv'], $payload['value']));
<add> return ($payload['mac'] === $this->hash($payload['iv'], $payload['value']));
<ide> }
<ide>
<ide> /**
| 1
|
Javascript
|
Javascript
|
move ismounted logic into the reactupdatequeue
|
ffd5b16d5f744be35db65ade2bb27bba52b2bd9b
|
<ide><path>src/isomorphic/classic/class/ReactClass.js
<ide> 'use strict';
<ide>
<ide> var ReactComponent = require('ReactComponent');
<del>var ReactCurrentOwner = require('ReactCurrentOwner');
<ide> var ReactElement = require('ReactElement');
<ide> var ReactErrorUtils = require('ReactErrorUtils');
<del>var ReactInstanceMap = require('ReactInstanceMap');
<del>var ReactLifeCycle = require('ReactLifeCycle');
<ide> var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide> var ReactUpdateQueue = require('ReactUpdateQueue');
<ide> var ReactClassMixin = {
<ide> * @final
<ide> */
<ide> isMounted: function() {
<del> if (__DEV__) {
<del> var owner = ReactCurrentOwner.current;
<del> if (owner !== null) {
<del> warning(
<del> owner._warnedAboutRefsInRender,
<del> '%s is accessing isMounted inside its render() function. ' +
<del> 'render() should be a pure function of props and state. It should ' +
<del> 'never access something that requires stale data from the previous ' +
<del> 'render, such as refs. Move this logic to componentDidMount and ' +
<del> 'componentDidUpdate instead.',
<del> owner.getName() || 'A component'
<del> );
<del> owner._warnedAboutRefsInRender = true;
<del> }
<del> }
<del> var internalInstance = ReactInstanceMap.get(this);
<del> if (internalInstance) {
<del> return internalInstance !== ReactLifeCycle.currentlyMountingInstance;
<del> } else {
<del> return false;
<del> }
<add> return ReactUpdateQueue.isMounted(this);
<ide> },
<ide>
<ide> /**
<ide><path>src/renderers/shared/reconciler/ReactUpdateQueue.js
<ide> function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
<ide> */
<ide> var ReactUpdateQueue = {
<ide>
<add> /**
<add> * Checks whether or not this composite component is mounted.
<add> * @param {ReactClass} publicInstance The instance we want to test.
<add> * @return {boolean} True if mounted, false otherwise.
<add> * @protected
<add> * @final
<add> */
<add> isMounted: function(publicInstance) {
<add> if (__DEV__) {
<add> var owner = ReactCurrentOwner.current;
<add> if (owner !== null) {
<add> warning(
<add> owner._warnedAboutRefsInRender,
<add> '%s is accessing isMounted inside its render() function. ' +
<add> 'render() should be a pure function of props and state. It should ' +
<add> 'never access something that requires stale data from the previous ' +
<add> 'render, such as refs. Move this logic to componentDidMount and ' +
<add> 'componentDidUpdate instead.',
<add> owner.getName() || 'A component'
<add> );
<add> owner._warnedAboutRefsInRender = true;
<add> }
<add> }
<add> var internalInstance = ReactInstanceMap.get(publicInstance);
<add> if (internalInstance) {
<add> return internalInstance !== ReactLifeCycle.currentlyMountingInstance;
<add> } else {
<add> return false;
<add> }
<add> },
<add>
<ide> /**
<ide> * Enqueue a callback that will be executed after all the pending updates
<ide> * have processed.
| 2
|
PHP
|
PHP
|
repaire help on view class document
|
bcbb63d1a7b36c7e95489ba2bed1baa021ec743c
|
<ide><path>src/View/View.php
<ide> * layout using `$this->set()`
<ide> *
<ide> * View class supports using plugins as themes. You can set
<del> * `$this->theme = 'SuperHot'` in your Controller to use plugin `SuperHot` as a
<add> *
<add> * `public function beforeRender(\Cake\Event\Event $event)
<add> * {
<add> * $this->viewBuilder()->theme('SuperHot');
<add> * }`
<add> * in your Controller to use plugin `SuperHot` as a
<ide> * theme. Eg. If current action is Posts::index() then View class will look for
<ide> * template file `plugins/SuperHot/Template/Posts/index.ctp`. If a theme template
<ide> * is not found for the current action the default app template file is used.
| 1
|
Python
|
Python
|
remove todos that will never fulfill
|
4c50658530037b40d71c29cdedad2ac8474c9c11
|
<ide><path>official/modeling/tf_utils.py
<ide> def is_special_none_tensor(tensor):
<ide> return tensor.shape.ndims == 0 and tensor.dtype == tf.int32
<ide>
<ide>
<del># TODO(hongkuny): consider moving custom string-map lookup to keras api.
<ide> def get_activation(identifier):
<ide> """Maps a identifier to a Python function, e.g., "relu" => `tf.nn.relu`.
<ide>
<ide><path>official/nlp/bert/model_training_utils.py
<ide> def _run_evaluation(current_training_step, test_iterator):
<ide> for metric in model.metrics:
<ide> training_summary[metric.name] = _float_metric_value(metric)
<ide> if eval_metrics:
<del> # TODO(hongkuny): Cleans up summary reporting in text.
<ide> training_summary['last_train_metrics'] = _float_metric_value(
<ide> train_metrics[0])
<ide> training_summary['eval_metrics'] = _float_metric_value(eval_metrics[0])
<ide><path>official/nlp/transformer/transformer.py
<ide> def create_model(params, is_train):
<ide> logits = tf.keras.layers.Lambda(lambda x: x, name="logits",
<ide> dtype=tf.float32)(logits)
<ide> model = tf.keras.Model([inputs, targets], logits)
<del> # TODO(reedwm): Can we do this loss in float16 instead of float32?
<ide> loss = metrics.transformer_loss(
<ide> logits, targets, label_smoothing, vocab_size)
<ide> model.add_loss(loss)
<ide> def _get_symbols_to_logits_fn(self, max_decode_length, training):
<ide> decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias(
<ide> max_decode_length, dtype=self.params["dtype"])
<ide>
<del> # TODO(b/139770046): Refactor code with better naming of i.
<ide> def symbols_to_logits_fn(ids, i, cache):
<ide> """Generate logits for next potential IDs.
<ide>
<ide><path>official/nlp/transformer/transformer_main.py
<ide> def train(self):
<ide> callbacks = [cb for cb in callbacks
<ide> if isinstance(cb, keras_utils.TimeHistory)]
<ide>
<del> # TODO(b/139418525): Refactor the custom training loop logic.
<ide> @tf.function
<ide> def train_steps(iterator, steps):
<ide> """Training steps function for TPU runs.
<ide> def _load_weights_if_possible(self, model, init_weight_path=None):
<ide> """Loads model weights when it is provided."""
<ide> if init_weight_path:
<ide> logging.info("Load weights: {}".format(init_weight_path))
<del> # TODO(b/139414977): Having the same variable restoring method for both
<del> # TPU and GPU.
<ide> if self.use_tpu:
<ide> checkpoint = tf.train.Checkpoint(
<ide> model=model, optimizer=self._create_optimizer())
| 4
|
Python
|
Python
|
fix typo in documentation
|
d1eefff16929c0ebf7fcf3f8e40313b51ffc2886
|
<ide><path>keras/layers/preprocessing/index_lookup.py
<ide> def vocabulary_size(self):
<ide> """Gets the current size of the layer's vocabulary.
<ide>
<ide> Returns:
<del> The integer size of the voculary, including optional mask and oov indices.
<add> The integer size of the vocabulary, including optional mask and oov indices.
<ide> """
<ide> return int(self.lookup_table.size().numpy()) + self._token_start_index()
<ide>
| 1
|
Python
|
Python
|
improve embedding defaults
|
76fe24f44d1238e3755c07cd377eddde2b74a913
|
<ide><path>spacy/_ml.py
<ide> def link_vectors_to_models(vocab):
<ide>
<ide> def Tok2Vec(width, embed_size, **kwargs):
<ide> pretrained_dims = kwargs.get('pretrained_dims', 0)
<del> cnn_maxout_pieces = kwargs.get('cnn_maxout_pieces', 3)
<add> cnn_maxout_pieces = kwargs.get('cnn_maxout_pieces', 2)
<ide> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH]
<ide> with Model.define_operators({'>>': chain, '|': concatenate, '**': clone, '+': add,
<ide> '*': reapply}):
| 1
|
PHP
|
PHP
|
add missing docblock
|
8ec69f85f90433d15c1afbbd7329700fe601635e
|
<ide><path>src/Illuminate/Support/Facades/Bus.php
<ide> class Bus extends Facade
<ide> * Replace the bound instance with a fake.
<ide> *
<ide> * @param array|string $jobsToFake
<add> * @param \Illuminate\Bus\BatchRepository|null $batchRepository
<ide> * @return \Illuminate\Support\Testing\Fakes\BusFake
<ide> */
<ide> public static function fake($jobsToFake = [], BatchRepository $batchRepository = null)
| 1
|
Javascript
|
Javascript
|
update require path after file move
|
f311963ff94b87c50d146150226d6d3cb07d26c3
|
<ide><path>test/pummel/test-debugger-repl-break-in-module.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<del>var repl = require('./helper-debugger-repl.js');
<add>var repl = require('../simple/helper-debugger-repl.js');
<ide>
<ide> repl.startDebugger('break-in-module/main.js');
<ide>
| 1
|
Python
|
Python
|
add newline at the end of printed warnings
|
46cf7ff519af6c1ee6921acb304091a7b46ec3d5
|
<ide><path>numpy/distutils/misc_util.py
<ide> def info(self, message):
<ide> print(message)
<ide>
<ide> def warn(self, message):
<del> sys.stderr.write('Warning: %s' % (message,))
<add> sys.stderr.write('Warning: %s\n' % (message,))
<ide>
<ide> def set_options(self, **options):
<ide> """
| 1
|
Javascript
|
Javascript
|
use async writefile in filehandle#appendfile
|
73a9c37307026e46a818a06cc3a375d4d02e65b7
|
<ide><path>lib/internal/fs/promises.js
<ide> class FileHandle {
<ide> }
<ide>
<ide> appendFile(data, options) {
<del> return appendFile(this, data, options);
<add> return writeFile(this, data, options);
<ide> }
<ide>
<ide> chmod(mode) {
| 1
|
Go
|
Go
|
finalize tarsum version 1 w/ refactor
|
a7aa2c8ad26149e9be753bc08964f35cb09d313c
|
<ide><path>pkg/tarsum/tarsum.go
<ide> import (
<ide> "encoding/hex"
<ide> "hash"
<ide> "io"
<del> "sort"
<del> "strconv"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> const (
<ide> // including the byte payload of the image's json metadata as well, and for
<ide> // calculating the checksums for buildcache.
<ide> func NewTarSum(r io.Reader, dc bool, v Version) (TarSum, error) {
<del> if _, ok := tarSumVersions[v]; !ok {
<del> return nil, ErrVersionNotImplemented
<add> headerSelector, err := getTarHeaderSelector(v)
<add> if err != nil {
<add> return nil, err
<ide> }
<del> return &tarSum{Reader: r, DisableCompression: dc, tarSumVersion: v}, nil
<add> return &tarSum{Reader: r, DisableCompression: dc, tarSumVersion: v, headerSelector: headerSelector}, nil
<ide> }
<ide>
<ide> // Create a new TarSum, providing a THash to use rather than the DefaultTHash
<ide> func NewTarSumHash(r io.Reader, dc bool, v Version, tHash THash) (TarSum, error) {
<del> if _, ok := tarSumVersions[v]; !ok {
<del> return nil, ErrVersionNotImplemented
<add> headerSelector, err := getTarHeaderSelector(v)
<add> if err != nil {
<add> return nil, err
<ide> }
<del> return &tarSum{Reader: r, DisableCompression: dc, tarSumVersion: v, tHash: tHash}, nil
<add> return &tarSum{Reader: r, DisableCompression: dc, tarSumVersion: v, headerSelector: headerSelector, tHash: tHash}, nil
<ide> }
<ide>
<ide> // TarSum is the generic interface for calculating fixed time
<ide> type tarSum struct {
<ide> currentFile string
<ide> finished bool
<ide> first bool
<del> DisableCompression bool // false by default. When false, the output gzip compressed.
<del> tarSumVersion Version // this field is not exported so it can not be mutated during use
<add> DisableCompression bool // false by default. When false, the output gzip compressed.
<add> tarSumVersion Version // this field is not exported so it can not be mutated during use
<add> headerSelector tarHeaderSelector // handles selecting and ordering headers for files in the archive
<ide> }
<ide>
<ide> func (ts tarSum) Hash() THash {
<ide> type simpleTHash struct {
<ide> func (sth simpleTHash) Name() string { return sth.n }
<ide> func (sth simpleTHash) Hash() hash.Hash { return sth.h() }
<ide>
<del>func (ts tarSum) selectHeaders(h *tar.Header, v Version) (set [][2]string) {
<del> for _, elem := range [][2]string{
<del> {"name", h.Name},
<del> {"mode", strconv.Itoa(int(h.Mode))},
<del> {"uid", strconv.Itoa(h.Uid)},
<del> {"gid", strconv.Itoa(h.Gid)},
<del> {"size", strconv.Itoa(int(h.Size))},
<del> {"mtime", strconv.Itoa(int(h.ModTime.UTC().Unix()))},
<del> {"typeflag", string([]byte{h.Typeflag})},
<del> {"linkname", h.Linkname},
<del> {"uname", h.Uname},
<del> {"gname", h.Gname},
<del> {"devmajor", strconv.Itoa(int(h.Devmajor))},
<del> {"devminor", strconv.Itoa(int(h.Devminor))},
<del> } {
<del> if v >= VersionDev && elem[0] == "mtime" {
<del> continue
<del> }
<del> set = append(set, elem)
<del> }
<del> return
<del>}
<del>
<ide> func (ts *tarSum) encodeHeader(h *tar.Header) error {
<del> for _, elem := range ts.selectHeaders(h, ts.Version()) {
<add> for _, elem := range ts.headerSelector.selectHeaders(h) {
<ide> if _, err := ts.h.Write([]byte(elem[0] + elem[1])); err != nil {
<ide> return err
<ide> }
<ide> }
<del>
<del> // include the additional pax headers, from an ordered list
<del> if ts.Version() >= VersionDev {
<del> var keys []string
<del> for k := range h.Xattrs {
<del> keys = append(keys, k)
<del> }
<del> sort.Strings(keys)
<del> for _, k := range keys {
<del> if _, err := ts.h.Write([]byte(k + h.Xattrs[k])); err != nil {
<del> return err
<del> }
<del> }
<del> }
<ide> return nil
<ide> }
<ide>
<ide><path>pkg/tarsum/versioning.go
<ide> package tarsum
<ide>
<ide> import (
<ide> "errors"
<add> "sort"
<add> "strconv"
<ide> "strings"
<add>
<add> "github.com/docker/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar"
<ide> )
<ide>
<ide> // versioning of the TarSum algorithm
<ide> // based on the prefix of the hash used
<ide> // i.e. "tarsum+sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b"
<ide> type Version int
<ide>
<add>// Prefix of "tarsum"
<ide> const (
<del> // Prefix of "tarsum"
<ide> Version0 Version = iota
<del> // Prefix of "tarsum.dev"
<del> // NOTE: this variable will be of an unsettled next-version of the TarSum calculation
<add> Version1
<add> // NOTE: this variable will be either the latest or an unsettled next-version of the TarSum calculation
<ide> VersionDev
<ide> )
<ide>
<ide> func GetVersions() []Version {
<ide> }
<ide>
<ide> var tarSumVersions = map[Version]string{
<del> 0: "tarsum",
<del> 1: "tarsum.dev",
<add> Version0: "tarsum",
<add> Version1: "tarsum.v1",
<add> VersionDev: "tarsum.dev",
<ide> }
<ide>
<ide> func (tsv Version) String() string {
<ide> func GetVersionFromTarsum(tarsum string) (Version, error) {
<ide> return -1, ErrNotVersion
<ide> }
<ide>
<add>// Errors that may be returned by functions in this package
<ide> var (
<ide> ErrNotVersion = errors.New("string does not include a TarSum Version")
<ide> ErrVersionNotImplemented = errors.New("TarSum Version is not yet implemented")
<ide> )
<add>
<add>// tarHeaderSelector is the interface which different versions
<add>// of tarsum should use for selecting and ordering tar headers
<add>// for each item in the archive.
<add>type tarHeaderSelector interface {
<add> selectHeaders(h *tar.Header) (orderedHeaders [][2]string)
<add>}
<add>
<add>type tarHeaderSelectFunc func(h *tar.Header) (orderedHeaders [][2]string)
<add>
<add>func (f tarHeaderSelectFunc) selectHeaders(h *tar.Header) (orderedHeaders [][2]string) {
<add> return f(h)
<add>}
<add>
<add>func v0TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) {
<add> return [][2]string{
<add> {"name", h.Name},
<add> {"mode", strconv.Itoa(int(h.Mode))},
<add> {"uid", strconv.Itoa(h.Uid)},
<add> {"gid", strconv.Itoa(h.Gid)},
<add> {"size", strconv.Itoa(int(h.Size))},
<add> {"mtime", strconv.Itoa(int(h.ModTime.UTC().Unix()))},
<add> {"typeflag", string([]byte{h.Typeflag})},
<add> {"linkname", h.Linkname},
<add> {"uname", h.Uname},
<add> {"gname", h.Gname},
<add> {"devmajor", strconv.Itoa(int(h.Devmajor))},
<add> {"devminor", strconv.Itoa(int(h.Devminor))},
<add> }
<add>}
<add>
<add>func v1TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) {
<add> // Get extended attributes.
<add> xAttrKeys := make([]string, len(h.Xattrs))
<add> for k := range h.Xattrs {
<add> xAttrKeys = append(xAttrKeys, k)
<add> }
<add> sort.Strings(xAttrKeys)
<add>
<add> // Make the slice with enough capacity to hold the 11 basic headers
<add> // we want from the v0 selector plus however many xattrs we have.
<add> orderedHeaders = make([][2]string, 0, 11+len(xAttrKeys))
<add>
<add> // Copy all headers from v0 excluding the 'mtime' header (the 5th element).
<add> v0headers := v0TarHeaderSelect(h)
<add> orderedHeaders = append(orderedHeaders, v0headers[0:5]...)
<add> orderedHeaders = append(orderedHeaders, v0headers[6:]...)
<add>
<add> // Finally, append the sorted xattrs.
<add> for _, k := range xAttrKeys {
<add> orderedHeaders = append(orderedHeaders, [2]string{k, h.Xattrs[k]})
<add> }
<add>
<add> return
<add>}
<add>
<add>var registeredHeaderSelectors = map[Version]tarHeaderSelectFunc{
<add> Version0: v0TarHeaderSelect,
<add> Version1: v1TarHeaderSelect,
<add> VersionDev: v1TarHeaderSelect,
<add>}
<add>
<add>func getTarHeaderSelector(v Version) (tarHeaderSelector, error) {
<add> headerSelector, ok := registeredHeaderSelectors[v]
<add> if !ok {
<add> return nil, ErrVersionNotImplemented
<add> }
<add>
<add> return headerSelector, nil
<add>}
<ide><path>pkg/tarsum/versioning_test.go
<ide> func TestVersion(t *testing.T) {
<ide> t.Errorf("expected %q, got %q", expected, v.String())
<ide> }
<ide>
<del> expected = "tarsum.dev"
<add> expected = "tarsum.v1"
<ide> v = 1
<ide> if v.String() != expected {
<ide> t.Errorf("expected %q, got %q", expected, v.String())
<ide> }
<add>
<add> expected = "tarsum.dev"
<add> v = 2
<add> if v.String() != expected {
<add> t.Errorf("expected %q, got %q", expected, v.String())
<add> }
<ide> }
<ide>
<ide> func TestGetVersion(t *testing.T) {
| 3
|
Java
|
Java
|
remove unnecessary calls to tostring()
|
19955c5b77ce4cf494fbf751fbf009a862490c47
|
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/SessionDisconnectEvent.java
<ide> public CloseStatus getCloseStatus() {
<ide>
<ide> @Override
<ide> public String toString() {
<del> return "SessionDisconnectEvent[sessionId=" + this.sessionId + ", " + this.status.toString() + "]";
<add> return "SessionDisconnectEvent[sessionId=" + this.sessionId + ", " + this.status + "]";
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java
<ide> public boolean equals(Object obj) {
<ide> private static class MyTypeToStringConverter implements Converter<MyType, String> {
<ide> @Override
<ide> public String convert(MyType source) {
<del> return "_" + source.toString();
<add> return "_" + source;
<ide> }
<ide> }
<ide>
<ide>
<ide> private static class MyTypeToBytesConverter implements Converter<MyType, byte[]> {
<ide> @Override
<ide> public byte[] convert(MyType source) {
<del> return ("~" + source.toString()).getBytes();
<add> return ("~" + source).getBytes();
<ide> }
<ide> }
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransportTests.java
<ide> public void connectReceiveAndCloseWithPrelude() throws Exception {
<ide> for (int i = 0; i < 2048; i++) {
<ide> sb.append('h');
<ide> }
<del> String body = sb.toString() + "\n" + "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]";
<add> String body = sb + "\n" + "o\n" + "a[\"foo\"]\n" + "c[3000,\"Go away!\"]";
<ide> ClientHttpResponse response = response(HttpStatus.OK, body);
<ide> connect(response);
<ide>
| 3
|
Text
|
Text
|
correct cs in readme
|
0a1b1a123abf9eb99871586ce5857a7b00b522b7
|
<ide><path>src/Collection/README.md
<ide> $collection = new Collection($items);
<ide>
<ide> // Create a new collection containing elements
<ide> // with a value greater than one.
<del>$overOne = $collection->filter(function($value, $key, $iterator) {
<add>$overOne = $collection->filter(function ($value, $key, $iterator) {
<ide> return $value > 1;
<ide> });
<ide> ```
<ide><path>src/Event/README.md
<ide> class Orders {
<ide> }
<ide>
<ide> $orders = new Orders();
<del>$orders->eventManager()->attach(function($event) {
<add>$orders->eventManager()->attach(function ($event) {
<ide> // Do something after the order was placed
<ide> ...
<ide> }, 'Orders.afterPlace');
<ide><path>src/Log/README.md
<ide> Log::config('production', [
<ide> It is also possible to create loggers by providing a closure.
<ide>
<ide> ```php
<del>Log::config('special', function() {
<add>Log::config('special', function () {
<ide> // Return any PSR-3 compatible logger
<ide> return new MyPSR3CompatibleLogger();
<ide> });
| 3
|
PHP
|
PHP
|
fix space between function + parenthesis
|
18e282f3aa6faead59bb8fbcdd9f0f6967c29ec2
|
<ide><path>lib/Cake/Model/Model.php
<ide> protected function _createLinks() {
<ide> $plugin = null;
<ide>
<ide> if (is_numeric($assoc)) {
<del> unset ($this->{$type}[$assoc]);
<add> unset($this->{$type}[$assoc]);
<ide> $assoc = $value;
<ide> $value = array();
<ide>
<ide> public function set($one, $two = null) {
<ide>
<ide> foreach ($fieldSet as $fieldName => $fieldValue) {
<ide> if (isset($this->validationErrors[$fieldName])) {
<del> unset ($this->validationErrors[$fieldName]);
<add> unset($this->validationErrors[$fieldName]);
<ide> }
<ide>
<ide> if ($modelName === $this->alias) {
| 1
|
PHP
|
PHP
|
add test case
|
a266d8bedef02872810ffb84c36fb8269dc993f0
|
<ide><path>lib/Cake/Test/Case/Cache/CacheTest.php
<ide> public function testConfig() {
<ide> $this->assertTrue(isset($results['settings']));
<ide> }
<ide>
<add>/**
<add> * testConfigInvalidEngine method
<add> *
<add> * @expectedException CacheException
<add> * @return void
<add> */
<add> public function testConfigInvalidEngine() {
<add> $settings = array('engine' => 'Imaginary');
<add> Cache::config('imaginary', $settings);
<add> }
<add>
<ide> /**
<ide> * Check that no fatal errors are issued doing normal things when Cache.disable is true.
<ide> *
| 1
|
PHP
|
PHP
|
add type in generatorcommand
|
49f640d45aea98cd838fd90e962a91e7e5d49022
|
<ide><path>src/Illuminate/Console/GeneratorCommand.php
<ide> abstract class GeneratorCommand extends Command {
<ide> */
<ide> protected $configKey = '';
<ide>
<add> /**
<add> * The type of class being generated.
<add> *
<add> * @var string
<add> */
<add> protected $type;
<add>
<ide> /**
<ide> * Create a new controller creator command instance.
<ide> *
| 1
|
Python
|
Python
|
show import errors in dag views
|
c203e7793c570eeb2968fa06a56470853563d73b
|
<ide><path>airflow/www/utils.py
<ide> import markdown
<ide> import sqlalchemy as sqla
<ide> from flask import Markup, Response, request, url_for
<add>from flask.helpers import flash
<ide> from flask_appbuilder.forms import FieldConverter
<ide> from flask_appbuilder.models.sqla import filters as fab_sqlafilters
<ide> from flask_appbuilder.models.sqla.interface import SQLAInterface
<ide> from pygments import highlight, lexers
<ide> from pygments.formatters import HtmlFormatter
<ide>
<add>from airflow.models import errors
<ide> from airflow.utils import timezone
<ide> from airflow.utils.code_utils import get_python_source
<ide> from airflow.utils.json import AirflowJsonEncoder
<ide> from airflow.www.widgets import AirflowDateTimePickerWidget
<ide>
<ide>
<add>def check_import_errors(fileloc, session):
<add> # Check dag import errors
<add> import_errors = session.query(errors.ImportError).filter(errors.ImportError.filename == fileloc).all()
<add> if import_errors:
<add> for import_error in import_errors:
<add> flash("Broken DAG: [{ie.filename}] {ie.stacktrace}".format(ie=import_error), "dag_import_error")
<add>
<add>
<ide> def get_sensitive_variables_fields():
<ide> import warnings
<ide>
<ide><path>airflow/www/views.py
<ide> def code(self, session=None):
<ide> escape(all_errors)
<ide> )
<ide>
<add> wwwutils.check_import_errors(dag_orm.fileloc, session)
<add>
<ide> return self.render_template(
<ide> 'airflow/dag_code.html',
<ide> html_code=html_code,
<ide> def dag_details(self, session=None):
<ide> title = "DAG Details"
<ide> root = request.args.get('root', '')
<ide>
<add> wwwutils.check_import_errors(dag.fileloc, session)
<add>
<ide> states = (
<ide> session.query(TaskInstance.state, sqla.func.count(TaskInstance.dag_id))
<ide> .filter(TaskInstance.dag_id == dag_id)
<ide> def recurse_nodes(task, visited):
<ide> )
<ide> @gzipped
<ide> @action_logging
<del> def tree(self):
<add> @provide_session
<add> def tree(self, session=None):
<ide> """Get Dag as tree."""
<ide> dag_id = request.args.get('dag_id')
<ide> dag = current_app.dag_bag.get_dag(dag_id)
<ide> if not dag:
<ide> flash(f'DAG "{dag_id}" seems to be missing from DagBag.', "error")
<ide> return redirect(url_for('Airflow.index'))
<add> wwwutils.check_import_errors(dag.fileloc, session)
<ide>
<ide> root = request.args.get('root')
<ide> if root:
<ide> def tree(self):
<ide> except (KeyError, ValueError):
<ide> base_date = dag.get_latest_execution_date() or timezone.utcnow()
<ide>
<del> with create_session() as session:
<del> dag_runs = (
<del> session.query(DagRun)
<del> .filter(DagRun.dag_id == dag.dag_id, DagRun.execution_date <= base_date)
<del> .order_by(DagRun.execution_date.desc())
<del> .limit(num_runs)
<del> .all()
<del> )
<add> dag_runs = (
<add> session.query(DagRun)
<add> .filter(DagRun.dag_id == dag.dag_id, DagRun.execution_date <= base_date)
<add> .order_by(DagRun.execution_date.desc())
<add> .limit(num_runs)
<add> .all()
<add> )
<ide> dag_runs = {dr.execution_date: alchemy_to_dict(dr) for dr in dag_runs}
<ide>
<ide> max_date = max(dag_runs.keys(), default=None)
<ide> def tree(self):
<ide> )
<ide> @gzipped
<ide> @action_logging
<del> def calendar(self):
<add> @provide_session
<add> def calendar(self, session=None):
<ide> """Get DAG runs as calendar"""
<ide>
<ide> def _convert_to_date(session, column):
<ide> def _convert_to_date(session, column):
<ide> flash(f'DAG "{dag_id}" seems to be missing from DagBag.', "error")
<ide> return redirect(url_for('Airflow.index'))
<ide>
<add> wwwutils.check_import_errors(dag.fileloc, session)
<add>
<ide> root = request.args.get('root')
<ide> if root:
<ide> dag = dag.partial_subset(task_ids_or_regex=root, include_downstream=False, include_upstream=True)
<ide>
<del> with create_session() as session:
<del> dag_states = (
<del> session.query(
<del> (_convert_to_date(session, DagRun.execution_date)).label('date'),
<del> DagRun.state,
<del> func.count('*').label('count'),
<del> )
<del> .filter(DagRun.dag_id == dag.dag_id)
<del> .group_by(_convert_to_date(session, DagRun.execution_date), DagRun.state)
<del> .order_by(_convert_to_date(session, DagRun.execution_date).asc())
<del> .all()
<add> dag_states = (
<add> session.query(
<add> (_convert_to_date(session, DagRun.execution_date)).label('date'),
<add> DagRun.state,
<add> func.count('*').label('count'),
<ide> )
<add> .filter(DagRun.dag_id == dag.dag_id)
<add> .group_by(_convert_to_date(session, DagRun.execution_date), DagRun.state)
<add> .order_by(_convert_to_date(session, DagRun.execution_date).asc())
<add> .all()
<add> )
<ide>
<ide> dag_states = [
<ide> {
<ide> def graph(self, session=None):
<ide> if not dag:
<ide> flash(f'DAG "{dag_id}" seems to be missing.', "error")
<ide> return redirect(url_for('Airflow.index'))
<add> wwwutils.check_import_errors(dag.fileloc, session)
<ide>
<ide> root = request.args.get('root')
<ide> if root:
<ide> def duration(self, session=None):
<ide> flash(f'DAG "{dag_id}" seems to be missing.', "error")
<ide> return redirect(url_for('Airflow.index'))
<ide>
<add> wwwutils.check_import_errors(dag.fileloc, session)
<add>
<ide> base_date = request.args.get('base_date')
<ide> num_runs = request.args.get('num_runs', default=default_dag_run, type=int)
<ide>
<ide> def tries(self, session=None):
<ide> else:
<ide> base_date = dag.get_latest_execution_date() or timezone.utcnow()
<ide>
<add> wwwutils.check_import_errors(dag.fileloc, session)
<add>
<ide> root = request.args.get('root')
<ide> if root:
<ide> dag = dag.partial_subset(task_ids_or_regex=root, include_upstream=True, include_downstream=False)
<ide> def landing_times(self, session=None):
<ide> else:
<ide> base_date = dag.get_latest_execution_date() or timezone.utcnow()
<ide>
<add> wwwutils.check_import_errors(dag.fileloc, session)
<add>
<ide> root = request.args.get('root')
<ide> if root:
<ide> dag = dag.partial_subset(task_ids_or_regex=root, include_upstream=True, include_downstream=False)
<ide> def gantt(self, session=None):
<ide> if root:
<ide> dag = dag.partial_subset(task_ids_or_regex=root, include_upstream=True, include_downstream=False)
<ide>
<add> wwwutils.check_import_errors(dag.fileloc, session)
<add>
<ide> dt_nr_dr_data = get_date_time_num_runs_dag_runs_form_data(request, session, dag)
<ide> dttm = dt_nr_dr_data['dttm']
<ide>
| 2
|
Ruby
|
Ruby
|
hide sensitive tokens from install/test/post
|
d02b4f321d01fbd4cd2b4c1bd76d1f06d1612126
|
<ide><path>Library/Homebrew/dev-cmd/mirror.rb
<ide> module Homebrew
<ide> def mirror
<ide> odie "This command requires at least formula argument!" if ARGV.named.empty?
<ide>
<del> bintray_user = ENV["BINTRAY_USER"]
<del> bintray_key = ENV["BINTRAY_KEY"]
<add> bintray_user = ENV["HOMEBREW_BINTRAY_USER"]
<add> bintray_key = ENV["HOMEBREW_BINTRAY_KEY"]
<ide> if !bintray_user || !bintray_key
<del> raise "Missing BINTRAY_USER or BINTRAY_KEY variables!"
<add> raise "Missing HOMEBREW_BINTRAY_USER or HOMEBREW_BINTRAY_KEY variables!"
<ide> end
<ide>
<ide> ARGV.formulae.each do |f|
<ide><path>Library/Homebrew/dev-cmd/pull.rb
<ide> def publish_changed_formula_bottles(_tap, changed_formulae_names)
<ide> end
<ide>
<ide> published = []
<del> bintray_creds = { user: ENV["BINTRAY_USER"], key: ENV["BINTRAY_KEY"] }
<add> bintray_creds = { user: ENV["HOMEBREW_BINTRAY_USER"], key: ENV["HOMEBREW_BINTRAY_KEY"] }
<ide> if bintray_creds[:user] && bintray_creds[:key]
<ide> changed_formulae_names.each do |name|
<ide> f = Formula[name]
<ide> def publish_changed_formula_bottles(_tap, changed_formulae_names)
<ide> published << f.full_name
<ide> end
<ide> else
<del> opoo "You must set BINTRAY_USER and BINTRAY_KEY to add or update bottles on Bintray!"
<add> opoo "You must set HOMEBREW_BINTRAY_USER and HOMEBREW_BINTRAY_KEY to add or update bottles on Bintray!"
<ide> end
<ide> published
<ide> end
<ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_user_path_1
<ide>
<ide> message = ""
<ide>
<del> paths.each do |p|
<add> paths(ENV["HOMEBREW_PATH"]).each do |p|
<ide> case p
<ide> when "/usr/bin"
<ide> unless $seen_prefix_bin
<ide> def check_for_config_scripts
<ide> /Applications/Server.app/Contents/ServerRoot/usr/sbin
<ide> ].map(&:downcase)
<ide>
<del> paths.each do |p|
<add> paths(ENV["HOMEBREW_PATH"]).each do |p|
<ide> next if whitelist.include?(p.downcase) || !File.directory?(p)
<ide>
<ide> realpath = Pathname.new(p).realpath.to_s
<ide><path>Library/Homebrew/extend/ENV.rb
<ide> def with_build_environment
<ide> ensure
<ide> replace(old_env)
<ide> end
<add>
<add> def clear_sensitive_environment!
<add> ENV.keys.each do |key|
<add> next unless /(cookie|key|token)/i =~ key
<add> ENV.delete key
<add> end
<add> end
<ide> end
<ide>
<ide> ENV.extend(EnvActivation)
<ide><path>Library/Homebrew/formula.rb
<ide> require "tap"
<ide> require "keg"
<ide> require "migrator"
<add>require "extend/ENV"
<ide>
<ide> # A formula provides instructions and metadata for Homebrew to install a piece
<ide> # of software. Every Homebrew formula is a {Formula}.
<ide> def run_post_install
<ide> @prefix_returns_versioned_prefix = true
<ide> build = self.build
<ide> self.build = Tab.for_formula(self)
<add>
<ide> old_tmpdir = ENV["TMPDIR"]
<ide> old_temp = ENV["TEMP"]
<ide> old_tmp = ENV["TMP"]
<add> old_path = ENV["HOMEBREW_PATH"]
<add>
<ide> ENV["TMPDIR"] = ENV["TEMP"] = ENV["TMP"] = HOMEBREW_TEMP
<add> ENV["HOMEBREW_PATH"] = nil
<add>
<add> ENV.clear_sensitive_environment!
<add>
<ide> with_logging("post_install") do
<ide> post_install
<ide> end
<ide> def run_post_install
<ide> ENV["TMPDIR"] = old_tmpdir
<ide> ENV["TEMP"] = old_temp
<ide> ENV["TMP"] = old_tmp
<add> ENV["HOMEBREW_PATH"] = old_path
<ide> @prefix_returns_versioned_prefix = false
<ide> end
<ide>
<ide> def run_test
<ide> old_temp = ENV["TEMP"]
<ide> old_tmp = ENV["TMP"]
<ide> old_term = ENV["TERM"]
<add> old_path = ENV["HOMEBREW_PATH"]
<add>
<ide> ENV["CURL_HOME"] = old_curl_home || old_home
<ide> ENV["TMPDIR"] = ENV["TEMP"] = ENV["TMP"] = HOMEBREW_TEMP
<ide> ENV["TERM"] = "dumb"
<add> ENV["HOMEBREW_PATH"] = nil
<add>
<add> ENV.clear_sensitive_environment!
<add>
<ide> mktemp("#{name}-test") do |staging|
<ide> staging.retain! if ARGV.keep_tmp?
<ide> @testpath = staging.tmpdir
<ide> def run_test
<ide> ENV["TEMP"] = old_temp
<ide> ENV["TMP"] = old_tmp
<ide> ENV["TERM"] = old_term
<add> ENV["HOMEBREW_PATH"] = old_path
<ide> @prefix_returns_versioned_prefix = false
<ide> end
<ide>
<ide> def stage
<ide> mkdir_p env_home
<ide>
<ide> old_home = ENV["HOME"]
<del> ENV["HOME"] = env_home
<ide> old_curl_home = ENV["CURL_HOME"]
<add> old_path = ENV["HOMEBREW_PATH"]
<add>
<add> ENV["HOME"] = env_home
<ide> ENV["CURL_HOME"] = old_curl_home || old_home
<add> ENV["HOMEBREW_PATH"] = nil
<add>
<ide> setup_home env_home
<ide>
<add> ENV.clear_sensitive_environment!
<add>
<ide> begin
<ide> yield staging
<ide> ensure
<ide> @buildpath = nil
<ide> ENV["HOME"] = old_home
<ide> ENV["CURL_HOME"] = old_curl_home
<add> ENV["HOMEBREW_PATH"] = old_path
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/global.rb
<ide> def raise_deprecation_exceptions?
<ide>
<ide> require "compat" unless ARGV.include?("--no-compat") || ENV["HOMEBREW_NO_COMPAT"]
<ide>
<del>ORIGINAL_PATHS = ENV["PATH"].split(File::PATH_SEPARATOR).map do |p|
<add>ORIGINAL_PATHS = ENV["HOMEBREW_PATH"].split(File::PATH_SEPARATOR).map do |p|
<ide> begin
<ide> Pathname.new(p).expand_path
<ide> rescue
<ide><path>Library/Homebrew/test/diagnostic_spec.rb
<ide> specify "#check_user_path_3" do
<ide> begin
<ide> sbin = HOMEBREW_PREFIX/"sbin"
<del> ENV["PATH"] = "#{HOMEBREW_PREFIX}/bin#{File::PATH_SEPARATOR}" +
<del> ENV["PATH"].gsub(/(?:^|#{Regexp.escape(File::PATH_SEPARATOR)})#{Regexp.escape(sbin)}/, "")
<add> ENV["HOMEBREW_PATH"] =
<add> "#{HOMEBREW_PREFIX}/bin#{File::PATH_SEPARATOR}" +
<add> ENV["HOMEBREW_PATH"].gsub(/(?:^|#{Regexp.escape(File::PATH_SEPARATOR)})#{Regexp.escape(sbin)}/, "")
<ide> (sbin/"something").mkpath
<ide>
<ide> expect(subject.check_user_path_1).to be nil
<ide> file = "#{path}/foo-config"
<ide> FileUtils.touch file
<ide> FileUtils.chmod 0755, file
<del> ENV["PATH"] = "#{path}#{File::PATH_SEPARATOR}#{ENV["PATH"]}"
<add> ENV["HOMEBREW_PATH"] =
<add> ENV["PATH"] =
<add> "#{path}#{File::PATH_SEPARATOR}#{ENV["PATH"]}"
<ide>
<ide> expect(subject.check_for_config_scripts)
<ide> .to match('"config" scripts exist')
<ide><path>Library/Homebrew/test/support/helper/spec/shared_context/integration_test.rb
<ide> def brew(*args)
<ide>
<ide> env.merge!(
<ide> "PATH" => path,
<add> "HOMEBREW_PATH" => path,
<ide> "HOMEBREW_BREW_FILE" => HOMEBREW_PREFIX/"bin/brew",
<ide> "HOMEBREW_INTEGRATION_TEST" => command_id_from_args(args),
<ide> "HOMEBREW_TEST_TMPDIR" => TEST_TMPDIR,
<ide><path>Library/Homebrew/utils.rb
<ide> def nostdout
<ide> end
<ide> end
<ide>
<del>def paths
<del> @paths ||= ENV["PATH"].split(File::PATH_SEPARATOR).collect do |p|
<add>def paths(env_path = ENV["PATH"])
<add> @paths ||= env_path.split(File::PATH_SEPARATOR).collect do |p|
<ide> begin
<ide> File.expand_path(p).chomp("/")
<ide> rescue ArgumentError
| 9
|
Python
|
Python
|
remove outdated comment about apache-beam
|
278aa5dc875a74e2a50dd067b8de48975a6e5df6
|
<ide><path>research/object_detection/packages/tf2/setup.py
<ide> from setuptools import find_packages
<ide> from setuptools import setup
<ide>
<del># Note: adding apache-beam to required packages causes conflict with
<del># tf-models-offical requirements. These packages request for incompatible
<del># oauth2client package.
<ide> REQUIRED_PACKAGES = [
<ide> # Required for apache-beam with PY3
<ide> 'avro-python3',
| 1
|
Text
|
Text
|
clarify the wording
|
24ab45f2acb8434119998e77464237041571d758
|
<ide><path>docs/basics/Actions.md
<ide> function addTodo(text) {
<ide>
<ide> This makes them portable and easy to test.
<ide>
<del>In Flux [traditional Flux](http://facebook.github.io/flux) action creators often trigger a dispatch when invoked, like so:
<add>In [traditional Flux](http://facebook.github.io/flux) action creators often trigger a dispatch when invoked, like so:
<ide>
<ide> ```js
<ide> function addTodoWithDispatch(text) {
<ide> function addTodoWithDispatch(text) {
<ide> }
<ide> ```
<ide>
<del>In Redux to actually initiate a dispatch, pass the result to the `dispatch()` function:
<add>In Redux this is *not* the case.
<add>Instead, to actually initiate a dispatch, pass the result to the `dispatch()` function:
<ide>
<ide> ```js
<ide> dispatch(addTodo(text))
| 1
|
Text
|
Text
|
add some helper text for magical add
|
8d94a85d62d6945be1217446738d856b3c2e2ddc
|
<ide><path>docs/reference/builder.md
<ide> guide](../articles/dockerfile_best-practices.md#build-cache) for more informatio
<ide> 2. The contents of the source tree, with conflicts resolved in favor
<ide> of "2." on a file-by-file basis.
<ide>
<add> > **Note**:
<add> > Whether a file is identified as a recognized compression format or not
<add> > is done soley based on the contents of the file, not the name of the file.
<add> > For example, if an empty file happens to end with `.tar.gz` this will not
<add> > be recognized as a compressed file and **will not** generate any kind of
<add> > decompression error message, rather the file will simply be copied to the
<add> > destination.
<add>
<ide> - If `<src>` is any other kind of file, it is copied individually along with
<ide> its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it
<ide> will be considered a directory and the contents of `<src>` will be written
| 1
|
Python
|
Python
|
add missing `from_config` method
|
fb4b95804df0ae20edccd14df875650aa223cb55
|
<ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/layers/paste_masks.py
<ide> def __init__(self, align_corners: bool = False, **kwargs):
<ide> align_corners: A `bool` bool, if True, the centers of the 4 corner
<ide> pixels of the input and output tensors are aligned, preserving the
<ide> values at the corner pixels.
<del> """
<add> """
<ide> super(BilinearGridSampler, self).__init__(**kwargs)
<ide> self.align_corners = align_corners
<ide>
<ide> def call(self, inputs):
<ide> def get_config(self):
<ide> return self._config_dict
<ide>
<add> @classmethod
<add> def from_config(cls, config):
<add> return cls(**config)
<ide>
<ide>
<ide> class PasteMasks(tf.keras.layers.Layer):
<ide> """Layer to paste instance masks."""
<ide>
<del> def __init__(self, output_size: List[int],
<del> grid_sampler, **kwargs):
<add> def __init__(self, output_size: List[int],
<add> grid_sampler, **kwargs):
<ide> """Generates panoptic segmentation masks.
<ide>
<ide> Args:
<ide> def call(self, inputs):
<ide>
<ide> def get_config(self):
<ide> return self._config_dict
<add>
<add> @classmethod
<add> def from_config(cls, config):
<add> return cls(**config)
| 1
|
PHP
|
PHP
|
change visibility of obfuscate method
|
a45157c26e26cdd191be9640f1e3f8fc44b78273
|
<ide><path>src/Illuminate/Html/HtmlBuilder.php
<ide> protected function attributeElement($key, $value)
<ide> * @param string $value
<ide> * @return string
<ide> */
<del> protected function obfuscate($value)
<add> public function obfuscate($value)
<ide> {
<ide> $safe = '';
<ide>
| 1
|
Mixed
|
Go
|
remove execdriver package
|
6eebe85290327ee9934ea996b6ef82c579789d97
|
<ide><path>daemon/README.md
<del>This directory contains code pertaining to running containers and storing images
<del>
<del>Code pertaining to running containers:
<del>
<del> - execdriver
<del>
<del>Code pertaining to storing images:
<del>
<del> - graphdriver
<ide><path>daemon/execdriver/driver.go
<del>package execdriver
<del>
<del>import (
<del> "errors"
<del> "io"
<del> "os/exec"
<del> "time"
<del>
<del> "github.com/opencontainers/runc/libcontainer"
<del>)
<del>
<del>// Context is a generic key value pair that allows
<del>// arbitrary data to be sent
<del>type Context map[string]string
<del>
<del>// Define error messages
<del>var (
<del> ErrNotRunning = errors.New("Container is not running")
<del> ErrWaitTimeoutReached = errors.New("Wait timeout reached")
<del> ErrDriverAlreadyRegistered = errors.New("A driver already registered this docker init function")
<del> ErrDriverNotFound = errors.New("The requested docker init has not been found")
<del>)
<del>
<del>// DriverCallback defines a callback function which is used in "Run" and "Exec".
<del>// This allows work to be done in the parent process when the child is passing
<del>// through PreStart, Start and PostStop events.
<del>// Callbacks are provided a processConfig pointer and the pid of the child.
<del>// The channel will be used to notify the OOM events.
<del>type DriverCallback func(processConfig *ProcessConfig, pid int, chOOM <-chan struct{}) error
<del>
<del>// Hooks is a struct containing function pointers to callbacks
<del>// used by any execdriver implementation exploiting hooks capabilities
<del>type Hooks struct {
<del> // PreStart is called before container's CMD/ENTRYPOINT is executed
<del> PreStart []DriverCallback
<del> // Start is called after the container's process is full started
<del> Start DriverCallback
<del> // PostStop is called after the container process exits
<del> PostStop []DriverCallback
<del>}
<del>
<del>// Terminal represents a pseudo TTY, it is for when
<del>// using a container interactively.
<del>type Terminal interface {
<del> io.Closer
<del> Resize(height, width int) error
<del>}
<del>
<del>// Driver is an interface for drivers to implement
<del>// including all basic functions a driver should have
<del>type Driver interface {
<del> // Run executes the process, blocks until the process exits and returns
<del> // the exit code. It's the last stage on Docker side for running a container.
<del> Run(c *Command, pipes *Pipes, hooks Hooks) (ExitStatus, error)
<del>
<del> // Exec executes the process in an existing container, blocks until the
<del> // process exits and returns the exit code.
<del> Exec(c *Command, processConfig *ProcessConfig, pipes *Pipes, hooks Hooks) (int, error)
<del>
<del> // Kill sends signals to process in container.
<del> Kill(c *Command, sig int) error
<del>
<del> // Pause pauses a container.
<del> Pause(c *Command) error
<del>
<del> // Unpause unpauses a container.
<del> Unpause(c *Command) error
<del>
<del> // Name returns the name of the driver.
<del> Name() string
<del>
<del> // GetPidsForContainer returns a list of pid for the processes running in a container.
<del> GetPidsForContainer(id string) ([]int, error)
<del>
<del> // Terminate kills a container by sending signal SIGKILL.
<del> Terminate(c *Command) error
<del>
<del> // Clean removes all traces of container exec.
<del> Clean(id string) error
<del>
<del> // Stats returns resource stats for a running container
<del> Stats(id string) (*ResourceStats, error)
<del>
<del> // Update updates resource configs for a container
<del> Update(c *Command) error
<del>
<del> // SupportsHooks refers to the driver capability to exploit pre/post hook functionality
<del> SupportsHooks() bool
<del>}
<del>
<del>// CommonResources contains the resource configs for a driver that are
<del>// common across platforms.
<del>type CommonResources struct {
<del> Memory int64 `json:"memory"`
<del> MemoryReservation int64 `json:"memory_reservation"`
<del> CPUShares int64 `json:"cpu_shares"`
<del> BlkioWeight uint16 `json:"blkio_weight"`
<del>}
<del>
<del>// ResourceStats contains information about resource usage by a container.
<del>type ResourceStats struct {
<del> *libcontainer.Stats
<del> Read time.Time `json:"read"`
<del> MemoryLimit int64 `json:"memory_limit"`
<del> SystemUsage uint64 `json:"system_usage"`
<del>}
<del>
<del>// CommonProcessConfig is the common platform agnostic part of the ProcessConfig
<del>// structure that describes a process that will be run inside a container.
<del>type CommonProcessConfig struct {
<del> exec.Cmd `json:"-"`
<del>
<del> Tty bool `json:"tty"`
<del> Entrypoint string `json:"entrypoint"`
<del> Arguments []string `json:"arguments"`
<del> Terminal Terminal `json:"-"` // standard or tty terminal
<del>}
<del>
<del>// CommonCommand is the common platform agnostic part of the Command structure
<del>// which wraps an os/exec.Cmd to add more metadata
<del>type CommonCommand struct {
<del> ContainerPid int `json:"container_pid"` // the pid for the process inside a container
<del> ID string `json:"id"`
<del> MountLabel string `json:"mount_label"` // TODO Windows. More involved, but can be factored out
<del> Mounts []Mount `json:"mounts"`
<del> Network *Network `json:"network"`
<del> ProcessConfig ProcessConfig `json:"process_config"` // Describes the init process of the container.
<del> ProcessLabel string `json:"process_label"` // TODO Windows. More involved, but can be factored out
<del> Resources *Resources `json:"resources"`
<del> Rootfs string `json:"rootfs"` // root fs of the container
<del> WorkingDir string `json:"working_dir"`
<del> TmpDir string `json:"tmpdir"` // Directory used to store docker tmpdirs.
<del>}
<ide><path>daemon/execdriver/driver_unix.go
<del>// +build !windows
<del>
<del>package execdriver
<del>
<del>import (
<del> "encoding/json"
<del> "io/ioutil"
<del> "os"
<del> "path/filepath"
<del> "strconv"
<del> "strings"
<del> "time"
<del>
<del> "github.com/docker/docker/daemon/execdriver/native/template"
<del> "github.com/docker/docker/pkg/idtools"
<del> "github.com/docker/docker/pkg/mount"
<del> "github.com/docker/go-units"
<del> "github.com/opencontainers/runc/libcontainer"
<del> "github.com/opencontainers/runc/libcontainer/cgroups/fs"
<del> "github.com/opencontainers/runc/libcontainer/configs"
<del> blkiodev "github.com/opencontainers/runc/libcontainer/configs"
<del>)
<del>
<del>// Mount contains information for a mount operation.
<del>type Mount struct {
<del> Source string `json:"source"`
<del> Destination string `json:"destination"`
<del> Writable bool `json:"writable"`
<del> Data string `json:"data"`
<del> Propagation string `json:"mountpropagation"`
<del>}
<del>
<del>// Resources contains all resource configs for a driver.
<del>// Currently these are all for cgroup configs.
<del>type Resources struct {
<del> CommonResources
<del>
<del> // Fields below here are platform specific
<del>
<del> BlkioWeightDevice []*blkiodev.WeightDevice `json:"blkio_weight_device"`
<del> BlkioThrottleReadBpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_read_bps_device"`
<del> BlkioThrottleWriteBpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_write_bps_device"`
<del> BlkioThrottleReadIOpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_read_iops_device"`
<del> BlkioThrottleWriteIOpsDevice []*blkiodev.ThrottleDevice `json:"blkio_throttle_write_iops_device"`
<del> MemorySwap int64 `json:"memory_swap"`
<del> KernelMemory int64 `json:"kernel_memory"`
<del> CPUQuota int64 `json:"cpu_quota"`
<del> CpusetCpus string `json:"cpuset_cpus"`
<del> CpusetMems string `json:"cpuset_mems"`
<del> CPUPeriod int64 `json:"cpu_period"`
<del> Rlimits []*units.Rlimit `json:"rlimits"`
<del> OomKillDisable bool `json:"oom_kill_disable"`
<del> PidsLimit int64 `json:"pids_limit"`
<del> MemorySwappiness int64 `json:"memory_swappiness"`
<del>}
<del>
<del>// ProcessConfig is the platform specific structure that describes a process
<del>// that will be run inside a container.
<del>type ProcessConfig struct {
<del> CommonProcessConfig
<del>
<del> // Fields below here are platform specific
<del> Privileged bool `json:"privileged"`
<del> User string `json:"user"`
<del> Console string `json:"-"` // dev/console path
<del>}
<del>
<del>// Ipc settings of the container
<del>// It is for IPC namespace setting. Usually different containers
<del>// have their own IPC namespace, however this specifies to use
<del>// an existing IPC namespace.
<del>// You can join the host's or a container's IPC namespace.
<del>type Ipc struct {
<del> ContainerID string `json:"container_id"` // id of the container to join ipc.
<del> HostIpc bool `json:"host_ipc"`
<del>}
<del>
<del>// Pid settings of the container
<del>// It is for PID namespace setting. Usually different containers
<del>// have their own PID namespace, however this specifies to use
<del>// an existing PID namespace.
<del>// Joining the host's PID namespace is currently the only supported
<del>// option.
<del>type Pid struct {
<del> HostPid bool `json:"host_pid"`
<del>}
<del>
<del>// UTS settings of the container
<del>// It is for UTS namespace setting. Usually different containers
<del>// have their own UTS namespace, however this specifies to use
<del>// an existing UTS namespace.
<del>// Joining the host's UTS namespace is currently the only supported
<del>// option.
<del>type UTS struct {
<del> HostUTS bool `json:"host_uts"`
<del>}
<del>
<del>// Network settings of the container
<del>type Network struct {
<del> Mtu int `json:"mtu"`
<del> ContainerID string `json:"container_id"` // id of the container to join network.
<del> NamespacePath string `json:"namespace_path"`
<del> HostNetworking bool `json:"host_networking"`
<del>}
<del>
<del>// Command wraps an os/exec.Cmd to add more metadata
<del>type Command struct {
<del> CommonCommand
<del>
<del> // Fields below here are platform specific
<del>
<del> AllowedDevices []*configs.Device `json:"allowed_devices"`
<del> AppArmorProfile string `json:"apparmor_profile"`
<del> AutoCreatedDevices []*configs.Device `json:"autocreated_devices"`
<del> CapAdd []string `json:"cap_add"`
<del> CapDrop []string `json:"cap_drop"`
<del> CgroupParent string `json:"cgroup_parent"` // The parent cgroup for this command.
<del> GIDMapping []idtools.IDMap `json:"gidmapping"`
<del> GroupAdd []string `json:"group_add"`
<del> Ipc *Ipc `json:"ipc"`
<del> OomScoreAdj int `json:"oom_score_adj"`
<del> Pid *Pid `json:"pid"`
<del> ReadonlyRootfs bool `json:"readonly_rootfs"`
<del> RemappedRoot *User `json:"remap_root"`
<del> SeccompProfile string `json:"seccomp_profile"`
<del> UIDMapping []idtools.IDMap `json:"uidmapping"`
<del> UTS *UTS `json:"uts"`
<del> NoNewPrivileges bool `json:"no_new_privileges"`
<del>}
<del>
<del>// SetRootPropagation sets the root mount propagation mode.
<del>func SetRootPropagation(config *configs.Config, propagation int) {
<del> config.RootPropagation = propagation
<del>}
<del>
<del>// InitContainer is the initialization of a container config.
<del>// It returns the initial configs for a container. It's mostly
<del>// defined by the default template.
<del>func InitContainer(c *Command) *configs.Config {
<del> container := template.New()
<del>
<del> container.Hostname = getEnv("HOSTNAME", c.ProcessConfig.Env)
<del> container.Cgroups.Name = c.ID
<del> container.Cgroups.Resources.AllowedDevices = c.AllowedDevices
<del> container.Devices = filterDevices(c.AutoCreatedDevices, (c.RemappedRoot.UID != 0))
<del> container.Rootfs = c.Rootfs
<del> container.Readonlyfs = c.ReadonlyRootfs
<del> // This can be overridden later by driver during mount setup based
<del> // on volume options
<del> SetRootPropagation(container, mount.RPRIVATE)
<del> container.Cgroups.Parent = c.CgroupParent
<del>
<del> // check to see if we are running in ramdisk to disable pivot root
<del> container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != ""
<del>
<del> return container
<del>}
<del>
<del>func filterDevices(devices []*configs.Device, userNamespacesEnabled bool) []*configs.Device {
<del> if !userNamespacesEnabled {
<del> return devices
<del> }
<del>
<del> filtered := []*configs.Device{}
<del> // if we have user namespaces enabled, these devices will not be created
<del> // because of the mknod limitation in the kernel for an unprivileged process.
<del> // Rather, they will be bind-mounted, which will only work if they exist;
<del> // check for existence and remove non-existent entries from the list
<del> for _, device := range devices {
<del> if _, err := os.Stat(device.Path); err == nil {
<del> filtered = append(filtered, device)
<del> }
<del> }
<del> return filtered
<del>}
<del>
<del>func getEnv(key string, env []string) string {
<del> for _, pair := range env {
<del> parts := strings.SplitN(pair, "=", 2)
<del> if parts[0] == key {
<del> return parts[1]
<del> }
<del> }
<del> return ""
<del>}
<del>
<del>// SetupCgroups setups cgroup resources for a container.
<del>func SetupCgroups(container *configs.Config, c *Command) error {
<del> if c.Resources != nil {
<del> container.Cgroups.Resources.CpuShares = c.Resources.CPUShares
<del> container.Cgroups.Resources.Memory = c.Resources.Memory
<del> container.Cgroups.Resources.MemoryReservation = c.Resources.MemoryReservation
<del> container.Cgroups.Resources.MemorySwap = c.Resources.MemorySwap
<del> container.Cgroups.Resources.KernelMemory = c.Resources.KernelMemory
<del> container.Cgroups.Resources.CpusetCpus = c.Resources.CpusetCpus
<del> container.Cgroups.Resources.CpusetMems = c.Resources.CpusetMems
<del> container.Cgroups.Resources.CpuPeriod = c.Resources.CPUPeriod
<del> container.Cgroups.Resources.CpuQuota = c.Resources.CPUQuota
<del> container.Cgroups.Resources.BlkioWeight = c.Resources.BlkioWeight
<del> container.Cgroups.Resources.BlkioWeightDevice = c.Resources.BlkioWeightDevice
<del> container.Cgroups.Resources.BlkioThrottleReadBpsDevice = c.Resources.BlkioThrottleReadBpsDevice
<del> container.Cgroups.Resources.BlkioThrottleWriteBpsDevice = c.Resources.BlkioThrottleWriteBpsDevice
<del> container.Cgroups.Resources.BlkioThrottleReadIOPSDevice = c.Resources.BlkioThrottleReadIOpsDevice
<del> container.Cgroups.Resources.BlkioThrottleWriteIOPSDevice = c.Resources.BlkioThrottleWriteIOpsDevice
<del> container.Cgroups.Resources.OomKillDisable = c.Resources.OomKillDisable
<del> container.Cgroups.Resources.PidsLimit = c.Resources.PidsLimit
<del> container.Cgroups.Resources.MemorySwappiness = c.Resources.MemorySwappiness
<del> }
<del>
<del> return nil
<del>}
<del>
<del>// Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
<del>func getNetworkInterfaceStats(interfaceName string) (*libcontainer.NetworkInterface, error) {
<del> out := &libcontainer.NetworkInterface{Name: interfaceName}
<del> // This can happen if the network runtime information is missing - possible if the
<del> // container was created by an old version of libcontainer.
<del> if interfaceName == "" {
<del> return out, nil
<del> }
<del> type netStatsPair struct {
<del> // Where to write the output.
<del> Out *uint64
<del> // The network stats file to read.
<del> File string
<del> }
<del> // Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.
<del> netStats := []netStatsPair{
<del> {Out: &out.RxBytes, File: "tx_bytes"},
<del> {Out: &out.RxPackets, File: "tx_packets"},
<del> {Out: &out.RxErrors, File: "tx_errors"},
<del> {Out: &out.RxDropped, File: "tx_dropped"},
<del>
<del> {Out: &out.TxBytes, File: "rx_bytes"},
<del> {Out: &out.TxPackets, File: "rx_packets"},
<del> {Out: &out.TxErrors, File: "rx_errors"},
<del> {Out: &out.TxDropped, File: "rx_dropped"},
<del> }
<del> for _, netStat := range netStats {
<del> data, err := readSysfsNetworkStats(interfaceName, netStat.File)
<del> if err != nil {
<del> return nil, err
<del> }
<del> *(netStat.Out) = data
<del> }
<del> return out, nil
<del>}
<del>
<del>// Reads the specified statistics available under /sys/class/net/<EthInterface>/statistics
<del>func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
<del> data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
<del> if err != nil {
<del> return 0, err
<del> }
<del> return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
<del>}
<del>
<del>// Stats collects all the resource usage information from a container.
<del>func Stats(containerDir string, containerMemoryLimit int64, machineMemory int64) (*ResourceStats, error) {
<del> f, err := os.Open(filepath.Join(containerDir, "state.json"))
<del> if err != nil {
<del> return nil, err
<del> }
<del> defer f.Close()
<del>
<del> type network struct {
<del> Type string
<del> HostInterfaceName string
<del> }
<del>
<del> state := struct {
<del> CgroupPaths map[string]string `json:"cgroup_paths"`
<del> Networks []network
<del> }{}
<del>
<del> if err := json.NewDecoder(f).Decode(&state); err != nil {
<del> return nil, err
<del> }
<del> now := time.Now()
<del>
<del> mgr := fs.Manager{Paths: state.CgroupPaths}
<del> cstats, err := mgr.GetStats()
<del> if err != nil {
<del> return nil, err
<del> }
<del> stats := &libcontainer.Stats{CgroupStats: cstats}
<del> // if the container does not have any memory limit specified set the
<del> // limit to the machines memory
<del> memoryLimit := containerMemoryLimit
<del> if memoryLimit == 0 {
<del> memoryLimit = machineMemory
<del> }
<del> for _, iface := range state.Networks {
<del> switch iface.Type {
<del> case "veth":
<del> istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
<del> if err != nil {
<del> return nil, err
<del> }
<del> stats.Interfaces = append(stats.Interfaces, istats)
<del> }
<del> }
<del> return &ResourceStats{
<del> Stats: stats,
<del> Read: now,
<del> MemoryLimit: memoryLimit,
<del> }, nil
<del>}
<del>
<del>// User contains the uid and gid representing a Unix user
<del>type User struct {
<del> UID int `json:"root_uid"`
<del> GID int `json:"root_gid"`
<del>}
<del>
<del>// ExitStatus provides exit reasons for a container.
<del>type ExitStatus struct {
<del> // The exit code with which the container exited.
<del> ExitCode int
<del>
<del> // Whether the container encountered an OOM.
<del> OOMKilled bool
<del>}
<ide><path>daemon/execdriver/driver_windows.go
<del>package execdriver
<del>
<del>import "github.com/docker/go-connections/nat"
<del>
<del>// Mount contains information for a mount operation.
<del>type Mount struct {
<del> Source string `json:"source"`
<del> Destination string `json:"destination"`
<del> Writable bool `json:"writable"`
<del>}
<del>
<del>// Resources contains all resource configs for a driver.
<del>// Currently these are all for cgroup configs.
<del>type Resources struct {
<del> CommonResources
<del>
<del> // Fields below here are platform specific
<del>}
<del>
<del>// ProcessConfig is the platform specific structure that describes a process
<del>// that will be run inside a container.
<del>type ProcessConfig struct {
<del> CommonProcessConfig
<del>
<del> // Fields below here are platform specific
<del> ConsoleSize [2]int `json:"-"` // h,w of initial console size
<del>}
<del>
<del>// Network settings of the container
<del>type Network struct {
<del> Interface *NetworkInterface `json:"interface"`
<del> ContainerID string `json:"container_id"` // id of the container to join network.
<del>}
<del>
<del>// NetworkInterface contains network configs for a driver
<del>type NetworkInterface struct {
<del> MacAddress string `json:"mac"`
<del> Bridge string `json:"bridge"`
<del> IPAddress string `json:"ip"`
<del>
<del> // PortBindings is the port mapping between the exposed port in the
<del> // container and the port on the host.
<del> PortBindings nat.PortMap `json:"port_bindings"`
<del>}
<del>
<del>// Command wraps an os/exec.Cmd to add more metadata
<del>type Command struct {
<del> CommonCommand
<del>
<del> // Fields below here are platform specific
<del>
<del> FirstStart bool `json:"first_start"` // Optimization for first boot of Windows
<del> Hostname string `json:"hostname"` // Windows sets the hostname in the execdriver
<del> LayerFolder string `json:"layer_folder"` // Layer folder for a command
<del> LayerPaths []string `json:"layer_paths"` // Layer paths for a command
<del> Isolation string `json:"isolation"` // Isolation technology for the container
<del> ArgsEscaped bool `json:"args_escaped"` // True if args are already escaped
<del> HvPartition bool `json:"hv_partition"` // True if it's an hypervisor partition
<del> EpList []string `json:"endpoints"` // List of network endpoints for HNS
<del>}
<del>
<del>// ExitStatus provides exit reasons for a container.
<del>type ExitStatus struct {
<del> // The exit code with which the container exited.
<del> ExitCode int
<del>}
<ide><path>daemon/execdriver/execdrivers/execdrivers_freebsd.go
<del>// +build freebsd
<del>
<del>package execdrivers
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/pkg/sysinfo"
<del>)
<del>
<del>// NewDriver returns a new execdriver.Driver from the given name configured with the provided options.
<del>func NewDriver(options []string, root, libPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) {
<del> return nil, fmt.Errorf("jail driver not yet supported on FreeBSD")
<del>}
<ide><path>daemon/execdriver/execdrivers/execdrivers_linux.go
<del>// +build linux
<del>
<del>package execdrivers
<del>
<del>import (
<del> "path"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/daemon/execdriver/native"
<del> "github.com/docker/docker/pkg/sysinfo"
<del>)
<del>
<del>// NewDriver returns a new execdriver.Driver from the given name configured with the provided options.
<del>func NewDriver(options []string, root, libPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) {
<del> return native.NewDriver(path.Join(root, "execdriver", "native"), options)
<del>}
<ide><path>daemon/execdriver/execdrivers/execdrivers_windows.go
<del>// +build windows
<del>
<del>package execdrivers
<del>
<del>import (
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/daemon/execdriver/windows"
<del> "github.com/docker/docker/pkg/sysinfo"
<del>)
<del>
<del>// NewDriver returns a new execdriver.Driver from the given name configured with the provided options.
<del>func NewDriver(options []string, root, libPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) {
<del> return windows.NewDriver(root, options)
<del>}
<ide><path>daemon/execdriver/native/create.go
<del>// +build linux,cgo
<del>
<del>package native
<del>
<del>import (
<del> "fmt"
<del> "path/filepath"
<del> "strings"
<del> "syscall"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/pkg/mount"
<del> "github.com/docker/docker/profiles/seccomp"
<del>
<del> "github.com/docker/docker/volume"
<del> "github.com/opencontainers/runc/libcontainer/apparmor"
<del> "github.com/opencontainers/runc/libcontainer/configs"
<del> "github.com/opencontainers/runc/libcontainer/devices"
<del>)
<del>
<del>// createContainer populates and configures the container type with the
<del>// data provided by the execdriver.Command
<del>func (d *Driver) createContainer(c *execdriver.Command, hooks execdriver.Hooks) (container *configs.Config, err error) {
<del> container = execdriver.InitContainer(c)
<del>
<del> if err := d.createIpc(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> if err := d.createPid(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> if err := d.createUTS(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> if err := d.setupRemappedRoot(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> if err := d.createNetwork(container, c, hooks); err != nil {
<del> return nil, err
<del> }
<del>
<del> if c.ProcessConfig.Privileged {
<del> if !container.Readonlyfs {
<del> // clear readonly for /sys
<del> for i := range container.Mounts {
<del> if container.Mounts[i].Destination == "/sys" {
<del> container.Mounts[i].Flags &= ^syscall.MS_RDONLY
<del> }
<del> }
<del> container.ReadonlyPaths = nil
<del> }
<del>
<del> // clear readonly for cgroup
<del> for i := range container.Mounts {
<del> if container.Mounts[i].Device == "cgroup" {
<del> container.Mounts[i].Flags &= ^syscall.MS_RDONLY
<del> }
<del> }
<del>
<del> container.MaskPaths = nil
<del> if err := d.setPrivileged(container); err != nil {
<del> return nil, err
<del> }
<del> } else {
<del> if err := d.setCapabilities(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> if c.SeccompProfile == "" {
<del> container.Seccomp, err = seccomp.GetDefaultProfile()
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<del> }
<del> // add CAP_ prefix to all caps for new libcontainer update to match
<del> // the spec format.
<del> for i, s := range container.Capabilities {
<del> if !strings.HasPrefix(s, "CAP_") {
<del> container.Capabilities[i] = fmt.Sprintf("CAP_%s", s)
<del> }
<del> }
<del> container.AdditionalGroups = c.GroupAdd
<del>
<del> if c.AppArmorProfile != "" {
<del> container.AppArmorProfile = c.AppArmorProfile
<del> }
<del>
<del> if c.SeccompProfile != "" && c.SeccompProfile != "unconfined" {
<del> container.Seccomp, err = seccomp.LoadProfile(c.SeccompProfile)
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<del>
<del> if err := execdriver.SetupCgroups(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> container.OomScoreAdj = c.OomScoreAdj
<del>
<del> if container.Readonlyfs {
<del> for i := range container.Mounts {
<del> switch container.Mounts[i].Destination {
<del> case "/proc", "/dev", "/dev/pts", "/dev/mqueue":
<del> continue
<del> }
<del> container.Mounts[i].Flags |= syscall.MS_RDONLY
<del> }
<del>
<del> /* These paths must be remounted as r/o */
<del> container.ReadonlyPaths = append(container.ReadonlyPaths, "/dev")
<del> }
<del>
<del> if err := d.setupMounts(container, c); err != nil {
<del> return nil, err
<del> }
<del>
<del> d.setupLabels(container, c)
<del> d.setupRlimits(container, c)
<del>
<del> container.NoNewPrivileges = c.NoNewPrivileges
<del> return container, nil
<del>}
<del>
<del>func (d *Driver) createNetwork(container *configs.Config, c *execdriver.Command, hooks execdriver.Hooks) error {
<del> if c.Network == nil {
<del> return nil
<del> }
<del> if c.Network.ContainerID != "" {
<del> d.Lock()
<del> active := d.activeContainers[c.Network.ContainerID]
<del> d.Unlock()
<del>
<del> if active == nil {
<del> return fmt.Errorf("%s is not a valid running container to join", c.Network.ContainerID)
<del> }
<del>
<del> state, err := active.State()
<del> if err != nil {
<del> return err
<del> }
<del>
<del> container.Namespaces.Add(configs.NEWNET, state.NamespacePaths[configs.NEWNET])
<del> return nil
<del> }
<del>
<del> if c.Network.NamespacePath != "" {
<del> container.Namespaces.Add(configs.NEWNET, c.Network.NamespacePath)
<del> return nil
<del> }
<del> // only set up prestart hook if the namespace path is not set (this should be
<del> // all cases *except* for --net=host shared networking)
<del> container.Hooks = &configs.Hooks{
<del> Prestart: []configs.Hook{
<del> configs.NewFunctionHook(func(s configs.HookState) error {
<del> if len(hooks.PreStart) > 0 {
<del> for _, fnHook := range hooks.PreStart {
<del> // A closed channel for OOM is returned here as it will be
<del> // non-blocking and return the correct result when read.
<del> chOOM := make(chan struct{})
<del> close(chOOM)
<del> if err := fnHook(&c.ProcessConfig, s.Pid, chOOM); err != nil {
<del> return err
<del> }
<del> }
<del> }
<del> return nil
<del> }),
<del> },
<del> }
<del> return nil
<del>}
<del>
<del>func (d *Driver) createIpc(container *configs.Config, c *execdriver.Command) error {
<del> if c.Ipc.HostIpc {
<del> container.Namespaces.Remove(configs.NEWIPC)
<del> return nil
<del> }
<del>
<del> if c.Ipc.ContainerID != "" {
<del> d.Lock()
<del> active := d.activeContainers[c.Ipc.ContainerID]
<del> d.Unlock()
<del>
<del> if active == nil {
<del> return fmt.Errorf("%s is not a valid running container to join", c.Ipc.ContainerID)
<del> }
<del>
<del> state, err := active.State()
<del> if err != nil {
<del> return err
<del> }
<del> container.Namespaces.Add(configs.NEWIPC, state.NamespacePaths[configs.NEWIPC])
<del> }
<del>
<del> return nil
<del>}
<del>
<del>func (d *Driver) createPid(container *configs.Config, c *execdriver.Command) error {
<del> if c.Pid.HostPid {
<del> container.Namespaces.Remove(configs.NEWPID)
<del> return nil
<del> }
<del>
<del> return nil
<del>}
<del>
<del>func (d *Driver) createUTS(container *configs.Config, c *execdriver.Command) error {
<del> if c.UTS.HostUTS {
<del> container.Namespaces.Remove(configs.NEWUTS)
<del> container.Hostname = ""
<del> return nil
<del> }
<del>
<del> return nil
<del>}
<del>
<del>func (d *Driver) setupRemappedRoot(container *configs.Config, c *execdriver.Command) error {
<del> if c.RemappedRoot.UID == 0 {
<del> container.Namespaces.Remove(configs.NEWUSER)
<del> return nil
<del> }
<del>
<del> // convert the Docker daemon id map to the libcontainer variant of the same struct
<del> // this keeps us from having to import libcontainer code across Docker client + daemon packages
<del> cuidMaps := []configs.IDMap{}
<del> cgidMaps := []configs.IDMap{}
<del> for _, idMap := range c.UIDMapping {
<del> cuidMaps = append(cuidMaps, configs.IDMap(idMap))
<del> }
<del> for _, idMap := range c.GIDMapping {
<del> cgidMaps = append(cgidMaps, configs.IDMap(idMap))
<del> }
<del> container.UidMappings = cuidMaps
<del> container.GidMappings = cgidMaps
<del>
<del> for _, node := range container.Devices {
<del> node.Uid = uint32(c.RemappedRoot.UID)
<del> node.Gid = uint32(c.RemappedRoot.GID)
<del> }
<del> // TODO: until a kernel/mount solution exists for handling remount in a user namespace,
<del> // we must clear the readonly flag for the cgroups mount (@mrunalp concurs)
<del> for i := range container.Mounts {
<del> if container.Mounts[i].Device == "cgroup" {
<del> container.Mounts[i].Flags &= ^syscall.MS_RDONLY
<del> }
<del> }
<del>
<del> return nil
<del>}
<del>
<del>func (d *Driver) setPrivileged(container *configs.Config) (err error) {
<del> container.Capabilities = execdriver.GetAllCapabilities()
<del> container.Cgroups.Resources.AllowAllDevices = true
<del>
<del> hostDevices, err := devices.HostDevices()
<del> if err != nil {
<del> return err
<del> }
<del> container.Devices = hostDevices
<del>
<del> if apparmor.IsEnabled() {
<del> container.AppArmorProfile = "unconfined"
<del> }
<del> return nil
<del>}
<del>
<del>func (d *Driver) setCapabilities(container *configs.Config, c *execdriver.Command) (err error) {
<del> container.Capabilities, err = execdriver.TweakCapabilities(container.Capabilities, c.CapAdd, c.CapDrop)
<del> return err
<del>}
<del>
<del>func (d *Driver) setupRlimits(container *configs.Config, c *execdriver.Command) {
<del> if c.Resources == nil {
<del> return
<del> }
<del>
<del> for _, rlimit := range c.Resources.Rlimits {
<del> container.Rlimits = append(container.Rlimits, configs.Rlimit{
<del> Type: rlimit.Type,
<del> Hard: rlimit.Hard,
<del> Soft: rlimit.Soft,
<del> })
<del> }
<del>}
<del>
<del>// If rootfs mount propagation is RPRIVATE, that means all the volumes are
<del>// going to be private anyway. There is no need to apply per volume
<del>// propagation on top. This is just an optimization so that cost of per volume
<del>// propagation is paid only if user decides to make some volume non-private
<del>// which will force rootfs mount propagation to be non RPRIVATE.
<del>func checkResetVolumePropagation(container *configs.Config) {
<del> if container.RootPropagation != mount.RPRIVATE {
<del> return
<del> }
<del> for _, m := range container.Mounts {
<del> m.PropagationFlags = nil
<del> }
<del>}
<del>
<del>func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info {
<del> for _, m := range mountinfo {
<del> if m.Mountpoint == dir {
<del> return m
<del> }
<del> }
<del> return nil
<del>}
<del>
<del>// Get the source mount point of directory passed in as argument. Also return
<del>// optional fields.
<del>func getSourceMount(source string) (string, string, error) {
<del> // Ensure any symlinks are resolved.
<del> sourcePath, err := filepath.EvalSymlinks(source)
<del> if err != nil {
<del> return "", "", err
<del> }
<del>
<del> mountinfos, err := mount.GetMounts()
<del> if err != nil {
<del> return "", "", err
<del> }
<del>
<del> mountinfo := getMountInfo(mountinfos, sourcePath)
<del> if mountinfo != nil {
<del> return sourcePath, mountinfo.Optional, nil
<del> }
<del>
<del> path := sourcePath
<del> for {
<del> path = filepath.Dir(path)
<del>
<del> mountinfo = getMountInfo(mountinfos, path)
<del> if mountinfo != nil {
<del> return path, mountinfo.Optional, nil
<del> }
<del>
<del> if path == "/" {
<del> break
<del> }
<del> }
<del>
<del> // If we are here, we did not find parent mount. Something is wrong.
<del> return "", "", fmt.Errorf("Could not find source mount of %s", source)
<del>}
<del>
<del>// Ensure mount point on which path is mounted, is shared.
<del>func ensureShared(path string) error {
<del> sharedMount := false
<del>
<del> sourceMount, optionalOpts, err := getSourceMount(path)
<del> if err != nil {
<del> return err
<del> }
<del> // Make sure source mount point is shared.
<del> optsSplit := strings.Split(optionalOpts, " ")
<del> for _, opt := range optsSplit {
<del> if strings.HasPrefix(opt, "shared:") {
<del> sharedMount = true
<del> break
<del> }
<del> }
<del>
<del> if !sharedMount {
<del> return fmt.Errorf("Path %s is mounted on %s but it is not a shared mount.", path, sourceMount)
<del> }
<del> return nil
<del>}
<del>
<del>// Ensure mount point on which path is mounted, is either shared or slave.
<del>func ensureSharedOrSlave(path string) error {
<del> sharedMount := false
<del> slaveMount := false
<del>
<del> sourceMount, optionalOpts, err := getSourceMount(path)
<del> if err != nil {
<del> return err
<del> }
<del> // Make sure source mount point is shared.
<del> optsSplit := strings.Split(optionalOpts, " ")
<del> for _, opt := range optsSplit {
<del> if strings.HasPrefix(opt, "shared:") {
<del> sharedMount = true
<del> break
<del> } else if strings.HasPrefix(opt, "master:") {
<del> slaveMount = true
<del> break
<del> }
<del> }
<del>
<del> if !sharedMount && !slaveMount {
<del> return fmt.Errorf("Path %s is mounted on %s but it is not a shared or slave mount.", path, sourceMount)
<del> }
<del> return nil
<del>}
<del>
<del>func (d *Driver) setupMounts(container *configs.Config, c *execdriver.Command) error {
<del> userMounts := make(map[string]struct{})
<del> for _, m := range c.Mounts {
<del> userMounts[m.Destination] = struct{}{}
<del> }
<del>
<del> // Filter out mounts that are overridden by user supplied mounts
<del> var defaultMounts []*configs.Mount
<del> _, mountDev := userMounts["/dev"]
<del> for _, m := range container.Mounts {
<del> if _, ok := userMounts[m.Destination]; !ok {
<del> if mountDev && strings.HasPrefix(m.Destination, "/dev/") {
<del> container.Devices = nil
<del> continue
<del> }
<del> defaultMounts = append(defaultMounts, m)
<del> }
<del> }
<del> container.Mounts = defaultMounts
<del>
<del> mountPropagationMap := map[string]int{
<del> "private": mount.PRIVATE,
<del> "rprivate": mount.RPRIVATE,
<del> "shared": mount.SHARED,
<del> "rshared": mount.RSHARED,
<del> "slave": mount.SLAVE,
<del> "rslave": mount.RSLAVE,
<del> }
<del>
<del> for _, m := range c.Mounts {
<del> for _, cm := range container.Mounts {
<del> if cm.Destination == m.Destination {
<del> return fmt.Errorf("Duplicate mount point '%s'", m.Destination)
<del> }
<del> }
<del>
<del> if m.Source == "tmpfs" {
<del> var (
<del> data = "size=65536k"
<del> flags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
<del> err error
<del> )
<del> if m.Data != "" {
<del> flags, data, err = mount.ParseTmpfsOptions(m.Data)
<del> if err != nil {
<del> return err
<del> }
<del> }
<del> container.Mounts = append(container.Mounts, &configs.Mount{
<del> Source: m.Source,
<del> Destination: m.Destination,
<del> Data: data,
<del> Device: "tmpfs",
<del> Flags: flags,
<del> PropagationFlags: []int{mountPropagationMap[volume.DefaultPropagationMode]},
<del> })
<del> continue
<del> }
<del> flags := syscall.MS_BIND | syscall.MS_REC
<del> var pFlag int
<del> if !m.Writable {
<del> flags |= syscall.MS_RDONLY
<del> }
<del>
<del> // Determine property of RootPropagation based on volume
<del> // properties. If a volume is shared, then keep root propagation
<del> // shared. This should work for slave and private volumes too.
<del> //
<del> // For slave volumes, it can be either [r]shared/[r]slave.
<del> //
<del> // For private volumes any root propagation value should work.
<del>
<del> pFlag = mountPropagationMap[m.Propagation]
<del> if pFlag == mount.SHARED || pFlag == mount.RSHARED {
<del> if err := ensureShared(m.Source); err != nil {
<del> return err
<del> }
<del> rootpg := container.RootPropagation
<del> if rootpg != mount.SHARED && rootpg != mount.RSHARED {
<del> execdriver.SetRootPropagation(container, mount.SHARED)
<del> }
<del> } else if pFlag == mount.SLAVE || pFlag == mount.RSLAVE {
<del> if err := ensureSharedOrSlave(m.Source); err != nil {
<del> return err
<del> }
<del> rootpg := container.RootPropagation
<del> if rootpg != mount.SHARED && rootpg != mount.RSHARED && rootpg != mount.SLAVE && rootpg != mount.RSLAVE {
<del> execdriver.SetRootPropagation(container, mount.RSLAVE)
<del> }
<del> }
<del>
<del> mount := &configs.Mount{
<del> Source: m.Source,
<del> Destination: m.Destination,
<del> Device: "bind",
<del> Flags: flags,
<del> }
<del>
<del> if pFlag != 0 {
<del> mount.PropagationFlags = []int{pFlag}
<del> }
<del>
<del> container.Mounts = append(container.Mounts, mount)
<del> }
<del>
<del> checkResetVolumePropagation(container)
<del> return nil
<del>}
<del>
<del>func (d *Driver) setupLabels(container *configs.Config, c *execdriver.Command) {
<del> container.ProcessLabel = c.ProcessLabel
<del> container.MountLabel = c.MountLabel
<del>}
<ide><path>daemon/execdriver/native/driver.go
<del>// +build linux,cgo
<del>
<del>package native
<del>
<del>import (
<del> "fmt"
<del> "io"
<del> "io/ioutil"
<del> "os"
<del> "os/exec"
<del> "path/filepath"
<del> "strings"
<del> "sync"
<del> "syscall"
<del> "time"
<del>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/docker/pkg/pools"
<del> "github.com/docker/docker/pkg/reexec"
<del> sysinfo "github.com/docker/docker/pkg/system"
<del> "github.com/docker/docker/pkg/term"
<del> aaprofile "github.com/docker/docker/profiles/apparmor"
<del> "github.com/opencontainers/runc/libcontainer"
<del> "github.com/opencontainers/runc/libcontainer/apparmor"
<del> "github.com/opencontainers/runc/libcontainer/cgroups/systemd"
<del> "github.com/opencontainers/runc/libcontainer/configs"
<del> "github.com/opencontainers/runc/libcontainer/system"
<del> "github.com/opencontainers/runc/libcontainer/utils"
<del>)
<del>
<del>// Define constants for native driver
<del>const (
<del> DriverName = "native"
<del> Version = "0.2"
<del>
<del> defaultApparmorProfile = "docker-default"
<del>)
<del>
<del>// Driver contains all information for native driver,
<del>// it implements execdriver.Driver.
<del>type Driver struct {
<del> root string
<del> activeContainers map[string]libcontainer.Container
<del> machineMemory int64
<del> factory libcontainer.Factory
<del> sync.Mutex
<del>}
<del>
<del>// NewDriver returns a new native driver, called from NewDriver of execdriver.
<del>func NewDriver(root string, options []string) (*Driver, error) {
<del> meminfo, err := sysinfo.ReadMemInfo()
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> if err := sysinfo.MkdirAll(root, 0700); err != nil {
<del> return nil, err
<del> }
<del>
<del> if apparmor.IsEnabled() {
<del> if err := aaprofile.InstallDefault(defaultApparmorProfile); err != nil {
<del> apparmorProfiles := []string{defaultApparmorProfile}
<del>
<del> // Allow daemon to run if loading failed, but are active
<del> // (possibly through another run, manually, or via system startup)
<del> for _, policy := range apparmorProfiles {
<del> if err := aaprofile.IsLoaded(policy); err != nil {
<del> return nil, fmt.Errorf("AppArmor enabled on system but the %s profile could not be loaded.", policy)
<del> }
<del> }
<del> }
<del> }
<del>
<del> // choose cgroup manager
<del> // this makes sure there are no breaking changes to people
<del> // who upgrade from versions without native.cgroupdriver opt
<del> cgm := libcontainer.Cgroupfs
<del>
<del> // parse the options
<del> for _, option := range options {
<del> key, val, err := parsers.ParseKeyValueOpt(option)
<del> if err != nil {
<del> return nil, err
<del> }
<del> key = strings.ToLower(key)
<del> switch key {
<del> case "native.cgroupdriver":
<del> // override the default if they set options
<del> switch val {
<del> case "systemd":
<del> if systemd.UseSystemd() {
<del> cgm = libcontainer.SystemdCgroups
<del> } else {
<del> // warn them that they chose the wrong driver
<del> logrus.Warn("You cannot use systemd as native.cgroupdriver, using cgroupfs instead")
<del> }
<del> case "cgroupfs":
<del> cgm = libcontainer.Cgroupfs
<del> default:
<del> return nil, fmt.Errorf("Unknown native.cgroupdriver given %q. try cgroupfs or systemd", val)
<del> }
<del> default:
<del> return nil, fmt.Errorf("Unknown option %s\n", key)
<del> }
<del> }
<del>
<del> f, err := libcontainer.New(
<del> root,
<del> cgm,
<del> libcontainer.InitPath(reexec.Self(), DriverName),
<del> )
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> return &Driver{
<del> root: root,
<del> activeContainers: make(map[string]libcontainer.Container),
<del> machineMemory: meminfo.MemTotal,
<del> factory: f,
<del> }, nil
<del>}
<del>
<del>// Run implements the exec driver Driver interface,
<del>// it calls libcontainer APIs to run a container.
<del>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) {
<del> destroyed := false
<del> var err error
<del> c.TmpDir, err = ioutil.TempDir("", c.ID)
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> defer os.RemoveAll(c.TmpDir)
<del>
<del> // take the Command and populate the libcontainer.Config from it
<del> container, err := d.createContainer(c, hooks)
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> p := &libcontainer.Process{
<del> Args: append([]string{c.ProcessConfig.Entrypoint}, c.ProcessConfig.Arguments...),
<del> Env: c.ProcessConfig.Env,
<del> Cwd: c.WorkingDir,
<del> User: c.ProcessConfig.User,
<del> }
<del>
<del> wg := sync.WaitGroup{}
<del> writers, err := setupPipes(container, &c.ProcessConfig, p, pipes, &wg)
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> cont, err := d.factory.Create(c.ID, container)
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> if err := cont.Start(p); err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> d.Lock()
<del> d.activeContainers[c.ID] = cont
<del> d.Unlock()
<del> defer func() {
<del> if !destroyed {
<del> cont.Destroy()
<del> }
<del> d.cleanContainer(c.ID)
<del> }()
<del>
<del> //close the write end of any opened pipes now that they are dup'ed into the container
<del> for _, writer := range writers {
<del> writer.Close()
<del> }
<del> // 'oom' is used to emit 'oom' events to the eventstream, 'oomKilled' is used
<del> // to set the 'OOMKilled' flag in state
<del> oom := notifyOnOOM(cont)
<del> oomKilled := notifyOnOOM(cont)
<del> if hooks.Start != nil {
<del> pid, err := p.Pid()
<del> if err != nil {
<del> p.Signal(os.Kill)
<del> p.Wait()
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> hooks.Start(&c.ProcessConfig, pid, oom)
<del> }
<del>
<del> waitF := p.Wait
<del> if nss := cont.Config().Namespaces; !nss.Contains(configs.NEWPID) {
<del> // we need such hack for tracking processes with inherited fds,
<del> // because cmd.Wait() waiting for all streams to be copied
<del> waitF = waitInPIDHost(p, cont)
<del> }
<del> ps, err := waitF()
<del> if err != nil {
<del> execErr, ok := err.(*exec.ExitError)
<del> if !ok {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> ps = execErr.ProcessState
<del> }
<del> // wait for all IO goroutine copiers to finish
<del> wg.Wait()
<del>
<del> cont.Destroy()
<del> destroyed = true
<del> // oomKilled will have an oom event if any process within the container was
<del> // OOM killed at any time, not only if the init process OOMed.
<del> //
<del> // Perhaps we only want the OOMKilled flag to be set if the OOM
<del> // resulted in a container death, but there isn't a good way to do this
<del> // because the kernel's cgroup oom notification does not provide information
<del> // such as the PID. This could be heuristically done by checking that the OOM
<del> // happened within some very small time slice for the container dying (and
<del> // optionally exit-code 137), but I don't think the cgroup oom notification
<del> // can be used to reliably determine this
<del> //
<del> // Even if there were multiple OOMs, it's sufficient to read one value
<del> // because libcontainer's oom notify will discard the channel after the
<del> // cgroup is destroyed
<del> _, oomKill := <-oomKilled
<del> return execdriver.ExitStatus{ExitCode: utils.ExitStatus(ps.Sys().(syscall.WaitStatus)), OOMKilled: oomKill}, nil
<del>}
<del>
<del>// notifyOnOOM returns a channel that signals if the container received an OOM notification
<del>// for any process. If it is unable to subscribe to OOM notifications then a closed
<del>// channel is returned as it will be non-blocking and return the correct result when read.
<del>func notifyOnOOM(container libcontainer.Container) <-chan struct{} {
<del> oom, err := container.NotifyOOM()
<del> if err != nil {
<del> logrus.Warnf("Your kernel does not support OOM notifications: %s", err)
<del> c := make(chan struct{})
<del> close(c)
<del> return c
<del> }
<del> return oom
<del>}
<del>
<del>func killCgroupProcs(c libcontainer.Container) {
<del> var procs []*os.Process
<del> if err := c.Pause(); err != nil {
<del> logrus.Warn(err)
<del> }
<del> pids, err := c.Processes()
<del> if err != nil {
<del> // don't care about childs if we can't get them, this is mostly because cgroup already deleted
<del> logrus.Warnf("Failed to get processes from container %s: %v", c.ID(), err)
<del> }
<del> for _, pid := range pids {
<del> if p, err := os.FindProcess(pid); err == nil {
<del> procs = append(procs, p)
<del> if err := p.Kill(); err != nil {
<del> logrus.Warn(err)
<del> }
<del> }
<del> }
<del> if err := c.Resume(); err != nil {
<del> logrus.Warn(err)
<del> }
<del> for _, p := range procs {
<del> if _, err := p.Wait(); err != nil {
<del> logrus.Warn(err)
<del> }
<del> }
<del>}
<del>
<del>func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*os.ProcessState, error) {
<del> return func() (*os.ProcessState, error) {
<del> pid, err := p.Pid()
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> process, err := os.FindProcess(pid)
<del> s, err := process.Wait()
<del> if err != nil {
<del> execErr, ok := err.(*exec.ExitError)
<del> if !ok {
<del> return s, err
<del> }
<del> s = execErr.ProcessState
<del> }
<del> killCgroupProcs(c)
<del> p.Wait()
<del> return s, err
<del> }
<del>}
<del>
<del>// Kill implements the exec driver Driver interface.
<del>func (d *Driver) Kill(c *execdriver.Command, sig int) error {
<del> d.Lock()
<del> active := d.activeContainers[c.ID]
<del> d.Unlock()
<del> if active == nil {
<del> return fmt.Errorf("active container for %s does not exist", c.ID)
<del> }
<del> state, err := active.State()
<del> if err != nil {
<del> return err
<del> }
<del> if state.InitProcessPid == -1 {
<del> return fmt.Errorf("avoid sending signal %d to container %s with pid -1", sig, c.ID)
<del> }
<del> return syscall.Kill(state.InitProcessPid, syscall.Signal(sig))
<del>}
<del>
<del>// Pause implements the exec driver Driver interface,
<del>// it calls libcontainer API to pause a container.
<del>func (d *Driver) Pause(c *execdriver.Command) error {
<del> d.Lock()
<del> active := d.activeContainers[c.ID]
<del> d.Unlock()
<del> if active == nil {
<del> return fmt.Errorf("active container for %s does not exist", c.ID)
<del> }
<del> return active.Pause()
<del>}
<del>
<del>// Unpause implements the exec driver Driver interface,
<del>// it calls libcontainer API to unpause a container.
<del>func (d *Driver) Unpause(c *execdriver.Command) error {
<del> d.Lock()
<del> active := d.activeContainers[c.ID]
<del> d.Unlock()
<del> if active == nil {
<del> return fmt.Errorf("active container for %s does not exist", c.ID)
<del> }
<del> return active.Resume()
<del>}
<del>
<del>// Terminate implements the exec driver Driver interface.
<del>func (d *Driver) Terminate(c *execdriver.Command) error {
<del> defer d.cleanContainer(c.ID)
<del> container, err := d.factory.Load(c.ID)
<del> if err != nil {
<del> return err
<del> }
<del> defer container.Destroy()
<del> state, err := container.State()
<del> if err != nil {
<del> return err
<del> }
<del> pid := state.InitProcessPid
<del> currentStartTime, err := system.GetProcessStartTime(pid)
<del> if err != nil {
<del> return err
<del> }
<del> if state.InitProcessStartTime == currentStartTime {
<del> err = syscall.Kill(pid, 9)
<del> syscall.Wait4(pid, nil, 0, nil)
<del> }
<del> return err
<del>}
<del>
<del>// Name implements the exec driver Driver interface.
<del>func (d *Driver) Name() string {
<del> return fmt.Sprintf("%s-%s", DriverName, Version)
<del>}
<del>
<del>// GetPidsForContainer implements the exec driver Driver interface.
<del>func (d *Driver) GetPidsForContainer(id string) ([]int, error) {
<del> d.Lock()
<del> active := d.activeContainers[id]
<del> d.Unlock()
<del>
<del> if active == nil {
<del> return nil, fmt.Errorf("active container for %s does not exist", id)
<del> }
<del> return active.Processes()
<del>}
<del>
<del>func (d *Driver) cleanContainer(id string) error {
<del> d.Lock()
<del> delete(d.activeContainers, id)
<del> d.Unlock()
<del> return os.RemoveAll(filepath.Join(d.root, id))
<del>}
<del>
<del>func (d *Driver) createContainerRoot(id string) error {
<del> return os.MkdirAll(filepath.Join(d.root, id), 0655)
<del>}
<del>
<del>// Clean implements the exec driver Driver interface.
<del>func (d *Driver) Clean(id string) error {
<del> return os.RemoveAll(filepath.Join(d.root, id))
<del>}
<del>
<del>// Stats implements the exec driver Driver interface.
<del>func (d *Driver) Stats(id string) (*execdriver.ResourceStats, error) {
<del> d.Lock()
<del> c := d.activeContainers[id]
<del> d.Unlock()
<del> if c == nil {
<del> return nil, execdriver.ErrNotRunning
<del> }
<del> now := time.Now()
<del> stats, err := c.Stats()
<del> if err != nil {
<del> return nil, err
<del> }
<del> memoryLimit := c.Config().Cgroups.Resources.Memory
<del> // if the container does not have any memory limit specified set the
<del> // limit to the machines memory
<del> if memoryLimit == 0 {
<del> memoryLimit = d.machineMemory
<del> }
<del> return &execdriver.ResourceStats{
<del> Stats: stats,
<del> Read: now,
<del> MemoryLimit: memoryLimit,
<del> }, nil
<del>}
<del>
<del>// Update updates configs for a container
<del>func (d *Driver) Update(c *execdriver.Command) error {
<del> d.Lock()
<del> cont := d.activeContainers[c.ID]
<del> d.Unlock()
<del> if cont == nil {
<del> return execdriver.ErrNotRunning
<del> }
<del> config := cont.Config()
<del> if err := execdriver.SetupCgroups(&config, c); err != nil {
<del> return err
<del> }
<del>
<del> if err := cont.Set(config); err != nil {
<del> return err
<del> }
<del>
<del> return nil
<del>}
<del>
<del>// TtyConsole implements the exec driver Terminal interface.
<del>type TtyConsole struct {
<del> console libcontainer.Console
<del>}
<del>
<del>// NewTtyConsole returns a new TtyConsole struct.
<del>func NewTtyConsole(console libcontainer.Console, pipes *execdriver.Pipes, wg *sync.WaitGroup) (*TtyConsole, error) {
<del> tty := &TtyConsole{
<del> console: console,
<del> }
<del>
<del> if err := tty.AttachPipes(pipes, wg); err != nil {
<del> tty.Close()
<del> return nil, err
<del> }
<del>
<del> return tty, nil
<del>}
<del>
<del>// Resize implements Resize method of Terminal interface
<del>func (t *TtyConsole) Resize(h, w int) error {
<del> return term.SetWinsize(t.console.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)})
<del>}
<del>
<del>// AttachPipes attaches given pipes to TtyConsole
<del>func (t *TtyConsole) AttachPipes(pipes *execdriver.Pipes, wg *sync.WaitGroup) error {
<del> wg.Add(1)
<del> go func() {
<del> defer wg.Done()
<del> if wb, ok := pipes.Stdout.(interface {
<del> CloseWriters() error
<del> }); ok {
<del> defer wb.CloseWriters()
<del> }
<del>
<del> pools.Copy(pipes.Stdout, t.console)
<del> }()
<del>
<del> if pipes.Stdin != nil {
<del> go func() {
<del> pools.Copy(t.console, pipes.Stdin)
<del>
<del> pipes.Stdin.Close()
<del> }()
<del> }
<del>
<del> return nil
<del>}
<del>
<del>// Close implements Close method of Terminal interface
<del>func (t *TtyConsole) Close() error {
<del> return t.console.Close()
<del>}
<del>
<del>func setupPipes(container *configs.Config, processConfig *execdriver.ProcessConfig, p *libcontainer.Process, pipes *execdriver.Pipes, wg *sync.WaitGroup) ([]io.WriteCloser, error) {
<del>
<del> writers := []io.WriteCloser{}
<del>
<del> rootuid, err := container.HostUID()
<del> if err != nil {
<del> return writers, err
<del> }
<del>
<del> if processConfig.Tty {
<del> cons, err := p.NewConsole(rootuid)
<del> if err != nil {
<del> return writers, err
<del> }
<del> term, err := NewTtyConsole(cons, pipes, wg)
<del> if err != nil {
<del> return writers, err
<del> }
<del> processConfig.Terminal = term
<del> return writers, nil
<del> }
<del> // not a tty--set up stdio pipes
<del> term := &execdriver.StdConsole{}
<del> processConfig.Terminal = term
<del>
<del> // if we are not in a user namespace, there is no reason to go through
<del> // the hassle of setting up os-level pipes with proper (remapped) ownership
<del> // so we will do the prior shortcut for non-userns containers
<del> if rootuid == 0 {
<del> p.Stdout = pipes.Stdout
<del> p.Stderr = pipes.Stderr
<del>
<del> r, w, err := os.Pipe()
<del> if err != nil {
<del> return writers, err
<del> }
<del> if pipes.Stdin != nil {
<del> go func() {
<del> io.Copy(w, pipes.Stdin)
<del> w.Close()
<del> }()
<del> p.Stdin = r
<del> }
<del> return writers, nil
<del> }
<del>
<del> // if we have user namespaces enabled (rootuid != 0), we will set
<del> // up os pipes for stderr, stdout, stdin so we can chown them to
<del> // the proper ownership to allow for proper access to the underlying
<del> // fds
<del> var fds []uintptr
<del>
<del> copyPipes := func(out io.Writer, in io.ReadCloser) {
<del> defer wg.Done()
<del> io.Copy(out, in)
<del> in.Close()
<del> }
<del>
<del> //setup stdout
<del> r, w, err := os.Pipe()
<del> if err != nil {
<del> w.Close()
<del> return writers, err
<del> }
<del> writers = append(writers, w)
<del> fds = append(fds, r.Fd(), w.Fd())
<del> if pipes.Stdout != nil {
<del> wg.Add(1)
<del> go copyPipes(pipes.Stdout, r)
<del> }
<del> term.Closers = append(term.Closers, r)
<del> p.Stdout = w
<del>
<del> //setup stderr
<del> r, w, err = os.Pipe()
<del> if err != nil {
<del> w.Close()
<del> return writers, err
<del> }
<del> writers = append(writers, w)
<del> fds = append(fds, r.Fd(), w.Fd())
<del> if pipes.Stderr != nil {
<del> wg.Add(1)
<del> go copyPipes(pipes.Stderr, r)
<del> }
<del> term.Closers = append(term.Closers, r)
<del> p.Stderr = w
<del>
<del> //setup stdin
<del> r, w, err = os.Pipe()
<del> if err != nil {
<del> r.Close()
<del> return writers, err
<del> }
<del> fds = append(fds, r.Fd(), w.Fd())
<del> if pipes.Stdin != nil {
<del> go func() {
<del> io.Copy(w, pipes.Stdin)
<del> w.Close()
<del> }()
<del> p.Stdin = r
<del> }
<del> for _, fd := range fds {
<del> if err := syscall.Fchown(int(fd), rootuid, rootuid); err != nil {
<del> return writers, fmt.Errorf("Failed to chown pipes fd: %v", err)
<del> }
<del> }
<del> return writers, nil
<del>}
<del>
<del>// SupportsHooks implements the execdriver Driver interface.
<del>// The libcontainer/runC-based native execdriver does exploit the hook mechanism
<del>func (d *Driver) SupportsHooks() bool {
<del> return true
<del>}
<ide><path>daemon/execdriver/native/driver_unsupported.go
<del>// +build !linux
<del>
<del>package native
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// NewDriver returns a new native driver, called from NewDriver of execdriver.
<del>func NewDriver(root string, options []string) (execdriver.Driver, error) {
<del> return nil, fmt.Errorf("native driver not supported on non-linux")
<del>}
<ide><path>daemon/execdriver/native/driver_unsupported_nocgo.go
<del>// +build linux,!cgo
<del>
<del>package native
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// NewDriver returns a new native driver, called from NewDriver of execdriver.
<del>func NewDriver(root string, options []string) (execdriver.Driver, error) {
<del> return nil, fmt.Errorf("native driver not supported on non-linux")
<del>}
<ide><path>daemon/execdriver/native/exec.go
<del>// +build linux
<del>
<del>package native
<del>
<del>import (
<del> "fmt"
<del> "os"
<del> "os/exec"
<del> "strings"
<del> "sync"
<del> "syscall"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/opencontainers/runc/libcontainer"
<del> // Blank import 'nsenter' so that init in that package will call c
<del> // function 'nsexec()' to do 'setns' before Go runtime take over,
<del> // it's used for join to exist ns like 'docker exec' command.
<del> _ "github.com/opencontainers/runc/libcontainer/nsenter"
<del> "github.com/opencontainers/runc/libcontainer/utils"
<del>)
<del>
<del>// Exec implements the exec driver Driver interface,
<del>// it calls libcontainer APIs to execute a container.
<del>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) {
<del> active := d.activeContainers[c.ID]
<del> if active == nil {
<del> return -1, fmt.Errorf("No active container exists with ID %s", c.ID)
<del> }
<del>
<del> user := processConfig.User
<del> if c.RemappedRoot.UID != 0 && user == "" {
<del> //if user namespaces are enabled, set user explicitly so uid/gid is set to 0
<del> //otherwise we end up with the overflow id and no permissions (65534)
<del> user = "0"
<del> }
<del>
<del> p := &libcontainer.Process{
<del> Args: append([]string{processConfig.Entrypoint}, processConfig.Arguments...),
<del> Env: c.ProcessConfig.Env,
<del> Cwd: c.WorkingDir,
<del> User: user,
<del> }
<del>
<del> if processConfig.Privileged {
<del> p.Capabilities = execdriver.GetAllCapabilities()
<del> }
<del> // add CAP_ prefix to all caps for new libcontainer update to match
<del> // the spec format.
<del> for i, s := range p.Capabilities {
<del> if !strings.HasPrefix(s, "CAP_") {
<del> p.Capabilities[i] = fmt.Sprintf("CAP_%s", s)
<del> }
<del> }
<del>
<del> config := active.Config()
<del> wg := sync.WaitGroup{}
<del> writers, err := setupPipes(&config, processConfig, p, pipes, &wg)
<del> if err != nil {
<del> return -1, err
<del> }
<del>
<del> if err := active.Start(p); err != nil {
<del> return -1, err
<del> }
<del> //close the write end of any opened pipes now that they are dup'ed into the container
<del> for _, writer := range writers {
<del> writer.Close()
<del> }
<del>
<del> if hooks.Start != nil {
<del> pid, err := p.Pid()
<del> if err != nil {
<del> p.Signal(os.Kill)
<del> p.Wait()
<del> return -1, err
<del> }
<del>
<del> // A closed channel for OOM is returned here as it will be
<del> // non-blocking and return the correct result when read.
<del> chOOM := make(chan struct{})
<del> close(chOOM)
<del> hooks.Start(&c.ProcessConfig, pid, chOOM)
<del> }
<del>
<del> ps, err := p.Wait()
<del> if err != nil {
<del> exitErr, ok := err.(*exec.ExitError)
<del> if !ok {
<del> return -1, err
<del> }
<del> ps = exitErr.ProcessState
<del> }
<del> // wait for all IO goroutine copiers to finish
<del> wg.Wait()
<del> return utils.ExitStatus(ps.Sys().(syscall.WaitStatus)), nil
<del>}
<ide><path>daemon/execdriver/native/init.go
<del>// +build linux
<del>
<del>package native
<del>
<del>import (
<del> "fmt"
<del> "os"
<del> "runtime"
<del>
<del> "github.com/docker/docker/pkg/reexec"
<del> "github.com/opencontainers/runc/libcontainer"
<del>)
<del>
<del>func init() {
<del> reexec.Register(DriverName, initializer)
<del>}
<del>
<del>func fatal(err error) {
<del> if lerr, ok := err.(libcontainer.Error); ok {
<del> lerr.Detail(os.Stderr)
<del> os.Exit(1)
<del> }
<del>
<del> fmt.Fprintln(os.Stderr, err)
<del> os.Exit(1)
<del>}
<del>
<del>func initializer() {
<del> runtime.GOMAXPROCS(1)
<del> runtime.LockOSThread()
<del> factory, err := libcontainer.New("")
<del> if err != nil {
<del> fatal(err)
<del> }
<del> if err := factory.StartInitialization(); err != nil {
<del> fatal(err)
<del> }
<del>
<del> panic("unreachable")
<del>}
<ide><path>daemon/execdriver/native/template/default_template_linux.go
<del>package template
<del>
<del>import (
<del> "syscall"
<del>
<del> "github.com/opencontainers/runc/libcontainer/apparmor"
<del> "github.com/opencontainers/runc/libcontainer/configs"
<del>)
<del>
<del>const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
<del>
<del>// New returns the docker default configuration for libcontainer
<del>func New() *configs.Config {
<del> container := &configs.Config{
<del> Capabilities: []string{
<del> "CHOWN",
<del> "DAC_OVERRIDE",
<del> "FSETID",
<del> "FOWNER",
<del> "MKNOD",
<del> "NET_RAW",
<del> "SETGID",
<del> "SETUID",
<del> "SETFCAP",
<del> "SETPCAP",
<del> "NET_BIND_SERVICE",
<del> "SYS_CHROOT",
<del> "KILL",
<del> "AUDIT_WRITE",
<del> },
<del> Namespaces: configs.Namespaces([]configs.Namespace{
<del> {Type: "NEWNS"},
<del> {Type: "NEWUTS"},
<del> {Type: "NEWIPC"},
<del> {Type: "NEWPID"},
<del> {Type: "NEWNET"},
<del> {Type: "NEWUSER"},
<del> }),
<del> Cgroups: &configs.Cgroup{
<del> ScopePrefix: "docker", // systemd only
<del> Resources: &configs.Resources{
<del> AllowAllDevices: false,
<del> MemorySwappiness: -1,
<del> },
<del> },
<del> Mounts: []*configs.Mount{
<del> {
<del> Source: "proc",
<del> Destination: "/proc",
<del> Device: "proc",
<del> Flags: defaultMountFlags,
<del> },
<del> {
<del> Source: "tmpfs",
<del> Destination: "/dev",
<del> Device: "tmpfs",
<del> Flags: syscall.MS_NOSUID | syscall.MS_STRICTATIME,
<del> Data: "mode=755",
<del> },
<del> {
<del> Source: "devpts",
<del> Destination: "/dev/pts",
<del> Device: "devpts",
<del> Flags: syscall.MS_NOSUID | syscall.MS_NOEXEC,
<del> Data: "newinstance,ptmxmode=0666,mode=0620,gid=5",
<del> },
<del> {
<del> Source: "mqueue",
<del> Destination: "/dev/mqueue",
<del> Device: "mqueue",
<del> Flags: defaultMountFlags,
<del> },
<del> {
<del> Source: "sysfs",
<del> Destination: "/sys",
<del> Device: "sysfs",
<del> Flags: defaultMountFlags | syscall.MS_RDONLY,
<del> },
<del> {
<del> Source: "cgroup",
<del> Destination: "/sys/fs/cgroup",
<del> Device: "cgroup",
<del> Flags: defaultMountFlags | syscall.MS_RDONLY,
<del> },
<del> },
<del> MaskPaths: []string{
<del> "/proc/kcore",
<del> "/proc/latency_stats",
<del> "/proc/timer_stats",
<del> },
<del> ReadonlyPaths: []string{
<del> "/proc/asound",
<del> "/proc/bus",
<del> "/proc/fs",
<del> "/proc/irq",
<del> "/proc/sys",
<del> "/proc/sysrq-trigger",
<del> },
<del> }
<del>
<del> if apparmor.IsEnabled() {
<del> container.AppArmorProfile = "docker-default"
<del> }
<del>
<del> return container
<del>}
<ide><path>daemon/execdriver/native/template/default_template_unsupported.go
<del>// +build !linux
<del>
<del>package template
<ide><path>daemon/execdriver/pipes.go
<del>package execdriver
<del>
<del>import (
<del> "io"
<del>)
<del>
<del>// Pipes is a wrapper around a container's output for
<del>// stdin, stdout, stderr
<del>type Pipes struct {
<del> Stdin io.ReadCloser
<del> Stdout, Stderr io.Writer
<del>}
<del>
<del>// NewPipes returns a wrapper around a container's output
<del>func NewPipes(stdin io.ReadCloser, stdout, stderr io.Writer, useStdin bool) *Pipes {
<del> p := &Pipes{
<del> Stdout: stdout,
<del> Stderr: stderr,
<del> }
<del> if useStdin {
<del> p.Stdin = stdin
<del> }
<del> return p
<del>}
<ide><path>daemon/execdriver/termconsole.go
<del>package execdriver
<del>
<del>import (
<del> "io"
<del> "os/exec"
<del>)
<del>
<del>// StdConsole defines standard console operations for execdriver
<del>type StdConsole struct {
<del> // Closers holds io.Closer references for closing at terminal close time
<del> Closers []io.Closer
<del>}
<del>
<del>// NewStdConsole returns a new StdConsole struct
<del>func NewStdConsole(processConfig *ProcessConfig, pipes *Pipes) (*StdConsole, error) {
<del> std := &StdConsole{}
<del>
<del> if err := std.AttachPipes(&processConfig.Cmd, pipes); err != nil {
<del> return nil, err
<del> }
<del> return std, nil
<del>}
<del>
<del>// AttachPipes attaches given pipes to exec.Cmd
<del>func (s *StdConsole) AttachPipes(command *exec.Cmd, pipes *Pipes) error {
<del> command.Stdout = pipes.Stdout
<del> command.Stderr = pipes.Stderr
<del>
<del> if pipes.Stdin != nil {
<del> stdin, err := command.StdinPipe()
<del> if err != nil {
<del> return err
<del> }
<del>
<del> go func() {
<del> defer stdin.Close()
<del> io.Copy(stdin, pipes.Stdin)
<del> }()
<del> }
<del> return nil
<del>}
<del>
<del>// Resize implements Resize method of Terminal interface
<del>func (s *StdConsole) Resize(h, w int) error {
<del> // we do not need to resize a non tty
<del> return nil
<del>}
<del>
<del>// Close implements Close method of Terminal interface
<del>func (s *StdConsole) Close() error {
<del> for _, c := range s.Closers {
<del> c.Close()
<del> }
<del> return nil
<del>}
<ide><path>daemon/execdriver/utils_unix.go
<del>// +build !windows
<del>
<del>package execdriver
<del>
<del>import (
<del> "fmt"
<del> "strings"
<del>
<del> "github.com/docker/docker/pkg/stringutils"
<del> "github.com/syndtr/gocapability/capability"
<del>)
<del>
<del>var capabilityList Capabilities
<del>
<del>func init() {
<del> last := capability.CAP_LAST_CAP
<del> // hack for RHEL6 which has no /proc/sys/kernel/cap_last_cap
<del> if last == capability.Cap(63) {
<del> last = capability.CAP_BLOCK_SUSPEND
<del> }
<del> for _, cap := range capability.List() {
<del> if cap > last {
<del> continue
<del> }
<del> capabilityList = append(capabilityList,
<del> &CapabilityMapping{
<del> Key: strings.ToUpper(cap.String()),
<del> Value: cap,
<del> },
<del> )
<del> }
<del>}
<del>
<del>type (
<del> // CapabilityMapping maps linux capability name to its value of capability.Cap type
<del> // Capabilities is one of the security systems in Linux Security Module (LSM)
<del> // framework provided by the kernel.
<del> // For more details on capabilities, see http://man7.org/linux/man-pages/man7/capabilities.7.html
<del> CapabilityMapping struct {
<del> Key string `json:"key,omitempty"`
<del> Value capability.Cap `json:"value,omitempty"`
<del> }
<del> // Capabilities contains all CapabilityMapping
<del> Capabilities []*CapabilityMapping
<del>)
<del>
<del>// String returns <key> of CapabilityMapping
<del>func (c *CapabilityMapping) String() string {
<del> return c.Key
<del>}
<del>
<del>// GetCapability returns CapabilityMapping which contains specific key
<del>func GetCapability(key string) *CapabilityMapping {
<del> for _, capp := range capabilityList {
<del> if capp.Key == key {
<del> cpy := *capp
<del> return &cpy
<del> }
<del> }
<del> return nil
<del>}
<del>
<del>// GetAllCapabilities returns all of the capabilities
<del>func GetAllCapabilities() []string {
<del> output := make([]string, len(capabilityList))
<del> for i, capability := range capabilityList {
<del> output[i] = capability.String()
<del> }
<del> return output
<del>}
<del>
<del>// TweakCapabilities can tweak capabilities by adding or dropping capabilities
<del>// based on the basics capabilities.
<del>func TweakCapabilities(basics, adds, drops []string) ([]string, error) {
<del> var (
<del> newCaps []string
<del> allCaps = GetAllCapabilities()
<del> )
<del>
<del> // look for invalid cap in the drop list
<del> for _, cap := range drops {
<del> if strings.ToLower(cap) == "all" {
<del> continue
<del> }
<del> if !stringutils.InSlice(allCaps, cap) {
<del> return nil, fmt.Errorf("Unknown capability drop: %q", cap)
<del> }
<del> }
<del>
<del> // handle --cap-add=all
<del> if stringutils.InSlice(adds, "all") {
<del> basics = allCaps
<del> }
<del>
<del> if !stringutils.InSlice(drops, "all") {
<del> for _, cap := range basics {
<del> // skip `all` already handled above
<del> if strings.ToLower(cap) == "all" {
<del> continue
<del> }
<del>
<del> // if we don't drop `all`, add back all the non-dropped caps
<del> if !stringutils.InSlice(drops, cap) {
<del> newCaps = append(newCaps, strings.ToUpper(cap))
<del> }
<del> }
<del> }
<del>
<del> for _, cap := range adds {
<del> // skip `all` already handled above
<del> if strings.ToLower(cap) == "all" {
<del> continue
<del> }
<del>
<del> if !stringutils.InSlice(allCaps, cap) {
<del> return nil, fmt.Errorf("Unknown capability to add: %q", cap)
<del> }
<del>
<del> // add cap if not already in the list
<del> if !stringutils.InSlice(newCaps, cap) {
<del> newCaps = append(newCaps, strings.ToUpper(cap))
<del> }
<del> }
<del> return newCaps, nil
<del>}
<ide><path>daemon/execdriver/windows/clean.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>// Clean implements the exec driver Driver interface.
<del>func (d *Driver) Clean(id string) error {
<del> return nil
<del>}
<ide><path>daemon/execdriver/windows/commandlinebuilder.go
<del>//+build windows
<del>
<del>package windows
<del>
<del>import (
<del> "errors"
<del> "syscall"
<del>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// createCommandLine creates a command line from the Entrypoint and args
<del>// of the ProcessConfig. It escapes the arguments if they are not already
<del>// escaped
<del>func createCommandLine(processConfig *execdriver.ProcessConfig, alreadyEscaped bool) (commandLine string, err error) {
<del> // While this should get caught earlier, just in case, validate that we
<del> // have something to run.
<del> if processConfig.Entrypoint == "" {
<del> return "", errors.New("No entrypoint specified")
<del> }
<del>
<del> // Build the command line of the process
<del> commandLine = processConfig.Entrypoint
<del> logrus.Debugf("Entrypoint: %s", processConfig.Entrypoint)
<del> for _, arg := range processConfig.Arguments {
<del> logrus.Debugf("appending %s", arg)
<del> if !alreadyEscaped {
<del> arg = syscall.EscapeArg(arg)
<del> }
<del> commandLine += " " + arg
<del> }
<del>
<del> logrus.Debugf("commandLine: %s", commandLine)
<del> return commandLine, nil
<del>}
<ide><path>daemon/execdriver/windows/exec.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del> "syscall"
<del>
<del> "github.com/Microsoft/hcsshim"
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// Exec implements the exec driver Driver interface.
<del>func (d *Driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, hooks execdriver.Hooks) (int, error) {
<del>
<del> var (
<del> term execdriver.Terminal
<del> err error
<del> exitCode int32
<del> )
<del>
<del> active := d.activeContainers[c.ID]
<del> if active == nil {
<del> return -1, fmt.Errorf("Exec - No active container exists with ID %s", c.ID)
<del> }
<del>
<del> createProcessParms := hcsshim.CreateProcessParams{
<del> EmulateConsole: processConfig.Tty, // Note NOT c.ProcessConfig.Tty
<del> WorkingDirectory: c.WorkingDir,
<del> }
<del>
<del> // Configure the environment for the process // Note NOT c.ProcessConfig.Env
<del> createProcessParms.Environment = setupEnvironmentVariables(processConfig.Env)
<del>
<del> // Create the commandline for the process // Note NOT c.ProcessConfig
<del> createProcessParms.CommandLine, err = createCommandLine(processConfig, false)
<del>
<del> if err != nil {
<del> return -1, err
<del> }
<del>
<del> // Start the command running in the container.
<del> pid, stdin, stdout, stderr, err := hcsshim.CreateProcessInComputeSystem(c.ID, pipes.Stdin != nil, true, !processConfig.Tty, createProcessParms)
<del> if err != nil {
<del> // TODO Windows: TP4 Workaround. In Hyper-V containers, there is a limitation
<del> // of one exec per container. This should be fixed post TP4. CreateProcessInComputeSystem
<del> // will return a specific error which we handle here to give a good error message
<del> // back to the user instead of an inactionable "An invalid argument was supplied"
<del> if herr, ok := err.(*hcsshim.HcsError); ok && herr.Err == hcsshim.WSAEINVAL {
<del> return -1, fmt.Errorf("The limit of docker execs per Hyper-V container has been exceeded")
<del> }
<del> logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
<del> return -1, err
<del> }
<del>
<del> // Now that the process has been launched, begin copying data to and from
<del> // the named pipes for the std handles.
<del> setupPipes(stdin, stdout, stderr, pipes)
<del>
<del> // Note NOT c.ProcessConfig.Tty
<del> if processConfig.Tty {
<del> term = NewTtyConsole(c.ID, pid)
<del> } else {
<del> term = NewStdConsole()
<del> }
<del> processConfig.Terminal = term
<del>
<del> // Invoke the start callback
<del> if hooks.Start != nil {
<del> // A closed channel for OOM is returned here as it will be
<del> // non-blocking and return the correct result when read.
<del> chOOM := make(chan struct{})
<del> close(chOOM)
<del> hooks.Start(&c.ProcessConfig, int(pid), chOOM)
<del> }
<del>
<del> if exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid, hcsshim.TimeoutInfinite); err != nil {
<del> if herr, ok := err.(*hcsshim.HcsError); ok && herr.Err == syscall.ERROR_BROKEN_PIPE {
<del> logrus.Debugf("Exiting Run() after WaitForProcessInComputeSystem failed with recognised error %s", err)
<del> return hcsshim.WaitErrExecFailed, nil
<del> }
<del> logrus.Warnf("WaitForProcessInComputeSystem failed (container may have been killed): %s", err)
<del> return -1, err
<del> }
<del>
<del> logrus.Debugln("Exiting Run()", c.ID)
<del> return int(exitCode), nil
<del>}
<ide><path>daemon/execdriver/windows/getpids.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import "fmt"
<del>
<del>// GetPidsForContainer implements the exec driver Driver interface.
<del>func (d *Driver) GetPidsForContainer(id string) ([]int, error) {
<del> // TODO Windows: Implementation required.
<del> return nil, fmt.Errorf("GetPidsForContainer: GetPidsForContainer() not implemented")
<del>}
<ide><path>daemon/execdriver/windows/namedpipes.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del> "io"
<del>
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// General comment. Handling I/O for a container is very different to Linux.
<del>// We use a named pipe to HCS to copy I/O both in and out of the container,
<del>// very similar to how docker daemon communicates with a CLI.
<del>
<del>// startStdinCopy asynchronously copies an io.Reader to the container's
<del>// process's stdin pipe and closes the pipe when there is no more data to copy.
<del>func startStdinCopy(dst io.WriteCloser, src io.Reader) {
<del>
<del> // Anything that comes from the client stdin should be copied
<del> // across to the stdin named pipe of the container.
<del> go func() {
<del> defer dst.Close()
<del> bytes, err := io.Copy(dst, src)
<del> log := fmt.Sprintf("Copied %d bytes from stdin.", bytes)
<del> if err != nil {
<del> log = log + " err=" + err.Error()
<del> }
<del> logrus.Debugf(log)
<del> }()
<del>}
<del>
<del>// startStdouterrCopy asynchronously copies data from the container's process's
<del>// stdout or stderr pipe to an io.Writer and closes the pipe when there is no
<del>// more data to copy.
<del>func startStdouterrCopy(dst io.Writer, src io.ReadCloser, name string) {
<del> // Anything that comes from the container named pipe stdout/err should be copied
<del> // across to the stdout/err of the client
<del> go func() {
<del> defer src.Close()
<del> bytes, err := io.Copy(dst, src)
<del> log := fmt.Sprintf("Copied %d bytes from %s.", bytes, name)
<del> if err != nil {
<del> log = log + " err=" + err.Error()
<del> }
<del> logrus.Debugf(log)
<del> }()
<del>}
<del>
<del>// setupPipes starts the asynchronous copying of data to and from the named
<del>// pipes used byt he HCS for the std handles.
<del>func setupPipes(stdin io.WriteCloser, stdout, stderr io.ReadCloser, pipes *execdriver.Pipes) {
<del> if stdin != nil {
<del> startStdinCopy(stdin, pipes.Stdin)
<del> }
<del> if stdout != nil {
<del> startStdouterrCopy(pipes.Stdout, stdout, "stdout")
<del> }
<del> if stderr != nil {
<del> startStdouterrCopy(pipes.Stderr, stderr, "stderr")
<del> }
<del>}
<ide><path>daemon/execdriver/windows/pauseunpause.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// Pause implements the exec driver Driver interface.
<del>func (d *Driver) Pause(c *execdriver.Command) error {
<del> return fmt.Errorf("Windows: Containers cannot be paused")
<del>}
<del>
<del>// Unpause implements the exec driver Driver interface.
<del>func (d *Driver) Unpause(c *execdriver.Command) error {
<del> return fmt.Errorf("Windows: Containers cannot be paused")
<del>}
<ide><path>daemon/execdriver/windows/run.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "encoding/json"
<del> "fmt"
<del> "os"
<del> "path/filepath"
<del> "strconv"
<del> "strings"
<del> "syscall"
<del> "time"
<del>
<del> "github.com/Microsoft/hcsshim"
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// defaultContainerNAT is the default name of the container NAT device that is
<del>// preconfigured on the server.
<del>const defaultContainerNAT = "ContainerNAT"
<del>
<del>// Win32 error codes that are used for various workarounds
<del>// These really should be ALL_CAPS to match golangs syscall library and standard
<del>// Win32 error conventions, but golint insists on CamelCase.
<del>const (
<del> CoEClassstring = syscall.Errno(0x800401F3) // Invalid class string
<del> ErrorNoNetwork = syscall.Errno(1222) // The network is not present or not started
<del> ErrorBadPathname = syscall.Errno(161) // The specified path is invalid
<del> ErrorInvalidObject = syscall.Errno(0x800710D8) // The object identifier does not represent a valid object
<del>)
<del>
<del>type layer struct {
<del> ID string
<del> Path string
<del>}
<del>
<del>type portBinding struct {
<del> Protocol string
<del> InternalPort int
<del> ExternalPort int
<del>}
<del>
<del>type natSettings struct {
<del> Name string
<del> PortBindings []portBinding
<del>}
<del>
<del>type networkConnection struct {
<del> NetworkName string
<del> // TODO Windows: Add Ip4Address string to this structure when hooked up in
<del> // docker CLI. This is present in the HCS JSON handler.
<del> EnableNat bool
<del> Nat natSettings
<del>}
<del>type networkSettings struct {
<del> MacAddress string
<del>}
<del>
<del>type device struct {
<del> DeviceType string
<del> Connection interface{}
<del> Settings interface{}
<del>}
<del>
<del>type mappedDir struct {
<del> HostPath string
<del> ContainerPath string
<del> ReadOnly bool
<del>}
<del>
<del>type containerInit struct {
<del> SystemType string // HCS requires this to be hard-coded to "Container"
<del> Name string // Name of the container. We use the docker ID.
<del> Owner string // The management platform that created this container
<del> IsDummy bool // Used for development purposes.
<del> VolumePath string // Windows volume path for scratch space
<del> Devices []device // Devices used by the container
<del> IgnoreFlushesDuringBoot bool // Optimization hint for container startup in Windows
<del> LayerFolderPath string // Where the layer folders are located
<del> Layers []layer // List of storage layers
<del> ProcessorWeight int64 `json:",omitempty"` // CPU Shares 0..10000 on Windows; where 0 will be omitted and HCS will default.
<del> HostName string // Hostname
<del> MappedDirectories []mappedDir // List of mapped directories (volumes/mounts)
<del> SandboxPath string // Location of unmounted sandbox (used for Hyper-V containers, not Windows Server containers)
<del> HvPartition bool // True if it a Hyper-V Container
<del> EndpointList []string // List of endpoints to be attached to container
<del>}
<del>
<del>// defaultOwner is a tag passed to HCS to allow it to differentiate between
<del>// container creator management stacks. We hard code "docker" in the case
<del>// of docker.
<del>const defaultOwner = "docker"
<del>
<del>// Run implements the exec driver Driver interface
<del>func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) {
<del>
<del> var (
<del> term execdriver.Terminal
<del> err error
<del> )
<del>
<del> // Allocate Network only if there is no network interface
<del> cu := &containerInit{
<del> SystemType: "Container",
<del> Name: c.ID,
<del> Owner: defaultOwner,
<del> IsDummy: dummyMode,
<del> VolumePath: c.Rootfs,
<del> IgnoreFlushesDuringBoot: c.FirstStart,
<del> LayerFolderPath: c.LayerFolder,
<del> ProcessorWeight: c.Resources.CPUShares,
<del> HostName: c.Hostname,
<del> EndpointList: c.EpList,
<del> }
<del>
<del> cu.HvPartition = c.HvPartition
<del>
<del> if cu.HvPartition {
<del> cu.SandboxPath = filepath.Dir(c.LayerFolder)
<del> } else {
<del> cu.VolumePath = c.Rootfs
<del> cu.LayerFolderPath = c.LayerFolder
<del> }
<del>
<del> for _, layerPath := range c.LayerPaths {
<del> _, filename := filepath.Split(layerPath)
<del> g, err := hcsshim.NameToGuid(filename)
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> cu.Layers = append(cu.Layers, layer{
<del> ID: g.ToString(),
<del> Path: layerPath,
<del> })
<del> }
<del>
<del> // Add the mounts (volumes, bind mounts etc) to the structure
<del> mds := make([]mappedDir, len(c.Mounts))
<del> for i, mount := range c.Mounts {
<del> mds[i] = mappedDir{
<del> HostPath: mount.Source,
<del> ContainerPath: mount.Destination,
<del> ReadOnly: !mount.Writable}
<del> }
<del> cu.MappedDirectories = mds
<del>
<del> // TODO Windows. At some point, when there is CLI on docker run to
<del> // enable the IP Address of the container to be passed into docker run,
<del> // the IP Address needs to be wired through to HCS in the JSON. It
<del> // would be present in c.Network.Interface.IPAddress. See matching
<del> // TODO in daemon\container_windows.go, function populateCommand.
<del>
<del> if c.Network.Interface != nil {
<del>
<del> var pbs []portBinding
<del>
<del> // Enumerate through the port bindings specified by the user and convert
<del> // them into the internal structure matching the JSON blob that can be
<del> // understood by the HCS.
<del> for i, v := range c.Network.Interface.PortBindings {
<del> proto := strings.ToUpper(i.Proto())
<del> if proto != "TCP" && proto != "UDP" {
<del> return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid protocol %s", i.Proto())
<del> }
<del>
<del> if len(v) > 1 {
<del> return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support more than one host port in NAT settings")
<del> }
<del>
<del> for _, v2 := range v {
<del> var (
<del> iPort, ePort int
<del> err error
<del> )
<del> if len(v2.HostIP) != 0 {
<del> return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support host IP addresses in NAT settings")
<del> }
<del> if ePort, err = strconv.Atoi(v2.HostPort); err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid container port %s: %s", v2.HostPort, err)
<del> }
<del> if iPort, err = strconv.Atoi(i.Port()); err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid internal port %s: %s", i.Port(), err)
<del> }
<del> if iPort < 0 || iPort > 65535 || ePort < 0 || ePort > 65535 {
<del> return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("specified NAT port is not in allowed range")
<del> }
<del> pbs = append(pbs,
<del> portBinding{ExternalPort: ePort,
<del> InternalPort: iPort,
<del> Protocol: proto})
<del> }
<del> }
<del>
<del> // TODO Windows: TP3 workaround. Allow the user to override the name of
<del> // the Container NAT device through an environment variable. This will
<del> // ultimately be a global daemon parameter on Windows, similar to -b
<del> // for the name of the virtual switch (aka bridge).
<del> cn := os.Getenv("DOCKER_CONTAINER_NAT")
<del> if len(cn) == 0 {
<del> cn = defaultContainerNAT
<del> }
<del>
<del> dev := device{
<del> DeviceType: "Network",
<del> Connection: &networkConnection{
<del> NetworkName: c.Network.Interface.Bridge,
<del> // TODO Windows: Fixme, next line. Needs HCS fix.
<del> EnableNat: false,
<del> Nat: natSettings{
<del> Name: cn,
<del> PortBindings: pbs,
<del> },
<del> },
<del> }
<del>
<del> if c.Network.Interface.MacAddress != "" {
<del> windowsStyleMAC := strings.Replace(
<del> c.Network.Interface.MacAddress, ":", "-", -1)
<del> dev.Settings = networkSettings{
<del> MacAddress: windowsStyleMAC,
<del> }
<del> }
<del> cu.Devices = append(cu.Devices, dev)
<del> } else {
<del> logrus.Debugln("No network interface")
<del> }
<del>
<del> configurationb, err := json.Marshal(cu)
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> configuration := string(configurationb)
<del>
<del> // TODO Windows TP5 timeframe. Remove when TP4 is no longer supported.
<del> // The following a workaround for Windows TP4 which has a networking
<del> // bug which fairly frequently returns an error. Back off and retry.
<del> maxAttempts := 5
<del> for i := 0; i < maxAttempts; i++ {
<del> err = hcsshim.CreateComputeSystem(c.ID, configuration)
<del> if err == nil {
<del> break
<del> }
<del>
<del> if !TP4RetryHack {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> if herr, ok := err.(*hcsshim.HcsError); ok {
<del> if herr.Err != syscall.ERROR_NOT_FOUND && // Element not found
<del> herr.Err != syscall.ERROR_FILE_NOT_FOUND && // The system cannot find the file specified
<del> herr.Err != ErrorNoNetwork && // The network is not present or not started
<del> herr.Err != ErrorBadPathname && // The specified path is invalid
<del> herr.Err != CoEClassstring && // Invalid class string
<del> herr.Err != ErrorInvalidObject { // The object identifier does not represent a valid object
<del> logrus.Debugln("Failed to create temporary container ", err)
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> logrus.Warnf("Invoking Windows TP4 retry hack (%d of %d)", i, maxAttempts-1)
<del> time.Sleep(50 * time.Millisecond)
<del> }
<del> }
<del>
<del> // Start the container
<del> logrus.Debugln("Starting container ", c.ID)
<del> err = hcsshim.StartComputeSystem(c.ID)
<del> if err != nil {
<del> logrus.Errorf("Failed to start compute system: %s", err)
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del> defer func() {
<del> // Stop the container
<del> if forceKill {
<del> logrus.Debugf("Forcibly terminating container %s", c.ID)
<del> if err := hcsshim.TerminateComputeSystem(c.ID, hcsshim.TimeoutInfinite, "exec-run-defer"); err != nil {
<del> logrus.Warnf("Ignoring error from TerminateComputeSystem %s", err)
<del> }
<del> } else {
<del> logrus.Debugf("Shutting down container %s", c.ID)
<del> if err := hcsshim.ShutdownComputeSystem(c.ID, hcsshim.TimeoutInfinite, "exec-run-defer"); err != nil {
<del> if herr, ok := err.(*hcsshim.HcsError); !ok ||
<del> (herr.Err != hcsshim.ERROR_SHUTDOWN_IN_PROGRESS &&
<del> herr.Err != ErrorBadPathname &&
<del> herr.Err != syscall.ERROR_PATH_NOT_FOUND) {
<del> logrus.Warnf("Ignoring error from ShutdownComputeSystem %s", err)
<del> }
<del> }
<del> }
<del> }()
<del>
<del> createProcessParms := hcsshim.CreateProcessParams{
<del> EmulateConsole: c.ProcessConfig.Tty,
<del> WorkingDirectory: c.WorkingDir,
<del> ConsoleSize: c.ProcessConfig.ConsoleSize,
<del> }
<del>
<del> // Configure the environment for the process
<del> createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
<del>
<del> createProcessParms.CommandLine, err = createCommandLine(&c.ProcessConfig, c.ArgsEscaped)
<del>
<del> if err != nil {
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> // Start the command running in the container.
<del> pid, stdin, stdout, stderr, err := hcsshim.CreateProcessInComputeSystem(c.ID, pipes.Stdin != nil, true, !c.ProcessConfig.Tty, createProcessParms)
<del> if err != nil {
<del> logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
<del> return execdriver.ExitStatus{ExitCode: -1}, err
<del> }
<del>
<del> // Now that the process has been launched, begin copying data to and from
<del> // the named pipes for the std handles.
<del> setupPipes(stdin, stdout, stderr, pipes)
<del>
<del> //Save the PID as we'll need this in Kill()
<del> logrus.Debugf("PID %d", pid)
<del> c.ContainerPid = int(pid)
<del>
<del> if c.ProcessConfig.Tty {
<del> term = NewTtyConsole(c.ID, pid)
<del> } else {
<del> term = NewStdConsole()
<del> }
<del> c.ProcessConfig.Terminal = term
<del>
<del> // Maintain our list of active containers. We'll need this later for exec
<del> // and other commands.
<del> d.Lock()
<del> d.activeContainers[c.ID] = &activeContainer{
<del> command: c,
<del> }
<del> d.Unlock()
<del>
<del> if hooks.Start != nil {
<del> // A closed channel for OOM is returned here as it will be
<del> // non-blocking and return the correct result when read.
<del> chOOM := make(chan struct{})
<del> close(chOOM)
<del> hooks.Start(&c.ProcessConfig, int(pid), chOOM)
<del> }
<del>
<del> exitCode, err := hcsshim.WaitForProcessInComputeSystem(c.ID, pid, hcsshim.TimeoutInfinite)
<del> if err != nil {
<del> if herr, ok := err.(*hcsshim.HcsError); ok && herr.Err != syscall.ERROR_BROKEN_PIPE {
<del> logrus.Warnf("WaitForProcessInComputeSystem failed (container may have been killed): %s", err)
<del> }
<del> // Do NOT return err here as the container would have
<del> // started, otherwise docker will deadlock. It's perfectly legitimate
<del> // for WaitForProcessInComputeSystem to fail in situations such
<del> // as the container being killed on another thread.
<del> return execdriver.ExitStatus{ExitCode: hcsshim.WaitErrExecFailed}, nil
<del> }
<del>
<del> logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID)
<del> return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil
<del>}
<del>
<del>// SupportsHooks implements the execdriver Driver interface.
<del>// The windows driver does not support the hook mechanism
<del>func (d *Driver) SupportsHooks() bool {
<del> return false
<del>}
<ide><path>daemon/execdriver/windows/stats.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// Stats implements the exec driver Driver interface.
<del>func (d *Driver) Stats(id string) (*execdriver.ResourceStats, error) {
<del> return nil, fmt.Errorf("Windows: Stats not implemented")
<del>}
<ide><path>daemon/execdriver/windows/stdconsole.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>// StdConsole is for when using a container non-interactively
<del>type StdConsole struct {
<del>}
<del>
<del>// NewStdConsole returns a new StdConsole struct.
<del>func NewStdConsole() *StdConsole {
<del> return &StdConsole{}
<del>}
<del>
<del>// Resize implements Resize method of Terminal interface.
<del>func (s *StdConsole) Resize(h, w int) error {
<del> // we do not need to resize a non tty
<del> return nil
<del>}
<del>
<del>// Close implements Close method of Terminal interface.
<del>func (s *StdConsole) Close() error {
<del> // nothing to close here
<del> return nil
<del>}
<ide><path>daemon/execdriver/windows/terminatekill.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del> "syscall"
<del>
<del> "github.com/Microsoft/hcsshim"
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// Terminate implements the exec driver Driver interface.
<del>func (d *Driver) Terminate(p *execdriver.Command) error {
<del> return kill(p.ID, p.ContainerPid, syscall.SIGTERM)
<del>}
<del>
<del>// Kill implements the exec driver Driver interface.
<del>func (d *Driver) Kill(p *execdriver.Command, sig int) error {
<del> return kill(p.ID, p.ContainerPid, syscall.Signal(sig))
<del>}
<del>
<del>func kill(id string, pid int, sig syscall.Signal) error {
<del> logrus.Debugf("WindowsExec: kill() id=%s pid=%d sig=%d", id, pid, sig)
<del> var err error
<del> context := fmt.Sprintf("kill: sig=%d pid=%d", sig, pid)
<del>
<del> if sig == syscall.SIGKILL || forceKill {
<del> // Terminate the compute system
<del> if err := hcsshim.TerminateComputeSystem(id, hcsshim.TimeoutInfinite, context); err != nil {
<del> logrus.Errorf("Failed to terminate %s - %q", id, err)
<del> }
<del>
<del> } else {
<del> // Terminate Process
<del> if err = hcsshim.TerminateProcessInComputeSystem(id, uint32(pid)); err != nil {
<del> logrus.Warnf("Failed to terminate pid %d in %s: %q", pid, id, err)
<del> // Ignore errors
<del> err = nil
<del> }
<del>
<del> // Shutdown the compute system
<del> if err := hcsshim.ShutdownComputeSystem(id, hcsshim.TimeoutInfinite, context); err != nil {
<del> logrus.Errorf("Failed to shutdown %s - %q", id, err)
<del> }
<del> }
<del> return err
<del>}
<ide><path>daemon/execdriver/windows/ttyconsole.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "github.com/Microsoft/hcsshim"
<del>)
<del>
<del>// TtyConsole implements the exec driver Terminal interface.
<del>type TtyConsole struct {
<del> id string
<del> processid uint32
<del>}
<del>
<del>// NewTtyConsole returns a new TtyConsole struct.
<del>func NewTtyConsole(id string, processid uint32) *TtyConsole {
<del> tty := &TtyConsole{
<del> id: id,
<del> processid: processid,
<del> }
<del> return tty
<del>}
<del>
<del>// Resize implements Resize method of Terminal interface.
<del>func (t *TtyConsole) Resize(h, w int) error {
<del> return hcsshim.ResizeConsoleInComputeSystem(t.id, t.processid, h, w)
<del>}
<del>
<del>// Close implements Close method of Terminal interface.
<del>func (t *TtyConsole) Close() error {
<del> return nil
<del>}
<ide><path>daemon/execdriver/windows/unsupported.go
<del>// +build !windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// NewDriver returns a new execdriver.Driver
<del>func NewDriver(root, initPath string) (execdriver.Driver, error) {
<del> return nil, fmt.Errorf("Windows driver not supported on non-Windows")
<del>}
<ide><path>daemon/execdriver/windows/update.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "github.com/docker/docker/daemon/execdriver"
<del>)
<del>
<del>// Update updates resource configs for a container.
<del>func (d *Driver) Update(c *execdriver.Command) error {
<del> // Updating resource isn't supported on Windows
<del> // but we should return nil for enabling updating container
<del> return nil
<del>}
<ide><path>daemon/execdriver/windows/windows.go
<del>// +build windows
<del>
<del>package windows
<del>
<del>import (
<del> "fmt"
<del> "strings"
<del> "sync"
<del>
<del> "github.com/Microsoft/hcsshim"
<del> "github.com/Sirupsen/logrus"
<del> "github.com/docker/docker/daemon/execdriver"
<del> "github.com/docker/docker/dockerversion"
<del> "github.com/docker/docker/pkg/parsers"
<del> "github.com/docker/engine-api/types/container"
<del>)
<del>
<del>// TP4RetryHack is a hack to retry CreateComputeSystem if it fails with
<del>// known return codes from Windows due to bugs in TP4.
<del>var TP4RetryHack bool
<del>
<del>// This is a daemon development variable only and should not be
<del>// used for running production containers on Windows.
<del>var dummyMode bool
<del>
<del>// This allows the daemon to terminate containers rather than shutdown
<del>// This allows the daemon to force kill (HCS terminate) rather than shutdown
<del>var forceKill bool
<del>
<del>// DefaultIsolation allows users to specify a default isolation technology for
<del>// when running a container on Windows. For example docker daemon -D
<del>// --exec-opt isolation=hyperv will cause Windows to always run containers
<del>// as Hyper-V containers unless otherwise specified.
<del>var DefaultIsolation container.Isolation = "process"
<del>
<del>// Define name and version for windows
<del>var (
<del> DriverName = "Windows 1854"
<del> Version = dockerversion.Version + " " + dockerversion.GitCommit
<del>)
<del>
<del>type activeContainer struct {
<del> command *execdriver.Command
<del>}
<del>
<del>// Driver contains all information for windows driver,
<del>// it implements execdriver.Driver
<del>type Driver struct {
<del> root string
<del> activeContainers map[string]*activeContainer
<del> sync.Mutex
<del>}
<del>
<del>// Name implements the exec driver Driver interface.
<del>func (d *Driver) Name() string {
<del> return fmt.Sprintf("\n Name: %s\n Build: %s \n Default Isolation: %s", DriverName, Version, DefaultIsolation)
<del>}
<del>
<del>// NewDriver returns a new windows driver, called from NewDriver of execdriver.
<del>func NewDriver(root string, options []string) (*Driver, error) {
<del>
<del> for _, option := range options {
<del> key, val, err := parsers.ParseKeyValueOpt(option)
<del> if err != nil {
<del> return nil, err
<del> }
<del> key = strings.ToLower(key)
<del> switch key {
<del>
<del> case "dummy":
<del> switch val {
<del> case "1":
<del> dummyMode = true
<del> logrus.Warn("Using dummy mode in Windows exec driver. This is for development use only!")
<del> }
<del>
<del> case "forcekill":
<del> switch val {
<del> case "1":
<del> forceKill = true
<del> logrus.Warn("Using force kill mode in Windows exec driver. This is for testing purposes only.")
<del> }
<del>
<del> case "isolation":
<del> if !container.Isolation(val).IsValid() {
<del> return nil, fmt.Errorf("Unrecognised exec driver option 'isolation':'%s'", val)
<del> }
<del> if container.Isolation(val).IsHyperV() {
<del> DefaultIsolation = "hyperv"
<del> }
<del> logrus.Infof("Windows default isolation: '%s'", val)
<del> default:
<del> return nil, fmt.Errorf("Unrecognised exec driver option %s\n", key)
<del> }
<del> }
<del>
<del> // TODO Windows TP5 timeframe. Remove this next block of code once TP4
<del> // is no longer supported. Also remove the workaround in run.go.
<del> //
<del> // Hack for TP4.
<del> // This overcomes an issue on TP4 which causes CreateComputeSystem to
<del> // intermittently fail. It's predominantly here to make Windows to Windows
<del> // CI more reliable.
<del> TP4RetryHack = hcsshim.IsTP4()
<del>
<del> return &Driver{
<del> root: root,
<del> activeContainers: make(map[string]*activeContainer),
<del> }, nil
<del>}
<del>
<del>// setupEnvironmentVariables convert a string array of environment variables
<del>// into a map as required by the HCS. Source array is in format [v1=k1] [v2=k2] etc.
<del>func setupEnvironmentVariables(a []string) map[string]string {
<del> r := make(map[string]string)
<del> for _, s := range a {
<del> arr := strings.Split(s, "=")
<del> if len(arr) == 2 {
<del> r[arr[0]] = arr[1]
<del> }
<del> }
<del> return r
<del>}
| 32
|
Java
|
Java
|
add viewresolverregistry#scripttemplate in webflux
|
b2681e1f4af623a782dab82ed5eef881316bb366
|
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/config/ViewResolverRegistry.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 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 org.springframework.web.reactive.result.view.ViewResolver;
<ide> import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
<ide> import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
<add>import org.springframework.web.reactive.result.view.script.ScriptTemplateConfigurer;
<add>import org.springframework.web.reactive.result.view.script.ScriptTemplateViewResolver;
<ide>
<ide> /**
<ide> * Assist with the configuration of a chain of {@link ViewResolver}'s supporting
<ide> * JSON, XML, etc.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Sebastien Deleuze
<ide> * @since 5.0
<ide> */
<ide> public class ViewResolverRegistry {
<ide> public UrlBasedViewResolverRegistration freeMarker() {
<ide> return registration;
<ide> }
<ide>
<add> /**
<add> * Register a script template view resolver with an empty default view name prefix and suffix.
<add> * <p><strong>Note</strong> that you must also configure script templating by
<add> * adding a {@link ScriptTemplateConfigurer} bean.
<add> * @since 5.0.4
<add> */
<add> public UrlBasedViewResolverRegistration scriptTemplate() {
<add> if (!checkBeanOfType(ScriptTemplateConfigurer.class)) {
<add> throw new BeanInitializationException("In addition to a script template view resolver " +
<add> "there must also be a single ScriptTemplateConfig bean in this web application context " +
<add> "(or its parent): ScriptTemplateConfigurer is the usual implementation. " +
<add> "This bean may be given any name.");
<add> }
<add> ScriptRegistration registration = new ScriptRegistration();
<add> UrlBasedViewResolver resolver = registration.getViewResolver();
<add> if (this.applicationContext != null) {
<add> resolver.setApplicationContext(this.applicationContext);
<add> }
<add> this.viewResolvers.add(resolver);
<add> return registration;
<add> }
<add>
<ide> /**
<ide> * Register a {@link ViewResolver} bean instance. This may be useful to
<ide> * configure a 3rd party resolver implementation or as an alternative to
<ide> public FreeMarkerRegistration() {
<ide> }
<ide> }
<ide>
<add> private static class ScriptRegistration extends UrlBasedViewResolverRegistration {
<add>
<add> public ScriptRegistration() {
<add> super(new ScriptTemplateViewResolver());
<add> getViewResolver();
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/config/ViewResolverRegistryTests.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> */
<ide> package org.springframework.web.reactive.config;
<ide>
<add>import java.util.List;
<add>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide>
<add>import org.springframework.beans.DirectFieldAccessor;
<ide> import org.springframework.core.Ordered;
<ide> import org.springframework.http.codec.json.Jackson2JsonEncoder;
<ide> import org.springframework.web.context.support.StaticWebApplicationContext;
<ide> import org.springframework.web.reactive.result.view.HttpMessageWriterView;
<ide> import org.springframework.web.reactive.result.view.UrlBasedViewResolver;
<ide> import org.springframework.web.reactive.result.view.View;
<add>import org.springframework.web.reactive.result.view.ViewResolver;
<ide> import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
<add>import org.springframework.web.reactive.result.view.script.ScriptTemplateConfigurer;
<add>import org.springframework.web.reactive.result.view.script.ScriptTemplateViewResolver;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * Unit tests for {@link ViewResolverRegistry}.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Sebastien Deleuze
<ide> */
<ide> public class ViewResolverRegistryTests {
<ide>
<ide> public class ViewResolverRegistryTests {
<ide> public void setup() {
<ide> StaticWebApplicationContext context = new StaticWebApplicationContext();
<ide> context.registerSingleton("freeMarkerConfigurer", FreeMarkerConfigurer.class);
<add> context.registerSingleton("scriptTemplateConfigurer", ScriptTemplateConfigurer.class);
<ide> this.registry = new ViewResolverRegistry(context);
<ide> }
<ide>
<ide> public void defaultViews() throws Exception {
<ide> assertSame(view, this.registry.getDefaultViews().get(0));
<ide> }
<ide>
<add> @Test // SPR-16431
<add> public void scriptTemplate() {
<add> this.registry.scriptTemplate().prefix("/").suffix(".html");
<add>
<add> List<ViewResolver> viewResolvers = this.registry.getViewResolvers();
<add> assertEquals(1, viewResolvers.size());
<add> assertEquals(ScriptTemplateViewResolver.class, viewResolvers.get(0).getClass());
<add> DirectFieldAccessor accessor = new DirectFieldAccessor(viewResolvers.get(0));
<add> assertEquals("/", accessor.getPropertyValue("prefix"));
<add> assertEquals(".html", accessor.getPropertyValue("suffix"));
<add> }
<add>
<ide> }
| 2
|
Javascript
|
Javascript
|
remove unnecessary annotations
|
9f9213dcd01977a19938c3d1ee4c62faf7a42cf4
|
<ide><path>lib/Entrypoint.js
<ide> /** @typedef {import("./Chunk.js")} Chunk */
<ide>
<ide> const ChunkGroup = require("./ChunkGroup");
<add>
<ide> /**
<del> *
<del> * @description Entrypoint serves as an encapsulation primitive for chunks that are
<add> * Entrypoint serves as an encapsulation primitive for chunks that are
<ide> * a part of a single ChunkGroup. They represent all bundles that need to be loaded for a
<ide> * single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects
<ide> * inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks.
<del> * @class Entrypoint
<del> * @extends {ChunkGroup}
<ide> */
<ide> class Entrypoint extends ChunkGroup {
<ide> /**
<ide> * Creates an instance of Entrypoint.
<ide> * @param {string} name the name of the entrypoint
<del> * @memberof Entrypoint
<ide> */
<ide> constructor(name) {
<ide> super(name);
<ide> class Entrypoint extends ChunkGroup {
<ide> }
<ide>
<ide> /**
<del> * @description isInitial will always return true for Entrypoint ChunkGroup.
<add> * isInitial will always return true for Entrypoint ChunkGroup.
<ide> * @return {true} returns true as all entrypoints are initial ChunkGroups
<del> * @memberof Entrypoint
<ide> */
<ide> isInitial() {
<ide> return true;
<ide> }
<ide>
<ide> /**
<del> * @description Sets the runtimeChunk for an entrypoint.
<add> * Sets the runtimeChunk for an entrypoint.
<ide> * @param {Chunk} chunk the chunk being set as the runtime chunk.
<ide> * @return {void}
<del> * @memberof Entrypoint
<ide> */
<ide> setRuntimeChunk(chunk) {
<ide> this.runtimeChunk = chunk;
<ide> }
<ide>
<ide> /**
<del> * @description Fetches the chunk reference containing the webpack bootstrap code
<add> * Fetches the chunk reference containing the webpack bootstrap code
<ide> * @return {Chunk} returns the runtime chunk or first chunk in `this.chunks`
<del> * @memberof Entrypoint
<ide> */
<ide> getRuntimeChunk() {
<ide> return this.runtimeChunk || this.chunks[0];
| 1
|
Javascript
|
Javascript
|
fix lensflareplugin example on firefox
|
a37b30695a59e28adeaa4e56bbce3ff7156a07d0
|
<ide><path>src/renderers/webgl/plugins/LensFlarePlugin.js
<ide> THREE.LensFlarePlugin = function ( renderer, flares ) {
<ide>
<ide> // save current RGB to temp texture
<ide>
<add> renderer.state.activeTexture( gl.TEXTURE0 );
<add> renderer.state.bindTexture( gl.TEXTURE_2D, null );
<ide> renderer.state.activeTexture( gl.TEXTURE1 );
<ide> renderer.state.bindTexture( gl.TEXTURE_2D, tempTexture );
<ide> gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
| 1
|
Ruby
|
Ruby
|
use optimistic rails version constraint in plugins
|
feb9f64847edd8e61bb1c9077ba7cc0ce75e156e
|
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb
<ide> def email
<ide> end
<ide> end
<ide>
<add> def rails_version_specifier(gem_version = Rails.gem_version)
<add> [">= #{gem_version}"]
<add> end
<add>
<ide> def valid_const?
<ide> if /-\d/.match?(original_name)
<ide> raise Error, "Invalid plugin name #{original_name}. Please give a name which does not contain a namespace starting with numeric characters."
<ide><path>railties/test/generators/plugin_generator_test.rb
<ide> def test_creating_gemspec
<ide> assert_file "bukkits.gemspec", /spec\.version\s+ = Bukkits::VERSION/
<ide> end
<ide>
<add> def test_gemspec_uses_optimistic_rails_version_constraint
<add> rails_version = "1.2.3.4.pre5"
<add>
<add> Rails.stub(:gem_version, Gem::Version.new(rails_version)) do
<add> run_generator
<add> end
<add>
<add> assert_file "bukkits.gemspec", /add_dependency "rails", ">= #{Regexp.escape rails_version}"/
<add> end
<add>
<ide> def test_usage_of_engine_commands
<ide> run_generator [destination_root, "--full"]
<ide> assert_file "bin/rails", /ENGINE_PATH = File\.expand_path\("\.\.\/lib\/bukkits\/engine", __dir__\)/
| 2
|
Javascript
|
Javascript
|
check dir existence only on error
|
eb19904cec9ef72a70639dea3c9a362ee604e2eb
|
<ide><path>packager/src/node-haste/DependencyGraph/ResolutionRequest.js
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> currDir !== '.' && currDir !== realPath.parse(fromModule.path).root;
<ide> currDir = path.dirname(currDir)) {
<ide> const searchPath = path.join(currDir, 'node_modules');
<del> if (this._options.dirExists(searchPath)) {
<del> searchQueue.push(
<del> path.join(searchPath, realModuleName)
<del> );
<del> }
<add> searchQueue.push(path.join(searchPath, realModuleName));
<ide> }
<ide>
<add> const extraSearchQueue = [];
<ide> if (this._options.extraNodeModules) {
<ide> const {extraNodeModules} = this._options;
<ide> const bits = toModuleName.split(path.sep);
<ide> const packageName = bits[0];
<ide> if (extraNodeModules[packageName]) {
<ide> bits[0] = extraNodeModules[packageName];
<del> searchQueue.push(path.join.apply(path, bits));
<add> extraSearchQueue.push(path.join.apply(path, bits));
<ide> }
<ide> }
<ide>
<del> for (let i = 0; i < searchQueue.length; ++i) {
<del> const resolvedModule = this._tryResolveNodeDep(searchQueue[i], fromModule, toModuleName);
<add> const fullSearchQueue = searchQueue.concat(extraSearchQueue);
<add> for (let i = 0; i < fullSearchQueue.length; ++i) {
<add> const resolvedModule = this._tryResolveNodeDep(fullSearchQueue[i], fromModule, toModuleName);
<ide> if (resolvedModule != null) {
<ide> return resolvedModule;
<ide> }
<ide> }
<ide>
<del> const hint = searchQueue.length ? ' or in these directories:' : '';
<add> const displaySearchQueue = searchQueue
<add> .filter(dirPath => this._options.dirExists(dirPath))
<add> .concat(extraSearchQueue);
<add>
<add> const hint = displaySearchQueue.length ? ' or in these directories:' : '';
<ide> throw new UnableToResolveError(
<ide> fromModule,
<ide> toModuleName,
<ide> `Module does not exist in the module map${hint}\n` +
<del> searchQueue.map(searchPath => ` ${path.dirname(searchPath)}\n`).join(', ') + '\n' +
<add> displaySearchQueue.map(searchPath => ` ${path.dirname(searchPath)}\n`).join(', ') + '\n' +
<ide> `This might be related to https://github.com/facebook/react-native/issues/4968\n` +
<ide> `To resolve try the following:\n` +
<ide> ` 1. Clear watchman watches: \`watchman watch-del-all\`.\n` +
| 1
|
Javascript
|
Javascript
|
add hasownproperty to devtools backend
|
c9d64e5f4c2b7cc70a618eec78900dbfd6d201e8
|
<ide><path>packages/react-devtools-shared/src/backend/renderer.js
<ide> import {format} from './utils';
<ide> import {enableProfilerChangedHookIndices} from 'react-devtools-feature-flags';
<ide> import is from 'shared/objectIs';
<ide> import isArray from 'shared/isArray';
<add>import hasOwnProperty from 'shared/hasOwnProperty';
<ide>
<ide> import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
<ide> import type {
<ide> export function attach(
<ide> return false;
<ide> }
<ide> const {deps} = memoizedState;
<del> const hasOwnProperty = Object.prototype.hasOwnProperty.bind(memoizedState);
<add> const boundHasOwnProperty = hasOwnProperty.bind(memoizedState);
<ide> return (
<del> hasOwnProperty('create') &&
<del> hasOwnProperty('destroy') &&
<del> hasOwnProperty('deps') &&
<del> hasOwnProperty('next') &&
<del> hasOwnProperty('tag') &&
<add> boundHasOwnProperty('create') &&
<add> boundHasOwnProperty('destroy') &&
<add> boundHasOwnProperty('deps') &&
<add> boundHasOwnProperty('next') &&
<add> boundHasOwnProperty('tag') &&
<ide> (deps === null || isArray(deps))
<ide> );
<ide> }
| 1
|
Javascript
|
Javascript
|
add new hook to progress
|
f1739f9af971bfe01a23c4c96a8104ce3fa938bb
|
<ide><path>lib/ProgressPlugin.js
<ide> class ProgressPlugin {
<ide> "optimize-chunks": [0.77, "chunk optimization"],
<ide> "optimize-chunks-advanced": [0.78, "advanced chunk optimization"],
<ide> // optimize-tree
<del> "revive-modules": [0.80, "module reviving"],
<del> "optimize-module-order": [0.81, "module order optimization"],
<del> "optimize-module-ids": [0.82, "module id optimization"],
<del> "revive-chunks": [0.83, "chunk reviving"],
<del> "optimize-chunk-order": [0.84, "chunk order optimization"],
<del> "optimize-chunk-ids": [0.85, "chunk id optimization"],
<del> "before-hash": [0.86, "hashing"],
<del> "before-module-assets": [0.87, "module assets processing"],
<del> "before-chunk-assets": [0.88, "chunk assets processing"],
<del> "additional-chunk-assets": [0.89, "additional chunk assets processing"],
<del> "record": [0.90, "recording"]
<add> "optimize-chunk-modules": [0.80, "chunk modules optimization"],
<add> "optimize-chunk-modules-advanced": [0.81, "advanced chunk modules optimization"],
<add> "revive-modules": [0.82, "module reviving"],
<add> "optimize-module-order": [0.83, "module order optimization"],
<add> "optimize-module-ids": [0.84, "module id optimization"],
<add> "revive-chunks": [0.85, "chunk reviving"],
<add> "optimize-chunk-order": [0.86, "chunk order optimization"],
<add> "optimize-chunk-ids": [0.87, "chunk id optimization"],
<add> "before-hash": [0.88, "hashing"],
<add> "before-module-assets": [0.89, "module assets processing"],
<add> "before-chunk-assets": [0.90, "chunk assets processing"],
<add> "additional-chunk-assets": [0.91, "additional chunk assets processing"],
<add> "record": [0.92, "recording"]
<ide> };
<ide> Object.keys(syncHooks).forEach(name => {
<ide> let pass = 0;
| 1
|
Ruby
|
Ruby
|
remove unused branches from options.coerce
|
094c184b12b29c5978b3c669352991650fcba313
|
<ide><path>Library/Homebrew/options.rb
<ide> def inspect
<ide>
<ide> def self.coerce(arg)
<ide> case arg
<del> when self then arg
<del> when Option then new << arg
<ide> when Array
<ide> opts = new
<ide> arg.each do |a|
<ide><path>Library/Homebrew/test/test_options.rb
<ide> def test_set_union
<ide> assert_equal [foo, bar, baz].sort, (@options | options).to_a.sort
<ide> end
<ide>
<del> def test_coerce_with_options
<del> assert_same @options, Options.coerce(@options)
<del> end
<del>
<del> def test_coerce_with_option
<del> option = Option.new("foo")
<del> assert_equal option, Options.coerce(option).to_a.first
<del> end
<del>
<ide> def test_coerce_with_array
<ide> array = %w{--foo --bar}
<ide> option1 = Option.new("foo")
| 2
|
Javascript
|
Javascript
|
remove todo comment
|
9775a4f5e33331f7809c6a2c0a35e953ae5392ca
|
<ide><path>lib/WebpackOptionsApply.js
<ide> class WebpackOptionsApply extends OptionsApply {
<ide> break;
<ide> }
<ide> default:
<del> // TODO options.cache.type type is : "memory" | "filesystem"
<ide> throw new Error(`Unknown cache type ${options.cache.type}`);
<ide> }
<ide> }
| 1
|
Go
|
Go
|
fix some issues with concurrency in aufs
|
55c91f2ab9bcd48cfa248a4e842bb78257c14134
|
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func (a *Driver) Create(id, parent, mountLabel string) error {
<ide> }
<ide> }
<ide> }
<add> a.Lock()
<ide> a.active[id] = &data{}
<add> a.Unlock()
<ide> return nil
<ide> }
<ide>
<ide> func (a *Driver) Remove(id string) error {
<ide> if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) {
<ide> return err
<ide> }
<add> if m != nil {
<add> a.Lock()
<add> delete(a.active, id)
<add> a.Unlock()
<add> }
<ide> return nil
<ide> }
<ide>
<ide> // Get returns the rootfs path for the id.
<ide> // This will mount the dir at it's given path
<ide> func (a *Driver) Get(id, mountLabel string) (string, error) {
<del> ids, err := getParentIds(a.rootPath(), id)
<del> if err != nil {
<del> if !os.IsNotExist(err) {
<del> return "", err
<del> }
<del> ids = []string{}
<del> }
<del>
<ide> // Protect the a.active from concurrent access
<ide> a.Lock()
<ide> defer a.Unlock()
<ide> func (a *Driver) Get(id, mountLabel string) (string, error) {
<ide> a.active[id] = m
<ide> }
<ide>
<add> parents, err := a.getParentLayerPaths(id)
<add> if err != nil && !os.IsNotExist(err) {
<add> return "", err
<add> }
<add>
<ide> // If a dir does not have a parent ( no layers )do not try to mount
<ide> // just return the diff path to the data
<ide> m.path = path.Join(a.rootPath(), "diff", id)
<del> if len(ids) > 0 {
<add> if len(parents) > 0 {
<ide> m.path = path.Join(a.rootPath(), "mnt", id)
<ide> if m.referenceCount == 0 {
<del> if err := a.mount(id, m, mountLabel); err != nil {
<add> if err := a.mount(id, m, mountLabel, parents); err != nil {
<ide> return "", err
<ide> }
<ide> }
<ide> func (a *Driver) getParentLayerPaths(id string) ([]string, error) {
<ide> return layers, nil
<ide> }
<ide>
<del>func (a *Driver) mount(id string, m *data, mountLabel string) error {
<add>func (a *Driver) mount(id string, m *data, mountLabel string, layers []string) error {
<ide> // If the id is mounted or we get an error return
<ide> if mounted, err := a.mounted(m); err != nil || mounted {
<ide> return err
<ide> func (a *Driver) mount(id string, m *data, mountLabel string) error {
<ide> rw = path.Join(a.rootPath(), "diff", id)
<ide> )
<ide>
<del> layers, err := a.getParentLayerPaths(id)
<del> if err != nil {
<del> return err
<del> }
<del>
<ide> if err := a.aufsMount(layers, rw, target, mountLabel); err != nil {
<ide> return fmt.Errorf("error creating aufs mount to %s: %v", target, err)
<ide> }
<ide><path>daemon/graphdriver/aufs/aufs_test.go
<ide> import (
<ide> "io/ioutil"
<ide> "os"
<ide> "path"
<add> "sync"
<ide> "testing"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/reexec"
<add> "github.com/docker/docker/pkg/stringid"
<ide> )
<ide>
<ide> var (
<ide> func init() {
<ide> reexec.Init()
<ide> }
<ide>
<del>func testInit(dir string, t *testing.T) graphdriver.Driver {
<add>func testInit(dir string, t testing.TB) graphdriver.Driver {
<ide> d, err := Init(dir, nil, nil, nil)
<ide> if err != nil {
<ide> if err == graphdriver.ErrNotSupported {
<ide> func testInit(dir string, t *testing.T) graphdriver.Driver {
<ide> return d
<ide> }
<ide>
<del>func newDriver(t *testing.T) *Driver {
<add>func newDriver(t testing.TB) *Driver {
<ide> if err := os.MkdirAll(tmp, 0755); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestMountMoreThan42LayersMatchingPathLength(t *testing.T) {
<ide> zeroes += "0"
<ide> }
<ide> }
<add>
<add>func BenchmarkConcurrentAccess(b *testing.B) {
<add> b.StopTimer()
<add> b.ResetTimer()
<add>
<add> d := newDriver(b)
<add> defer os.RemoveAll(tmp)
<add> defer d.Cleanup()
<add>
<add> numConcurent := 256
<add> // create a bunch of ids
<add> var ids []string
<add> for i := 0; i < numConcurent; i++ {
<add> ids = append(ids, stringid.GenerateNonCryptoID())
<add> }
<add>
<add> if err := d.Create(ids[0], "", ""); err != nil {
<add> b.Fatal(err)
<add> }
<add>
<add> if err := d.Create(ids[1], ids[0], ""); err != nil {
<add> b.Fatal(err)
<add> }
<add>
<add> parent := ids[1]
<add> ids = append(ids[2:])
<add>
<add> chErr := make(chan error, numConcurent)
<add> var outerGroup sync.WaitGroup
<add> outerGroup.Add(len(ids))
<add> b.StartTimer()
<add>
<add> // here's the actual bench
<add> for _, id := range ids {
<add> go func(id string) {
<add> defer outerGroup.Done()
<add> if err := d.Create(id, parent, ""); err != nil {
<add> b.Logf("Create %s failed", id)
<add> chErr <- err
<add> return
<add> }
<add> var innerGroup sync.WaitGroup
<add> for i := 0; i < b.N; i++ {
<add> innerGroup.Add(1)
<add> go func() {
<add> d.Get(id, "")
<add> d.Put(id)
<add> innerGroup.Done()
<add> }()
<add> }
<add> innerGroup.Wait()
<add> d.Remove(id)
<add> }(id)
<add> }
<add>
<add> outerGroup.Wait()
<add> b.StopTimer()
<add> close(chErr)
<add> for err := range chErr {
<add> if err != nil {
<add> b.Log(err)
<add> b.Fail()
<add> }
<add> }
<add>}
| 2
|
Python
|
Python
|
simplify theano tensor instantiation
|
02d5f72be4ae1bc37a30336d3d83be24d0d2db35
|
<ide><path>keras/backend/theano_backend.py
<ide> def placeholder(shape=None, ndim=None, dtype=_FLOATX, name=None):
<ide> raise Exception('Specify either a shape or ndim value.')
<ide> if shape is not None:
<ide> ndim = len(shape)
<del> if ndim == 0:
<del> return T.scalar(name=name, dtype=dtype)
<del> elif ndim == 1:
<del> return T.vector(name=name, dtype=dtype)
<del> elif ndim == 2:
<del> return T.matrix(name=name, dtype=dtype)
<del> elif ndim == 3:
<del> return T.tensor3(name=name, dtype=dtype)
<del> elif ndim == 4:
<del> return T.tensor4(name=name, dtype=dtype)
<del> else:
<del> raise Exception('ndim too large: ' + str(ndim))
<add> broadcast = (False,) * ndim
<add> return T.TensorType(dtype, broadcast)(name)
<ide>
<ide>
<ide> def shape(x):
| 1
|
Ruby
|
Ruby
|
remove unnecessary require
|
db7416cda0700876ad3438774b804eb80a05a758
|
<ide><path>activerecord/test/cases/arel/helper.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "active_support"
<del>require "rubygems"
<ide> require "minitest/autorun"
<ide> require "arel"
<ide>
| 1
|
Python
|
Python
|
remove unused 'preprocess' argument in tok2vec'
|
8f42f8d305787cb74bf7d85ef16c9cd40b948895
|
<ide><path>spacy/_ml.py
<ide> def drop_layer_fwd(X, drop=0.):
<ide> return model
<ide>
<ide>
<del>def Tok2Vec(width, embed_size, preprocess=True, pretrained_dims=0):
<add>def Tok2Vec(width, embed_size, pretrained_dims=0):
<ide> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH]
<ide> with Model.define_operators({'>>': chain, '|': concatenate, '**': clone, '+': add}):
<ide> norm = HashEmbed(width, embed_size, column=cols.index(NORM), name='embed_norm')
<ide> def Tok2Vec(width, embed_size, preprocess=True, pretrained_dims=0):
<ide> >> LN(Maxout(width, width*4, pieces=3)), column=5)
<ide> )
<ide> )
<del> if pretrained_dims:
<add> if pretrained_dims >= 1:
<ide> embed = concatenate_lists(trained_vectors, SpacyVectors)
<ide> else:
<ide> embed = trained_vectors
| 1
|
Python
|
Python
|
fix regression in ignoring symlinks
|
8494fc7036c33683af06a0e57474b8a6157fda05
|
<ide><path>airflow/utils/file.py
<ide> class _IgnoreRule(Protocol):
<ide>
<ide> @staticmethod
<ide> def compile(pattern: str, base_dir: Path, definition_file: Path) -> Optional['_IgnoreRule']:
<del> pass
<add> """
<add> Build an ignore rule from the supplied pattern where base_dir
<add> and definition_file should be absolute paths.
<add> """
<ide>
<ide> @staticmethod
<ide> def match(path: Path, rules: List['_IgnoreRule']) -> bool:
<del> pass
<add> """Match a candidate absolute path against a list of rules"""
<ide>
<ide>
<ide> class _RegexpIgnoreRule(NamedTuple):
<ide> class _RegexpIgnoreRule(NamedTuple):
<ide> def compile(pattern: str, base_dir: Path, definition_file: Path) -> Optional[_IgnoreRule]:
<ide> """Build an ignore rule from the supplied regexp pattern and log a useful warning if it is invalid"""
<ide> try:
<del> return _RegexpIgnoreRule(re.compile(pattern), base_dir.resolve())
<add> return _RegexpIgnoreRule(re.compile(pattern), base_dir)
<ide> except re.error as e:
<ide> log.warning("Ignoring invalid regex '%s' from %s: %s", pattern, definition_file, e)
<ide> return None
<ide>
<ide> @staticmethod
<ide> def match(path: Path, rules: List[_IgnoreRule]) -> bool:
<ide> """Match a list of ignore rules against the supplied path"""
<del> test_path: Path = path.resolve()
<ide> for rule in rules:
<ide> if not isinstance(rule, _RegexpIgnoreRule):
<ide> raise ValueError(f"_RegexpIgnoreRule cannot match rules of type: {type(rule)}")
<del> if rule.pattern.search(str(test_path.relative_to(rule.base_dir))) is not None:
<add> if rule.pattern.search(str(path.relative_to(rule.base_dir))) is not None:
<ide> return True
<ide> return False
<ide>
<ide> def compile(pattern: str, _, definition_file: Path) -> Optional[_IgnoreRule]:
<ide> # > If there is a separator at the beginning or middle (or both) of the pattern, then the
<ide> # > pattern is relative to the directory level of the particular .gitignore file itself.
<ide> # > Otherwise the pattern may also match at any level below the .gitignore level.
<del> relative_to = definition_file.resolve().parent
<add> relative_to = definition_file.parent
<ide> ignore_pattern = GitWildMatchPattern(pattern)
<ide> return _GlobIgnoreRule(ignore_pattern.regex, pattern, ignore_pattern.include, relative_to)
<ide>
<ide> @staticmethod
<ide> def match(path: Path, rules: List[_IgnoreRule]) -> bool:
<ide> """Match a list of ignore rules against the supplied path"""
<del> test_path: Path = path.resolve()
<ide> matched = False
<ide> for r in rules:
<ide> if not isinstance(r, _GlobIgnoreRule):
<ide> raise ValueError(f"_GlobIgnoreRule cannot match rules of type: {type(r)}")
<ide> rule: _GlobIgnoreRule = r # explicit typing to make mypy play nicely
<del> rel_path = str(test_path.relative_to(rule.relative_to) if rule.relative_to else test_path.name)
<del> if rule.raw_pattern.endswith("/") and test_path.is_dir():
<add> rel_path = str(path.relative_to(rule.relative_to) if rule.relative_to else path.name)
<add> if rule.raw_pattern.endswith("/") and path.is_dir():
<ide> # ensure the test path will potentially match a directory pattern if it is a directory
<ide> rel_path += "/"
<ide> if rule.include is not None and rule.pattern.match(rel_path) is not None:
<ide> def _find_path_from_directory(
<ide>
<ide> :return: a generator of file paths which should not be ignored.
<ide> """
<add> # A Dict of patterns, keyed using resolved, absolute paths
<ide> patterns_by_dir: Dict[Path, List[_IgnoreRule]] = {}
<ide>
<ide> for root, dirs, files in os.walk(base_dir_path, followlinks=True):
<del> patterns: List[_IgnoreRule] = patterns_by_dir.get(Path(root), [])
<add> patterns: List[_IgnoreRule] = patterns_by_dir.get(Path(root).resolve(), [])
<ide>
<ide> ignore_file_path = Path(root) / ignore_file_name
<ide> if ignore_file_path.is_file():
<ide> def _find_path_from_directory(
<ide>
<ide> dirs[:] = [subdir for subdir in dirs if not ignore_rule_type.match(Path(root) / subdir, patterns)]
<ide>
<del> patterns_by_dir.update({Path(root) / sd: patterns.copy() for sd in dirs})
<add> # explicit loop for infinite recursion detection since we are following symlinks in this walk
<add> for sd in dirs:
<add> dirpath = (Path(root) / sd).resolve()
<add> if dirpath in patterns_by_dir:
<add> raise RuntimeError(
<add> "Detected recursive loop when walking DAG directory "
<add> + f"{base_dir_path}: {dirpath} has appeared more than once."
<add> )
<add> patterns_by_dir.update({dirpath: patterns.copy()})
<ide>
<ide> for file in files:
<ide> if file == ignore_file_name:
<ide><path>tests/utils/test_file.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<add>import os
<ide> import os.path
<ide> import unittest
<add>from pathlib import Path
<ide> from unittest import mock
<ide>
<add>import pytest
<add>
<ide> from airflow.utils.file import correct_maybe_zipped, find_path_from_directory, open_maybe_zipped
<ide> from tests.models import TEST_DAGS_FOLDER
<ide>
<ide> def test_open_maybe_zipped_archive(self):
<ide> assert isinstance(content, str)
<ide>
<ide>
<del>class TestListPyFilesPath(unittest.TestCase):
<add>class TestListPyFilesPath:
<add> @pytest.fixture()
<add> def test_dir(self, tmp_path):
<add> # create test tree with symlinks
<add> source = os.path.join(tmp_path, "folder")
<add> target = os.path.join(tmp_path, "symlink")
<add> py_file = os.path.join(source, "hello_world.py")
<add> ignore_file = os.path.join(tmp_path, ".airflowignore")
<add> os.mkdir(source)
<add> os.symlink(source, target)
<add> # write ignore files
<add> with open(ignore_file, 'w') as f:
<add> f.write("folder")
<add> # write sample pyfile
<add> with open(py_file, 'w') as f:
<add> f.write("print('hello world')")
<add> return tmp_path
<add>
<ide> def test_find_path_from_directory_regex_ignore(self):
<ide> should_ignore = [
<ide> "test_invalid_cron.py",
<ide> def test_find_path_from_directory_glob_ignore(self):
<ide> assert len(list(filter(lambda file: os.path.basename(file) in should_not_ignore, files))) == len(
<ide> should_not_ignore
<ide> )
<add>
<add> def test_find_path_from_directory_respects_symlinks_regexp_ignore(self, test_dir):
<add> ignore_list_file = ".airflowignore"
<add> found = list(find_path_from_directory(test_dir, ignore_list_file))
<add>
<add> assert os.path.join(test_dir, "symlink", "hello_world.py") in found
<add> assert os.path.join(test_dir, "folder", "hello_world.py") not in found
<add>
<add> def test_find_path_from_directory_respects_symlinks_glob_ignore(self, test_dir):
<add> ignore_list_file = ".airflowignore"
<add> found = list(find_path_from_directory(test_dir, ignore_list_file, ignore_file_syntax="glob"))
<add>
<add> assert os.path.join(test_dir, "symlink", "hello_world.py") in found
<add> assert os.path.join(test_dir, "folder", "hello_world.py") not in found
<add>
<add> def test_find_path_from_directory_fails_on_recursive_link(self, test_dir):
<add> # add a recursive link
<add> recursing_src = os.path.join(test_dir, "folder2", "recursor")
<add> recursing_tgt = os.path.join(test_dir, "folder2")
<add> os.mkdir(recursing_tgt)
<add> os.symlink(recursing_tgt, recursing_src)
<add>
<add> ignore_list_file = ".airflowignore"
<add>
<add> try:
<add> list(find_path_from_directory(test_dir, ignore_list_file, ignore_file_syntax="glob"))
<add> assert False, "Walking a self-recursive tree should fail"
<add> except RuntimeError as err:
<add> assert (
<add> str(err)
<add> == f"Detected recursive loop when walking DAG directory {test_dir}: "
<add> + f"{Path(recursing_tgt).resolve()} has appeared more than once."
<add> )
| 2
|
Python
|
Python
|
fix tf t5
|
d97d06d05f3349f81716268df244d45b037518ef
|
<ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def call(
<ide> ), "past_key_value should have 2 past states: keys and values. Got {} past states".format(
<ide> len(past_key_value)
<ide> )
<del> real_seq_length += past_key_value[0].shape[2] if query_length is None else query_length
<add> real_seq_length += shape_list(past_key_value[0])[2] if query_length is None else query_length
<ide>
<del> key_length = real_seq_length if key_value_states is None else key_value_states.shape[1]
<add> key_length = real_seq_length if key_value_states is None else shape_list(key_value_states)[1]
<ide>
<ide> def shape(hidden_states):
<ide> """ projection """
<ide> def call(
<ide> training=inputs["training"],
<ide> )
<ide>
<del> past = (inputs["encoder_outputs"], decoder_outputs[1]) if inputs["use_cache"] else None
<del>
<ide> if not inputs["return_dict"]:
<add> past = (inputs["encoder_outputs"], decoder_outputs[1]) if inputs["use_cache"] else None
<ide> if past is not None:
<ide> decoder_outputs = decoder_outputs[:1] + (past,) + decoder_outputs[2:]
<ide> return decoder_outputs + inputs["encoder_outputs"]
<ide>
<add> past = (inputs["encoder_outputs"].to_tuple(), decoder_outputs[1]) if inputs["use_cache"] else None
<add>
<ide> return TFSeq2SeqModelOutput(
<ide> last_hidden_state=decoder_outputs.last_hidden_state,
<ide> past_key_values=past,
<ide> def call(
<ide>
<ide> loss = None if inputs["labels"] is None else self.compute_loss(inputs["labels"], logits)
<ide>
<del> past = (inputs["encoder_outputs"], decoder_outputs[1]) if inputs["use_cache"] else None
<ide> if not inputs["return_dict"]:
<add> past = (inputs["encoder_outputs"], decoder_outputs[1]) if inputs["use_cache"] else None
<ide> if past is not None:
<ide> decoder_outputs = decoder_outputs[:1] + (past,) + decoder_outputs[2:]
<ide> output = (logits,) + decoder_outputs[1:] + inputs["encoder_outputs"]
<ide> def call(
<ide> attentions=attentions,
<ide> )
<ide>
<add> past = (inputs["encoder_outputs"].to_tuple(), decoder_outputs[1]) if inputs["use_cache"] else None
<add>
<ide> return TFSeq2SeqLMOutput(
<ide> loss=loss,
<ide> logits=logits,
| 1
|
Text
|
Text
|
fix broken link to gwt code splitting article
|
7e5eef9bf17f6aac027db13d95b98041f60b0622
|
<ide><path>README.md
<ide> MIT (http://opensource.org/licenses/mit-license.php)
<ide>
<ide> (In chronological order)
<ide>
<del>* @google for [Google Web Toolkit (GWT)](https://code.google.com/p/google-web-toolkit/), which aims to compile Java to JavaScript. It features a similar [Code Splitting](https://code.google.com/p/google-web-toolkit//wiki/CodeSplitting) as webpack.
<add>* @google for [Google Web Toolkit (GWT)](https://code.google.com/p/google-web-toolkit/), which aims to compile Java to JavaScript. It features a similar [Code Splitting](https://code.google.com/p/google-web-toolkit/wiki/CodeSplitting) as webpack.
<ide> * @medikoo for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a similar project. webpack was born because I wanted Code Splitting for modules-webpack. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion).
<ide> * @substack for [browserify](http://browserify.org/), which is a similar project and source for many ideas.
<ide> * @jrburke for [require.js](http://requirejs.org/), which is a similar project and source for many ideas.
| 1
|
Javascript
|
Javascript
|
add id to inline gtag script
|
7cdce8fdddeb308d51ff193e670d6cf59e184e90
|
<ide><path>examples/with-google-analytics/pages/_app.js
<ide> const App = ({ Component, pageProps }) => {
<ide> src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
<ide> />
<ide> <Script
<add> id="gtag-init"
<ide> strategy="afterInteractive"
<ide> dangerouslySetInnerHTML={{
<ide> __html: `
| 1
|
Javascript
|
Javascript
|
fix coding style
|
99b7e5311a04583e67c0e9daab5a9595a5157cdc
|
<ide><path>src/math/Quaternion.js
<ide> THREE.Quaternion.prototype = {
<ide>
<ide> slerp: function ( qb, t ) {
<ide>
<del> if (t === 0) {
<add> if (t === 0) return this;
<ide>
<del> return this;
<del>
<del> }
<del>
<del> else if (t === 1) {
<del>
<del> return this.copy( qb );
<del>
<del> }
<add> if (t === 1) return this.copy( qb );
<ide>
<ide> var x = this._x, y = this._y, z = this._z, w = this._w;
<ide>
<ide><path>test/unit/math/Quaternion.js
<ide> test( "slerp", function() {
<ide> var a = new THREE.Quaternion( 0.675341, 0.408783, 0.328567, 0.518512 );
<ide> var b = new THREE.Quaternion( 0.660279, 0.436474, 0.35119, 0.500187 );
<ide>
<del> ok( a.slerp(b, 0).equals(a), "Passed!" );
<del> ok( a.slerp(b, 1).equals(b), "Passed!" );
<add> ok( a.slerp( b, 0 ).equals( a ), "Passed!" );
<add> ok( a.slerp( b, 1 ).equals( b ), "Passed!" );
<ide> });
| 2
|
Javascript
|
Javascript
|
add todo comment
|
deb798d8a7097181c1f08aceb81235b650631356
|
<ide><path>lib/NormalModule.js
<ide> class NormalModule extends Module {
<ide> })
<ide> );
<ide> },
<add> // TODO remove in webpack 5
<ide> exec: (code, filename) => {
<ide> // @ts-ignore Argument of type 'this' is not assignable to parameter of type 'Module'.
<ide> const module = new NativeModule(filename, this);
| 1
|
Python
|
Python
|
add dilbert model for squad
|
19b7c9b0b7d69a12c291200198155c7681125428
|
<ide><path>pytorch_transformers/modeling_dilbert.py
<ide>
<ide>
<ide> DILBERT_PRETRAINED_MODEL_ARCHIVE_MAP = {
<del> 'dilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/dilbert-base-uncased-pytorch_model.bin"
<add> 'dilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/dilbert-base-uncased-pytorch_model.bin",
<add> 'dilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/dilbert-base-uncased-distilled-squad-pytorch_model.bin"
<ide> }
<ide>
<ide> DILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
<del> 'dilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/dilbert-base-uncased-config.json"
<add> 'dilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/dilbert-base-uncased-config.json",
<add> 'dilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/dilbert-base-uncased-distilled-squad-config.json"
<ide> }
<ide>
<ide>
<ide> def init_weights(self, module):
<ide> DILBERT_START_DOCSTRING = r"""
<ide> Smaller, faster, cheaper, lighter: DilBERT
<ide>
<del> For more information on DilBERT, you should check TODO(Victor): Link to Medium
<add> For more information on DilBERT, you should check TODO(Link): Link to Medium
<ide>
<ide> Parameters:
<ide> config (:class:`~pytorch_transformers.DilBertConfig`): Model configuration class with all the parameters of the model.
| 1
|
Javascript
|
Javascript
|
provide minerr as public property
|
ef4458a798b6736050436bb63e5a5c90ce958790
|
<ide><path>src/AngularPublic.js
<ide> function publishExternalAPI(angular){
<ide> 'isNumber': isNumber,
<ide> 'isElement': isElement,
<ide> 'isArray': isArray,
<add> '$$minErr': minErr,
<ide> 'version': version,
<ide> 'isDate': isDate,
<ide> 'lowercase': lowercase,
<ide><path>src/ngResource/resource.js
<ide> 'use strict';
<ide>
<del>var ngResourceMinErr = minErr('ngResource');
<add>var ngResourceMinErr = angular.$$minErr('ngResource');
<ide>
<ide> /**
<ide> * @ngdoc overview
<ide><path>src/ngSanitize/sanitize.js
<ide> 'use strict';
<ide>
<del>var ngSanitizeMinErr = minErr('ngSanitize');
<add>var ngSanitizeMinErr = angular.$$minErr('ngSanitize');
<ide>
<ide> /**
<ide> * @ngdoc overview
| 3
|
Javascript
|
Javascript
|
increase coverage of internal/socket_list
|
610ac7d8581012e627a4f4b67450b423ddbda415
|
<ide><path>test/parallel/test-internal-socket-list-receive.js
<ide> const key = 'test-key';
<ide>
<ide> const list = new SocketListReceive(child, key);
<ide> list.child.emit('internalMessage', { key, cmd: 'NODE_SOCKET_NOTIFY_CLOSE' });
<add> list.child.emit('internalMessage', { key, cmd: 'NODE_SOCKET_GET_COUNT' });
<ide> }
<ide>
<ide> // Verify that a "NODE_SOCKET_ALL_CLOSED" message will be sent.
<ide><path>test/parallel/test-internal-socket-list-send.js
<ide> const key = 'test-key';
<ide> assert.strictEqual(child.listenerCount('disconnect'), 0);
<ide> }));
<ide> }
<add>
<add>// Verify that an error will be received in callback when child is
<add>// disconnected after sending a message and before getting the reply.
<add>{
<add> const count = 1;
<add> const child = Object.assign(new EventEmitter(), {
<add> connected: true,
<add> send: function(msg) {
<add> process.nextTick(() => {
<add> this.emit('disconnect');
<add> this.emit('internalMessage', { key, count, cmd: 'NODE_SOCKET_COUNT' });
<add> });
<add> }
<add> });
<add>
<add> const list = new SocketListSend(child, key);
<add>
<add> list.getConnections(common.mustCall((err, msg) => {
<add> assert.strictEqual(err.message, 'child closed before reply');
<add> assert.strictEqual(child.listenerCount('internalMessage'), 0);
<add> }));
<add>}
| 2
|
Text
|
Text
|
add release notes for 1.6.3
|
a59f46b37db4cc88db9721108f294f31bf71e549
|
<ide><path>CHANGELOG.md
<add><a name="1.6.3"></a>
<add># 1.6.3 scriptalicious-bootstrapping (2017-03-08)
<add>
<add>
<add>## Security Related
<add>These fixes are relevant only to AngularJS apps that are part of a browser extension.
<add>
<add>- **Angular:**
<add> - do not auto-bootstrap if the `src` exists but is empty
<add> ([3536e8](https://github.com/angular/angular.js/commit/3536e83d8a085b02bd6dcec8324800b7e6c734e4))
<add> - do not auto bootstrap if the currentScript has been clobbered
<add> ([95f964](https://github.com/angular/angular.js/commit/95f964b827b6f5b5aab10af54f7831316c7a9935))
<add> - do not auto-bootstrap if the script source is bad and inside SVG
<add> ([c8f78a](https://github.com/angular/angular.js/commit/c8f78a8ca9debc33a6deaf951f344b8d372bf210))
<add>
<add>
<add>## Bug Fixes
<add>- **$log:** don't parse error stacks manually outside of IE/Edge
<add> ([64e5af](https://github.com/angular/angular.js/commit/64e5afc4786fdfd850c6bdb488a5aa2b8b077f74),
<add> [#15590](https://github.com/angular/angular.js/issues/15590),
<add> [#15767](https://github.com/angular/angular.js/issues/15767))
<add>- **$sanitize:** prevent clobbered elements from freezing the browser
<add> ([3bb1dd](https://github.com/angular/angular.js/commit/3bb1dd5d7f7dcde6fea5a3148f8f10e92f451e9d),
<add> [#15699](https://github.com/angular/angular.js/issues/15699))
<add>- **$animate:**
<add> - reset `classNameFilter` to `null` when a disallowed RegExp is used
<add> ([a584fb](https://github.com/angular/angular.js/commit/a584fb6e1569fc1dd85e23b251a7c126edc2dd5b),
<add> [#14913](https://github.com/angular/angular.js/issues/14913))
<add> - improve detection on `ng-animate` in `classNameFilter` RegExp
<add> ([1f1331](https://github.com/angular/angular.js/commit/1f13313f403381581e1c31c57ebfe7a96546c6e4),
<add> [#14806](https://github.com/angular/angular.js/issues/14806))
<add>- **filterFilter:** don't throw if `key.charAt` is not a function
<add> ([f27d19](https://github.com/angular/angular.js/commit/f27d19ed606bf05ba41698159ebbc5fbc195033e),
<add> [#15644](https://github.com/angular/angular.js/issues/15644),
<add> [#15660](https://github.com/angular/angular.js/issues/15660))
<add>- **select:**
<add> - add attribute "selected" for select[multiple]
<add> ([851367](https://github.com/angular/angular.js/commit/8513674911300b27d518383a905fde9b3f25f7ae))
<add> - keep original selection when using shift to add options in IE/Edge
<add> ([97b74a](https://github.com/angular/angular.js/commit/97b74ad6fbcbc4b63e37e9eb44962d6f8de83e8b),
<add> [#15675](https://github.com/angular/angular.js/issues/15675),
<add> [#15676](https://github.com/angular/angular.js/issues/15676))
<add>- **$jsonpCallbacks:** allow `$window` to be mocked in unit tests
<add> ([5ca0de](https://github.com/angular/angular.js/commit/5ca0de64873c32ab2f540a3226e73c4175a15c50),
<add> [#15685](https://github.com/angular/angular.js/issues/15685),
<add> [#15686](https://github.com/angular/angular.js/issues/15686))
<add>
<add>
<add>## New Features
<add>- **info:** add `angularVersion` info to each module
<add> ([1e582e](https://github.com/angular/angular.js/commit/1e582e4fa486f340150bba95927f1b26d9142de2))
<add>- **$injector:** add new `modules` property
<add> ([742123](https://github.com/angular/angular.js/commit/7421235f247e5b7113345401bc5727cfbf81ddc2))
<add>- **Module:** add `info()` method
<add> ([09ba69](https://github.com/angular/angular.js/commit/09ba69078de6ba52c70571b82b6205929f6facc5),
<add> [#15225](https://github.com/angular/angular.js/issues/15225))
<add>- **errorHandlingConfig:** make the depth for object stringification in errors configurable
<add> ([4a5eaf](https://github.com/angular/angular.js/commit/4a5eaf7bec85ceca8b934ebaff4d1834a1a09f57),
<add> [#15402](https://github.com/angular/angular.js/issues/15402),
<add> [#15433](https://github.com/angular/angular.js/issues/15433))
<add>
<add>
<ide> <a name="1.6.2"></a>
<ide> # 1.6.2 llamacorn-lovehug (2017-02-07)
<ide>
| 1
|
Ruby
|
Ruby
|
support a warmup for jruby
|
930d235981c429bde8a604622393f70ec69a4985
|
<ide><path>actionpack/examples/minimal.rb
<ide> def index
<ide> end
<ide> end
<ide>
<del># Runner.run(MetalPostController, N, 'metal')
<del># Runner.run(HttpPostController.action(:index), N, 'http') if defined? HttpPostController
<del># Runner.run(BasePostController.action(:index), N, 'base')
<del>Runner.run(BasePostController.action(:partial), N, 'partial')
<del>Runner.run(BasePostController.action(:many_partials), N, 'many_partials')
<del>Runner.run(BasePostController.action(:partial_collection), N, 'collection')
<del>Runner.run(BasePostController.action(:show_template), N, 'template')
<add>(ENV["M"] || 1).to_i.times do
<add> Runner.run(BasePostController.action(:partial), N, 'partial')
<add> Runner.run(BasePostController.action(:many_partials), N, 'many_partials')
<add> Runner.run(BasePostController.action(:partial_collection), N, 'collection')
<add> Runner.run(BasePostController.action(:show_template), N, 'template')
<add>end
<ide>\ No newline at end of file
| 1
|
Go
|
Go
|
consolidate documentation for -h option
|
fec81690ccaf4c4b81342f632bc1a3ec3ad6b86c
|
<ide><path>docker/flags.go
<ide> import (
<ide> "os"
<ide> "path/filepath"
<ide>
<del> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/opts"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> )
<ide> func init() {
<ide> flCa = flag.String([]string{"-tlscacert"}, filepath.Join(dockerCertPath, defaultCaFile), "Trust only remotes providing a certificate signed by the CA given here")
<ide> flCert = flag.String([]string{"-tlscert"}, filepath.Join(dockerCertPath, defaultCertFile), "Path to TLS certificate file")
<ide> flKey = flag.String([]string{"-tlskey"}, filepath.Join(dockerCertPath, defaultKeyFile), "Path to TLS key file")
<del> opts.HostListVar(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode\nspecified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")
<add> opts.HostListVar(&flHosts, []string{"H", "-host"}, "The socket(s) to bind to in daemon mode or connect to in client mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.")
<ide>
<ide> flag.Usage = func() {
<del> fmt.Fprintf(os.Stderr, "Usage: docker [OPTIONS] COMMAND [arg...]\n -H=[unix://%s]: tcp://host:port to bind/connect to or unix://path/to/socket to use\n\nA self-sufficient runtime for linux containers.\n\nOptions:\n", api.DEFAULTUNIXSOCKET)
<add> fmt.Fprint(os.Stderr, "Usage: docker [OPTIONS] COMMAND [arg...]\n\nA self-sufficient runtime for linux containers.\n\nOptions:\n")
<ide>
<ide> flag.PrintDefaults()
<ide>
| 1
|
Ruby
|
Ruby
|
remove accidental additional test
|
96fdbd3be3e6c5c57e394019e8b812da6d705769
|
<ide><path>activerecord/test/cases/connection_adapters/connection_specification_test.rb
<ide> def test_dup_deep_copy_config
<ide> spec = ConnectionSpecification.new({ :a => :b }, "bar")
<ide> assert_not_equal(spec.config.object_id, spec.dup.config.object_id)
<ide> end
<del>
<del> def test_handle_missing_scheme
<del> spec = ConnectionSpecification.new({ :url => 'testing' }, "bar")
<del> assert_not_equal(spec.config.object_id, spec.dup.config.object_id)
<del> end
<ide> end
<ide> end
<ide> end
| 1
|
Text
|
Text
|
explain `hex` encoding in buffer api
|
e43ee3712fd21710d6da07c4b7892fd1aa84d5e9
|
<ide><path>doc/api/buffer.md
<ide> The character encodings currently supported by Node.js include:
<ide>
<ide> * `'binary'`: Alias for `'latin1'`.
<ide>
<del>* `'hex'`: Encode each byte as two hexadecimal characters.
<add>* `'hex'`: Encode each byte as two hexadecimal characters. Data truncation
<add> may occur for unsanitized input. For example:
<add>
<add>```js
<add>Buffer.from('1ag', 'hex');
<add>// Prints <Buffer 1a>, data truncated when first non-hexadecimal value
<add>// ('g') encountered.
<add>
<add>Buffer.from('1a7g', 'hex');
<add>// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').
<add>
<add>Buffer.from('1634', 'hex');
<add>// Prints <Buffer 16 34>, all data represented.
<add>```
<ide>
<ide> Modern Web browsers follow the [WHATWG Encoding Standard][] which aliases
<ide> both `'latin1'` and `'ISO-8859-1'` to `'win-1252'`. This means that while doing
| 1
|
Javascript
|
Javascript
|
fix lineartologluv convert
|
d682f4c2c0f5a22052fd050b916fe14a672f94e7
|
<ide><path>src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl.js
<ide> vec4 LinearToRGBD( in vec4 value, in float maxRange ) {
<ide> // M matrix, for encoding
<ide> const mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );
<ide> vec4 LinearToLogLuv( in vec4 value ) {
<del> vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;
<add> vec3 Xp_Y_XYZp = cLogLuvM * value.rgb;
<ide> Xp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );
<ide> vec4 vResult;
<ide> vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;
| 1
|
Text
|
Text
|
improve introduction to concerns section
|
45e3719afd1c2982fb9c3cb2de9be7fa13ea6bc3
|
<ide><path>guides/source/getting_started.md
<ide> we defined it as an instance variable.
<ide>
<ide> ### Using Concerns
<ide>
<del> A concern is any module that contains methods you would like to be able to share across multiple controllers or models. In other frameworks they are often known as mixins. They are a good way to keep your controllers and models small and keep your code DRY.
<add>A concern is any module that contains methods representing a well-defined slice of the functionality that a model or controller is responsible for. In other frameworks they are often known as mixins. Concerns are a way to make large controllers or models easier to understand and manage. This also has the advantage of reusability when multiple models (or controllers) share the same concerns.
<ide>
<ide> You can use concerns in your controller or model the same way you would use any module. When you first created your app with `rails new blog` , two folders were created within `app/` along with the rest:
<ide>
<ide> Then, in our `index` action template (`app/views/articles/index.html.erb`) we wo
<ide>
<ide> However, if you look again at our models now, you can see that the logic is duplicated. If in future we increase the functionality of our blog - to include private messages, for instance - we might find ourselves duplicating the logic yet again. This is where concerns come in handy.
<ide>
<del>Let's call our new concern (module) `Visible`, a module to use for any model that has a status. We can create a new file inside `app/models/concerns` called `visible.rb` , and store all of the status methods that were duplicated in the models.
<add>A concern is only responsible for a focused subset of the model's responsibility; the methods in our concern will all be related to the visibility of a model. Let's call our new concern (module) `Visible`. We can create a new file inside `app/models/concerns` called `visible.rb` , and store all of the status methods that were duplicated in the models.
<ide>
<ide> `app/models/concerns/visible.rb`
<ide>
| 1
|
Mixed
|
Ruby
|
move schemamigration to an independent object
|
436277da88507f9aae0874e62f3e61a8546b9683
|
<ide><path>activerecord/CHANGELOG.md
<add>* Move `ActiveRecord::SchemaMigration` to an independent object.
<add>
<add> `ActiveRecord::SchemaMigration` no longer inherits from `ActiveRecord::Base` and is now an independent object that should be instantiated with a `connection`. This class is private and should not be used by applications directly. If you want to interact with the schema migrations table, please access it on the connection directly, for example: `ActiveRecord::Base.connection.schema_migration`.
<add>
<add> *Eileen M. Uchitelle*
<add>
<ide> * Deprecate `all_connection_pools` and make `connection_pool_list` more explicit.
<ide>
<ide> Following on #45924 `all_connection_pools` is now deprecated. `connection_pool_list` will either take an explicit role or applications can opt into the new behavior by passing `:all`.
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def check_constraint_exists?(table_name, **options)
<ide> end
<ide>
<ide> def dump_schema_information # :nodoc:
<del> versions = schema_migration.all_versions
<add> versions = schema_migration.versions
<ide> insert_versions_sql(versions) if versions.any?
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def migration_context # :nodoc:
<ide> end
<ide>
<ide> def schema_migration # :nodoc:
<del> @schema_migration ||= begin
<del> conn = self
<del> connection_name = conn.pool.pool_config.connection_name
<del>
<del> return ActiveRecord::SchemaMigration if connection_name == "ActiveRecord::Base"
<del>
<del> schema_migration_name = "#{connection_name}::SchemaMigration"
<del>
<del> Class.new(ActiveRecord::SchemaMigration) do
<del> define_singleton_method(:name) { schema_migration_name }
<del> define_singleton_method(:to_s) { schema_migration_name }
<del>
<del> self.connection_specification_name = connection_name
<del> end
<del> end
<add> SchemaMigration.new(self)
<ide> end
<ide>
<ide> def internal_metadata # :nodoc:
<ide><path>activerecord/lib/active_record/migration.rb
<ide> def method_missing(method, *arguments, &block)
<ide>
<ide> def copy(destination, sources, options = {})
<ide> copied = []
<del> schema_migration = options[:schema_migration] || ActiveRecord::SchemaMigration
<ide>
<ide> FileUtils.mkdir_p(destination) unless File.exist?(destination)
<ide>
<del> destination_migrations = ActiveRecord::MigrationContext.new(destination, schema_migration).migrations
<add> destination_migrations = ActiveRecord::MigrationContext.new(destination, SchemaMigration::NullSchemaMigration.new).migrations
<ide> last = destination_migrations.last
<ide> sources.each do |scope, path|
<del> source_migrations = ActiveRecord::MigrationContext.new(path, schema_migration).migrations
<add> source_migrations = ActiveRecord::MigrationContext.new(path, SchemaMigration::NullSchemaMigration.new).migrations
<ide>
<ide> source_migrations.each do |migration|
<ide> source = File.binread(migration.filename)
<ide> def next_migration_number(number)
<ide> if ActiveRecord.timestamped_migrations
<ide> [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max
<ide> else
<del> SchemaMigration.normalize_migration_number(number)
<add> "%.3d" % number.to_i
<ide> end
<ide> end
<ide>
<ide> def load_migration
<ide> #
<ide> # A migration context requires the path to the migrations is set
<ide> # in the +migrations_paths+ parameter. Optionally a +schema_migration+
<del> # class can be provided. For most applications, +SchemaMigration+ is
<del> # sufficient. Multiple database applications need a +SchemaMigration+
<del> # per primary database.
<add> # class can be provided. Multiple database applications will instantiate
<add> # a +SchemaMigration+ object per database. From the Rake tasks, Rails will
<add> # handle this for you.
<ide> class MigrationContext
<ide> attr_reader :migrations_paths, :schema_migration, :internal_metadata
<ide>
<del> def initialize(migrations_paths, schema_migration = SchemaMigration, internal_metadata = InternalMetadata)
<add> def initialize(migrations_paths, schema_migration = nil, internal_metadata = InternalMetadata)
<add> if schema_migration == SchemaMigration
<add> schema_migration = SchemaMigration.new(ActiveRecord::Base.connection)
<add>
<add> ActiveSupport::Deprecation.warn("SchemaMigration no longer inherits from ActiveRecord::Base. Please instaniate a new SchemaMigration object with the desired connection, ie `ActiveRecord::SchemaMigration.new(ActiveRecord::Base.connection)`.")
<add> end
<add>
<ide> @migrations_paths = migrations_paths
<del> @schema_migration = schema_migration
<add> @schema_migration = schema_migration || SchemaMigration.new(ActiveRecord::Base.connection)
<ide> @internal_metadata = internal_metadata
<ide> end
<ide>
<ide> def open # :nodoc:
<ide>
<ide> def get_all_versions # :nodoc:
<ide> if schema_migration.table_exists?
<del> schema_migration.all_versions.map(&:to_i)
<add> schema_migration.integer_versions
<ide> else
<ide> []
<ide> end
<ide> class << self
<ide>
<ide> # For cases where a table doesn't exist like loading from schema cache
<ide> def current_version
<del> MigrationContext.new(migrations_paths, SchemaMigration, InternalMetadata).current_version
<add> schema_migration = SchemaMigration.new(ActiveRecord::Base.connection)
<add>
<add> MigrationContext.new(migrations_paths, schema_migration, InternalMetadata).current_version
<ide> end
<ide> end
<ide>
<ide> def migrated
<ide> end
<ide>
<ide> def load_migrated
<del> @migrated_versions = Set.new(@schema_migration.all_versions.map(&:to_i))
<add> @migrated_versions = Set.new(@schema_migration.integer_versions)
<ide> end
<ide>
<ide> private
<ide> def validate(migrations)
<ide> def record_version_state_after_migrating(version)
<ide> if down?
<ide> migrated.delete(version)
<del> @schema_migration.delete_by(version: version.to_s)
<add> @schema_migration.delete_version(version.to_s)
<ide> else
<ide> migrated << version
<del> @schema_migration.create!(version: version.to_s)
<add> @schema_migration.create_version(version.to_s)
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/schema_migration.rb
<ide> # frozen_string_literal: true
<ide>
<del>require "active_record/scoping/default"
<del>require "active_record/scoping/named"
<del>
<ide> module ActiveRecord
<ide> # This class is used to create a table that keeps track of which migrations
<ide> # have been applied to a given database. When a migration is run, its schema
<del> # number is inserted in to the `SchemaMigration.table_name` so it doesn't need
<add> # number is inserted in to the schema migrations table so it doesn't need
<ide> # to be executed the next time.
<del> class SchemaMigration < ActiveRecord::Base # :nodoc:
<del> class << self
<del> def primary_key
<del> "version"
<del> end
<add> class SchemaMigration # :nodoc:
<add> attr_reader :connection, :arel_table
<add>
<add> def initialize(connection)
<add> @connection = connection
<add> @arel_table = Arel::Table.new(table_name)
<add> end
<add>
<add> def create_version(version)
<add> im = Arel::InsertManager.new(arel_table)
<add> im.insert(arel_table[primary_key] => version)
<add> connection.insert(im, "#{self} Create", primary_key, version)
<add> end
<add>
<add> def delete_version(version)
<add> dm = Arel::DeleteManager.new(arel_table)
<add> dm.wheres = [arel_table[primary_key].eq(version)]
<ide>
<del> def table_name
<del> "#{table_name_prefix}#{schema_migrations_table_name}#{table_name_suffix}"
<add> connection.delete(dm, "#{self} Destroy")
<add> end
<add>
<add> def delete_all_versions
<add> versions.each do |version|
<add> delete_version(version)
<ide> end
<add> end
<add>
<add> def primary_key
<add> "version"
<add> end
<add>
<add> def table_name
<add> "#{ActiveRecord::Base.table_name_prefix}#{ActiveRecord::Base.schema_migrations_table_name}#{ActiveRecord::Base.table_name_suffix}"
<add> end
<ide>
<del> def create_table
<del> unless connection.table_exists?(table_name)
<del> connection.create_table(table_name, id: false) do |t|
<del> t.string :version, **connection.internal_string_options_for_primary_key
<del> end
<add> def create_table
<add> unless connection.table_exists?(table_name)
<add> connection.create_table(table_name, id: false) do |t|
<add> t.string :version, **connection.internal_string_options_for_primary_key
<ide> end
<ide> end
<add> end
<ide>
<del> def drop_table
<del> connection.drop_table table_name, if_exists: true
<del> end
<add> def drop_table
<add> connection.drop_table table_name, if_exists: true
<add> end
<ide>
<del> def normalize_migration_number(number)
<del> "%.3d" % number.to_i
<del> end
<add> def normalize_migration_number(number)
<add> "%.3d" % number.to_i
<add> end
<ide>
<del> def normalized_versions
<del> all_versions.map { |v| normalize_migration_number v }
<del> end
<add> def normalized_versions
<add> versions.map { |v| normalize_migration_number v }
<add> end
<ide>
<del> def all_versions
<del> order(:version).pluck(:version)
<del> end
<add> def versions
<add> sm = Arel::SelectManager.new(arel_table)
<add> sm.project(arel_table[primary_key])
<add> sm.order(arel_table[primary_key].asc)
<add> connection.select_values(sm)
<add> end
<ide>
<del> def table_exists?
<del> connection.data_source_exists?(table_name)
<del> end
<add> def integer_versions
<add> versions.map(&:to_i)
<add> end
<add>
<add> def count
<add> sm = Arel::SelectManager.new(arel_table)
<add> sm.project(*Arel::Nodes::Count.new([Arel.star]))
<add> connection.select_values(sm).first
<add> end
<add>
<add> def table_exists?
<add> connection.data_source_exists?(table_name)
<ide> end
<ide>
<del> def version
<del> super.to_i
<add> class NullSchemaMigration
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/tasks/database_tasks.rb
<ide> def prepare_all
<ide> ActiveRecord::Base.establish_connection(db_config)
<ide>
<ide> begin
<del> database_initialized = ActiveRecord::SchemaMigration.table_exists?
<add> database_initialized = ActiveRecord::Base.connection.schema_migration.table_exists?
<ide> rescue ActiveRecord::NoDatabaseError
<ide> create(db_config)
<ide> retry
<ide><path>activerecord/test/cases/active_record_schema_test.rb
<ide> class ActiveRecordSchemaTest < ActiveRecord::TestCase
<ide> @connection.drop_table :nep_schema_migrations rescue nil
<ide> @connection.drop_table :has_timestamps rescue nil
<ide> @connection.drop_table :multiple_indexes rescue nil
<del> @schema_migration.delete_all rescue nil
<add> @schema_migration.delete_all_versions rescue nil
<ide> ActiveRecord::Migration.verbose = @original_verbose
<ide> end
<ide>
<ide> def test_has_primary_key
<ide>
<ide> @schema_migration.create_table
<ide> assert_difference "@schema_migration.count", 1 do
<del> @schema_migration.create version: 12
<add> @schema_migration.create_version(12)
<ide> end
<ide> ensure
<ide> @schema_migration.drop_table
<ide> def test_schema_define
<ide> def test_schema_define_with_table_name_prefix
<ide> old_table_name_prefix = ActiveRecord::Base.table_name_prefix
<ide> ActiveRecord::Base.table_name_prefix = "nep_"
<del> @schema_migration.reset_table_name
<ide> @internal_metadata.reset_table_name
<ide> ActiveRecord::Schema.define(version: 7) do
<ide> create_table :fruits do |t|
<ide> def test_schema_define_with_table_name_prefix
<ide> assert_equal 7, @connection.migration_context.current_version
<ide> ensure
<ide> ActiveRecord::Base.table_name_prefix = old_table_name_prefix
<del> @schema_migration.reset_table_name
<ide> @internal_metadata.reset_table_name
<ide> end
<ide>
<ide><path>activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
<ide> class SchemaMigrationsTest < ActiveRecord::Mysql2TestCase
<ide> self.use_transactional_tests = false
<ide>
<add> def setup
<add> @schema_migration = ActiveRecord::Base.connection.schema_migration
<add> end
<add>
<ide> def test_renaming_index_on_foreign_key
<ide> connection.add_index "engines", "car_id"
<ide> connection.add_foreign_key :engines, :cars, name: "fk_engines_cars"
<ide> def test_renaming_index_on_foreign_key
<ide>
<ide> def test_initializes_schema_migrations_for_encoding_utf8mb4
<ide> with_encoding_utf8mb4 do
<del> table_name = ActiveRecord::SchemaMigration.table_name
<add> table_name = @schema_migration.table_name
<ide> connection.drop_table table_name, if_exists: true
<ide>
<del> ActiveRecord::SchemaMigration.create_table
<add> @schema_migration.create_table
<ide>
<ide> assert connection.column_exists?(table_name, :version, :string)
<ide> end
<ide><path>activerecord/test/cases/adapters/mysql2/table_options_test.rb
<ide> def teardown
<ide> ActiveRecord::Base.logger = @logger_was
<ide> ActiveRecord::Migration.verbose = @verbose_was
<ide> ActiveRecord::Base.connection.drop_table "mysql_table_options", if_exists: true
<del> ActiveRecord::SchemaMigration.delete_all rescue nil
<add> ActiveRecord::Base.connection.schema_migration.delete_all_versions rescue nil
<ide> end
<ide>
<ide> test "new migrations do not contain default ENGINE=InnoDB option" do
<ide><path>activerecord/test/cases/adapters/postgresql/extension_migration_test.rb
<ide> def setup
<ide>
<ide> ActiveRecord::Base.table_name_prefix = "p_"
<ide> ActiveRecord::Base.table_name_suffix = "_s"
<del> @connection.schema_migration.reset_table_name
<ide> @connection.internal_metadata.reset_table_name
<ide>
<del> @connection.schema_migration.delete_all rescue nil
<add> @connection.schema_migration.delete_all_versions rescue nil
<ide> ActiveRecord::Migration.verbose = false
<ide> end
<ide>
<ide> def teardown
<del> @connection.schema_migration.delete_all rescue nil
<add> @connection.schema_migration.delete_all_versions rescue nil
<ide> ActiveRecord::Migration.verbose = true
<ide>
<ide> ActiveRecord::Base.table_name_prefix = @old_table_name_prefix
<ide> ActiveRecord::Base.table_name_suffix = @old_table_name_suffix
<del> @connection.schema_migration.reset_table_name
<ide> @connection.internal_metadata.reset_table_name
<ide>
<ide> super
<ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> def migrate(x)
<ide> ensure
<ide> drop_table "pg_uuids_4"
<ide> ActiveRecord::Migration.verbose = @verbose_was
<del> ActiveRecord::Base.connection.schema_migration.delete_all
<add> ActiveRecord::Base.connection.schema_migration.delete_all_versions
<ide> end
<ide> uses_transaction :test_schema_dumper_for_uuid_primary_key_default_in_legacy_migration
<ide> end
<ide> def migrate(x)
<ide> ensure
<ide> drop_table "pg_uuids_4"
<ide> ActiveRecord::Migration.verbose = @verbose_was
<del> ActiveRecord::Base.connection.schema_migration.delete_all
<add> ActiveRecord::Base.connection.schema_migration.delete_all_versions
<ide> end
<ide> uses_transaction :test_schema_dumper_for_uuid_primary_key_with_default_nil_in_legacy_migration
<ide> end
<ide><path>activerecord/test/cases/migration/compatibility_test.rb
<ide> def setup
<ide> teardown do
<ide> connection.drop_table :testings rescue nil
<ide> ActiveRecord::Migration.verbose = @verbose_was
<del> @schema_migration.delete_all rescue nil
<add> @schema_migration.delete_all_versions rescue nil
<ide> end
<ide>
<ide> def test_migration_doesnt_remove_named_index
<ide> def setup
<ide>
<ide> def teardown
<ide> ActiveRecord::Migration.verbose = @verbose_was
<del> @schema_migration.delete_all rescue nil
<add> @schema_migration.delete_all_versions rescue nil
<ide> connection.drop_table :testings rescue nil
<ide> end
<ide>
<ide> def setup
<ide> def teardown
<ide> @migration.migrate(:down) if @migration
<ide> ActiveRecord::Migration.verbose = @verbose_was
<del> ActiveRecord::SchemaMigration.delete_all rescue nil
<add> ActiveRecord::Base.connection.schema_migration.delete_all_versions rescue nil
<ide> LegacyPrimaryKey.reset_column_information
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration/logger_test.rb
<ide> def setup
<ide> super
<ide> @schema_migration = ActiveRecord::Base.connection.schema_migration
<ide> @schema_migration.create_table
<del> @schema_migration.delete_all
<add> @schema_migration.delete_all_versions
<ide> @internal_metadata = ActiveRecord::Base.connection.internal_metadata
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def setup
<ide> ActiveRecord::Base.table_name_prefix = ""
<ide> ActiveRecord::Base.table_name_suffix = ""
<ide>
<del> ActiveRecord::SchemaMigration.create_table
<del> ActiveRecord::SchemaMigration.delete_all
<add> @schema_migration.create_table
<add> @schema_migration.delete_all_versions
<ide>
<ide> %w(things awesome_things prefix_things_suffix p_awesome_things_s).each do |table|
<ide> Thing.connection.drop_table(table) rescue nil
<ide> def setup
<ide> ActiveRecord::Migration.verbose = @verbose_was
<ide> end
<ide>
<add> def test_passing_a_schema_migration_class_to_migration_context_is_deprecated
<add> migrations_path = MIGRATIONS_ROOT + "/valid"
<add> migrator = assert_deprecated { ActiveRecord::MigrationContext.new(migrations_path, ActiveRecord::SchemaMigration) }
<add> migrator.up
<add>
<add> assert_equal 3, migrator.current_version
<add> assert_equal false, migrator.needs_migration?
<add>
<add> migrator.down
<add> assert_equal 0, migrator.current_version
<add> assert_equal true, migrator.needs_migration?
<add>
<add> @schema_migration.create_version(3)
<add> assert_equal true, migrator.needs_migration?
<add> end
<add>
<ide> def test_migration_context_with_default_schema_migration
<ide> migrations_path = MIGRATIONS_ROOT + "/valid"
<ide> migrator = ActiveRecord::MigrationContext.new(migrations_path)
<ide> def test_migration_context_with_default_schema_migration
<ide> assert_equal 0, migrator.current_version
<ide> assert_equal true, migrator.needs_migration?
<ide>
<del> ActiveRecord::SchemaMigration.create!(version: 3)
<add> @schema_migration.create_version(3)
<ide> assert_equal true, migrator.needs_migration?
<ide> end
<ide>
<ide> def test_migrator_versions
<ide> assert_equal 0, migrator.current_version
<ide> assert_equal true, migrator.needs_migration?
<ide>
<del> ActiveRecord::SchemaMigration.create!(version: 3)
<add> @schema_migration.create_version(3)
<ide> assert_equal true, migrator.needs_migration?
<ide> end
<ide>
<ide> def migrate(x)
<ide> def test_schema_migrations_table_name
<ide> original_schema_migrations_table_name = ActiveRecord::Base.schema_migrations_table_name
<ide>
<del> assert_equal "schema_migrations", ActiveRecord::SchemaMigration.table_name
<add> assert_equal "schema_migrations", @schema_migration.table_name
<ide> ActiveRecord::Base.table_name_prefix = "prefix_"
<ide> ActiveRecord::Base.table_name_suffix = "_suffix"
<ide> Reminder.reset_table_name
<del> assert_equal "prefix_schema_migrations_suffix", ActiveRecord::SchemaMigration.table_name
<add> assert_equal "prefix_schema_migrations_suffix", @schema_migration.table_name
<ide> ActiveRecord::Base.schema_migrations_table_name = "changed"
<ide> Reminder.reset_table_name
<del> assert_equal "prefix_changed_suffix", ActiveRecord::SchemaMigration.table_name
<add> assert_equal "prefix_changed_suffix", @schema_migration.table_name
<ide> ActiveRecord::Base.table_name_prefix = ""
<ide> ActiveRecord::Base.table_name_suffix = ""
<ide> Reminder.reset_table_name
<del> assert_equal "changed", ActiveRecord::SchemaMigration.table_name
<add> assert_equal "changed", @schema_migration.table_name
<ide> ensure
<ide> ActiveRecord::Base.schema_migrations_table_name = original_schema_migrations_table_name
<del> ActiveRecord::SchemaMigration.reset_table_name
<ide> Reminder.reset_table_name
<ide> end
<ide>
<ide> def test_internal_metadata_create_table_wont_be_affected_by_schema_cache
<ide> end
<ide>
<ide> def test_schema_migration_create_table_wont_be_affected_by_schema_cache
<del> ActiveRecord::SchemaMigration.drop_table
<del> assert_not_predicate ActiveRecord::SchemaMigration, :table_exists?
<add> @schema_migration.drop_table
<add> assert_not_predicate @schema_migration, :table_exists?
<ide>
<del> ActiveRecord::SchemaMigration.connection.transaction do
<del> ActiveRecord::SchemaMigration.create_table
<del> assert_predicate ActiveRecord::SchemaMigration, :table_exists?
<add> @schema_migration.connection.transaction do
<add> @schema_migration.create_table
<add> assert_predicate @schema_migration, :table_exists?
<ide>
<del> schema_migration = ActiveRecord::SchemaMigration.create!(version: "foo")
<del> assert_equal "foo", schema_migration[:version]
<add> assert_equal "foo", @schema_migration.create_version("foo")
<ide> raise ActiveRecord::Rollback
<ide> end
<ide>
<del> ActiveRecord::SchemaMigration.connection.transaction do
<del> ActiveRecord::SchemaMigration.create_table
<del> assert_predicate ActiveRecord::SchemaMigration, :table_exists?
<add> @schema_migration.connection.transaction do
<add> @schema_migration.create_table
<add> assert_predicate @schema_migration, :table_exists?
<ide>
<del> schema_migration = ActiveRecord::SchemaMigration.create!(version: "bar")
<del> assert_equal "bar", schema_migration[:version]
<add> assert_equal "bar", @schema_migration.create_version("bar")
<ide> raise ActiveRecord::Rollback
<ide> end
<ide> ensure
<del> ActiveRecord::SchemaMigration.create_table
<add> @schema_migration.create_table
<ide> end
<ide>
<ide> def test_proper_table_name_on_migration
<ide><path>activerecord/test/cases/migrator_test.rb
<ide> def setup
<ide> super
<ide> @schema_migration = ActiveRecord::Base.connection.schema_migration
<ide> @schema_migration.create_table
<del> @schema_migration.delete_all rescue nil
<add> @schema_migration.delete_all_versions rescue nil
<ide> @internal_metadata = ActiveRecord::Base.connection.internal_metadata
<ide> @verbose_was = ActiveRecord::Migration.verbose
<ide> ActiveRecord::Migration.message_count = 0
<ide> def puts(*)
<ide> end
<ide>
<ide> teardown do
<del> @schema_migration.delete_all rescue nil
<add> @schema_migration.delete_all_versions rescue nil
<ide> ActiveRecord::Migration.verbose = @verbose_was
<ide> ActiveRecord::Migration.class_eval do
<ide> undef :puts
<ide> def test_relative_migrations
<ide> end
<ide>
<ide> def test_finds_pending_migrations
<del> @schema_migration.create!(version: "1")
<add> @schema_migration.create_version("1")
<ide> migration_list = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)]
<ide> migrations = ActiveRecord::Migrator.new(:up, migration_list, @schema_migration, @internal_metadata).pending_migrations
<ide>
<ide> def test_migrations_status
<ide> path = MIGRATIONS_ROOT + "/valid"
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide>
<del> @schema_migration.create(version: 2)
<del> @schema_migration.create(version: 10)
<add> @schema_migration.create_version(2)
<add> @schema_migration.create_version(10)
<ide>
<ide> assert_equal [
<ide> ["down", "001", "Valid people have last names"],
<ide> def test_migrations_status_order_new_and_old_version
<ide> path = MIGRATIONS_ROOT + "/old_and_new_versions"
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide>
<del> @schema_migration.create(version: 230)
<del> @schema_migration.create(version: 231)
<del> @schema_migration.create(version: 20210716122844)
<del> @schema_migration.create(version: 20210716123013)
<add> @schema_migration.create_version(230)
<add> @schema_migration.create_version(231)
<add> @schema_migration.create_version(20210716122844)
<add> @schema_migration.create_version(20210716123013)
<ide>
<ide> assert_equal [
<ide> ["up", "230", "Add people hobby"],
<ide> def test_migrations_status_order_new_and_old_version_applied_out_of_order
<ide> path = MIGRATIONS_ROOT + "/old_and_new_versions"
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide>
<del> @schema_migration.create(version: 230)
<del> @schema_migration.create(version: 231)
<add> @schema_migration.create_version(230)
<add> @schema_migration.create_version(231)
<ide>
<ide> # "Apply" a newer migration and not an older to simulate out-of-order
<ide> # migration application which should not affect ordering in status and is
<ide> # possible if a branch is merged which contains a migration which has an
<ide> # earlier version but is judged to be compatible with existing migrations.
<del> @schema_migration.create(version: 20210716123013)
<add> @schema_migration.create_version(20210716123013)
<ide>
<ide> assert_equal [
<ide> ["up", "230", "Add people hobby"],
<ide> def test_migrations_status_in_subdirectories
<ide> path = MIGRATIONS_ROOT + "/valid_with_subdirectories"
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide>
<del> @schema_migration.create(version: 2)
<del> @schema_migration.create(version: 10)
<add> @schema_migration.create_version(2)
<add> @schema_migration.create_version(10)
<ide>
<ide> assert_equal [
<ide> ["down", "001", "Valid people have last names"],
<ide> def test_migrations_status_from_two_directories
<ide> paths = [MIGRATIONS_ROOT + "/valid_with_timestamps", MIGRATIONS_ROOT + "/to_copy_with_timestamps"]
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide>
<del> @schema_migration.create(version: "20100101010101")
<del> @schema_migration.create(version: "20160528010101")
<add> @schema_migration.create_version("20100101010101")
<add> @schema_migration.create_version("20160528010101")
<ide>
<ide> assert_equal [
<ide> ["down", "20090101010101", "People have hobbies"],
<ide> def test_down_calls_down
<ide> end
<ide>
<ide> def test_current_version
<del> @schema_migration.create!(version: "1000")
<add> @schema_migration.create_version("1000")
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide> migrator = ActiveRecord::MigrationContext.new("db/migrate", schema_migration)
<ide> assert_equal 1000, migrator.current_version
<ide> def test_migrator_output_when_running_single_migration
<ide>
<ide> result = migrator.run(:up, 1)
<ide>
<del> assert_equal(1, result.version)
<add> assert_equal("1", result)
<ide> end
<ide>
<ide> def test_migrator_rollback
<ide> def test_migrator_db_has_no_schema_migrations_table
<ide> _, migrator = migrator_class(3)
<ide> migrator = migrator.new("valid", schema_migration)
<ide>
<del> ActiveRecord::SchemaMigration.drop_table
<del> assert_not_predicate ActiveRecord::SchemaMigration, :table_exists?
<add> @schema_migration.drop_table
<add> assert_not_predicate @schema_migration, :table_exists?
<ide> migrator.migrate(1)
<del> assert_predicate ActiveRecord::SchemaMigration, :table_exists?
<add> assert_predicate @schema_migration, :table_exists?
<ide> end
<ide>
<ide> def test_migrator_forward
<ide> def test_migrator_forward
<ide>
<ide> def test_only_loads_pending_migrations
<ide> # migrate up to 1
<del> @schema_migration.create!(version: "1")
<add> @schema_migration.create_version("1")
<ide>
<ide> schema_migration = ActiveRecord::Base.connection.schema_migration
<ide> calls, migrator = migrator_class(3)
<ide><path>activerecord/test/cases/multi_db_migrator_test.rb
<ide> def setup
<ide> @connection_a.schema_migration.create_table
<ide> @connection_b.schema_migration.create_table
<ide>
<del> @connection_a.schema_migration.delete_all rescue nil
<del> @connection_b.schema_migration.delete_all rescue nil
<add> @connection_a.schema_migration.delete_all_versions rescue nil
<add> @connection_b.schema_migration.delete_all_versions rescue nil
<ide>
<ide> @path_a = MIGRATIONS_ROOT + "/valid"
<ide> @path_b = MIGRATIONS_ROOT + "/to_copy"
<ide> def puts(*)
<ide> end
<ide>
<ide> teardown do
<del> @connection_a.schema_migration.delete_all rescue nil
<del> @connection_b.schema_migration.delete_all rescue nil
<add> @connection_a.schema_migration.delete_all_versions rescue nil
<add> @connection_b.schema_migration.delete_all_versions rescue nil
<ide>
<ide> ActiveRecord::Migration.verbose = @verbose_was
<ide> ActiveRecord::Migration.class_eval do
<ide> def puts(*)
<ide> end
<ide> end
<ide>
<del> def test_schema_migration_class_names
<del> assert_equal "ActiveRecord::SchemaMigration", @schema_migration_a.name
<del> assert_equal "ARUnit2Model::SchemaMigration", @schema_migration_b.name
<add> def test_schema_migration_is_different_for_different_connections
<add> assert_not_equal @schema_migration_a, @schema_migration_b
<add> assert_not_equal @schema_migration_a.connection, @schema_migration_b.connection
<add> assert "ActiveRecord::Base", @schema_migration_a.connection.pool.pool_config.connection_name
<add> assert "Arunit2", @schema_migration_b.connection.pool.pool_config.connection_name
<ide> end
<ide>
<ide> def test_finds_migrations
<ide> def test_finds_migrations
<ide> end
<ide>
<ide> def test_migrations_status
<del> @schema_migration_a.create(version: 2)
<del> @schema_migration_a.create(version: 10)
<add> @schema_migration_a.create_version(2)
<add> @schema_migration_a.create_version(10)
<ide>
<ide> assert_equal [
<ide> ["down", "001", "Valid people have last names"],
<ide> def test_migrations_status
<ide> ["up", "010", "********** NO FILE **********"],
<ide> ], ActiveRecord::MigrationContext.new(@path_a, @schema_migration_a).migrations_status
<ide>
<del> @schema_migration_b.create(version: 4)
<add> @schema_migration_b.create_version(4)
<ide>
<ide> assert_equal [
<ide> ["down", "001", "People have hobbies"],
<ide> def test_get_all_versions
<ide> end
<ide>
<ide> def test_finds_pending_migrations
<del> @schema_migration_a.create!(version: "1")
<add> @schema_migration_a.create_version("1")
<ide> migration_list_a = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)]
<ide> migrations_a = ActiveRecord::Migrator.new(:up, migration_list_a, @schema_migration_a, @internal_metadata_a).pending_migrations
<ide>
<ide> assert_equal 1, migrations_a.size
<ide> assert_equal migration_list_a.last, migrations_a.first
<ide>
<del> @schema_migration_b.create!(version: "1")
<add> @schema_migration_b.create_version("1")
<ide> migration_list_b = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)]
<ide> migrations_b = ActiveRecord::Migrator.new(:up, migration_list_b, @schema_migration_b, @internal_metadata_b).pending_migrations
<ide>
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> class SchemaDumperTest < ActiveRecord::TestCase
<ide> self.use_transactional_tests = false
<ide>
<ide> setup do
<del> ActiveRecord::SchemaMigration.create_table
<add> @schema_migration = ActiveRecord::Base.connection.schema_migration
<add> @schema_migration.create_table
<ide> end
<ide>
<ide> def standard_dump
<ide> @@standard_dump ||= dump_all_table_schema
<ide> end
<ide>
<ide> def test_dump_schema_information_with_empty_versions
<del> ActiveRecord::SchemaMigration.delete_all
<add> @schema_migration.delete_all_versions
<ide> schema_info = ActiveRecord::Base.connection.dump_schema_information
<ide> assert_no_match(/INSERT INTO/, schema_info)
<ide> end
<ide>
<ide> def test_dump_schema_information_outputs_lexically_reverse_ordered_versions_regardless_of_database_order
<ide> versions = %w{ 20100101010101 20100201010101 20100301010101 }
<ide> versions.shuffle.each do |v|
<del> ActiveRecord::SchemaMigration.create!(version: v)
<add> @schema_migration.create_version(v)
<ide> end
<ide>
<ide> schema_info = ActiveRecord::Base.connection.dump_schema_information
<ide> def test_dump_schema_information_outputs_lexically_reverse_ordered_versions_rega
<ide> STR
<ide> assert_equal expected, schema_info
<ide> ensure
<del> ActiveRecord::SchemaMigration.delete_all
<add> @schema_migration.delete_all_versions
<ide> end
<ide>
<ide> def test_schema_dump_include_migration_version
<ide><path>activerecord/test/cases/tasks/database_tasks_test.rb
<ide> def test_migrate_using_empty_scope_and_verbose_mode
<ide> end
<ide>
<ide> class DatabaseTasksMigrateStatusTest < DatabaseTasksMigrationTestCase
<add> def setup
<add> @schema_migration = ActiveRecord::Base.connection.schema_migration
<add> end
<add>
<ide> def test_migrate_status_table
<del> ActiveRecord::SchemaMigration.create_table
<add> @schema_migration.create_table
<ide> output = capture_migration_status
<ide> assert_match(/database: :memory:/, output)
<ide> assert_match(/down 001 Valid people have last names/, output)
<ide> assert_match(/down 002 We need reminders/, output)
<ide> assert_match(/down 003 Innocent jointable/, output)
<del> ActiveRecord::SchemaMigration.drop_table
<add> @schema_migration.drop_table
<ide> end
<ide>
<ide> private
<ide> class DatabaseTasksTruncateAllTest < ActiveRecord::TestCase
<ide> fixtures :authors, :author_addresses
<ide>
<ide> def setup
<del> SchemaMigration.create_table
<del> SchemaMigration.create!(version: SchemaMigration.table_name)
<add> @schema_migration = ActiveRecord::Base.connection.schema_migration
<add> @schema_migration.create_table
<add> @schema_migration.create_version(@schema_migration.table_name)
<ide> InternalMetadata.create_table
<ide> InternalMetadata.create!(key: InternalMetadata.table_name)
<add> @old_configurations = ActiveRecord::Base.configurations
<ide> end
<ide>
<ide> def teardown
<del> SchemaMigration.delete_all
<add> @schema_migration.delete_all_versions
<ide> InternalMetadata.delete_all
<ide> clean_up_connection_handler
<add> ActiveRecord::Base.configurations = @old_configurations
<ide> end
<ide>
<ide> def test_truncate_tables
<del> assert_operator SchemaMigration.count, :>, 0
<add> assert_operator @schema_migration.count, :>, 0
<ide> assert_operator InternalMetadata.count, :>, 0
<ide> assert_operator Author.count, :>, 0
<ide> assert_operator AuthorAddress.count, :>, 0
<ide>
<del> old_configurations = ActiveRecord::Base.configurations
<ide> db_config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary")
<ide> configurations = { development: db_config.configuration_hash }
<ide> ActiveRecord::Base.configurations = configurations
<ide> def test_truncate_tables
<ide> )
<ide> end
<ide>
<del> assert_operator SchemaMigration.count, :>, 0
<add> assert_operator @schema_migration.count, :>, 0
<ide> assert_operator InternalMetadata.count, :>, 0
<ide> assert_equal 0, Author.count
<ide> assert_equal 0, AuthorAddress.count
<del> ensure
<del> ActiveRecord::Base.configurations = old_configurations
<ide> end
<ide> end
<ide>
<ide> class DatabaseTasksTruncateAllWithPrefixTest < DatabaseTasksTruncateAllTest
<ide> setup do
<ide> ActiveRecord::Base.table_name_prefix = "p_"
<ide>
<del> SchemaMigration.reset_table_name
<ide> InternalMetadata.reset_table_name
<ide> end
<ide>
<ide> teardown do
<ide> ActiveRecord::Base.table_name_prefix = nil
<ide>
<del> SchemaMigration.reset_table_name
<ide> InternalMetadata.reset_table_name
<ide> end
<ide> end
<ide> class DatabaseTasksTruncateAllWithSuffixTest < DatabaseTasksTruncateAllTest
<ide> setup do
<ide> ActiveRecord::Base.table_name_suffix = "_s"
<ide>
<del> SchemaMigration.reset_table_name
<ide> InternalMetadata.reset_table_name
<ide> end
<ide>
<ide> teardown do
<ide> ActiveRecord::Base.table_name_suffix = nil
<ide>
<del> SchemaMigration.reset_table_name
<ide> InternalMetadata.reset_table_name
<ide> end
<ide> end
<ide><path>railties/test/application/loading_test.rb
<ide> class Post < ApplicationRecord
<ide>
<ide> initial = [
<ide> ActiveStorage::Record, ActiveStorage::Blob, ActiveStorage::Attachment,
<del> ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata, ApplicationRecord
<add> ActiveRecord::InternalMetadata, ApplicationRecord
<ide> ].collect(&:to_s).sort
<ide>
<ide> assert_equal initial, ActiveRecord::Base.descendants.collect(&:to_s).sort.uniq
<ide> get "/load"
<ide> assert_equal [Post].collect(&:to_s).sort, ActiveRecord::Base.descendants.collect(&:to_s).sort - initial
<ide> get "/unload"
<del> assert_equal ["ActiveRecord::InternalMetadata", "ActiveRecord::SchemaMigration"], ActiveRecord::Base.descendants.collect(&:to_s).sort.uniq
<add> assert_equal ["ActiveRecord::InternalMetadata"], ActiveRecord::Base.descendants.collect(&:to_s).sort.uniq
<ide> end
<ide>
<ide> test "initialize can't be called twice" do
<ide><path>railties/test/railties/engine_test.rb
<ide> def boot_rails
<ide>
<ide> def migrations
<ide> migration_root = File.expand_path(ActiveRecord::Migrator.migrations_paths.first, app_path)
<del> ActiveRecord::MigrationContext.new(migration_root, ActiveRecord::SchemaMigration).migrations
<add> ActiveRecord::MigrationContext.new(migration_root, ActiveRecord::SchemaMigration::NullSchemaMigration.new).migrations
<ide> end
<ide>
<ide> test "serving sprocket's assets" do
| 20
|
Python
|
Python
|
add batch_dot to core.py layers
|
4e5348c5cab9842d8508375d3b6bf06b97d9db50
|
<ide><path>keras/layers/core.py
<ide> def get_output(self, train=False):
<ide> elif self.mode == 'dot':
<ide> l1 = self.layers[0].get_output(train)
<ide> l2 = self.layers[1].get_output(train)
<del> output = K.tensordot(l1, l2, self.dot_axes) # T.batched_tensordot(l1, l2, self.dot_axes)
<add> output = K.batch_dot(l1, l2, self.dot_axes)
<ide> output_shape = list(self.output_shape)
<ide> output_shape[0] = -1
<ide> output = K.reshape(output, (tuple(output_shape)))
<ide> return output
<ide> elif self.mode == 'cos':
<ide> l1 = self.layers[0].get_output(train)
<ide> l2 = self.layers[1].get_output(train)
<del> output = K.tensordot(l1, l2, self.dot_axes) / K.sqrt(
<del> K.tensordot(l1, l1, self.dot_axes) * K.tensordot(l2, l2, self.dot_axes))
<add> output = K.batch_dot(l1, l2, self.dot_axes) / K.sqrt(
<add> K.batch_dot(l1, l1, self.dot_axes) * K.batch_dot(l2, l2, self.dot_axes))
<ide> output = output.dimshuffle((0, 'x'))
<ide> return output
<ide> else:
<ide> def get_output_mul(self, train=False):
<ide> return s
<ide>
<ide> def get_output_dot(self, train=False):
<del> if K._BACKEND != 'theano':
<del> raise Exception('"dot" merge mode will only work with Theano.')
<del> from theano import tensor as T
<ide> l1 = self.get_output_at(0, train)
<ide> l2 = self.get_output_at(1, train)
<del> output = T.batched_tensordot(l1, l2, self.dot_axes)
<del> output = output.dimshuffle((0, 'x'))
<add> output = K.batch_dot(l1, l2, self.dot_axes)
<add> output = K.expand_dims(output, -1)
<ide> return output
<ide>
<ide> def get_output_cos(self, train=False):
<del> if K._BACKEND != 'theano':
<del> raise Exception('"cos" merge mode will only work with Theano.')
<del> import theano
<del> from theano import tensor as T
<ide> l1 = self.get_output_at(0, train)
<ide> l2 = self.get_output_at(1, train)
<del> output = T.batched_tensordot(l1, l2, self.dot_axes) / T.sqrt(T.batched_tensordot(l1, l1, self.dot_axes) * T.batched_tensordot(l2, l2, self.dot_axes))
<del> output = output.dimshuffle((0, 'x'))
<add> output = K.batch_dot(l1, l2, self.dot_axes) / K.sqrt(K.batch_dot(l1, l1, self.dot_axes) * K.batch_dot(l2, l2, self.dot_axes))
<add> output = K.expand_dims(output, -1)
<ide> return output
<ide>
<ide> def get_output(self, train=False):
| 1
|
Javascript
|
Javascript
|
fix tests for all timezones
|
331029bbc1c29f455c9604d7b20a0255f2940994
|
<ide><path>src/test/moment/now.js
<ide> test('now - custom value', function (assert) {
<ide>
<ide> try {
<ide> assert.ok(moment().toISOString() === CUSTOM_DATE, 'moment() constructor should use the function defined by moment.now, but it did not');
<del> assert.ok(moment([]).toISOString() === '2015-01-01T00:00:00.000Z', 'moment() constructor should fall back to the date defined by moment.now when an empty array is given, but it did not');
<add> assert.ok(moment.utc().toISOString() === CUSTOM_DATE, 'moment() constructor should use the function defined by moment.now, but it did not');
<ide> assert.ok(moment.utc([]).toISOString() === '2015-01-01T00:00:00.000Z', 'moment() constructor should fall back to the date defined by moment.now when an empty array is given, but it did not');
<ide> } finally {
<ide> moment.fn.now = oldFn;
| 1
|
Ruby
|
Ruby
|
match the whole string
|
d153355d35954e0e553d4b1b34db10a0ea7fa6a4
|
<ide><path>tasks/release.rb
<ide> abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed"
<ide> end
<ide>
<del> unless ENV['SKIP_TAG'] || `git tag | grep #{tag}`.strip.empty?
<add> unless ENV['SKIP_TAG'] || `git tag | grep '^#{tag}$`.strip.empty?
<ide> abort "[ABORTING] `git tag` shows that #{tag} already exists. Has this version already\n"\
<ide> " been released? Git tagging can be skipped by setting SKIP_TAG=1"
<ide> end
| 1
|
Mixed
|
Python
|
remove deprecated functions and update readme
|
e41999f846338f42f82b88dd8713b7fb9c95f377
|
<ide><path>compression/README.md
<ide> code for the following papers:
<ide>
<ide> ## Organization
<ide> [Image Encoder](image_encoder/): Encoding and decoding images into their binary representation.
<add>[Entropy Coder](entropy_coder/): Lossless compression of the binary representation.
<ide>
<ide> ## Contact Info
<ide> Model repository maintained by Nick Johnston ([nickj-google](https://github.com/nickj-google)).
<ide><path>compression/entropy_coder/README.md
<ide> the width of the binary codes,
<ide> sliced into N groups of K, where each additional group is used by the image
<ide> decoder to add more details to the reconstructed image.
<ide>
<add>The code in this directory only contains the underlying code probability model
<add>but does not perform the actual compression using arithmetic coding.
<add>The code probability model is enough to compute the theoretical compression
<add>ratio.
<add>
<ide>
<ide> ## Prerequisites
<ide> The only software requirements for running the encoder and decoder is having
<ide> Tensorflow installed.
<ide> You will also need to add the top level source directory of the entropy coder
<ide> to your `PYTHONPATH`, for example:
<ide>
<del>`export PYTHONPATH=${PYTHONPATH}:/tmp/compression/entropy_coder`
<add>`export PYTHONPATH=${PYTHONPATH}:/tmp/models/compression`
<ide>
<ide>
<ide> ## Training the entropy coder
<ide> less.
<ide>
<ide> To generate a synthetic dataset with 20000 samples:
<ide>
<add>`mkdir -p /tmp/dataset`
<add>
<ide> `python ./dataset/gen_synthetic_dataset.py --dataset_dir=/tmp/dataset/
<ide> --count=20000`
<ide>
<ide><path>compression/entropy_coder/core/entropy_coder_train.py
<ide> def train():
<ide> decay_steps=decay_steps,
<ide> decay_rate=decay_rate,
<ide> staircase=True)
<del> tf.contrib.deprecated.scalar_summary('Learning Rate', learning_rate)
<add> tf.summary.scalar('Learning Rate', learning_rate)
<ide> optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate,
<ide> epsilon=1.0)
<ide>
<ide><path>compression/entropy_coder/progressive/progressive.py
<ide> def BuildGraph(self, input_codes):
<ide> code_length.append(code_length_block(
<ide> blocks.ConvertSignCodeToZeroOneCode(x),
<ide> blocks.ConvertSignCodeToZeroOneCode(predicted_x)))
<del> tf.contrib.deprecated.scalar_summary('code_length_layer_{:02d}'.format(k),
<del> code_length[-1])
<add> tf.summary.scalar('code_length_layer_{:02d}'.format(k), code_length[-1])
<ide> code_length = tf.stack(code_length)
<ide> self.loss = tf.reduce_mean(code_length)
<del> tf.contrib.deprecated.scalar_summary('loss', self.loss)
<add> tf.summary.scalar('loss', self.loss)
<ide>
<ide> # Loop over all the remaining layers just to make sure they are
<ide> # instantiated. Otherwise, loading model params could fail.
| 4
|
Go
|
Go
|
follow symlink for --device argument
|
7ed569efdc822811cdac3b398a16757a54fbe4c4
|
<ide><path>daemon/container_operations_unix.go
<ide> func killProcessDirectly(container *container.Container) error {
<ide> }
<ide>
<ide> func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []*configs.Device, err error) {
<del> device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
<add> resolvedPathOnHost := deviceMapping.PathOnHost
<add>
<add> // check if it is a symbolic link
<add> if src, e := os.Lstat(deviceMapping.PathOnHost); e == nil && src.Mode()&os.ModeSymlink == os.ModeSymlink {
<add> if linkedPathOnHost, e := os.Readlink(deviceMapping.PathOnHost); e == nil {
<add> resolvedPathOnHost = linkedPathOnHost
<add> }
<add> }
<add>
<add> device, err := devices.DeviceFromPath(resolvedPathOnHost, deviceMapping.CgroupPermissions)
<ide> // if there was no error, return the device
<ide> if err == nil {
<ide> device.Path = deviceMapping.PathInContainer
<ide> func getDevicesFromPath(deviceMapping containertypes.DeviceMapping) (devs []*con
<ide> if err == devices.ErrNotADevice {
<ide>
<ide> // check if it is a directory
<del> if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
<add> if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() {
<ide>
<ide> // mount the internal devices recursively
<del> filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
<add> filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error {
<ide> childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
<ide> if e != nil {
<ide> // ignore the device
<ide> return nil
<ide> }
<ide>
<ide> // add the device to userSpecified devices
<del> childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
<add> childDevice.Path = strings.Replace(dpath, resolvedPathOnHost, deviceMapping.PathInContainer, 1)
<ide> devs = append(devs, childDevice)
<ide>
<ide> return nil
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
<ide> c.Assert(err, checker.NotNil, check.Commentf(out))
<ide> c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
<ide> }
<add>
<add>// TestRunDeviceSymlink checks run with device that follows symlink (#13840)
<add>func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
<add> testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
<add> if _, err := os.Stat("/dev/zero"); err != nil {
<add> c.Skip("Host does not have /dev/zero")
<add> }
<add>
<add> // Create a temporary directory to create symlink
<add> tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
<add> c.Assert(err, checker.IsNil)
<add>
<add> defer os.RemoveAll(tmpDir)
<add>
<add> // Create a symbolic link to /dev/zero
<add> symZero := filepath.Join(tmpDir, "zero")
<add> err = os.Symlink("/dev/zero", symZero)
<add> c.Assert(err, checker.IsNil)
<add>
<add> // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
<add> // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
<add> tmpFile := filepath.Join(tmpDir, "temp")
<add> err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
<add> c.Assert(err, checker.IsNil)
<add> symFile := filepath.Join(tmpDir, "file")
<add> err = os.Symlink(tmpFile, symFile)
<add> c.Assert(err, checker.IsNil)
<add>
<add> // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
<add> out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
<add> c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
<add>
<add> // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
<add> out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
<add> c.Assert(err, check.NotNil)
<add> c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
<add>}
| 2
|
PHP
|
PHP
|
add missing citext type mapping
|
618eeebeb6f78a2c19d567dc7e5e71732ef397ab
|
<ide><path>src/Illuminate/Database/Console/DatabaseInspectionCommand.php
<ide> abstract class DatabaseInspectionCommand extends Command
<ide> */
<ide> protected $typeMappings = [
<ide> 'bit' => 'string',
<add> 'citext' => 'string',
<ide> 'enum' => 'string',
<ide> 'geometry' => 'string',
<ide> 'geomcollection' => 'string',
| 1
|
PHP
|
PHP
|
fix duplicate column errors in isunique rules
|
14dfc65fc9ab9cbb97a8f806bf9a81ff58b76a43
|
<ide><path>src/ORM/Rule/IsUnique.php
<ide> public function __invoke(EntityInterface $entity, array $options)
<ide> return true;
<ide> }
<ide>
<del> $conditions = $entity->extract($this->_fields);
<add> $alias = $options['repository']->alias();
<add> $conditions = $this->_alias($alias, $entity->extract($this->_fields));
<ide> if ($entity->isNew() === false) {
<ide> $keys = (array)$options['repository']->primaryKey();
<del> $keys = $entity->extract($keys);
<add> $keys = $this->_alias($alias, $entity->extract($keys));
<ide> if (array_filter($keys, 'strlen')) {
<ide> $conditions['NOT'] = $keys;
<ide> }
<ide> }
<ide>
<ide> return !$options['repository']->exists($conditions);
<ide> }
<add>
<add> /**
<add> * Add a model alias to all the keys in a set of conditions.
<add> *
<add> * @param string $alias The alias to add.
<add> * @param array $conditions The conditions to alias.
<add> * @return array
<add> */
<add> protected function _alias($alias, $conditions)
<add> {
<add> $aliased = [];
<add> foreach ($conditions as $key => $value) {
<add> $aliased["$alias.$key"] = $value;
<add> }
<add> return $aliased;
<add> }
<ide> }
<ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php
<ide> public function testIsUniqueWithCleanFields()
<ide> $this->assertFalse($table->save($entity));
<ide> }
<ide>
<add> /**
<add> * Tests the existsIn with coflicting columns
<add> *
<add> * @group save
<add> * @return void
<add> */
<add> public function testExistsInAliasPrefix()
<add> {
<add> $entity = new Entity([
<add> 'title' => 'An Article',
<add> 'author_id' => 1
<add> ]);
<add>
<add> $table = TableRegistry::get('Articles');
<add> $table->belongsTo('Authors');
<add> $rules = $table->rulesChecker();
<add> $rules->add($rules->isUnique(['author_id']));
<add>
<add> $table->Authors->eventManager()->on('Model.beforeFind', function ($event, $query) {
<add> $query->leftJoin(['a2' => 'authors']);
<add> });
<add>
<add> $this->assertFalse($table->save($entity));
<add> $this->assertEquals(['_isUnique' => 'This value is already in use'], $entity->errors('author_id'));
<add> }
<add>
<ide> /**
<ide> * Tests the existsIn rule when passing non dirty fields
<ide> *
| 2
|
Javascript
|
Javascript
|
add test to contextreplacemntplugin
|
405a4aef27ece5357ed730518f5531ee18947fa8
|
<ide><path>test/ContextReplacementPlugin.test.js
<add>"use strict";
<add>
<add>const should = require("should");
<add>const sinon = require("sinon");
<add>const ContextReplacementPlugin = require("../lib/ContextReplacementPlugin");
<add>const applyPluginWithOptions = require("./helpers/applyPluginWithOptions");
<add>const PluginEnvironment = require("./helpers/PluginEnvironment");
<add>
<add>describe("ContextReplacementPlugin", () => {
<add> it("has apply function", () => (new ContextReplacementPlugin()).apply.should.be.a.Function());
<add>
<add> it("should consume resourceRegExp as regular expression", ()=> {
<add> let instance = new ContextReplacementPlugin(/selector/, "mock", "mock", "mock");
<add> should(instance.resourceRegExp instanceof RegExp).be.exactly(true);
<add> });
<add>
<add> it("should consume newContentResource as function", ()=> {
<add> let instance = new ContextReplacementPlugin(/selector/, ()=>{}, "mock", "mock");
<add> should(instance.newContentCallback).be.a.Function();
<add> });
<add>
<add> it("should consume newContentResource as not an string or function", ()=> {
<add> let instance = new ContextReplacementPlugin(/selector/, 42, "newContentRecursive", "newContentRegExp");
<add>
<add> should(instance.resourceRegExp instanceof RegExp).be.exactly(true);
<add> should(instance.newContentResource).be.exactly(undefined);
<add> should(instance.newContentRecursive).be.exactly(undefined);
<add> should(instance.newContentRegExp).be.exactly(42);
<add> });
<add>
<add> it("should consume newContentResource as an object", ()=> {
<add> let instance = new ContextReplacementPlugin(/selector/, "newResource", { test: "obj"}, /selector/);
<add>
<add> should(instance.resourceRegExp instanceof RegExp).be.exactly(true);
<add> should(instance.newContentResource).be.exactly("newResource");
<add> should(instance.newContentRecursive).be.exactly(undefined);
<add> should(instance.newContentRegExp).be.exactly(undefined);
<add> should(instance.newContentCreateContextMap).be.a.Function();
<add>
<add> let x = (nothing, obj) => {
<add> should(obj.test).be.exactly("obj")
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> instance.newContentCreateContextMap(undefined, spy);
<add>
<add> should(spy.called).be.exactly(true)
<add>
<add> });
<add>
<add> it("should consume newContentResource as an object", ()=> {
<add> let instance = new ContextReplacementPlugin(/selector/, "newResource", ()=>{}, /selector/);
<add>
<add> should(instance.resourceRegExp instanceof RegExp).be.exactly(true);
<add> should(instance.newContentResource).be.exactly("newResource");
<add> should(instance.newContentRecursive).be.exactly(undefined);
<add> should(instance.newContentRegExp).be.exactly(undefined);
<add> should(instance.newContentCreateContextMap).be.a.Function();
<add> });
<add>
<add> describe("when applied", ()=> {
<add>
<add> describe("when before resolve is called", ()=> {
<add> it("default call", () => {
<add> let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> should(result.request).be.exactly('./folder')
<add> should(result.dependencies[0].critical).be.exactly(false )
<add> should(result.recursive).be.exactly(true)
<add> should(result.regExp instanceof RegExp).be.exactly(true)
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.beforeResolve.handler({
<add> request: "selector",
<add> dependencies: [
<add> {critical: true}
<add> ]
<add> }, spy)
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add>
<add> it("default call with newContentCallback as a function", () => {
<add> let obj = buildPluginWithParams(/selector/, (result) => {
<add> should(result.request).be.exactly('selector')
<add> should(result.dependencies[0].critical).be.exactly(false )
<add> should(result.recursive).be.exactly(undefined)
<add> should(result.regExp).be.exactly(undefined)
<add> }, true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> should(result.request).be.exactly('selector')
<add> should(result.dependencies[0].critical).be.exactly(false )
<add> should(result.recursive).be.exactly(undefined)
<add> should(result.regExp).be.exactly(undefined)
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.beforeResolve.handler({
<add> request: "selector",
<add> dependencies: [
<add> {critical: false}
<add> ]
<add> }, spy)
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add>
<add> it("call when result is false", () => {
<add> let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> should(result).be.Undefined();
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.beforeResolve.handler(false, spy);
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add> });
<add>
<add> describe("when after resolve is called", ()=> {
<add> it("default call where regex is correct", () => {
<add> let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> result.resource.should.containEql('/selector/folder')
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.afterResolve.handler({
<add> resource: "selector",
<add> dependencies: [
<add> {critical: true}
<add> ]
<add> }, spy)
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add>
<add> it("default call where regex is incorrect", () => {
<add> let obj = buildPluginWithParams(/selector/, "./folder", true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> result.resource.should.containEql('importwontwork')
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.afterResolve.handler({
<add> resource: "importwontwork",
<add> dependencies: [
<add> {critical: true}
<add> ]
<add> }, spy)
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add>
<add> it("default call where regex is correct", () => {
<add> let obj = buildPluginWithParams(/selector/,(result) => {
<add> //noop
<add> }, true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> result.resource.should.equal('selector')
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.afterResolve.handler({
<add> resource: "selector",
<add> dependencies: [
<add> {critical: true}
<add> ]
<add> }, spy)
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add>
<add> it("default call where regex is correct", () => {
<add> let obj = buildPluginWithParams(/selector/,(result) => {
<add> result.resource = "imadifferentselector"
<add> }, true, /filter/);
<add>
<add> let x = (nothing, result) => {
<add> result.resource.should.containEql('selector/imadifferentselector')
<add> } ;
<add>
<add> let spy = sinon.spy(x);
<add>
<add> obj.afterResolve.handler({
<add> resource: "selector",
<add> dependencies: [
<add> {critical: true}
<add> ]
<add> }, spy)
<add>
<add> should(spy.called).be.exactly(true)
<add> });
<add>
<add> })
<add>
<add> });
<add>});
<add>
<add>let buildPluginWithParams = (resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) => {
<add> let instance = new ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp);
<add>
<add> let pluginEnvironment = new PluginEnvironment();
<add> instance.apply(pluginEnvironment.getEnvironmentStub());
<add>
<add> let contextModuleFactory = pluginEnvironment.getEventBindings()[0];
<add> pluginEnvironment.getEventBindings().length.should.be.exactly(1)
<add>
<add> let contextModuleFactoryPluginEnv = new PluginEnvironment();
<add>
<add> contextModuleFactory.handler(contextModuleFactoryPluginEnv.getEnvironmentStub());
<add>
<add> let contextModuleFactoryEventBindings = contextModuleFactoryPluginEnv.getEventBindings();
<add> contextModuleFactoryPluginEnv.getEventBindings().length.should.be.exactly(2);
<add>
<add> let beforeResolve = contextModuleFactoryEventBindings[0];
<add> let afterResolve = contextModuleFactoryEventBindings[1];
<add>
<add> return {
<add> contextModuleFactory,
<add> beforeResolve,
<add> afterResolve
<add> }
<add>};
<ide>\ No newline at end of file
| 1
|
Javascript
|
Javascript
|
use encodeuriquery instead of escape
|
7e1f364177111ba6cceac82f6c6bcc254448292b
|
<ide><path>src/Angular.js
<ide> function parseKeyValue(/**string*/keyValue) {
<ide> forEach((keyValue || "").split('&'), function(keyValue){
<ide> if (keyValue) {
<ide> key_value = keyValue.split('=');
<del> key = unescape(key_value[0]);
<del> obj[key] = isDefined(key_value[1]) ? unescape(key_value[1]) : true;
<add> key = decodeURIComponent(key_value[0]);
<add> obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
<ide> }
<ide> });
<ide> return obj;
<ide> function parseKeyValue(/**string*/keyValue) {
<ide> function toKeyValue(obj) {
<ide> var parts = [];
<ide> forEach(obj, function(value, key) {
<del> parts.push(escape(key) + (value === true ? '' : '=' + escape(value)));
<add> parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
<ide> });
<ide> return parts.length ? parts.join('&') : '';
<ide> }
<ide><path>src/service/location.js
<ide> LocationUrl.prototype = LocationHashbangUrl.prototype = {
<ide> if (paramValue === null) {
<ide> delete this.$$search[search];
<ide> } else {
<del> this.$$search[search] = escape(paramValue);
<add> this.$$search[search] = encodeUriQuery(paramValue);
<ide> }
<ide> } else {
<ide> this.$$search = isString(search) ? parseKeyValue(search) : search;
| 2
|
Ruby
|
Ruby
|
shorten troubleshooting url
|
b89123d487673df623ebbba8aac61b29d2f9470f
|
<ide><path>Library/Homebrew/os.rb
<ide> def self.linux?
<ide> end
<ide>
<ide> if OS.mac?
<del> ISSUES_URL = "https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/Troubleshooting.md#troubleshooting"
<add> ISSUES_URL = "http://git.io/brew-troubleshooting"
<ide> PATH_OPEN = "/usr/bin/open"
<ide> elsif OS.linux?
<ide> ISSUES_URL = "https://github.com/Homebrew/linuxbrew/wiki/troubleshooting"
| 1
|
Javascript
|
Javascript
|
add /auth paths to whitelist
|
933e2896172ec09e58ef3ee5c8e6ffd57dec3dcd
|
<ide><path>api-server/server/middlewares/request-authorization.js
<ide> import { jwtSecret as _jwtSecret } from '../../../config/secrets';
<ide>
<ide> import { wrapHandledError } from '../utils/create-handled-error';
<ide>
<add>const authRE = /^\/auth\//;
<ide> const newsShortLinksRE = /^\/n\/|^\/p\//;
<add>const resubscribeRE = /^\/resubscribe\//;
<ide> const showCertRE = /^\/certificate\/showCert\//;
<del>const updatePaypalRE = /^\/donate\/update-paypal/;
<del>// signin may not have a trailing slash
<add>// note: signin may not have a trailing slash
<ide> const signinRE = /^\/signin/;
<del>const unsubscribeRE = /^\/u\/|^\/unsubscribe\/|^\/ue\//;
<ide> const unsubscribedRE = /^\/unsubscribed\//;
<del>const resubscribeRE = /^\/resubscribe\//;
<add>const unsubscribeRE = /^\/u\/|^\/unsubscribe\/|^\/ue\//;
<add>const updatePaypalRE = /^\/donate\/update-paypal/;
<ide>
<ide> const _whiteListREs = [
<add> authRE,
<ide> newsShortLinksRE,
<add> resubscribeRE,
<ide> showCertRE,
<del> updatePaypalRE,
<ide> signinRE,
<del> unsubscribeRE,
<ide> unsubscribedRE,
<del> resubscribeRE
<add> unsubscribeRE,
<add> updatePaypalRE
<ide> ];
<ide>
<ide> export function isWhiteListedPath(path, whiteListREs = _whiteListREs) {
<ide><path>api-server/server/middlewares/request-authorization.test.js
<ide> const mockGetUserById = id =>
<ide>
<ide> describe('request-authorization', () => {
<ide> describe('isWhiteListedPath', () => {
<del> const whiteList = [/^\/is-ok\//, /^\/this-is\/also\/ok\//];
<add> const authRE = /^\/auth\//;
<add> const newsShortLinksRE = /^\/n\/|^\/p\//;
<add> const resubscribeRE = /^\/resubscribe\//;
<add> const showCertRE = /^\/certificate\/showCert\//;
<add> // note: signin may not have a trailing slash
<add> const signinRE = /^\/signin/;
<add> const unsubscribedRE = /^\/unsubscribed\//;
<add> const unsubscribeRE = /^\/u\/|^\/unsubscribe\/|^\/ue\//;
<add> const updatePaypalRE = /^\/donate\/update-paypal/;
<add>
<add> const whiteList = [
<add> authRE,
<add> newsShortLinksRE,
<add> resubscribeRE,
<add> showCertRE,
<add> signinRE,
<add> unsubscribedRE,
<add> unsubscribeRE,
<add> updatePaypalRE
<add> ];
<ide>
<ide> it('returns a boolean', () => {
<ide> const result = isWhiteListedPath();
<ide> describe('request-authorization', () => {
<ide> it('returns true for a white listed path', () => {
<ide> expect.assertions(2);
<ide>
<del> const resultA = isWhiteListedPath('/is-ok/should-be/good', whiteList);
<del> const resultB = isWhiteListedPath('/this-is/also/ok/surely', whiteList);
<add> const resultA = isWhiteListedPath(
<add> '/auth/auth0/callback?code=yF_mGjswLsef-_RLo',
<add> whiteList
<add> );
<add> const resultB = isWhiteListedPath('/ue/WmjInLerysPrcon6fMb/', whiteList);
<ide> expect(resultA).toBe(true);
<ide> expect(resultB).toBe(true);
<ide> });
<ide>
<ide> it('returns false for a non-white-listed path', () => {
<del> const result = isWhiteListedPath('/hax0r-42/no-go', whiteList);
<del> expect(result).toBe(false);
<add> const resultA = isWhiteListedPath('/hax0r-42/no-go', whiteList);
<add> const resultB = isWhiteListedPath('/update-current-challenge', whiteList);
<add> expect(resultA).toBe(false);
<add> expect(resultB).toBe(false);
<ide> });
<ide> });
<ide>
| 2
|
Javascript
|
Javascript
|
build esm target first.
|
efba1d0b0150d6fc4987273de0f9fb29275b35f7
|
<ide><path>utils/build/rollup.config.js
<ide> ${ code }`;
<ide> }
<ide>
<ide> export default [
<add> {
<add> input: 'src/Three.js',
<add> plugins: [
<add> addons(),
<add> glconstants(),
<add> glsl(),
<add> header()
<add> ],
<add> output: [
<add> {
<add> format: 'esm',
<add> file: 'build/three.module.js'
<add> }
<add> ]
<add> },
<ide> {
<ide> input: 'src/Three.js',
<ide> plugins: [
<ide> export default [
<ide> file: 'build/three.min.js'
<ide> }
<ide> ]
<del> },
<del> {
<del> input: 'src/Three.js',
<del> plugins: [
<del> addons(),
<del> glconstants(),
<del> glsl(),
<del> header()
<del> ],
<del> output: [
<del> {
<del> format: 'esm',
<del> file: 'build/three.module.js'
<del> }
<del> ]
<ide> }
<ide> ];
| 1
|
Javascript
|
Javascript
|
update quaternionkeyframetrack inheritance
|
319f2156a699f3bde9d70ebb6b2cff3b74639971
|
<ide><path>src/animation/tracks/QuaternionKeyframeTrack.js
<ide> import { InterpolateLinear } from '../../constants.js';
<del>import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype.js';
<add>import { KeyframeTrack } from '../KeyframeTrack.js';
<ide> import { QuaternionLinearInterpolant } from '../../math/interpolants/QuaternionLinearInterpolant.js';
<del>import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js';
<ide>
<ide> /**
<ide> *
<ide> import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js';
<ide>
<ide> function QuaternionKeyframeTrack( name, times, values, interpolation ) {
<ide>
<del> KeyframeTrackConstructor.call( this, name, times, values, interpolation );
<add> KeyframeTrack.call( this, name, times, values, interpolation );
<ide>
<ide> }
<ide>
<del>QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrackPrototype ), {
<add>QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
<ide>
<ide> constructor: QuaternionKeyframeTrack,
<ide>
| 1
|
Go
|
Go
|
fix a bad assumption
|
fff605c3b3557acf6bf793813d695fba59d7fa21
|
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunEnvironment(c *check.C) {
<ide> })
<ide> result.Assert(c, icmd.Success)
<ide>
<del> actualEnv := strings.Split(strings.TrimSpace(result.Combined()), "\n")
<add> actualEnv := strings.Split(strings.TrimSuffix(result.Stdout(), "\n"), "\n")
<ide> sort.Strings(actualEnv)
<ide>
<ide> goodEnv := []string{
| 1
|
Text
|
Text
|
simplify urlobject.hash description
|
458c2bbb8f0192269c07109b0181300095085bbf
|
<ide><path>doc/api/url.md
<ide> For example: `'user:pass'`.
<ide> #### urlObject.hash
<ide>
<ide> The `hash` property consists of the "fragment" portion of the URL including
<del>the leading ASCII hash (`#`) character.
<add>the leading `#` character.
<ide>
<ide> For example: `'#hash'`.
<ide>
| 1
|
PHP
|
PHP
|
fix cs error
|
392117e551dc6023f3255865ce95352036dcdb07
|
<ide><path>src/View/Helper/HtmlHelper.php
<ide> public function script($url, array $options = array()) {
<ide> }
<ide> $this->_includedAssets[__METHOD__][$url] = true;
<ide>
<del>
<ide> $out = $this->formatTemplate('javascriptlink', [
<ide> 'url' => $url,
<ide> 'attrs' => $this->templater()->formatAttributes($options, ['block', 'once']),
| 1
|
Python
|
Python
|
fix provide_batch_fn for semi-supervised case
|
703dc8d769cdde1c8d178b33eee25b006c326955
|
<ide><path>domain_adaptation/domain_separation/dsn_train.py
<ide> def main(_):
<ide> if FLAGS.target_labeled_dataset != 'none':
<ide> # 1000 is the maximum number of labelled target samples that exists in
<ide> # the datasets.
<del> target_semi_images, target_semi_labels = data_provider.provide(
<add> target_semi_images, target_semi_labels = provide_batch_fn()(
<ide> FLAGS.target_labeled_dataset, 'train', FLAGS.batch_size)
<ide>
<ide> # Calculate the proportion of source domain samples in the semi-
| 1
|
Javascript
|
Javascript
|
remove view tests
|
44a299b5cc777acdaf65a2035a950186bb7a7be2
|
<ide><path>packages/ember/tests/routing/basic_test.js
<ide> QUnit.test('Model passed via renderTemplate model is set as controller\'s model'
<ide> equal(jQuery('p:contains(emberjs)', '#qunit-fixture').length, 1, 'Passed model was set as controllers model');
<ide> });
<ide>
<del>test('Renders correct view with slash notation', function() {
<del> setTemplate('home/page', compile('<p>{{view.name}}</p>'));
<del>
<del> Router.map(function() {
<del> this.route('home', { path: '/' });
<del> });
<del>
<del> App.HomeRoute = Route.extend({
<del> renderTemplate() {
<del> this.render('home/page');
<del> }
<del> });
<del>
<del> App.HomePageView = EmberView.extend({
<del> name: 'Home/Page'
<del> });
<del>
<del> bootApplication();
<del>
<del> equal(jQuery('p:contains(Home/Page)', '#qunit-fixture').length, 1, 'The homepage template was rendered');
<del>});
<del>
<del>test('Renders the view given in the view option', function() {
<del> setTemplate('home', compile('<p>{{view.name}}</p>'));
<del>
<del> Router.map(function() {
<del> this.route('home', { path: '/' });
<del> });
<del>
<del> App.HomeRoute = Route.extend({
<del> renderTemplate() {
<del> this.render({ view: 'homePage' });
<del> }
<del> });
<del>
<del> App.HomePageView = EmberView.extend({
<del> name: 'Home/Page'
<del> });
<del>
<del> bootApplication();
<del>
<del> equal(jQuery('p:contains(Home/Page)', '#qunit-fixture').length, 1, 'The homepage view was rendered');
<del>});
<del>
<del>test('render does not replace templateName if user provided', function() {
<del> Router.map(function() {
<del> this.route('home', { path: '/' });
<del> });
<del>
<del> setTemplate('the_real_home_template', compile(
<del> '<p>THIS IS THE REAL HOME</p>'
<del> ));
<del>
<del> App.HomeView = EmberView.extend({
<del> templateName: 'the_real_home_template'
<del> });
<del> App.HomeController = Controller.extend();
<del> App.HomeRoute = Route.extend();
<del>
<del> bootApplication();
<del>
<del> equal(jQuery('p', '#qunit-fixture').text(), 'THIS IS THE REAL HOME', 'The homepage template was rendered');
<del>});
<del>
<del>test('render does not replace template if user provided', function () {
<del> Router.map(function () {
<del> this.route('home', { path: '/' });
<del> });
<del>
<del> App.HomeView = EmberView.extend({
<del> template: compile('<p>THIS IS THE REAL HOME</p>')
<del> });
<del> App.HomeController = Controller.extend();
<del> App.HomeRoute = Route.extend();
<del>
<del> bootApplication();
<del>
<del> run(function () {
<del> router.handleURL('/');
<del> });
<del>
<del> equal(jQuery('p', '#qunit-fixture').text(), 'THIS IS THE REAL HOME', 'The homepage template was rendered');
<del>});
<del>
<ide> QUnit.test('render uses templateName from route', function() {
<ide> Router.map(function() {
<ide> this.route('home', { path: '/' });
| 1
|
Javascript
|
Javascript
|
fix race in test-http2-origin
|
985c5f5b7e079689211649f19097617075a19a42
|
<ide><path>test/parallel/test-http2-origin.js
<ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary');
<ide> ['https://example.org', 'https://example.com']
<ide> ];
<ide>
<del> const countdown = new Countdown(2, () => {
<add> const countdown = new Countdown(3, () => {
<ide> client.close();
<ide> server.close();
<ide> });
<ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary');
<ide> countdown.dec();
<ide> }, 2));
<ide>
<del> client.request().on('close', mustCall()).resume();
<add> client.request().on('close', mustCall(() => countdown.dec())).resume();
<ide> }));
<ide> }
<ide>
<ide> const ca = readKey('fake-startcom-root-cert.pem', 'binary');
<ide> const originSet = [`https://localhost:${server.address().port}`];
<ide> const client = connect(originSet[0], { ca });
<ide>
<add> const countdown = new Countdown(2, () => {
<add> client.close();
<add> server.close();
<add> });
<add>
<ide> client.on('origin', mustCall((origins) => {
<ide> originSet.push(...check);
<ide> deepStrictEqual(client.originSet, originSet);
<ide> deepStrictEqual(origins, check);
<del> client.close();
<del> server.close();
<add> countdown.dec();
<ide> }));
<ide>
<del> client.request().on('close', mustCall()).resume();
<add> client.request().on('close', mustCall(() => countdown.dec())).resume();
<ide> }));
<ide> }
<ide>
| 1
|
Python
|
Python
|
support spacy-legacy via the registry
|
a203e3dbb8ae3c202f4f24d2bcceed7ed7568b15
|
<ide><path>spacy/errors.py
<ide> class Errors:
<ide> "issue tracker: http://github.com/explosion/spaCy/issues")
<ide>
<ide> # TODO: fix numbering after merging develop into master
<add> E893 = ("Could not find function '{name}' in function registry '{reg_name}'. "
<add> "If you're using a custom function, make sure the code is available. "
<add> "If the function is provided by a third-party package, e.g. "
<add> "spacy-transformers, make sure the package is installed in your "
<add> "environment.\n\nAvailable names: {available}")
<add> E894 = ("Unknown function registry: '{name}'.")
<ide> E895 = ("The 'textcat' component received gold-standard annotations with "
<ide> "multiple labels per document. In spaCy 3 you should use the "
<ide> "'textcat_multilabel' component for this instead. "
<ide><path>spacy/ml/models/textcat.py
<ide> from thinc.api import Model, reduce_mean, Linear, list2ragged, Logistic
<ide> from thinc.api import chain, concatenate, clone, Dropout, ParametricAttention
<ide> from thinc.api import SparseLinear, Softmax, softmax_activation, Maxout, reduce_sum
<del>from thinc.api import HashEmbed, with_array, with_cpu, uniqued
<del>from thinc.api import Relu, residual, expand_window
<add>from thinc.api import with_cpu, Relu, residual
<ide> from thinc.layers.chain import init as init_chain
<ide>
<del>from ...attrs import ID, ORTH, PREFIX, SUFFIX, SHAPE, LOWER
<add>from ...attrs import ORTH
<ide> from ...util import registry
<ide> from ..extract_ngrams import extract_ngrams
<ide> from ..staticvectors import StaticVectors
<del>from ..featureextractor import FeatureExtractor
<ide> from ...tokens import Doc
<ide> from .tok2vec import get_tok2vec_width
<ide>
<ide> def init_ensemble_textcat(model, X, Y) -> Model:
<ide> return model
<ide>
<ide>
<del># TODO: move to legacy
<del>@registry.architectures.register("spacy.TextCatEnsemble.v1")
<del>def build_text_classifier_v1(
<del> width: int,
<del> embed_size: int,
<del> pretrained_vectors: Optional[bool],
<del> exclusive_classes: bool,
<del> ngram_size: int,
<del> window_size: int,
<del> conv_depth: int,
<del> dropout: Optional[float],
<del> nO: Optional[int] = None,
<del>) -> Model:
<del> # Don't document this yet, I'm not sure it's right.
<del> cols = [ORTH, LOWER, PREFIX, SUFFIX, SHAPE, ID]
<del> with Model.define_operators({">>": chain, "|": concatenate, "**": clone}):
<del> lower = HashEmbed(
<del> nO=width, nV=embed_size, column=cols.index(LOWER), dropout=dropout, seed=10
<del> )
<del> prefix = HashEmbed(
<del> nO=width // 2,
<del> nV=embed_size,
<del> column=cols.index(PREFIX),
<del> dropout=dropout,
<del> seed=11,
<del> )
<del> suffix = HashEmbed(
<del> nO=width // 2,
<del> nV=embed_size,
<del> column=cols.index(SUFFIX),
<del> dropout=dropout,
<del> seed=12,
<del> )
<del> shape = HashEmbed(
<del> nO=width // 2,
<del> nV=embed_size,
<del> column=cols.index(SHAPE),
<del> dropout=dropout,
<del> seed=13,
<del> )
<del> width_nI = sum(layer.get_dim("nO") for layer in [lower, prefix, suffix, shape])
<del> trained_vectors = FeatureExtractor(cols) >> with_array(
<del> uniqued(
<del> (lower | prefix | suffix | shape)
<del> >> Maxout(nO=width, nI=width_nI, normalize=True),
<del> column=cols.index(ORTH),
<del> )
<del> )
<del> if pretrained_vectors:
<del> static_vectors = StaticVectors(width)
<del> vector_layer = trained_vectors | static_vectors
<del> vectors_width = width * 2
<del> else:
<del> vector_layer = trained_vectors
<del> vectors_width = width
<del> tok2vec = vector_layer >> with_array(
<del> Maxout(width, vectors_width, normalize=True)
<del> >> residual(
<del> (
<del> expand_window(window_size=window_size)
<del> >> Maxout(
<del> nO=width, nI=width * ((window_size * 2) + 1), normalize=True
<del> )
<del> )
<del> )
<del> ** conv_depth,
<del> pad=conv_depth,
<del> )
<del> cnn_model = (
<del> tok2vec
<del> >> list2ragged()
<del> >> ParametricAttention(width)
<del> >> reduce_sum()
<del> >> residual(Maxout(nO=width, nI=width))
<del> >> Linear(nO=nO, nI=width)
<del> >> Dropout(0.0)
<del> )
<del>
<del> linear_model = build_bow_text_classifier(
<del> nO=nO,
<del> ngram_size=ngram_size,
<del> exclusive_classes=exclusive_classes,
<del> no_output_layer=False,
<del> )
<del> nO_double = nO * 2 if nO else None
<del> if exclusive_classes:
<del> output_layer = Softmax(nO=nO, nI=nO_double)
<del> else:
<del> output_layer = Linear(nO=nO, nI=nO_double) >> Dropout(0.0) >> Logistic()
<del> model = (linear_model | cnn_model) >> output_layer
<del> model.set_ref("tok2vec", tok2vec)
<del> if model.has_dim("nO") is not False:
<del> model.set_dim("nO", nO)
<del> model.set_ref("output_layer", linear_model.get_ref("output_layer"))
<del> model.attrs["multi_label"] = not exclusive_classes
<del> return model
<del>
<del>
<ide> @registry.architectures.register("spacy.TextCatLowData.v1")
<ide> def build_text_classifier_lowdata(
<ide> width: int, dropout: Optional[float], nO: Optional[int] = None
<ide><path>spacy/ml/models/tok2vec.py
<ide> def build_hash_embed_cnn_tok2vec(
<ide> )
<ide>
<ide>
<del># TODO: archive
<del>@registry.architectures.register("spacy.Tok2Vec.v1")
<del>def _build_Tok2Vec_model(
<del> embed: Model[List[Doc], List[Floats2d]],
<del> encode: Model[List[Floats2d], List[Floats2d]],
<del>) -> Model[List[Doc], List[Floats2d]]:
<del> """Construct a tok2vec model out of embedding and encoding subnetworks.
<del> See https://explosion.ai/blog/deep-learning-formula-nlp
<del>
<del> embed (Model[List[Doc], List[Floats2d]]): Embed tokens into context-independent
<del> word vector representations.
<del> encode (Model[List[Floats2d], List[Floats2d]]): Encode context into the
<del> embeddings, using an architecture such as a CNN, BiLSTM or transformer.
<del> """
<del> receptive_field = encode.attrs.get("receptive_field", 0)
<del> tok2vec = chain(embed, with_array(encode, pad=receptive_field))
<del> tok2vec.set_dim("nO", encode.get_dim("nO"))
<del> tok2vec.set_ref("embed", embed)
<del> tok2vec.set_ref("encode", encode)
<del> return tok2vec
<del>
<del>
<ide> @registry.architectures.register("spacy.Tok2Vec.v2")
<ide> def build_Tok2Vec_model(
<ide> embed: Model[List[Doc], List[Floats2d]],
<ide> def CharacterEmbed(
<ide> return model
<ide>
<ide>
<del># TODO: archive
<del>@registry.architectures.register("spacy.MaxoutWindowEncoder.v1")
<del>def _MaxoutWindowEncoder(
<del> width: int, window_size: int, maxout_pieces: int, depth: int
<del>) -> Model[List[Floats2d], List[Floats2d]]:
<del> """Encode context using convolutions with maxout activation, layer
<del> normalization and residual connections.
<del>
<del> width (int): The input and output width. These are required to be the same,
<del> to allow residual connections. This value will be determined by the
<del> width of the inputs. Recommended values are between 64 and 300.
<del> window_size (int): The number of words to concatenate around each token
<del> to construct the convolution. Recommended value is 1.
<del> maxout_pieces (int): The number of maxout pieces to use. Recommended
<del> values are 2 or 3.
<del> depth (int): The number of convolutional layers. Recommended value is 4.
<del> """
<del> cnn = chain(
<del> expand_window(window_size=window_size),
<del> Maxout(
<del> nO=width,
<del> nI=width * ((window_size * 2) + 1),
<del> nP=maxout_pieces,
<del> dropout=0.0,
<del> normalize=True,
<del> ),
<del> )
<del> model = clone(residual(cnn), depth)
<del> model.set_dim("nO", width)
<del> model.attrs["receptive_field"] = window_size * depth
<del> return model
<del>
<del>
<ide> @registry.architectures.register("spacy.MaxoutWindowEncoder.v2")
<ide> def MaxoutWindowEncoder(
<ide> width: int, window_size: int, maxout_pieces: int, depth: int
<ide> def MaxoutWindowEncoder(
<ide> return with_array(model, pad=receptive_field)
<ide>
<ide>
<del># TODO: archive
<del>@registry.architectures.register("spacy.MishWindowEncoder.v1")
<del>def _MishWindowEncoder(
<del> width: int, window_size: int, depth: int
<del>) -> Model[List[Floats2d], List[Floats2d]]:
<del> """Encode context using convolutions with mish activation, layer
<del> normalization and residual connections.
<del>
<del> width (int): The input and output width. These are required to be the same,
<del> to allow residual connections. This value will be determined by the
<del> width of the inputs. Recommended values are between 64 and 300.
<del> window_size (int): The number of words to concatenate around each token
<del> to construct the convolution. Recommended value is 1.
<del> depth (int): The number of convolutional layers. Recommended value is 4.
<del> """
<del> cnn = chain(
<del> expand_window(window_size=window_size),
<del> Mish(nO=width, nI=width * ((window_size * 2) + 1), dropout=0.0, normalize=True),
<del> )
<del> model = clone(residual(cnn), depth)
<del> model.set_dim("nO", width)
<del> return model
<del>
<del>
<ide> @registry.architectures.register("spacy.MishWindowEncoder.v2")
<ide> def MishWindowEncoder(
<ide> width: int, window_size: int, depth: int
<ide><path>spacy/util.py
<ide> class registry(thinc.registry):
<ide> models = catalogue.create("spacy", "models", entry_points=True)
<ide> cli = catalogue.create("spacy", "cli", entry_points=True)
<ide>
<add> @classmethod
<add> def get(cls, registry_name: str, func_name: str) -> Callable:
<add> """Get a registered function from the registry."""
<add> # We're overwriting this classmethod so we're able to provide more
<add> # specific error messages and implement a fallback to spacy-legacy.
<add> if not hasattr(cls, registry_name):
<add> raise ValueError(Errors.E894.format(name=registry_name))
<add> reg = getattr(cls, registry_name)
<add> try:
<add> func = reg.get(func_name)
<add> except catalogue.RegistryError:
<add> if func_name.startswith("spacy."):
<add> legacy_name = func_name.replace("spacy.", "spacy-legacy.")
<add> try:
<add> return reg.get(legacy_name)
<add> except catalogue.RegistryError:
<add> pass
<add> available = ", ".join(sorted(reg.get_all().keys())) or "none"
<add> raise ValueError(
<add> Errors.E893.format(
<add> name=func_name, reg_name=registry_name, available=available
<add> )
<add> ) from None
<add> return func
<add>
<add> @classmethod
<add> def has(cls, registry_name: str, func_name: str) -> bool:
<add> """Check whether a function is available in a registry."""
<add> if not hasattr(cls, registry_name):
<add> return False
<add> reg = getattr(cls, registry_name)
<add> if func_name.startswith("spacy."):
<add> legacy_name = func_name.replace("spacy.", "spacy-legacy.")
<add> return func_name in reg or legacy_name in reg
<add> return func_name in reg
<add>
<ide>
<ide> class SimpleFrozenDict(dict):
<ide> """Simplified implementation of a frozen dict, mainly used as default
| 4
|
PHP
|
PHP
|
add distinct pagination test
|
6a1981a9ee5799cb220ac1aa7256fa3a36c0a4bd
|
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testGetPaginationCountGetsResultCount()
<ide> }
<ide>
<ide>
<add> public function testGetPaginationCountGetsResultCountWithSelectDistinct()
<add> {
<add> unset($_SERVER['orders']);
<add> $builder = $this->getBuilder();
<add> $builder->getConnection()->shouldReceive('select')->once()->with('select count(distinct "foo", "bar") as aggregate from "users"', array())->andReturn(array(array('aggregate' => 1)));
<add> $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($query, $results)
<add> {
<add> $_SERVER['orders'] = $query->orders;
<add> return $results;
<add> });
<add> $results = $builder->distinct()->select('foo', 'bar')->from('users')->orderBy('foo', 'desc')->getPaginationCount();
<add>
<add> $this->assertNull($_SERVER['orders']);
<add> unset($_SERVER['orders']);
<add>
<add> $this->assertEquals(array('foo', 'bar'), $builder->columns);
<add> $this->assertEquals(array(0 => array('column' => 'foo', 'direction' => 'desc')), $builder->orders);
<add> $this->assertEquals(1, $results);
<add> }
<add>
<add>
<ide> public function testPluckMethodReturnsSingleColumn()
<ide> {
<ide> $builder = $this->getBuilder();
| 1
|
Python
|
Python
|
add test utils and get_doc helper function
|
909f24d7df2ad1cde8232051297c6688d5ca33d9
|
<ide><path>spacy/tests/util.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>from ..tokens import Doc
<add>from ..attrs import ORTH, POS, HEAD, DEP
<add>
<add>
<add>def get_doc(vocab, words, tags=None, heads=None, deps=None):
<add> """Create Doc object from given vocab, words and annotations."""
<add> tags = tags or [''] * len(words)
<add> heads = heads or [0] * len(words)
<add> deps = deps or [''] * len(words)
<add>
<add> doc = Doc(vocab, words=words)
<add> attrs = doc.to_array([POS, HEAD, DEP])
<add> for i, (tag, head, dep) in enumerate(zip(tags, heads, deps)):
<add> attrs[i, 0] = doc.vocab.strings[tag]
<add> attrs[i, 1] = head
<add> attrs[i, 2] = doc.vocab.strings[dep]
<add> doc.from_array([POS, HEAD, DEP], attrs)
<add> return doc
| 1
|
Ruby
|
Ruby
|
modify #find_versions url usage
|
d7a26cd6d33163c61cd28ef39bd06a555e7a6c34
|
<ide><path>Library/Homebrew/cask/cask.rb
<ide> class Cask
<ide>
<ide> attr_reader :token, :sourcefile_path, :source, :config, :default_config
<ide>
<del> attr_accessor :download
<add> attr_accessor :download, :allow_reassignment
<ide>
<ide> def self.all
<ide> Tap.flat_map(&:cask_files).map do |f|
<ide> def tap
<ide> @tap
<ide> end
<ide>
<del> def initialize(token, sourcefile_path: nil, source: nil, tap: nil, config: nil, &block)
<add> def initialize(token, sourcefile_path: nil, source: nil, tap: nil, config: nil, allow_reassignment: false, &block)
<ide> @token = token
<ide> @sourcefile_path = sourcefile_path
<ide> @source = source
<ide> @tap = tap
<add> @allow_reassignment = allow_reassignment
<ide> @block = block
<ide>
<ide> @default_config = config || Config.new
<ide><path>Library/Homebrew/cask/dsl.rb
<ide> def desc(description = nil)
<ide> def set_unique_stanza(stanza, should_return)
<ide> return instance_variable_get("@#{stanza}") if should_return
<ide>
<del> if instance_variable_defined?("@#{stanza}")
<add> if !@cask.allow_reassignment && instance_variable_defined?("@#{stanza}")
<ide> raise CaskInvalidError.new(cask, "'#{stanza}' stanza may only appear once.")
<ide> end
<ide>
<ide> def language(*args, default: false, &block)
<ide>
<ide> return unless default
<ide>
<del> unless @language_blocks.default.nil?
<add> if !@cask.allow_reassignment && @language_blocks.default.present?
<ide> raise CaskInvalidError.new(cask, "Only one default language may be defined.")
<ide> end
<ide>
<ide> def livecheck(&block)
<ide> @livecheck ||= Livecheck.new(self)
<ide> return @livecheck unless block
<ide>
<del> raise CaskInvalidError.new(cask, "'livecheck' stanza may only appear once.") if @livecheckable
<add> if !@cask.allow_reassignment && @livecheckable
<add> raise CaskInvalidError.new(cask, "'livecheck' stanza may only appear once.")
<add> end
<ide>
<ide> @livecheckable = true
<ide> @livecheck.instance_eval(&block)
<ide><path>Library/Homebrew/livecheck/strategy/extract_plist.rb
<ide> def self.find_versions(cask:, url: nil, regex: nil, **_unused, &block)
<ide>
<ide> match_data = { matches: {}, regex: regex, url: url }
<ide>
<del> if url && url != cask.url.to_s
<del> cask_object_for_livecheck = Cask::Cask.new("livecheck-cask", config: cask.config) do
<del> url url.to_s
<del> end
<del>
<del> unversioned_cask_checker = UnversionedCaskChecker.new(cask, livecheck_url: cask_object_for_livecheck)
<add> unversioned_cask_checker = if url.present? && url != cask.url.to_s
<add> # Create a copy of the `cask` that uses the `livecheck` block URL
<add> cask_copy = Cask::CaskLoader.load(cask.full_name)
<add> cask_copy.allow_reassignment = true
<add> cask_copy.url { url }
<add> UnversionedCaskChecker.new(cask_copy)
<ide> else
<del> unversioned_cask_checker = UnversionedCaskChecker.new(cask)
<add> UnversionedCaskChecker.new(cask)
<ide> end
<ide>
<ide> items = unversioned_cask_checker.all_versions.transform_values { |v| Item.new(bundle_version: v) }
<ide><path>Library/Homebrew/unversioned_cask_checker.rb
<ide> class UnversionedCaskChecker
<ide>
<ide> sig { returns(Cask::Cask) }
<ide> attr_reader :cask
<del> attr_reader :livecheck_url
<ide>
<del> sig { params(cask: Cask::Cask, livecheck_url: T.nilable(Cask::Cask)).void }
<del> def initialize(cask, livecheck_url: nil)
<add> sig { params(cask: Cask::Cask).void }
<add> def initialize(cask)
<ide> @cask = cask
<del> @livecheck_url = livecheck_url
<ide> end
<ide>
<ide> sig { returns(Cask::Installer) }
<ide> def installer
<del> @installer ||= if livecheck_url
<del> Cask::Installer.new(livecheck_url, verify_download_integrity: false)
<del> else
<del> Cask::Installer.new(cask, verify_download_integrity: false)
<del> end
<add> @installer ||= Cask::Installer.new(cask, verify_download_integrity: false)
<ide> end
<ide>
<ide> sig { returns(T::Array[Cask::Artifact::App]) }
| 4
|
Ruby
|
Ruby
|
add fix for loading fixtures in engine tests
|
0176aef1ebaa9f69001c7045a51727a8ea9b61b8
|
<ide><path>railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
<ide> # Load fixtures from the engine
<ide> if ActiveSupport::TestCase.respond_to?(:fixture_path=)
<ide> ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
<add> ActiveSupport::TestCase.fixtures :all
<ide> end
| 1
|
Text
|
Text
|
improve unusual phrasing
|
90fa884f94424ad0af3e28b1ad8b8c75b120b3de
|
<ide><path>README.md
<ide> the browser how to do dependency injection and inversion of control.
<ide>
<ide> Oh yeah and it helps with server-side communication, taming async callbacks with promises and
<ide> deferreds. It also makes client-side navigation and deeplinking with hashbang urls or HTML5 pushState a
<del>piece of cake. The best of all: it makes development fun!
<add>piece of cake. Best of all?? It makes development fun!
<ide>
<ide> * Web site: http://angularjs.org
<ide> * Tutorial: http://docs.angularjs.org/tutorial
| 1
|
PHP
|
PHP
|
fix double encoding in debug()
|
52010a3e9d9f0b734036722368a5f879237ad451
|
<ide><path>lib/Cake/Utility/Debugger.php
<ide> protected static function _export($var, $depth, $indent) {
<ide> if (trim($var) == '') {
<ide> return "''";
<ide> }
<del> return "'" . h($var) . "'";
<add> return "'" . $var . "'";
<ide> break;
<ide> case 'array':
<ide> return self::_array($var, $depth - 1, $indent + 1);
| 1
|
Javascript
|
Javascript
|
check endless loop while writing empty string
|
16facd7ef48b9d43af02009524983b05901dc26b
|
<ide><path>test/parallel/test-http2-client-write-empty-string.js
<add>'use strict';
<add>
<add>const assert = require('assert');
<add>const http2 = require('http2');
<add>
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>for (const chunkSequence of [
<add> [ '' ],
<add> [ '', '' ]
<add>]) {
<add> const server = http2.createServer();
<add> server.on('stream', common.mustCall((stream, headers, flags) => {
<add> stream.respond({ 'content-type': 'text/html' });
<add>
<add> let data = '';
<add> stream.on('data', common.mustNotCall((chunk) => {
<add> data += chunk.toString();
<add> }));
<add> stream.on('end', common.mustCall(() => {
<add> stream.end(`"${data}"`);
<add> }));
<add> }));
<add>
<add> server.listen(0, common.mustCall(() => {
<add> const port = server.address().port;
<add> const client = http2.connect(`http://localhost:${port}`);
<add>
<add> const req = client.request({
<add> ':method': 'POST',
<add> ':path': '/'
<add> });
<add>
<add> req.on('response', common.mustCall((headers) => {
<add> assert.strictEqual(headers[':status'], 200);
<add> assert.strictEqual(headers['content-type'], 'text/html');
<add> }));
<add>
<add> let data = '';
<add> req.setEncoding('utf8');
<add> req.on('data', common.mustCallAtLeast((d) => data += d));
<add> req.on('end', common.mustCall(() => {
<add> assert.strictEqual(data, '""');
<add> server.close();
<add> client.close();
<add> }));
<add>
<add> for (const chunk of chunkSequence)
<add> req.write(chunk);
<add> req.end();
<add> }));
<add>}
| 1
|
Javascript
|
Javascript
|
implement websockets based on-demand-entries ping
|
af07611a632311eeeac3360bfef6190ef2ddb72f
|
<ide><path>packages/next/client/on-demand-entries-client.js
<del>/* global location */
<add>/* global location, WebSocket */
<ide>
<ide> import Router from 'next/router'
<ide> import fetch from 'unfetch'
<ide>
<del>export default ({assetPrefix}) => {
<add>const { hostname } = location
<add>const retryTime = 5000
<add>let ws = null
<add>let lastHref = null
<add>
<add>export default async ({ assetPrefix }) => {
<ide> Router.ready(() => {
<ide> Router.events.on('routeChangeComplete', ping)
<ide> })
<ide>
<del> async function ping () {
<del> try {
<del> const url = `${assetPrefix || ''}/_next/on-demand-entries-ping?page=${Router.pathname}`
<del> const res = await fetch(url, {
<del> credentials: 'same-origin'
<del> })
<del> const payload = await res.json()
<del> if (payload.invalid) {
<del> // Payload can be invalid even if the page is not exists.
<del> // So, we need to make sure it's exists before reloading.
<del> const pageRes = await fetch(location.href, {
<del> credentials: 'same-origin'
<del> })
<del> if (pageRes.status === 200) {
<del> location.reload()
<add> const setup = async (reconnect) => {
<add> if (ws && ws.readyState === ws.OPEN) {
<add> return Promise.resolve()
<add> }
<add>
<add> return new Promise(resolve => {
<add> ws = new WebSocket(`ws://${hostname}:${process.env.NEXT_WS_PORT}`)
<add> ws.onopen = () => resolve()
<add> ws.onclose = () => {
<add> setTimeout(async () => {
<add> // check if next restarted and we have to reload to get new port
<add> await fetch(`${assetPrefix}/_next/on-demand-entries-ping`)
<add> .then(res => res.status === 200 && location.reload())
<add> .catch(() => {})
<add> await setup(true)
<add> resolve()
<add> }, retryTime)
<add> }
<add> ws.onmessage = async ({ data }) => {
<add> const payload = JSON.parse(data)
<add> if (payload.invalid && lastHref !== location.href) {
<add> // Payload can be invalid even if the page does not exist.
<add> // So, we need to make sure it exists before reloading.
<add> const pageRes = await fetch(location.href, {
<add> credentials: 'omit'
<add> })
<add> if (pageRes.status === 200) {
<add> location.reload()
<add> } else {
<add> lastHref = location.href
<add> }
<ide> }
<ide> }
<del> } catch (err) {
<del> console.error(`Error with on-demand-entries-ping: ${err.message}`)
<add> })
<add> }
<add> await setup()
<add>
<add> async function ping () {
<add> if (ws.readyState === ws.OPEN) {
<add> ws.send(Router.pathname)
<ide> }
<ide> }
<ide>
<ide> export default ({assetPrefix}) => {
<ide> // at this point.
<ide> while (!document.hidden) {
<ide> await ping()
<del> await new Promise((resolve) => {
<add> await new Promise(resolve => {
<ide> pingerTimeout = setTimeout(resolve, 5000)
<ide> })
<ide> }
<ide> }
<ide>
<del> document.addEventListener('visibilitychange', () => {
<del> if (!document.hidden) {
<del> runPinger()
<del> } else {
<del> clearTimeout(pingerTimeout)
<del> }
<del> }, false)
<add> document.addEventListener(
<add> 'visibilitychange',
<add> () => {
<add> if (!document.hidden) {
<add> runPinger()
<add> } else {
<add> clearTimeout(pingerTimeout)
<add> }
<add> },
<add> false
<add> )
<ide>
<ide> setTimeout(() => {
<del> runPinger()
<del> .catch((err) => {
<del> console.error(err)
<del> })
<add> runPinger().catch(err => {
<add> console.error(err)
<add> })
<ide> }, 10000)
<ide> }
<ide><path>packages/next/server/hot-reloader.js
<ide> import errorOverlayMiddleware from './lib/error-overlay-middleware'
<ide> import del from 'del'
<ide> import onDemandEntryHandler, {normalizePage} from './on-demand-entry-handler'
<ide> import webpack from 'webpack'
<add>import WebSocket from 'ws'
<ide> import getBaseWebpackConfig from '../build/webpack-config'
<ide> import {IS_BUNDLED_PAGE_REGEX, ROUTE_NAME_REGEX, BLOCKED_PAGES, CLIENT_STATIC_FILES_PATH} from 'next-server/constants'
<ide> import {route} from 'next-server/dist/server/router'
<ide> export default class HotReloader {
<ide> return del(join(this.dir, this.config.distDir), { force: true })
<ide> }
<ide>
<add> addWsPort (configs) {
<add> configs[0].plugins.push(new webpack.DefinePlugin({
<add> 'process.env.NEXT_WS_PORT': this.wsPort
<add> }))
<add> }
<add>
<ide> async start () {
<ide> await this.clean()
<ide>
<add> await new Promise(resolve => {
<add> // create dynamic entries WebSocket
<add> this.wss = new WebSocket.Server({ port: 0 }, () => {
<add> this.wsPort = this.wss.address().port
<add> resolve()
<add> })
<add> })
<add>
<ide> const configs = await Promise.all([
<ide> getBaseWebpackConfig(this.dir, { dev: true, isServer: false, config: this.config, buildId: this.buildId }),
<ide> getBaseWebpackConfig(this.dir, { dev: true, isServer: true, config: this.config, buildId: this.buildId })
<ide> ])
<add> this.addWsPort(configs)
<ide>
<ide> const multiCompiler = webpack(configs)
<ide>
<ide> export default class HotReloader {
<ide> }
<ide>
<ide> async stop (webpackDevMiddleware) {
<add> this.wss.close()
<ide> const middleware = webpackDevMiddleware || this.webpackDevMiddleware
<ide> if (middleware) {
<ide> return new Promise((resolve, reject) => {
<ide> export default class HotReloader {
<ide> getBaseWebpackConfig(this.dir, { dev: true, isServer: false, config: this.config, buildId: this.buildId }),
<ide> getBaseWebpackConfig(this.dir, { dev: true, isServer: true, config: this.config, buildId: this.buildId })
<ide> ])
<add> this.addWsPort(configs)
<ide>
<ide> const compiler = webpack(configs)
<ide>
<ide> export default class HotReloader {
<ide> this.webpackDevMiddleware = webpackDevMiddleware
<ide> this.webpackHotMiddleware = webpackHotMiddleware
<ide> this.onDemandEntries = onDemandEntries
<add> this.wss.on('connection', this.onDemandEntries.wsConnection)
<ide> this.middlewares = [
<ide> webpackDevMiddleware,
<ide> webpackHotMiddleware,
<ide> export default class HotReloader {
<ide> dev: true,
<ide> reload: this.reload.bind(this),
<ide> pageExtensions: this.config.pageExtensions,
<add> wsPort: this.wsPort,
<ide> ...this.config.onDemandEntries
<ide> })
<ide>
<ide><path>packages/next/server/on-demand-entry-handler.js
<ide> import DynamicEntryPlugin from 'webpack/lib/DynamicEntryPlugin'
<ide> import { EventEmitter } from 'events'
<ide> import { join } from 'path'
<del>import { parse } from 'url'
<ide> import fs from 'fs'
<ide> import promisify from '../lib/promisify'
<ide> import globModule from 'glob'
<ide> export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
<ide> reload,
<ide> pageExtensions,
<ide> maxInactiveAge = 1000 * 60,
<del> pagesBufferLength = 2
<add> pagesBufferLength = 2,
<add> wsPort
<ide> }) {
<ide> const {compilers} = multiCompiler
<ide> const invalidator = new Invalidator(devMiddleware, multiCompiler)
<ide> export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
<ide> })
<ide> },
<ide>
<add> wsConnection (ws) {
<add> ws.onmessage = ({ data }) => {
<add> const page = normalizePage(data)
<add> const entryInfo = entries[page]
<add>
<add> // If there's no entry.
<add> // Then it seems like an weird issue.
<add> if (!entryInfo) {
<add> const message = `Client pings, but there's no entry for page: ${page}`
<add> console.error(message)
<add> return sendJson(ws, { invalid: true })
<add> }
<add>
<add> sendJson(ws, { success: true })
<add>
<add> // We don't need to maintain active state of anything other than BUILT entries
<add> if (entryInfo.status !== BUILT) return
<add>
<add> // If there's an entryInfo
<add> if (!lastAccessPages.includes(page)) {
<add> lastAccessPages.unshift(page)
<add>
<add> // Maintain the buffer max length
<add> if (lastAccessPages.length > pagesBufferLength) {
<add> lastAccessPages.pop()
<add> }
<add> }
<add> entryInfo.lastActiveTime = Date.now()
<add> }
<add> },
<add>
<ide> middleware () {
<ide> return (req, res, next) => {
<ide> if (stopped) {
<ide> export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
<ide> } else {
<ide> if (!/^\/_next\/on-demand-entries-ping/.test(req.url)) return next()
<ide>
<del> const { query } = parse(req.url, true)
<del> const page = normalizePage(query.page)
<del> const entryInfo = entries[page]
<del>
<del> // If there's no entry.
<del> // Then it seems like an weird issue.
<del> if (!entryInfo) {
<del> const message = `Client pings, but there's no entry for page: ${page}`
<del> console.error(message)
<del> sendJson(res, { invalid: true })
<del> return
<del> }
<del>
<del> sendJson(res, { success: true })
<del>
<del> // We don't need to maintain active state of anything other than BUILT entries
<del> if (entryInfo.status !== BUILT) return
<del>
<del> // If there's an entryInfo
<del> if (!lastAccessPages.includes(page)) {
<del> lastAccessPages.unshift(page)
<del>
<del> // Maintain the buffer max length
<del> if (lastAccessPages.length > pagesBufferLength) lastAccessPages.pop()
<del> }
<del> entryInfo.lastActiveTime = Date.now()
<add> res.statusCode = 200
<add> res.setHeader('port', wsPort)
<add> res.end('200')
<ide> }
<ide> }
<ide> }
<ide> export function normalizePage (page) {
<ide> return unixPagePath.replace(/\/index$/, '')
<ide> }
<ide>
<del>function sendJson (res, payload) {
<del> res.setHeader('Content-Type', 'application/json')
<del> res.status = 200
<del> res.end(JSON.stringify(payload))
<add>function sendJson (ws, data) {
<add> ws.send(JSON.stringify(data))
<ide> }
<ide>
<ide> // Make sure only one invalidation happens at a time
<ide><path>test/integration/ondemand/test/index.test.js
<ide> import { join, resolve } from 'path'
<ide> import { existsSync } from 'fs'
<ide> import webdriver from 'next-webdriver'
<add>import WebSocket from 'ws'
<ide> import {
<ide> renderViaHTTP,
<add> fetchViaHTTP,
<ide> findPort,
<ide> launchApp,
<ide> killApp,
<ide> import {
<ide>
<ide> const context = {}
<ide>
<add>const doPing = path => {
<add> return new Promise(resolve => {
<add> context.ws.onmessage = () => resolve()
<add> context.ws.send(path)
<add> })
<add>}
<add>
<ide> jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
<ide>
<ide> describe('On Demand Entries', () => {
<ide> it('should pass', () => {})
<ide> beforeAll(async () => {
<ide> context.appPort = await findPort()
<ide> context.server = await launchApp(join(__dirname, '../'), context.appPort)
<add> await new Promise(resolve => {
<add> fetchViaHTTP(context.appPort, '/_next/on-demand-entries-ping').then(res => {
<add> const wsPort = res.headers.get('port')
<add> context.ws = new WebSocket(
<add> `ws://localhost:${wsPort}`
<add> )
<add> context.ws.on('open', () => resolve())
<add> })
<add> })
<add> })
<add> afterAll(() => {
<add> context.ws.close()
<add> killApp(context.server)
<ide> })
<del> afterAll(() => killApp(context.server))
<ide>
<ide> it('should compile pages for SSR', async () => {
<ide> // The buffer of built page uses the on-demand-entries-ping to know which pages should be
<ide> // buffered. Therefore, we need to double each render call with a ping.
<ide> const pageContent = await renderViaHTTP(context.appPort, '/')
<del> await renderViaHTTP(context.appPort, '/_next/on-demand-entries-ping', {page: '/'})
<add> await doPing('/')
<ide> expect(pageContent.includes('Index Page')).toBeTruthy()
<ide> })
<ide>
<ide> it('should compile pages for JSON page requests', async () => {
<del> const pageContent = await renderViaHTTP(context.appPort, '/_next/static/development/pages/about.js')
<add> const pageContent = await renderViaHTTP(
<add> context.appPort,
<add> '/_next/static/development/pages/about.js'
<add> )
<ide> expect(pageContent.includes('About Page')).toBeTruthy()
<ide> })
<ide>
<ide> describe('On Demand Entries', () => {
<ide>
<ide> // Render two pages after the index, since the server keeps at least two pages
<ide> await renderViaHTTP(context.appPort, '/about')
<del> await renderViaHTTP(context.appPort, '/_next/on-demand-entries-ping', {page: '/about'})
<add> await doPing('/about')
<ide> const aboutPagePath = resolve(__dirname, '../.next/static/development/pages/about.js')
<ide>
<ide> await renderViaHTTP(context.appPort, '/third')
<del> await renderViaHTTP(context.appPort, '/_next/on-demand-entries-ping', {page: '/third'})
<add> await doPing('/third')
<ide> const thirdPagePath = resolve(__dirname, '../.next/static/development/pages/third.js')
<ide>
<ide> // Wait maximum of jasmine.DEFAULT_TIMEOUT_INTERVAL checking
| 4
|
Ruby
|
Ruby
|
use fetch rather than []
|
6e4a01c70ab0579acab10f3f6489fa8f3480be8d
|
<ide><path>Library/Homebrew/cmd/--env.rb
<ide> def build_env_keys env
<ide> HOMEBREW_USE_GCC HOMEBREW_USE_LLVM HOMEBREW_SVN HOMEBREW_GIT
<ide> HOMEBREW_SDKROOT
<ide> MAKE GIT CPP
<del> ACLOCAL_PATH OBJC PATH ].select{ |key| env[key] }
<add> ACLOCAL_PATH OBJC PATH ].select{ |key| env.fetch(key) if env.key? key }
<ide> end
<ide>
<ide> def dump_build_env env
| 1
|
Python
|
Python
|
improve messages in project cli [ci skip]
|
6316d5f3989a53e4868cd346256fa614bd49e711
|
<ide><path>spacy/cli/project/assets.py
<ide> def project_assets(project_dir: Path, *, sparse_checkout: bool = False) -> None:
<ide> branch=asset["git"].get("branch"),
<ide> sparse=sparse_checkout,
<ide> )
<add> msg.good(f"Downloaded asset {dest}")
<ide> else:
<ide> url = asset.get("url")
<ide> if not url:
<ide><path>spacy/cli/project/run.py
<ide> def project_run(
<ide> for dep in cmd.get("deps", []):
<ide> if not (project_dir / dep).exists():
<ide> err = f"Missing dependency specified by command '{subcommand}': {dep}"
<del> err_help = "Maybe you forgot to run the 'project assets' command?"
<add> err_help = "Maybe you forgot to run the 'project assets' command or a previous step?"
<ide> err_kwargs = {"exits": 1} if not dry else {}
<ide> msg.fail(err, err_help, **err_kwargs)
<ide> with working_dir(project_dir) as current_dir:
| 2
|
Python
|
Python
|
skip megatron tests for now
|
d31c7b104ee19b1572044c416191f451e8f74ddd
|
<ide><path>tests/test_modeling_megatron_bert.py
<ide> def prepare_config_and_inputs_for_common(self):
<ide>
<ide>
<ide> @require_torch
<add>@unittest.skip("Temporary skip to make the CI pass reliably.")
<ide> class MegatronBertModelTest(ModelTesterMixin, unittest.TestCase):
<ide>
<ide> all_model_classes = (
| 1
|
Text
|
Text
|
update docs with allow_add_remove
|
bda25479aa7e73c90bc77b7c7219eaa411af138e
|
<ide><path>docs/api-guide/serializers.md
<ide> This allows you to write views that update or create multiple items when a `PUT`
<ide>
<ide> Bulk updates will update any instances that already exist, and create new instances for data items that do not have a corresponding instance.
<ide>
<del>When performing a bulk update you may want any items that are not present in the incoming data to be deleted. To do so, pass `allow_delete=True` to the serializer.
<add>When performing a bulk update you may want any items that are not present in the incoming data to be deleted. To do so, pass `allow_add_remove=True` to the serializer.
<ide>
<del> serializer = BookSerializer(queryset, data=data, many=True, allow_delete=True)
<add> serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
<ide> serializer.is_valid()
<ide> # True
<ide> serializer.save() # `.save()` will be called on each updated or newly created instance.
<ide> # `.delete()` will be called on any other items in the `queryset`.
<ide>
<del>Passing `allow_delete=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating any objects found in the incoming data.
<add>Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating any objects found in the incoming data.
<ide>
<ide> #### How identity is determined when performing bulk updates
<ide>
| 1
|
Java
|
Java
|
finalize api for testcontextannotationutils
|
fc9650a9a658cb3636400531afe6a87440f02f99
|
<ide><path>spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java
<ide>
<ide> import org.springframework.core.SpringProperties;
<ide> import org.springframework.core.annotation.AnnotatedElementUtils;
<del>import org.springframework.core.annotation.AnnotationAttributes;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.core.annotation.MergedAnnotation;
<ide> import org.springframework.core.annotation.MergedAnnotationCollectors;
<ide> private static <T extends Annotation> T findMergedAnnotation(Class<?> clazz, Cla
<ide>
<ide> AnnotationDescriptor<T> descriptor =
<ide> findAnnotationDescriptor(clazz, annotationType, searchEnclosingClass, new HashSet<>());
<del> return (descriptor != null ? descriptor.synthesizeAnnotation() : null);
<add> return (descriptor != null ? descriptor.getAnnotation() : null);
<ide> }
<ide>
<ide> /**
<ide> private static <T extends Annotation> AnnotationDescriptor<T> findAnnotationDesc
<ide> if (!AnnotationUtils.isInJavaLangAnnotationPackage(composedType.getName()) && visited.add(composedAnn)) {
<ide> descriptor = findAnnotationDescriptor(composedType, annotationType, searchEnclosingClass, visited);
<ide> if (descriptor != null) {
<del> return new AnnotationDescriptor<>(
<del> clazz, descriptor.getDeclaringClass(), composedAnn, descriptor.getAnnotation());
<add> return new AnnotationDescriptor<>(clazz, descriptor.getDeclaringClass(), descriptor.getAnnotation());
<ide> }
<ide> }
<ide> }
<ide> private static <T extends Annotation> AnnotationDescriptor<T> findAnnotationDesc
<ide> for (Class<?> ifc : clazz.getInterfaces()) {
<ide> descriptor = findAnnotationDescriptor(ifc, annotationType, searchEnclosingClass, visited);
<ide> if (descriptor != null) {
<del> return new AnnotationDescriptor<>(clazz, descriptor.getDeclaringClass(),
<del> descriptor.getComposedAnnotation(), descriptor.getAnnotation());
<add> return new AnnotationDescriptor<>(clazz, descriptor.getDeclaringClass(), descriptor.getAnnotation());
<ide> }
<ide> }
<ide>
<ide> private static UntypedAnnotationDescriptor findAnnotationDescriptorForTypes(@Nul
<ide> composedAnnotation.annotationType(), annotationTypes, visited);
<ide> if (descriptor != null) {
<ide> return new UntypedAnnotationDescriptor(clazz, descriptor.getDeclaringClass(),
<del> composedAnnotation, descriptor.getAnnotation(), annotationTypes);
<add> descriptor.getAnnotation(), annotationTypes);
<ide> }
<ide> }
<ide> }
<ide> private static UntypedAnnotationDescriptor findAnnotationDescriptorForTypes(@Nul
<ide> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(ifc, annotationTypes, visited);
<ide> if (descriptor != null) {
<ide> return new UntypedAnnotationDescriptor(clazz, descriptor.getDeclaringClass(),
<del> descriptor.getComposedAnnotation(), descriptor.getAnnotation(), annotationTypes);
<add> descriptor.getAnnotation(), annotationTypes);
<ide> }
<ide> }
<ide>
<ide> private static void assertNonEmptyAnnotationTypeArray(Class<?>[] annotationTypes
<ide> /**
<ide> * Descriptor for an {@link Annotation}, including the {@linkplain
<ide> * #getDeclaringClass() class} on which the annotation is <em>declared</em>
<del> * as well as the actual {@linkplain #getAnnotation() annotation} instance.
<del> * <p>If the annotation is used as a meta-annotation, the descriptor also includes
<del> * the {@linkplain #getComposedAnnotation() composed annotation} on which the
<del> * annotation is present. In such cases, the <em>root declaring class</em> is
<del> * not directly annotated with the annotation but rather indirectly via the
<del> * composed annotation.
<add> * as well as the {@linkplain #getAnnotation() merged annotation} instance.
<add> * <p>If the annotation is used as a meta-annotation, the <em>root declaring
<add> * class</em> is not directly annotated with the annotation but rather
<add> * indirectly via a composed annotation.
<ide> * <p>Given the following example, if we are searching for the {@code @Transactional}
<ide> * annotation <em>on</em> the {@code TransactionalTests} class, then the
<ide> * properties of the {@code AnnotationDescriptor} would be as follows.
<ide> * <ul>
<ide> * <li>rootDeclaringClass: {@code TransactionalTests} class object</li>
<ide> * <li>declaringClass: {@code TransactionalTests} class object</li>
<del> * <li>composedAnnotation: {@code null}</li>
<ide> * <li>annotation: instance of the {@code Transactional} annotation</li>
<ide> * </ul>
<ide> * <p><pre style="code">
<ide> private static void assertNonEmptyAnnotationTypeArray(Class<?>[] annotationTypes
<ide> * <ul>
<ide> * <li>rootDeclaringClass: {@code UserRepositoryTests} class object</li>
<ide> * <li>declaringClass: {@code RepositoryTests} class object</li>
<del> * <li>composedAnnotation: instance of the {@code RepositoryTests} annotation</li>
<ide> * <li>annotation: instance of the {@code Transactional} annotation</li>
<ide> * </ul>
<ide> * <p><pre style="code">
<ide> private static void assertNonEmptyAnnotationTypeArray(Class<?>[] annotationTypes
<ide>
<ide> private final Class<?> declaringClass;
<ide>
<del> @Nullable
<del> private final Annotation composedAnnotation;
<del>
<ide> private final T annotation;
<ide>
<del> private final AnnotationAttributes annotationAttributes;
<del>
<ide> AnnotationDescriptor(Class<?> rootDeclaringClass, T annotation) {
<del> this(rootDeclaringClass, rootDeclaringClass, null, annotation);
<add> this(rootDeclaringClass, rootDeclaringClass, annotation);
<ide> }
<ide>
<del> AnnotationDescriptor(Class<?> rootDeclaringClass, Class<?> declaringClass,
<del> @Nullable Annotation composedAnnotation, T annotation) {
<del>
<add> @SuppressWarnings("unchecked")
<add> AnnotationDescriptor(Class<?> rootDeclaringClass, Class<?> declaringClass, T annotation) {
<ide> Assert.notNull(rootDeclaringClass, "'rootDeclaringClass' must not be null");
<ide> Assert.notNull(declaringClass, "'declaringClass' must not be null");
<ide> Assert.notNull(annotation, "Annotation must not be null");
<ide> this.rootDeclaringClass = rootDeclaringClass;
<ide> this.declaringClass = declaringClass;
<del> this.composedAnnotation = composedAnnotation;
<del> this.annotation = annotation;
<del> AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
<del> rootDeclaringClass, annotation.annotationType().getName(), false, false);
<del> Assert.state(attributes != null, "No annotation attributes");
<del> this.annotationAttributes = attributes;
<add> this.annotation = (T) AnnotatedElementUtils.findMergedAnnotation(
<add> rootDeclaringClass, annotation.annotationType());
<add> Assert.state(this.annotation != null,
<add> () -> "Failed to find merged annotation for " + annotation);
<ide> }
<ide>
<ide> public Class<?> getRootDeclaringClass() {
<ide> public Class<?> getDeclaringClass() {
<ide> return this.declaringClass;
<ide> }
<ide>
<del> T getAnnotation() {
<del> return this.annotation;
<del> }
<del>
<ide> /**
<del> * Synthesize the merged {@link #getAnnotationAttributes AnnotationAttributes}
<del> * in this descriptor back into an annotation of the target
<del> * {@linkplain #getAnnotationType annotation type}.
<del> * @see #getAnnotationAttributes()
<del> * @see #getAnnotationType()
<del> * @see AnnotationUtils#synthesizeAnnotation(java.util.Map, Class, java.lang.reflect.AnnotatedElement)
<add> * Get the merged annotation for this descriptor.
<ide> */
<del> public T synthesizeAnnotation() {
<del> return AnnotationUtils.synthesizeAnnotation(
<del> getAnnotationAttributes(), getAnnotationType(), getRootDeclaringClass());
<add> public T getAnnotation() {
<add> return this.annotation;
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> Class<T> getAnnotationType() {
<ide> return (Class<T>) this.annotation.annotationType();
<ide> }
<ide>
<del> AnnotationAttributes getAnnotationAttributes() {
<del> return this.annotationAttributes;
<del> }
<del>
<del> @Nullable
<del> Annotation getComposedAnnotation() {
<del> return this.composedAnnotation;
<del> }
<del>
<del> @Nullable
<del> Class<? extends Annotation> getComposedAnnotationType() {
<del> return (this.composedAnnotation != null ? this.composedAnnotation.annotationType() : null);
<del> }
<del>
<ide> /**
<del> * Find the next {@link AnnotationDescriptor} for the specified
<del> * {@linkplain #getAnnotationType() annotation type} in the hierarchy
<del> * above the {@linkplain #getRootDeclaringClass() root declaring class}
<del> * of this descriptor.
<add> * Find the next {@link AnnotationDescriptor} for the specified annotation
<add> * type in the hierarchy above the {@linkplain #getRootDeclaringClass()
<add> * root declaring class} of this descriptor.
<ide> * <p>If a corresponding annotation is found in the superclass hierarchy
<ide> * of the root declaring class, that will be returned. Otherwise, an
<ide> * attempt will be made to find a corresponding annotation in the
<ide> public AnnotationDescriptor<T> next() {
<ide> }
<ide>
<ide> /**
<del> * Find <strong>all</strong> annotations of the specified
<del> * {@linkplain #getAnnotationType() annotation type} that are present or
<del> * meta-present on the {@linkplain #getRootDeclaringClass() root declaring
<del> * class} of this descriptor.
<add> * Find <strong>all</strong> annotations of the specified annotation type
<add> * that are present or meta-present on the {@linkplain #getRootDeclaringClass()
<add> * root declaring class} of this descriptor.
<ide> * @return the set of all merged, synthesized {@code Annotations} found,
<ide> * or an empty set if none were found
<ide> */
<ide> public String toString() {
<ide> return new ToStringCreator(this)
<ide> .append("rootDeclaringClass", this.rootDeclaringClass.getName())
<ide> .append("declaringClass", this.declaringClass.getName())
<del> .append("composedAnnotation", this.composedAnnotation)
<ide> .append("annotation", this.annotation)
<ide> .toString();
<ide> }
<ide> public static class UntypedAnnotationDescriptor extends AnnotationDescriptor<Ann
<ide> UntypedAnnotationDescriptor(Class<?> rootDeclaringClass, Annotation annotation,
<ide> Class<? extends Annotation>[] annotationTypes) {
<ide>
<del> this(rootDeclaringClass, rootDeclaringClass, null, annotation, annotationTypes);
<add> this(rootDeclaringClass, rootDeclaringClass, annotation, annotationTypes);
<ide> }
<ide>
<ide> UntypedAnnotationDescriptor(Class<?> rootDeclaringClass, Class<?> declaringClass,
<del> @Nullable Annotation composedAnnotation, Annotation annotation,
<del> Class<? extends Annotation>[] annotationTypes) {
<add> Annotation annotation, Class<? extends Annotation>[] annotationTypes) {
<ide>
<del> super(rootDeclaringClass, declaringClass, composedAnnotation, annotation);
<add> super(rootDeclaringClass, declaringClass, annotation);
<ide> this.annotationTypes = annotationTypes;
<ide> }
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/AbstractTestContextBootstrapper.java
<ide> public final List<TestExecutionListener> getTestExecutionListeners() {
<ide> // Traverse the class hierarchy...
<ide> while (descriptor != null) {
<ide> Class<?> declaringClass = descriptor.getDeclaringClass();
<del> TestExecutionListeners testExecutionListeners = descriptor.synthesizeAnnotation();
<add> TestExecutionListeners testExecutionListeners = descriptor.getAnnotation();
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace(String.format("Retrieved @TestExecutionListeners [%s] for declaring class [%s].",
<ide> testExecutionListeners, declaringClass.getName()));
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/ActiveProfilesUtils.java
<ide> static String[] resolveActiveProfiles(Class<?> testClass) {
<ide>
<ide> while (descriptor != null) {
<ide> Class<?> rootDeclaringClass = descriptor.getRootDeclaringClass();
<del> ActiveProfiles annotation = descriptor.synthesizeAnnotation();
<add> ActiveProfiles annotation = descriptor.getAnnotation();
<ide>
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s]",
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java
<ide> static List<List<ContextConfigurationAttributes>> resolveContextHierarchyAttribu
<ide> List<ContextConfigurationAttributes> configAttributesList = new ArrayList<>();
<ide>
<ide> if (contextConfigDeclaredLocally) {
<del> ContextConfiguration contextConfiguration = (ContextConfiguration) desc.synthesizeAnnotation();
<add> ContextConfiguration contextConfiguration = (ContextConfiguration) desc.getAnnotation();
<ide> convertContextConfigToConfigAttributesAndAddToList(
<ide> contextConfiguration, rootDeclaringClass, configAttributesList);
<ide> }
<ide> static List<ContextConfigurationAttributes> resolveContextConfigurationAttribute
<ide> ContextConfiguration previousAnnotation = null;
<ide> Class<?> previousDeclaringClass = null;
<ide> while (descriptor != null) {
<del> ContextConfiguration currentAnnotation = descriptor.synthesizeAnnotation();
<add> ContextConfiguration currentAnnotation = descriptor.getAnnotation();
<ide> // Don't ignore duplicate @ContextConfiguration declaration without resources,
<ide> // because the ContextLoader will likely detect default resources specific to the
<ide> // annotated class.
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/DefaultActiveProfilesResolver.java
<ide> public String[] resolve(Class<?> testClass) {
<ide> return EMPTY_STRING_ARRAY;
<ide> }
<ide> else {
<del> ActiveProfiles annotation = descriptor.synthesizeAnnotation();
<add> ActiveProfiles annotation = descriptor.getAnnotation();
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s].", annotation,
<ide> descriptor.getDeclaringClass().getName()));
<ide><path>spring-test/src/test/java/org/springframework/test/context/OverriddenMetaAnnotationAttributesTestContextAnnotationUtilsTests.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;
<add>
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.core.annotation.AliasFor;
<add>import org.springframework.test.context.TestContextAnnotationUtils.AnnotationDescriptor;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.springframework.test.context.TestContextAnnotationUtils.findAnnotationDescriptor;
<add>
<add>/**
<add> * Unit tests for {@link TestContextAnnotationUtils} that verify support for
<add> * overridden meta-annotation attributes.
<add> *
<add> * <p>See <a href="https://jira.spring.io/browse/SPR-10181">SPR-10181</a>.
<add> *
<add> * @author Sam Brannen
<add> * @since 5.3, though originally since 4.0 for the deprecated
<add> * {@link org.springframework.test.util.MetaAnnotationUtils} support
<add> * @see TestContextAnnotationUtilsTests
<add> */
<add>class OverriddenMetaAnnotationAttributesTestContextAnnotationUtilsTests {
<add>
<add> @Test
<add> void contextConfigurationValue() {
<add> Class<?> rootDeclaringClass = MetaValueConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(rootDeclaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(rootDeclaringClass);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(MetaValueConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getAnnotation().value()).containsExactly("foo.xml");
<add> assertThat(descriptor.getAnnotation().locations()).containsExactly("foo.xml");
<add> }
<add>
<add> @Test
<add> void overriddenContextConfigurationValue() {
<add> Class<?> rootDeclaringClass = OverriddenMetaValueConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(rootDeclaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(rootDeclaringClass);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(MetaValueConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getAnnotation().value()).containsExactly("bar.xml");
<add> assertThat(descriptor.getAnnotation().locations()).containsExactly("bar.xml");
<add> }
<add>
<add> @Test
<add> void contextConfigurationLocationsAndInheritLocations() {
<add> Class<?> rootDeclaringClass = MetaLocationsConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(rootDeclaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(rootDeclaringClass);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(MetaLocationsConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getAnnotation().value()).isEmpty();
<add> assertThat(descriptor.getAnnotation().locations()).isEmpty();
<add> assertThat(descriptor.getAnnotation().inheritLocations()).isTrue();
<add> }
<add>
<add> @Test
<add> void overriddenContextConfigurationLocationsAndInheritLocations() {
<add> Class<?> rootDeclaringClass = OverriddenMetaLocationsConfigTestCase.class;
<add> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(rootDeclaringClass,
<add> ContextConfiguration.class);
<add> assertThat(descriptor).isNotNull();
<add> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(rootDeclaringClass);
<add> assertThat(descriptor.getDeclaringClass()).isEqualTo(MetaLocationsConfig.class);
<add> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<add> assertThat(descriptor.getAnnotation().value()).containsExactly("bar.xml");
<add> assertThat(descriptor.getAnnotation().locations()).containsExactly("bar.xml");
<add> assertThat(descriptor.getAnnotation().inheritLocations()).isTrue();
<add> }
<add>
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @ContextConfiguration
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @interface MetaValueConfig {
<add>
<add> @AliasFor(annotation = ContextConfiguration.class)
<add> String[] value() default "foo.xml";
<add> }
<add>
<add> @MetaValueConfig
<add> static class MetaValueConfigTestCase {
<add> }
<add>
<add> @MetaValueConfig("bar.xml")
<add> static class OverriddenMetaValueConfigTestCase {
<add> }
<add>
<add> @ContextConfiguration(locations = "foo.xml", inheritLocations = false)
<add> @Retention(RetentionPolicy.RUNTIME)
<add> @interface MetaLocationsConfig {
<add>
<add> String[] locations() default {};
<add>
<add> boolean inheritLocations();
<add> }
<add>
<add> @MetaLocationsConfig(inheritLocations = true)
<add> static class MetaLocationsConfigTestCase {
<add> }
<add>
<add> @MetaLocationsConfig(locations = "bar.xml", inheritLocations = true)
<add> static class OverriddenMetaLocationsConfigTestCase {
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/OverriddenMetaAnnotationAttributesTests.java
<del>/*
<del> * Copyright 2002-2020 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;
<del>
<del>import java.lang.annotation.Retention;
<del>import java.lang.annotation.RetentionPolicy;
<del>
<del>import org.junit.jupiter.api.Test;
<del>
<del>import org.springframework.core.annotation.AnnotationAttributes;
<del>import org.springframework.test.context.TestContextAnnotationUtils.AnnotationDescriptor;
<del>
<del>import static org.assertj.core.api.Assertions.assertThat;
<del>import static org.springframework.test.context.TestContextAnnotationUtils.findAnnotationDescriptor;
<del>
<del>/**
<del> * Unit tests for {@link TestContextAnnotationUtils} that verify support for
<del> * overridden meta-annotation attributes.
<del> *
<del> * <p>See <a href="https://jira.spring.io/browse/SPR-10181">SPR-10181</a>.
<del> *
<del> * @author Sam Brannen
<del> * @since 4.0
<del> * @see TestContextAnnotationUtilsTests
<del> */
<del>class OverriddenMetaAnnotationAttributesTests {
<del>
<del> @Test
<del> void contextConfigurationValue() throws Exception {
<del> Class<MetaValueConfigTestCase> declaringClass = MetaValueConfigTestCase.class;
<del> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<del> ContextConfiguration.class);
<del> assertThat(descriptor).isNotNull();
<del> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<del> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<del> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<del>
<del> // direct access to annotation value:
<del> assertThat(descriptor.getAnnotation().value()).isEqualTo(new String[] { "foo.xml" });
<del> }
<del>
<del> @Test
<del> void overriddenContextConfigurationValue() throws Exception {
<del> Class<?> declaringClass = OverriddenMetaValueConfigTestCase.class;
<del> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<del> ContextConfiguration.class);
<del> assertThat(descriptor).isNotNull();
<del> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<del> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<del> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaValueConfig.class);
<del>
<del> // direct access to annotation value:
<del> assertThat(descriptor.getAnnotation().value()).isEqualTo(new String[] { "foo.xml" });
<del>
<del> // overridden attribute:
<del> AnnotationAttributes attributes = descriptor.getAnnotationAttributes();
<del>
<del> // NOTE: we would like to be able to override the 'value' attribute; however,
<del> // Spring currently does not allow overrides for the 'value' attribute.
<del> // See SPR-11393 for related discussions.
<del> assertThat(attributes.getStringArray("value")).isEqualTo(new String[] { "foo.xml" });
<del> }
<del>
<del> @Test
<del> void contextConfigurationLocationsAndInheritLocations() throws Exception {
<del> Class<MetaLocationsConfigTestCase> declaringClass = MetaLocationsConfigTestCase.class;
<del> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<del> ContextConfiguration.class);
<del> assertThat(descriptor).isNotNull();
<del> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<del> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<del> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<del>
<del> // direct access to annotation attributes:
<del> assertThat(descriptor.getAnnotation().locations()).isEqualTo(new String[] { "foo.xml" });
<del> assertThat(descriptor.getAnnotation().inheritLocations()).isFalse();
<del> }
<del>
<del> @Test
<del> void overriddenContextConfigurationLocationsAndInheritLocations() throws Exception {
<del> Class<?> declaringClass = OverriddenMetaLocationsConfigTestCase.class;
<del> AnnotationDescriptor<ContextConfiguration> descriptor = findAnnotationDescriptor(declaringClass,
<del> ContextConfiguration.class);
<del> assertThat(descriptor).isNotNull();
<del> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(declaringClass);
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<del> assertThat(descriptor.getAnnotationType()).isEqualTo(ContextConfiguration.class);
<del> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaLocationsConfig.class);
<del>
<del> // direct access to annotation attributes:
<del> assertThat(descriptor.getAnnotation().locations()).isEqualTo(new String[] { "foo.xml" });
<del> assertThat(descriptor.getAnnotation().inheritLocations()).isFalse();
<del>
<del> // overridden attributes:
<del> AnnotationAttributes attributes = descriptor.getAnnotationAttributes();
<del> assertThat(attributes.getStringArray("locations")).isEqualTo(new String[] { "bar.xml" });
<del> assertThat(attributes.getBoolean("inheritLocations")).isTrue();
<del> }
<del>
<del>
<del> // -------------------------------------------------------------------------
<del>
<del> @ContextConfiguration("foo.xml")
<del> @Retention(RetentionPolicy.RUNTIME)
<del> static @interface MetaValueConfig {
<del>
<del> String[] value() default {};
<del> }
<del>
<del> @MetaValueConfig
<del> static class MetaValueConfigTestCase {
<del> }
<del>
<del> @MetaValueConfig("bar.xml")
<del> static class OverriddenMetaValueConfigTestCase {
<del> }
<del>
<del> @ContextConfiguration(locations = "foo.xml", inheritLocations = false)
<del> @Retention(RetentionPolicy.RUNTIME)
<del> static @interface MetaLocationsConfig {
<del>
<del> String[] locations() default {};
<del>
<del> boolean inheritLocations();
<del> }
<del>
<del> @MetaLocationsConfig(inheritLocations = true)
<del> static class MetaLocationsConfigTestCase {
<del> }
<del>
<del> @MetaLocationsConfig(locations = "bar.xml", inheritLocations = true)
<del> static class OverriddenMetaLocationsConfigTestCase {
<del> }
<del>
<del>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/TestContextAnnotationUtilsTests.java
<ide> * Unit tests for {@link TestContextAnnotationUtils}.
<ide> *
<ide> * @author Sam Brannen
<del> * @since 4.0
<del> * @see OverriddenMetaAnnotationAttributesTests
<add> * @since 5.3, though originally since 4.0 for the deprecated
<add> * {@link org.springframework.test.util.MetaAnnotationUtils} support
<add> * @see OverriddenMetaAnnotationAttributesTestContextAnnotationUtilsTests
<ide> */
<ide> class TestContextAnnotationUtilsTests {
<ide>
<ide> void findAnnotationDescriptorWithLocalAndMetaComponentAnnotation() {
<ide>
<ide> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(HasLocalAndMetaComponentAnnotation.class);
<ide> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<del> assertThat(descriptor.getComposedAnnotation()).isNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isNull();
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForClassWithMetaAnnotatedInterface() {
<ide> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(ClassWithMetaAnnotatedInterface.class);
<ide> assertThat(descriptor.getDeclaringClass()).isEqualTo(Meta1.class);
<ide> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<del> assertThat(descriptor.getComposedAnnotation().annotationType()).isEqualTo(Meta1.class);
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForClassWithLocalMetaAnnotationAndAnnotatedSupercla
<ide> assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(MetaAnnotatedAndSuperAnnotatedContextConfigClass.class);
<ide> assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(MetaConfig.class);
<ide> assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(ContextConfiguration.class);
<del> assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(MetaConfig.class);
<ide>
<del> assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).as("configured classes").isEqualTo(new Class<?>[] {String.class});
<add> assertThat(descriptor.getAnnotation().classes()).as("configured classes").containsExactly(String.class);
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForSubClassWithLocalMetaAnnotationAndMetaAnnotatedI
<ide> */
<ide> @Test
<ide> void findAnnotationDescriptorOnMetaMetaAnnotatedClass() {
<del> Class<MetaMetaAnnotatedClass> startClass = MetaMetaAnnotatedClass.class;
<del> assertAtComponentOnComposedAnnotation(startClass, startClass, Meta2.class, "meta2", MetaMeta.class);
<add> Class<?> startClass = MetaMetaAnnotatedClass.class;
<add> assertAtComponentOnComposedAnnotation(startClass, startClass, Meta2.class, "meta2");
<ide> }
<ide>
<ide> /**
<ide> * @since 4.0.3
<ide> */
<ide> @Test
<ide> void findAnnotationDescriptorOnMetaMetaMetaAnnotatedClass() {
<del> Class<MetaMetaMetaAnnotatedClass> startClass = MetaMetaMetaAnnotatedClass.class;
<del> assertAtComponentOnComposedAnnotation(startClass, startClass, Meta2.class, "meta2", MetaMetaMeta.class);
<add> Class<?> startClass = MetaMetaMetaAnnotatedClass.class;
<add> assertAtComponentOnComposedAnnotation(startClass, startClass, Meta2.class, "meta2");
<ide> }
<ide>
<ide> /**
<ide> private void assertAtComponentOnComposedAnnotation(
<ide> private void assertAtComponentOnComposedAnnotation(
<ide> Class<?> startClass, Class<?> rootDeclaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<ide>
<del> assertAtComponentOnComposedAnnotation(startClass, rootDeclaringClass, composedAnnotationType, name, composedAnnotationType);
<add> assertAtComponentOnComposedAnnotation(startClass, rootDeclaringClass, composedAnnotationType, name);
<ide> }
<ide>
<ide> private void assertAtComponentOnComposedAnnotation(Class<?> startClass, Class<?> rootDeclaringClass,
<del> Class<?> declaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<add> Class<?> declaringClass, String name) {
<ide>
<ide> AnnotationDescriptor<Component> descriptor = findAnnotationDescriptor(startClass, Component.class);
<ide> assertThat(descriptor).as("AnnotationDescriptor should not be null").isNotNull();
<ide> assertThat(descriptor.getRootDeclaringClass()).as("rootDeclaringClass").isEqualTo(rootDeclaringClass);
<ide> assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(declaringClass);
<ide> assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(Component.class);
<ide> assertThat(descriptor.getAnnotation().value()).as("component name").isEqualTo(name);
<del> assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(composedAnnotationType);
<ide> }
<ide>
<ide> }
<ide> void findAnnotationDescriptorForTypesWithLocalAndMetaComponentAnnotation() {
<ide> HasLocalAndMetaComponentAnnotation.class, Transactional.class, annotationType, Order.class);
<ide> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(HasLocalAndMetaComponentAnnotation.class);
<ide> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<del> assertThat(descriptor.getComposedAnnotation()).isNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isNull();
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForTypesWithMetaComponentAnnotation() {
<del> Class<HasMetaComponentAnnotation> startClass = HasMetaComponentAnnotation.class;
<add> Class<?> startClass = HasMetaComponentAnnotation.class;
<ide> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(startClass, "meta1", Meta1.class);
<ide> }
<ide>
<ide> void findAnnotationDescriptorForTypesWithMetaAnnotationWithDefaultAttributes() {
<ide> assertThat(descriptor).isNotNull();
<ide> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(startClass);
<ide> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<del> assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEqualTo(new Class<?>[] {});
<del> assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).isEqualTo(new Class<?>[] {MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class});
<del> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaConfig.class);
<add> assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEmpty();
<add> assertThat(((ContextConfiguration) descriptor.getAnnotation()).classes())
<add> .containsExactly(MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class);
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForTypesWithMetaAnnotationWithOverriddenAttributes(
<ide> assertThat(descriptor).isNotNull();
<ide> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(startClass);
<ide> assertThat(descriptor.getAnnotationType()).isEqualTo(annotationType);
<del> assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEqualTo(new Class<?>[] {});
<del> assertThat(descriptor.getAnnotationAttributes().getClassArray("classes")).isEqualTo(new Class<?>[] {TestContextAnnotationUtilsTests.class});
<del> assertThat(descriptor.getComposedAnnotation()).isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).isEqualTo(MetaConfig.class);
<add> assertThat(((ContextConfiguration) descriptor.getAnnotation()).value()).isEmpty();
<add> assertThat(((ContextConfiguration) descriptor.getAnnotation()).classes())
<add> .containsExactly(TestContextAnnotationUtilsTests.class);
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForTypesForInterfaceWithMetaAnnotation() {
<del> Class<InterfaceWithMetaAnnotation> startClass = InterfaceWithMetaAnnotation.class;
<add> Class<?> startClass = InterfaceWithMetaAnnotation.class;
<ide> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(startClass, "meta1", Meta1.class);
<ide> }
<ide>
<ide> void findAnnotationDescriptorForTypesForClassWithMetaAnnotatedInterface() {
<ide> assertThat(descriptor.getRootDeclaringClass()).isEqualTo(ClassWithMetaAnnotatedInterface.class);
<ide> assertThat(descriptor.getDeclaringClass()).isEqualTo(Meta1.class);
<ide> assertThat(descriptor.getAnnotation()).isEqualTo(rawAnnotation);
<del> assertThat(descriptor.getComposedAnnotation().annotationType()).isEqualTo(Meta1.class);
<ide> }
<ide>
<ide> @Test
<ide> void findAnnotationDescriptorForTypesForClassWithLocalMetaAnnotationAndMetaAnnotatedInterface() {
<del> Class<ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface> startClass = ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class;
<add> Class<?> startClass = ClassWithLocalMetaAnnotationAndMetaAnnotatedInterface.class;
<ide> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(startClass, "meta2", Meta2.class);
<ide> }
<ide>
<ide> void findAnnotationDescriptorForTypesForSubClassWithLocalMetaAnnotationAndMetaAn
<ide> */
<ide> @Test
<ide> void findAnnotationDescriptorForTypesOnMetaMetaAnnotatedClass() {
<del> Class<MetaMetaAnnotatedClass> startClass = MetaMetaAnnotatedClass.class;
<add> Class<?> startClass = MetaMetaAnnotatedClass.class;
<ide> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<del> startClass, startClass, Meta2.class, "meta2", MetaMeta.class);
<add> startClass, startClass, Meta2.class, "meta2");
<ide> }
<ide>
<ide> /**
<ide> * @since 4.0.3
<ide> */
<ide> @Test
<ide> void findAnnotationDescriptorForTypesOnMetaMetaMetaAnnotatedClass() {
<del> Class<MetaMetaMetaAnnotatedClass> startClass = MetaMetaMetaAnnotatedClass.class;
<add> Class<?> startClass = MetaMetaMetaAnnotatedClass.class;
<ide> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<del> startClass, startClass, Meta2.class, "meta2", MetaMetaMeta.class);
<add> startClass, startClass, Meta2.class, "meta2");
<ide> }
<ide>
<ide> /**
<ide> private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Clas
<ide> Class<?> rootDeclaringClass, String name, Class<? extends Annotation> composedAnnotationType) {
<ide>
<ide> assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(
<del> startClass, rootDeclaringClass, composedAnnotationType, name, composedAnnotationType);
<add> startClass, rootDeclaringClass, composedAnnotationType, name);
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Class<?> startClass,
<del> Class<?> rootDeclaringClass, Class<?> declaringClass, String name,
<del> Class<? extends Annotation> composedAnnotationType) {
<add> Class<?> rootDeclaringClass, Class<?> declaringClass, String name) {
<ide>
<ide> Class<Component> annotationType = Component.class;
<ide> UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(
<ide> private void assertAtComponentOnComposedAnnotationForMultipleCandidateTypes(Clas
<ide> assertThat(descriptor.getDeclaringClass()).as("declaringClass").isEqualTo(declaringClass);
<ide> assertThat(descriptor.getAnnotationType()).as("annotationType").isEqualTo(annotationType);
<ide> assertThat(((Component) descriptor.getAnnotation()).value()).as("component name").isEqualTo(name);
<del> assertThat(descriptor.getComposedAnnotation()).as("composedAnnotation should not be null").isNotNull();
<del> assertThat(descriptor.getComposedAnnotationType()).as("composedAnnotationType").isEqualTo(composedAnnotationType);
<ide> }
<ide>
<ide> }
| 8
|
Ruby
|
Ruby
|
add deprecation paths for tap --full/--shallow
|
b5a7337b059c33d0c3a4bd70788095fcb401add8
|
<ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap_args
<ide> assumptions, so taps can be cloned from places other than GitHub and
<ide> using protocols other than HTTPS, e.g. SSH, git, HTTP, FTP(S), rsync.
<ide> EOS
<add> # odeprecated "brew tap --full"
<add> switch "--full",
<add> description: "Convert a shallow clone to a full clone without untapping. Taps are only cloned as "\
<add> "shallow clones if `--shallow` was originally passed."
<add> # odeprecated "brew tap --shallow"
<add> switch "--shallow",
<add> description: "Fetch tap as a shallow clone rather than a full clone. Useful for continuous integration."
<ide> switch "--force-auto-update",
<ide> description: "Auto-update tap even if it is not hosted on GitHub. By default, only taps "\
<ide> "hosted on GitHub are auto-updated (for performance reasons)."
| 1
|
Ruby
|
Ruby
|
fix postgresql query_cache test
|
1f63cd9190a44d5604ec7ea69cc78e31760611cf
|
<ide><path>activerecord/test/cases/query_cache_test.rb
<ide> def test_cache_is_not_available_when_using_a_not_connected_connection
<ide> refute Task.connected?
<ide>
<ide> Task.cache do
<add> Task.connection # warmup postgresql connection setup queries
<ide> assert_queries(2) { Task.find(1); Task.find(1) }
<ide> end
<ide> ensure
| 1
|
Python
|
Python
|
reduce code re-use with pytest mark
|
3b117e7e8c0f9a84185181a7fdbb7e4de979f0ec
|
<ide><path>numpy/lib/tests/test_arraysetops.py
<ide> def test_ediff1d_scalar_handling(self,
<ide> assert_equal(actual, expected)
<ide> assert actual.dtype == expected.dtype
<ide>
<del> def test_isin(self):
<add> @pytest.mark.parametrize("kind", [None, "sort", "table"])
<add> def test_isin(self, kind):
<ide> # the tests for in1d cover most of isin's behavior
<ide> # if in1d is removed, would need to change those tests to test
<ide> # isin instead.
<ide> def _isin_slow(a, b):
<ide> return a in b
<ide> isin_slow = np.vectorize(_isin_slow, otypes=[bool], excluded={1})
<ide>
<del> def assert_isin_equal(a, b, old_algorithm=None):
<del> kind = "sort" if old_algorithm else None
<add> def assert_isin_equal(a, b):
<ide> x = isin(a, b, kind=kind)
<ide> y = isin_slow(a, b)
<ide> assert_array_equal(x, y)
<ide> def assert_isin_equal(a, b, old_algorithm=None):
<ide> a = np.arange(24).reshape([2, 3, 4])
<ide> b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]])
<ide> assert_isin_equal(a, b)
<del> assert_isin_equal(a, b, old_algorithm=True)
<ide>
<ide> # array-likes as both arguments
<ide> c = [(9, 8), (7, 6)]
<ide> d = (9, 7)
<ide> assert_isin_equal(c, d)
<del> assert_isin_equal(c, d, old_algorithm=True)
<ide>
<ide> # zero-d array:
<ide> f = np.array(3)
<ide> assert_isin_equal(f, b)
<ide> assert_isin_equal(a, f)
<ide> assert_isin_equal(f, f)
<del> assert_isin_equal(f, b, old_algorithm=True)
<del> assert_isin_equal(a, f, old_algorithm=True)
<del> assert_isin_equal(f, f, old_algorithm=True)
<ide>
<ide> # scalar:
<ide> assert_isin_equal(5, b)
<ide> assert_isin_equal(a, 6)
<ide> assert_isin_equal(5, 6)
<del> assert_isin_equal(5, b, old_algorithm=True)
<del> assert_isin_equal(a, 6, old_algorithm=True)
<del> assert_isin_equal(5, 6, old_algorithm=True)
<ide>
<ide> # empty array-like:
<ide> x = []
<ide> assert_isin_equal(x, b)
<ide> assert_isin_equal(a, x)
<ide> assert_isin_equal(x, x)
<del> assert_isin_equal(x, b, old_algorithm=True)
<del> assert_isin_equal(a, x, old_algorithm=True)
<del> assert_isin_equal(x, x, old_algorithm=True)
<ide>
<del> def test_in1d(self):
<add> @pytest.mark.parametrize("kind", [None, "sort", "table"])
<add> def test_in1d(self, kind):
<ide> # we use two different sizes for the b array here to test the
<ide> # two different paths in in1d().
<ide> for mult in (1, 10):
<ide> # One check without np.array to make sure lists are handled correct
<ide> a = [5, 7, 1, 2]
<ide> b = [2, 4, 3, 1, 5] * mult
<ide> ec = np.array([True, False, True, True])
<del> c = in1d(a, b, assume_unique=True)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, assume_unique=True, kind="sort")
<add> c = in1d(a, b, assume_unique=True, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a[0] = 8
<ide> ec = np.array([False, False, True, True])
<del> c = in1d(a, b, assume_unique=True)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, assume_unique=True, kind="sort")
<add> c = in1d(a, b, assume_unique=True, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a[0], a[3] = 4, 8
<ide> ec = np.array([True, False, True, False])
<del> c = in1d(a, b, assume_unique=True)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, assume_unique=True, kind="sort")
<add> c = in1d(a, b, assume_unique=True, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
<ide> b = [2, 3, 4] * mult
<ide> ec = [False, True, False, True, True, True, True, True, True,
<ide> False, True, False, False, False]
<del> c = in1d(a, b)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, kind="sort")
<add> c = in1d(a, b, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> b = b + [5, 5, 4] * mult
<ide> ec = [True, True, True, True, True, True, True, True, True, True,
<ide> True, False, True, True]
<del> c = in1d(a, b)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, kind="sort")
<add> c = in1d(a, b, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a = np.array([5, 7, 1, 2])
<ide> b = np.array([2, 4, 3, 1, 5] * mult)
<ide> ec = np.array([True, False, True, True])
<del> c = in1d(a, b)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, kind="sort")
<add> c = in1d(a, b, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a = np.array([5, 7, 1, 1, 2])
<ide> b = np.array([2, 4, 3, 3, 1, 5] * mult)
<ide> ec = np.array([True, False, True, True, True])
<del> c = in1d(a, b)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, kind="sort")
<add> c = in1d(a, b, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a = np.array([5, 5])
<ide> b = np.array([2, 2] * mult)
<ide> ec = np.array([False, False])
<del> c = in1d(a, b)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, kind="sort")
<add> c = in1d(a, b, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<ide> a = np.array([5])
<ide> b = np.array([2])
<ide> ec = np.array([False])
<del> c = in1d(a, b)
<del> assert_array_equal(c, ec)
<del> c = in1d(a, b, kind="sort")
<add> c = in1d(a, b, kind=kind)
<ide> assert_array_equal(c, ec)
<ide>
<del> assert_array_equal(in1d([], []), [])
<del>
<del> def test_in1d_hit_alternate_algorithm_floats(self):
<del> # Perform the above test but with floats
<del> # This forces the old in1d (pre-Oct 1/2018) algorithm
<del> for mult in (1, 10):
<del> # One check without np.array to make sure lists are handled correct
<del> a = [5, 7, 1, 2]
<del> b = [2, 4, 3, 1, 5] * mult
<del> ec = np.array([True, False, True, True])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32), assume_unique=True)
<del> assert_array_equal(c, ec)
<del>
<del> a[0] = 8
<del> ec = np.array([False, False, True, True])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32), assume_unique=True)
<del> assert_array_equal(c, ec)
<del>
<del> a[0], a[3] = 4, 8
<del> ec = np.array([True, False, True, False])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32), assume_unique=True)
<del> assert_array_equal(c, ec)
<del>
<del> a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
<del> b = [2, 3, 4] * mult
<del> ec = [False, True, False, True, True, True, True, True, True,
<del> False, True, False, False, False]
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32))
<del> assert_array_equal(c, ec)
<del>
<del> b = b + [5, 5, 4] * mult
<del> ec = [True, True, True, True, True, True, True, True, True, True,
<del> True, False, True, True]
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32))
<del> assert_array_equal(c, ec)
<del>
<del> a = np.array([5, 7, 1, 2])
<del> b = np.array([2, 4, 3, 1, 5] * mult)
<del> ec = np.array([True, False, True, True])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32))
<del> assert_array_equal(c, ec)
<del>
<del> a = np.array([5, 7, 1, 1, 2])
<del> b = np.array([2, 4, 3, 3, 1, 5] * mult)
<del> ec = np.array([True, False, True, True, True])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32))
<del> assert_array_equal(c, ec)
<del>
<del> a = np.array([5, 5])
<del> b = np.array([2, 2] * mult)
<del> ec = np.array([False, False])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32))
<del> assert_array_equal(c, ec)
<del>
<del> a = np.array([5])
<del> b = np.array([2])
<del> ec = np.array([False])
<del> c = in1d(np.array(a, dtype=np.float32),
<del> np.array(b, dtype=np.float32))
<del> assert_array_equal(c, ec)
<del>
<del> assert_array_equal(in1d([], []), [])
<add> assert_array_equal(in1d([], [], kind=kind), [])
<ide>
<ide> def test_in1d_char_array(self):
<ide> a = np.array(['a', 'b', 'c', 'd', 'e', 'c', 'e', 'b'])
<ide> def test_in1d_char_array(self):
<ide>
<ide> assert_array_equal(c, ec)
<ide>
<del> def test_in1d_invert(self):
<add> @pytest.mark.parametrize("kind", [None, "sort", "table"])
<add> def test_in1d_invert(self, kind):
<ide> "Test in1d's invert parameter"
<ide> # We use two different sizes for the b array here to test the
<ide> # two different paths in in1d().
<ide> for mult in (1, 10):
<ide> a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5])
<ide> b = [2, 3, 4] * mult
<del> assert_array_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
<del> assert_array_equal(np.invert(in1d(a, b)),
<del> in1d(a, b, invert=True, kind="sort"))
<del>
<del> for mult in (1, 10):
<del> a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5],
<del> dtype=np.float32)
<del> b = [2, 3, 4] * mult
<del> b = np.array(b, dtype=np.float32)
<del> assert_array_equal(np.invert(in1d(a, b)), in1d(a, b, invert=True))
<del> assert_array_equal(np.invert(in1d(a, b)),
<del> in1d(a, b, invert=True, kind="sort"))
<del>
<del> def test_in1d_ravel(self):
<add> assert_array_equal(np.invert(in1d(a, b, kind=kind)),
<add> in1d(a, b, invert=True, kind=kind))
<add>
<add> # float:
<add> if kind in {None, "sort"}:
<add> for mult in (1, 10):
<add> a = np.array([5, 4, 5, 3, 4, 4, 3, 4, 3, 5, 2, 1, 5, 5],
<add> dtype=np.float32)
<add> b = [2, 3, 4] * mult
<add> b = np.array(b, dtype=np.float32)
<add> assert_array_equal(np.invert(in1d(a, b, kind=kind)),
<add> in1d(a, b, invert=True, kind=kind))
<add>
<add> @pytest.mark.parametrize("kind", [None, "sort", "table"])
<add> def test_in1d_ravel(self, kind):
<ide> # Test that in1d ravels its input arrays. This is not documented
<ide> # behavior however. The test is to ensure consistentency.
<ide> a = np.arange(6).reshape(2, 3)
<ide> b = np.arange(3, 9).reshape(3, 2)
<ide> long_b = np.arange(3, 63).reshape(30, 2)
<ide> ec = np.array([False, False, False, True, True, True])
<ide>
<del> assert_array_equal(in1d(a, b, assume_unique=True), ec)
<del> assert_array_equal(in1d(a, b, assume_unique=False), ec)
<del> assert_array_equal(in1d(a, long_b, assume_unique=True), ec)
<del> assert_array_equal(in1d(a, long_b, assume_unique=False), ec)
<del> assert_array_equal(in1d(a, b, assume_unique=True, kind="sort"),
<add> assert_array_equal(in1d(a, b, assume_unique=True, kind=kind),
<ide> ec)
<ide> assert_array_equal(in1d(a, b, assume_unique=False,
<del> kind="sort"),
<add> kind=kind),
<ide> ec)
<ide> assert_array_equal(in1d(a, long_b, assume_unique=True,
<del> kind="sort"),
<add> kind=kind),
<ide> ec)
<ide> assert_array_equal(in1d(a, long_b, assume_unique=False,
<del> kind="sort"),
<add> kind=kind),
<ide> ec)
<ide>
<ide> def test_in1d_hit_alternate_algorithm(self):
<ide> def test_in1d_hit_alternate_algorithm(self):
<ide> c = in1d(a, b, assume_unique=True)
<ide> assert_array_equal(c, ec)
<ide>
<del> def test_in1d_boolean(self):
<add> @pytest.mark.parametrize("kind", [None, "sort", "table"])
<add> def test_in1d_boolean(self, kind):
<ide> """Test that in1d works for boolean input"""
<ide> a = np.array([True, False])
<ide> b = np.array([False, False, False])
<ide> expected = np.array([False, True])
<ide> assert_array_equal(expected,
<del> in1d(a, b))
<del> assert_array_equal(expected,
<del> in1d(a, b, kind="sort"))
<del> assert_array_equal(np.invert(expected),
<del> in1d(a, b, invert=True))
<add> in1d(a, b, kind=kind))
<ide> assert_array_equal(np.invert(expected),
<del> in1d(a, b, invert=True, kind="sort"))
<add> in1d(a, b, invert=True, kind=kind))
<ide>
<ide> def test_in1d_first_array_is_object(self):
<ide> ar1 = [None]
| 1
|
PHP
|
PHP
|
fix failing test from 2.3 merge
|
b47744befa4b9a1dcdb4d7666a1502a670de73b9
|
<ide><path>lib/Cake/Test/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testNumbers() {
<ide>
<ide> $result = $this->Paginator->numbers(array('first' => 1, 'tag' => 'li', 'currentClass' => 'active', 'currentTag' => 'a'));
<ide> $expected = array(
<del> array('li' => array()), array('a' => array('href' => '/index/page:1')), '1', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=1')), '1', '/a', '/li',
<ide> ' | ',
<ide> array('li' => array('class' => 'active')), array('a' => array()), '2', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:4')), '4', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:5')), '5', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:6')), '6', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:7')), '7', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:8')), '8', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:9')), '9', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> public function testNumbers() {
<ide> $expected = array(
<ide> array('li' => array('class' => 'current')), array('span' => array()), '1', '/span', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:2')), '2', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<ide> ' | ',
<del> array('li' => array()), array('a' => array('href' => '/index/page:3')), '3', '/a', '/li',
<add> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
| 1
|
Ruby
|
Ruby
|
add on_linux and on_macos blocks
|
8b85ef2e8851b32eaac3f3094c7a6044eceb20e3
|
<ide><path>Library/Homebrew/extend/os/linux/formula.rb
<ide> # frozen_string_literal: true
<ide>
<ide> class Formula
<add> undef on_linux
<add>
<add> def on_linux(&_block)
<add> raise "No block content defined for on_linux block" unless block_given?
<add>
<add> yield
<add> end
<add>
<ide> undef shared_library
<ide>
<ide> def shared_library(name, version = nil)
<ide> class << self
<ide> undef on_linux
<ide>
<ide> def on_linux(&_block)
<add> raise "No block content defined for on_linux block" unless block_given?
<add>
<ide> yield
<ide> end
<ide>
<ide><path>Library/Homebrew/extend/os/mac/formula.rb
<ide> # frozen_string_literal: true
<ide>
<ide> class Formula
<add> undef on_macos
<add>
<add> def on_macos(&_block)
<add> raise "No block content defined for on_macos block" unless block_given?
<add>
<add> yield
<add> end
<add>
<ide> class << self
<ide> undef on_macos
<ide>
<ide> def on_macos(&_block)
<add> raise "No block content defined for on_macos block" unless block_given?
<add>
<ide> yield
<ide> end
<ide> end
<ide><path>Library/Homebrew/formula.rb
<ide> def inspect
<ide> "#<Formula #{name} (#{active_spec_sym}) #{path}>"
<ide> end
<ide>
<add> # Block only executed on macOS. No-op on Linux.
<add> # <pre>on_macos do
<add> # Do something mac specific
<add> # end</pre>
<add> def on_macos(&_block)
<add> raise "No block content defined for on_macos block" unless block_given?
<add> end
<add>
<add> # Block only executed on Linux. No-op on macOS.
<add> # <pre>on_linux do
<add> # Do something linux specific
<add> # end</pre>
<add> def on_linux(&_block)
<add> raise "No block content defined for on_linux block" unless block_given?
<add> end
<add>
<ide> # Standard parameters for cargo builds.
<ide> def std_cargo_args
<ide> ["--locked", "--root", prefix, "--path", "."]
<ide> def uses_from_macos(dep, bounds = {})
<ide> # <pre>on_macos do
<ide> # depends_on "mac_only_dep"
<ide> # end</pre>
<del> def on_macos(&_block); end
<add> def on_macos(&_block)
<add> raise "No block content defined for on_macos block" unless block_given?
<add> end
<ide>
<ide> # Block only executed on Linux. No-op on macOS.
<ide> # <pre>on_linux do
<ide> # depends_on "linux_only_dep"
<ide> # end</pre>
<del> def on_linux(&_block); end
<add> def on_linux(&_block)
<add> raise "No block content defined for on_linux block" unless block_given?
<add> end
<ide>
<ide> # @!attribute [w] option
<ide> # Options can be used as arguments to `brew install`.
<ide><path>Library/Homebrew/test/formula_spec.rb
<ide> def setup_tab_for_prefix(prefix, options = {})
<ide> expect(f.any_installed_version).to eq(PkgVersion.parse("1.0_1"))
<ide> end
<ide> end
<add>
<add> describe "#on_macos", :needs_macos do
<add> let(:f) do
<add> Class.new(Testball) do
<add> @test = 0
<add> attr_reader :test
<add>
<add> def install
<add> on_macos do
<add> @test = 1
<add> end
<add> on_linux do
<add> @test = 2
<add> end
<add> end
<add> end.new
<add> end
<add>
<add> it "only calls code within on_macos" do
<add> f.brew { f.install }
<add> expect(f.test).to eq(1)
<add> end
<add> end
<add>
<add> describe "#on_linux", :needs_linux do
<add> let(:f) do
<add> Class.new(Testball) do
<add> @test = 0
<add> attr_reader :test
<add>
<add> def install
<add> on_macos do
<add> @test = 1
<add> end
<add> on_linux do
<add> @test = 2
<add> end
<add> end
<add> end.new
<add> end
<add>
<add> it "only calls code within on_linux" do
<add> f.brew { f.install }
<add> expect(f.test).to eq(2)
<add> end
<add> end
<ide> end
| 4
|
Python
|
Python
|
add sqrt for proper noise sigma calculation
|
34c54cb19c51c6345f2bcbcc109b75e9f7bf32f6
|
<ide><path>keras/layers/noise.py
<ide> def get_output(self, train):
<ide> # self.p refers to drop probability rather than
<ide> # retain probability (as in paper), for consistency
<ide> X *= K.random_normal(shape=K.shape(X), mean=1.0,
<del> std=self.p / (1.0 - self.p))
<add> std=K.sqrt(self.p / (1.0 - self.p)))
<ide> return X
<ide>
<ide> def get_config(self):
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.