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 |
|---|---|---|---|---|---|
Mixed | Go | repurpose the package and rename to useragent | cf8c0d0f56021fbea7bc89e378bb937b53aeca3b | <ide><path>pkg/requestdecorator/README.md
<del>This package provides helper functions for decorating a request with user agent
<del>versions, auth, meta headers.
<ide><path>pkg/requestdecorator/requestdecorator.go
<del>// Package requestdecorator provides helper functions to decorate a request with
<del>// user agent versions, auth, meta headers.
<del>package requestdecorator
<del>
<del>import (
<del> "errors"
<del> "io"
<del> "net/http"
<del> "strings"
<del>
<del> "github.com/Sirupsen/logrus"
<del>)
<del>
<del>var (
<del> ErrNilRequest = errors.New("request cannot be nil")
<del>)
<del>
<del>// UAVersionInfo is used to model UserAgent versions.
<del>type UAVersionInfo struct {
<del> Name string
<del> Version string
<del>}
<del>
<del>func NewUAVersionInfo(name, version string) UAVersionInfo {
<del> return UAVersionInfo{
<del> Name: name,
<del> Version: version,
<del> }
<del>}
<del>
<del>func (vi *UAVersionInfo) isValid() bool {
<del> const stopChars = " \t\r\n/"
<del> name := vi.Name
<del> vers := vi.Version
<del> if len(name) == 0 || strings.ContainsAny(name, stopChars) {
<del> return false
<del> }
<del> if len(vers) == 0 || strings.ContainsAny(vers, stopChars) {
<del> return false
<del> }
<del> return true
<del>}
<del>
<del>// Convert versions to a string and append the string to the string base.
<del>//
<del>// Each UAVersionInfo will be converted to a string in the format of
<del>// "product/version", where the "product" is get from the name field, while
<del>// version is get from the version field. Several pieces of verson information
<del>// will be concatinated and separated by space.
<del>func AppendVersions(base string, versions ...UAVersionInfo) string {
<del> if len(versions) == 0 {
<del> return base
<del> }
<del>
<del> verstrs := make([]string, 0, 1+len(versions))
<del> if len(base) > 0 {
<del> verstrs = append(verstrs, base)
<del> }
<del>
<del> for _, v := range versions {
<del> if !v.isValid() {
<del> continue
<del> }
<del> verstrs = append(verstrs, v.Name+"/"+v.Version)
<del> }
<del> return strings.Join(verstrs, " ")
<del>}
<del>
<del>// Decorator is used to change an instance of
<del>// http.Request. It could be used to add more header fields,
<del>// change body, etc.
<del>type Decorator interface {
<del> // ChangeRequest() changes the request accordingly.
<del> // The changed request will be returned or err will be non-nil
<del> // if an error occur.
<del> ChangeRequest(req *http.Request) (newReq *http.Request, err error)
<del>}
<del>
<del>// UserAgentDecorator appends the product/version to the user agent field
<del>// of a request.
<del>type UserAgentDecorator struct {
<del> Versions []UAVersionInfo
<del>}
<del>
<del>func (h *UserAgentDecorator) ChangeRequest(req *http.Request) (*http.Request, error) {
<del> if req == nil {
<del> return req, ErrNilRequest
<del> }
<del>
<del> userAgent := AppendVersions(req.UserAgent(), h.Versions...)
<del> if len(userAgent) > 0 {
<del> req.Header.Set("User-Agent", userAgent)
<del> }
<del> return req, nil
<del>}
<del>
<del>type MetaHeadersDecorator struct {
<del> Headers map[string][]string
<del>}
<del>
<del>func (h *MetaHeadersDecorator) ChangeRequest(req *http.Request) (*http.Request, error) {
<del> if h.Headers == nil {
<del> return req, ErrNilRequest
<del> }
<del> for k, v := range h.Headers {
<del> req.Header[k] = v
<del> }
<del> return req, nil
<del>}
<del>
<del>type AuthDecorator struct {
<del> login string
<del> password string
<del>}
<del>
<del>func NewAuthDecorator(login, password string) Decorator {
<del> return &AuthDecorator{
<del> login: login,
<del> password: password,
<del> }
<del>}
<del>
<del>func (self *AuthDecorator) ChangeRequest(req *http.Request) (*http.Request, error) {
<del> if req == nil {
<del> return req, ErrNilRequest
<del> }
<del> req.SetBasicAuth(self.login, self.password)
<del> return req, nil
<del>}
<del>
<del>// RequestFactory creates an HTTP request
<del>// and applies a list of decorators on the request.
<del>type RequestFactory struct {
<del> decorators []Decorator
<del>}
<del>
<del>func NewRequestFactory(d ...Decorator) *RequestFactory {
<del> return &RequestFactory{
<del> decorators: d,
<del> }
<del>}
<del>
<del>func (f *RequestFactory) AddDecorator(d ...Decorator) {
<del> f.decorators = append(f.decorators, d...)
<del>}
<del>
<del>func (f *RequestFactory) GetDecorators() []Decorator {
<del> return f.decorators
<del>}
<del>
<del>// NewRequest() creates a new *http.Request,
<del>// applies all decorators in the Factory on the request,
<del>// then applies decorators provided by d on the request.
<del>func (h *RequestFactory) NewRequest(method, urlStr string, body io.Reader, d ...Decorator) (*http.Request, error) {
<del> req, err := http.NewRequest(method, urlStr, body)
<del> if err != nil {
<del> return nil, err
<del> }
<del>
<del> // By default, a nil factory should work.
<del> if h == nil {
<del> return req, nil
<del> }
<del> for _, dec := range h.decorators {
<del> req, _ = dec.ChangeRequest(req)
<del> }
<del> for _, dec := range d {
<del> req, _ = dec.ChangeRequest(req)
<del> }
<del> logrus.Debugf("%v -- HEADERS: %v", req.URL, req.Header)
<del> return req, err
<del>}
<ide><path>pkg/requestdecorator/requestdecorator_test.go
<del>package requestdecorator
<del>
<del>import (
<del> "net/http"
<del> "strings"
<del> "testing"
<del>)
<del>
<del>func TestUAVersionInfo(t *testing.T) {
<del> uavi := NewUAVersionInfo("foo", "bar")
<del> if !uavi.isValid() {
<del> t.Fatalf("UAVersionInfo should be valid")
<del> }
<del> uavi = NewUAVersionInfo("", "bar")
<del> if uavi.isValid() {
<del> t.Fatalf("Expected UAVersionInfo to be invalid")
<del> }
<del> uavi = NewUAVersionInfo("foo", "")
<del> if uavi.isValid() {
<del> t.Fatalf("Expected UAVersionInfo to be invalid")
<del> }
<del>}
<del>
<del>func TestUserAgentDecorator(t *testing.T) {
<del> httpVersion := make([]UAVersionInfo, 2)
<del> httpVersion = append(httpVersion, NewUAVersionInfo("testname", "testversion"))
<del> httpVersion = append(httpVersion, NewUAVersionInfo("name", "version"))
<del> uad := &UserAgentDecorator{
<del> Versions: httpVersion,
<del> }
<del>
<del> req, err := http.NewRequest("GET", "/something", strings.NewReader("test"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> reqDecorated, err := uad.ChangeRequest(req)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if reqDecorated.Header.Get("User-Agent") != "testname/testversion name/version" {
<del> t.Fatalf("Request should have User-Agent 'testname/testversion name/version'")
<del> }
<del>}
<del>
<del>func TestUserAgentDecoratorErr(t *testing.T) {
<del> httpVersion := make([]UAVersionInfo, 0)
<del> uad := &UserAgentDecorator{
<del> Versions: httpVersion,
<del> }
<del>
<del> var req *http.Request
<del> _, err := uad.ChangeRequest(req)
<del> if err == nil {
<del> t.Fatalf("Expected to get ErrNilRequest instead no error was returned")
<del> }
<del>}
<del>
<del>func TestMetaHeadersDecorator(t *testing.T) {
<del> var headers = map[string][]string{
<del> "key1": {"value1"},
<del> "key2": {"value2"},
<del> }
<del> mhd := &MetaHeadersDecorator{
<del> Headers: headers,
<del> }
<del>
<del> req, err := http.NewRequest("GET", "/something", strings.NewReader("test"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> reqDecorated, err := mhd.ChangeRequest(req)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> v, ok := reqDecorated.Header["key1"]
<del> if !ok {
<del> t.Fatalf("Expected to have header key1")
<del> }
<del> if v[0] != "value1" {
<del> t.Fatalf("Expected value for key1 isn't value1")
<del> }
<del>
<del> v, ok = reqDecorated.Header["key2"]
<del> if !ok {
<del> t.Fatalf("Expected to have header key2")
<del> }
<del> if v[0] != "value2" {
<del> t.Fatalf("Expected value for key2 isn't value2")
<del> }
<del>}
<del>
<del>func TestMetaHeadersDecoratorErr(t *testing.T) {
<del> mhd := &MetaHeadersDecorator{}
<del>
<del> var req *http.Request
<del> _, err := mhd.ChangeRequest(req)
<del> if err == nil {
<del> t.Fatalf("Expected to get ErrNilRequest instead no error was returned")
<del> }
<del>}
<del>
<del>func TestAuthDecorator(t *testing.T) {
<del> ad := NewAuthDecorator("test", "password")
<del>
<del> req, err := http.NewRequest("GET", "/something", strings.NewReader("test"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> reqDecorated, err := ad.ChangeRequest(req)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> username, password, ok := reqDecorated.BasicAuth()
<del> if !ok {
<del> t.Fatalf("Cannot retrieve basic auth info from request")
<del> }
<del> if username != "test" {
<del> t.Fatalf("Expected username to be test, got %s", username)
<del> }
<del> if password != "password" {
<del> t.Fatalf("Expected password to be password, got %s", password)
<del> }
<del>}
<del>
<del>func TestAuthDecoratorErr(t *testing.T) {
<del> ad := &AuthDecorator{}
<del>
<del> var req *http.Request
<del> _, err := ad.ChangeRequest(req)
<del> if err == nil {
<del> t.Fatalf("Expected to get ErrNilRequest instead no error was returned")
<del> }
<del>}
<del>
<del>func TestRequestFactory(t *testing.T) {
<del> ad := NewAuthDecorator("test", "password")
<del> httpVersion := make([]UAVersionInfo, 2)
<del> httpVersion = append(httpVersion, NewUAVersionInfo("testname", "testversion"))
<del> httpVersion = append(httpVersion, NewUAVersionInfo("name", "version"))
<del> uad := &UserAgentDecorator{
<del> Versions: httpVersion,
<del> }
<del>
<del> requestFactory := NewRequestFactory(ad, uad)
<del>
<del> if l := len(requestFactory.GetDecorators()); l != 2 {
<del> t.Fatalf("Expected to have two decorators, got %d", l)
<del> }
<del>
<del> req, err := requestFactory.NewRequest("GET", "/test", strings.NewReader("test"))
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> username, password, ok := req.BasicAuth()
<del> if !ok {
<del> t.Fatalf("Cannot retrieve basic auth info from request")
<del> }
<del> if username != "test" {
<del> t.Fatalf("Expected username to be test, got %s", username)
<del> }
<del> if password != "password" {
<del> t.Fatalf("Expected password to be password, got %s", password)
<del> }
<del> if req.Header.Get("User-Agent") != "testname/testversion name/version" {
<del> t.Fatalf("Request should have User-Agent 'testname/testversion name/version'")
<del> }
<del>}
<del>
<del>func TestRequestFactoryNewRequestWithDecorators(t *testing.T) {
<del> ad := NewAuthDecorator("test", "password")
<del>
<del> requestFactory := NewRequestFactory(ad)
<del>
<del> if l := len(requestFactory.GetDecorators()); l != 1 {
<del> t.Fatalf("Expected to have one decorators, got %d", l)
<del> }
<del>
<del> ad2 := NewAuthDecorator("test2", "password2")
<del>
<del> req, err := requestFactory.NewRequest("GET", "/test", strings.NewReader("test"), ad2)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> username, password, ok := req.BasicAuth()
<del> if !ok {
<del> t.Fatalf("Cannot retrieve basic auth info from request")
<del> }
<del> if username != "test2" {
<del> t.Fatalf("Expected username to be test, got %s", username)
<del> }
<del> if password != "password2" {
<del> t.Fatalf("Expected password to be password, got %s", password)
<del> }
<del>}
<del>
<del>func TestRequestFactoryAddDecorator(t *testing.T) {
<del> requestFactory := NewRequestFactory()
<del>
<del> if l := len(requestFactory.GetDecorators()); l != 0 {
<del> t.Fatalf("Expected to have zero decorators, got %d", l)
<del> }
<del>
<del> ad := NewAuthDecorator("test", "password")
<del> requestFactory.AddDecorator(ad)
<del>
<del> if l := len(requestFactory.GetDecorators()); l != 1 {
<del> t.Fatalf("Expected to have one decorators, got %d", l)
<del> }
<del>}
<del>
<del>func TestRequestFactoryNil(t *testing.T) {
<del> var requestFactory RequestFactory
<del> _, err := requestFactory.NewRequest("GET", "/test", strings.NewReader("test"))
<del> if err != nil {
<del> t.Fatalf("Expected not to get and error, got %s", err)
<del> }
<del>}
<ide><path>pkg/useragent/README.md
<add>This package provides helper functions to pack version information into a single User-Agent header.
<ide><path>pkg/useragent/useragent.go
<add>// Package useragent provides helper functions to pack
<add>// version information into a single User-Agent header.
<add>package useragent
<add>
<add>import (
<add> "errors"
<add> "strings"
<add>)
<add>
<add>var (
<add> ErrNilRequest = errors.New("request cannot be nil")
<add>)
<add>
<add>// VersionInfo is used to model UserAgent versions.
<add>type VersionInfo struct {
<add> Name string
<add> Version string
<add>}
<add>
<add>func (vi *VersionInfo) isValid() bool {
<add> const stopChars = " \t\r\n/"
<add> name := vi.Name
<add> vers := vi.Version
<add> if len(name) == 0 || strings.ContainsAny(name, stopChars) {
<add> return false
<add> }
<add> if len(vers) == 0 || strings.ContainsAny(vers, stopChars) {
<add> return false
<add> }
<add> return true
<add>}
<add>
<add>// Convert versions to a string and append the string to the string base.
<add>//
<add>// Each VersionInfo will be converted to a string in the format of
<add>// "product/version", where the "product" is get from the name field, while
<add>// version is get from the version field. Several pieces of verson information
<add>// will be concatinated and separated by space.
<add>//
<add>// Example:
<add>// AppendVersions("base", VersionInfo{"foo", "1.0"}, VersionInfo{"bar", "2.0"})
<add>// results in "base foo/1.0 bar/2.0".
<add>func AppendVersions(base string, versions ...VersionInfo) string {
<add> if len(versions) == 0 {
<add> return base
<add> }
<add>
<add> verstrs := make([]string, 0, 1+len(versions))
<add> if len(base) > 0 {
<add> verstrs = append(verstrs, base)
<add> }
<add>
<add> for _, v := range versions {
<add> if !v.isValid() {
<add> continue
<add> }
<add> verstrs = append(verstrs, v.Name+"/"+v.Version)
<add> }
<add> return strings.Join(verstrs, " ")
<add>}
<ide><path>pkg/useragent/useragent_test.go
<add>package useragent
<add>
<add>import "testing"
<add>
<add>func TestVersionInfo(t *testing.T) {
<add> vi := VersionInfo{"foo", "bar"}
<add> if !vi.isValid() {
<add> t.Fatalf("VersionInfo should be valid")
<add> }
<add> vi = VersionInfo{"", "bar"}
<add> if vi.isValid() {
<add> t.Fatalf("Expected VersionInfo to be invalid")
<add> }
<add> vi = VersionInfo{"foo", ""}
<add> if vi.isValid() {
<add> t.Fatalf("Expected VersionInfo to be invalid")
<add> }
<add>}
<add>
<add>func TestAppendVersions(t *testing.T) {
<add> vis := []VersionInfo{
<add> {"foo", "1.0"},
<add> {"bar", "0.1"},
<add> {"pi", "3.1.4"},
<add> }
<add> v := AppendVersions("base", vis...)
<add> expect := "base foo/1.0 bar/0.1 pi/3.1.4"
<add> if v != expect {
<add> t.Fatalf("expected %q, got %q", expect, v)
<add> }
<add>}
<ide><path>registry/registry.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/autogen/dockerversion"
<ide> "github.com/docker/docker/pkg/parsers/kernel"
<del> "github.com/docker/docker/pkg/requestdecorator"
<ide> "github.com/docker/docker/pkg/timeoutconn"
<add> "github.com/docker/docker/pkg/useragent"
<ide> )
<ide>
<ide> var (
<ide> func cloneRequest(r *http.Request) *http.Request {
<ide>
<ide> func (tr *DockerHeaders) RoundTrip(req *http.Request) (*http.Response, error) {
<ide> req = cloneRequest(req)
<del> httpVersion := make([]requestdecorator.UAVersionInfo, 0, 4)
<del> httpVersion = append(httpVersion, requestdecorator.NewUAVersionInfo("docker", dockerversion.VERSION))
<del> httpVersion = append(httpVersion, requestdecorator.NewUAVersionInfo("go", runtime.Version()))
<del> httpVersion = append(httpVersion, requestdecorator.NewUAVersionInfo("git-commit", dockerversion.GITCOMMIT))
<add> httpVersion := make([]useragent.VersionInfo, 0, 4)
<add> httpVersion = append(httpVersion, useragent.VersionInfo{"docker", dockerversion.VERSION})
<add> httpVersion = append(httpVersion, useragent.VersionInfo{"go", runtime.Version()})
<add> httpVersion = append(httpVersion, useragent.VersionInfo{"git-commit", dockerversion.GITCOMMIT})
<ide> if kernelVersion, err := kernel.GetKernelVersion(); err == nil {
<del> httpVersion = append(httpVersion, requestdecorator.NewUAVersionInfo("kernel", kernelVersion.String()))
<add> httpVersion = append(httpVersion, useragent.VersionInfo{"kernel", kernelVersion.String()})
<ide> }
<del> httpVersion = append(httpVersion, requestdecorator.NewUAVersionInfo("os", runtime.GOOS))
<del> httpVersion = append(httpVersion, requestdecorator.NewUAVersionInfo("arch", runtime.GOARCH))
<add> httpVersion = append(httpVersion, useragent.VersionInfo{"os", runtime.GOOS})
<add> httpVersion = append(httpVersion, useragent.VersionInfo{"arch", runtime.GOARCH})
<ide>
<del> userAgent := requestdecorator.AppendVersions(req.UserAgent(), httpVersion...)
<add> userAgent := useragent.AppendVersions(req.UserAgent(), httpVersion...)
<ide>
<ide> req.Header.Set("User-Agent", userAgent)
<ide> | 7 |
Ruby | Ruby | fix patching test for no-compat mode | 33befcf312e12496fc1a6b0df531f03d97dfe954 | <ide><path>Library/Homebrew/formula.rb
<ide> def stage
<ide> end
<ide>
<ide> def prepare_patches
<del> active_spec.add_legacy_patches(patches)
<add> active_spec.add_legacy_patches(patches) if respond_to?(:patches)
<ide>
<ide> patchlist.grep(DATAPatch) { |p| p.path = path }
<ide>
<ide><path>Library/Homebrew/test/test_patching.rb
<ide> def test_patch_string_with_strip
<ide> def test_patch_DATA_constant
<ide> assert_patched formula("test", Pathname.new(__FILE__).expand_path) {
<ide> def patches
<del> Formula::DATA
<add> :DATA
<ide> end
<ide> }
<ide> end | 2 |
Text | Text | add romankl to collaborators | 52351430cf360913b09e626783d9c660f13016c4 | <ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [qard](https://github.com/qard) - **Stephen Belanger** <admin@stephenbelanger.com>
<ide> * [rlidwka](https://github.com/rlidwka) - **Alex Kocharin** <alex@kocharin.ru>
<ide> * [robertkowalski](https://github.com/robertkowalski) - **Robert Kowalski** <rok@kowalski.gd>
<add>* [romankl](https://github.com/romankl) - **Roman Klauke** <romaaan.git@gmail.com>
<ide> * [saghul](https://github.com/saghul) - **Saúl Ibarra Corretgé** <saghul@gmail.com>
<ide> * [sam-github](https://github.com/sam-github) - **Sam Roberts** <vieuxtech@gmail.com>
<ide> * [seishun](https://github.com/seishun) - **Nikolai Vavilov** <vvnicholas@gmail.com> | 1 |
PHP | PHP | add support for tinytext, mediumtext and longtext | 2784faf8d4eb6924e3a22e7844412fb4fa6f78be | <ide><path>src/Database/Schema/MysqlSchema.php
<ide> protected function _convertColumn($column)
<ide> return ['type' => 'string', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'text') !== false) {
<add> $lengthName = substr($col, 0, -4);
<add> $length = isset(Table::$columnLengths[$lengthName]) ? Table::$columnLengths[$lengthName] : null;
<ide> return ['type' => 'text', 'length' => $length];
<ide> }
<ide> if (strpos($col, 'blob') !== false || $col === 'binary') {
<ide> public function columnSql(Table $table, $name)
<ide> 'binary' => ' LONGBLOB',
<ide> 'float' => ' FLOAT',
<ide> 'decimal' => ' DECIMAL',
<del> 'text' => ' TEXT',
<ide> 'date' => ' DATE',
<ide> 'time' => ' TIME',
<ide> 'datetime' => ' DATETIME',
<ide> public function columnSql(Table $table, $name)
<ide> ];
<ide> $specialMap = [
<ide> 'string' => true,
<add> 'text' => true,
<ide> ];
<ide> if (isset($typeMap[$data['type']])) {
<ide> $out .= $typeMap[$data['type']];
<ide> public function columnSql(Table $table, $name)
<ide> if (!isset($data['length'])) {
<ide> $data['length'] = 255;
<ide> }
<add> break;
<add> case 'text':
<add> $isKnownLength = in_array($data['length'], Table::$columnLengths);
<add> if (empty($data['length']) || !$isKnownLength) {
<add> $out .= ' TEXT';
<add> break;
<add> }
<add>
<add> if ($isKnownLength) {
<add> $length = array_search($data['length'], Table::$columnLengths);
<add> $out .= ' ' . strtoupper($length) . 'TEXT';
<add> }
<add>
<ide> break;
<ide> }
<ide> }
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> 'binary' => ' BYTEA',
<ide> 'float' => ' FLOAT',
<ide> 'decimal' => ' DECIMAL',
<del> 'text' => ' TEXT',
<ide> 'date' => ' DATE',
<ide> 'time' => ' TIME',
<ide> 'datetime' => ' TIMESTAMP',
<ide> public function columnSql(Table $table, $name)
<ide> $out .= $type;
<ide> }
<ide>
<del> if ($data['type'] === 'string') {
<add> if ($data['type'] === 'text' && $data['length'] !== Table::LENGTH_TINY) {
<add> $out .= ' TEXT';
<add> }
<add>
<add> if ($data['type'] === 'string' || ($data['type'] === 'text' && $data['length'] === Table::LENGTH_TINY)) {
<ide> $isFixed = !empty($data['fixed']);
<ide> $type = ' VARCHAR';
<ide> if ($isFixed) {
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> $data = $table->column($name);
<ide> $typeMap = [
<ide> 'uuid' => ' CHAR(36)',
<del> 'string' => ' VARCHAR',
<del> 'integer' => ' INTEGER',
<ide> 'biginteger' => ' BIGINT',
<ide> 'boolean' => ' BOOLEAN',
<ide> 'binary' => ' BLOB',
<ide> 'float' => ' FLOAT',
<ide> 'decimal' => ' DECIMAL',
<del> 'text' => ' TEXT',
<ide> 'date' => ' DATE',
<ide> 'time' => ' TIME',
<ide> 'datetime' => ' DATETIME',
<ide> 'timestamp' => ' TIMESTAMP',
<ide> ];
<del> if (!isset($typeMap[$data['type']])) {
<del> throw new Exception(sprintf('Unknown column type for "%s"', $name));
<del> }
<ide>
<ide> $out = $this->_driver->quoteIdentifier($name);
<ide> $hasUnsigned = ['biginteger', 'integer', 'float', 'decimal'];
<ide> public function columnSql(Table $table, $name)
<ide> $out .= ' UNSIGNED';
<ide> }
<ide> }
<del> $out .= $typeMap[$data['type']];
<ide>
<del> $hasLength = ['integer', 'string'];
<del> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) {
<del> if ($data['type'] !== 'integer' || [$name] !== (array)$table->primaryKey()) {
<add> if (isset($typeMap[$data['type']])) {
<add> $out .= $typeMap[$data['type']];
<add> }
<add>
<add> if ($data['type'] === 'text' && $data['length'] !== Table::LENGTH_TINY) {
<add> $out .= ' TEXT';
<add> }
<add>
<add> if ($data['type'] === 'string' || ($data['type'] === 'text' && $data['length'] === Table::LENGTH_TINY)) {
<add> $out .= ' VARCHAR';
<add>
<add> if (isset($data['length'])) {
<add> $out .= '(' . (int)$data['length'] . ')';
<add> }
<add> }
<add>
<add> if ($data['type'] === 'integer') {
<add> $out .= ' INTEGER';
<add> if (isset($data['length']) && [$name] !== (array)$table->primaryKey()) {
<ide> $out .= '(' . (int)$data['length'] . ')';
<ide> }
<ide> }
<add>
<ide> $hasPrecision = ['float', 'decimal'];
<ide> if (in_array($data['type'], $hasPrecision, true) &&
<ide> (isset($data['length']) || isset($data['precision']))
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> 'binary' => ' VARBINARY(MAX)',
<ide> 'float' => ' FLOAT',
<ide> 'decimal' => ' DECIMAL',
<del> 'text' => ' NVARCHAR(MAX)',
<ide> 'date' => ' DATE',
<ide> 'time' => ' TIME',
<ide> 'datetime' => ' DATETIME',
<ide> public function columnSql(Table $table, $name)
<ide> }
<ide> }
<ide>
<del> if ($data['type'] === 'string') {
<add> if ($data['type'] === 'text' && $data['length'] !== Table::LENGTH_TINY) {
<add> $out .= ' NVARCHAR(MAX)';
<add> }
<add>
<add> if ($data['type'] === 'string' || ($data['type'] === 'text' && $data['length'] === Table::LENGTH_TINY)) {
<ide> $type = ' NVARCHAR';
<ide>
<ide> if (!empty($data['fixed'])) {
<ide><path>src/Database/Schema/Table.php
<ide> class Table
<ide> */
<ide> protected $_temporary = false;
<ide>
<add> /**
<add> * Column length when using a `tiny` text column type
<add> *
<add> * @var int
<add> */
<add> const LENGTH_TINY = 255;
<add>
<add> /**
<add> * Column length when using a `medium` text column type
<add> *
<add> * @var int
<add> */
<add> const LENGTH_MEDIUM = 16777215;
<add>
<add> /**
<add> * Column length when using a `long` text column type
<add> *
<add> * @var int
<add> */
<add> const LENGTH_LONG = 4294967295;
<add>
<add> public static $columnLengths = [
<add> 'tiny' => self::LENGTH_TINY,
<add> 'medium' => self::LENGTH_MEDIUM,
<add> 'long' => self::LENGTH_LONG
<add> ];
<add>
<add>
<ide> /**
<ide> * The valid keys that can be used in a column
<ide> * definition.
<ide><path>tests/Fixture/TagsFixture.php
<ide> */
<ide> namespace Cake\Test\Fixture;
<ide>
<add>use Cake\Database\Schema\Table;
<ide> use Cake\TestSuite\Fixture\TestFixture;
<ide>
<ide> /**
<ide> class TagsFixture extends TestFixture
<ide> public $fields = [
<ide> 'id' => ['type' => 'integer', 'null' => false],
<ide> 'name' => ['type' => 'string', 'null' => false],
<add> 'description' => ['type' => 'text', 'length' => Table::LENGTH_MEDIUM],
<ide> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
<ide> ];
<ide>
<ide> class TagsFixture extends TestFixture
<ide> * @var array
<ide> */
<ide> public $records = [
<del> ['name' => 'tag1'],
<del> ['name' => 'tag2'],
<del> ['name' => 'tag3']
<add> ['name' => 'tag1', 'description' => 'A big description'],
<add> ['name' => 'tag2', 'description' => 'Another big description'],
<add> ['name' => 'tag3', 'description' => 'Yet another one']
<ide> ];
<ide> }
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public static function convertColumnProvider()
<ide> ],
<ide> [
<ide> 'TINYTEXT',
<del> ['type' => 'text', 'length' => null]
<add> ['type' => 'text', 'length' => 255]
<add> ],
<add> [
<add> 'MEDIUMTEXT',
<add> ['type' => 'text', 'length' => 16777215]
<add> ],
<add> [
<add> 'LONGTEXT',
<add> ['type' => 'text', 'length' => 4294967295]
<ide> ],
<ide> [
<ide> 'BLOB',
<ide> public static function convertColumnProvider()
<ide> }
<ide>
<ide> /**
<del> * Test parsing MySQL column types form field description.
<add> * Test parsing MySQL column types from field description.
<ide> *
<ide> * @dataProvider convertColumnProvider
<ide> * @return void
<ide> public static function columnSqlProvider()
<ide> ['type' => 'text', 'null' => false],
<ide> '`body` TEXT NOT NULL'
<ide> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
<add> '`body` TINYTEXT NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
<add> '`body` MEDIUMTEXT NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
<add> '`body` LONGTEXT NOT NULL'
<add> ],
<ide> // Integers
<ide> [
<ide> 'post_id',
<ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php
<ide>
<ide> use Cake\Core\Configure;
<ide> use Cake\Database\Schema\Collection as SchemaCollection;
<add>use Cake\Database\Schema\MysqlSchema;
<ide> use Cake\Database\Schema\PostgresSchema;
<ide> use Cake\Database\Schema\Table;
<ide> use Cake\Datasource\ConnectionManager;
<ide> public static function columnSqlProvider()
<ide> ['type' => 'text', 'null' => false],
<ide> '"body" TEXT NOT NULL'
<ide> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
<add> '"body" VARCHAR(' . Table::LENGTH_TINY . ') NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
<add> '"body" TEXT NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
<add> '"body" TEXT NOT NULL'
<add> ],
<ide> // Integers
<ide> [
<ide> 'post_id',
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public static function columnSqlProvider()
<ide> ['type' => 'text', 'null' => false],
<ide> '"body" TEXT NOT NULL'
<ide> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
<add> '"body" VARCHAR(' . Table::LENGTH_TINY . ') NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
<add> '"body" TEXT NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
<add> '"body" TEXT NOT NULL'
<add> ],
<ide> // Integers
<ide> [
<ide> 'post_id',
<ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php
<ide> public static function columnSqlProvider()
<ide> ['type' => 'text', 'null' => false],
<ide> '[body] NVARCHAR(MAX) NOT NULL'
<ide> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_TINY, 'null' => false],
<add> '[body] NVARCHAR(' . Table::LENGTH_TINY . ') NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_MEDIUM, 'null' => false],
<add> '[body] NVARCHAR(MAX) NOT NULL'
<add> ],
<add> [
<add> 'body',
<add> ['type' => 'text', 'length' => Table::LENGTH_LONG, 'null' => false],
<add> '[body] NVARCHAR(MAX) NOT NULL'
<add> ],
<ide> // Integers
<ide> [
<ide> 'post_id',
<ide><path>tests/TestCase/ORM/QueryTest.php
<ide> public function testBelongsToManyEagerLoadingNoHydration($strategy)
<ide> [
<ide> 'id' => 1,
<ide> 'name' => 'tag1',
<del> '_joinData' => ['article_id' => 1, 'tag_id' => 1]
<add> '_joinData' => ['article_id' => 1, 'tag_id' => 1],
<add> 'description' => 'A big description'
<ide> ],
<ide> [
<ide> 'id' => 2,
<ide> 'name' => 'tag2',
<del> '_joinData' => ['article_id' => 1, 'tag_id' => 2]
<add> '_joinData' => ['article_id' => 1, 'tag_id' => 2],
<add> 'description' => 'Another big description'
<ide> ]
<ide> ]
<ide> ],
<ide> public function testBelongsToManyEagerLoadingNoHydration($strategy)
<ide> [
<ide> 'id' => 1,
<ide> 'name' => 'tag1',
<del> '_joinData' => ['article_id' => 2, 'tag_id' => 1]
<add> '_joinData' => ['article_id' => 2, 'tag_id' => 1],
<add> 'description' => 'A big description'
<ide> ],
<ide> [
<ide> 'id' => 3,
<ide> 'name' => 'tag3',
<del> '_joinData' => ['article_id' => 2, 'tag_id' => 3]
<add> '_joinData' => ['article_id' => 2, 'tag_id' => 3],
<add> 'description' => 'Yet another one'
<ide> ]
<ide> ]
<ide> ],
<ide> public function testBelongsToManyEagerLoadingNoHydration($strategy)
<ide> [
<ide> 'id' => 3,
<ide> 'name' => 'tag3',
<del> '_joinData' => ['article_id' => 2, 'tag_id' => 3]
<add> '_joinData' => ['article_id' => 2, 'tag_id' => 3],
<add> 'description' => 'Yet another one'
<ide> ]
<ide> ]
<ide> ],
<ide> public function testFilteringByBelongsToManyNoHydration()
<ide> 'Tags' => [
<ide> 'id' => 3,
<ide> 'name' => 'tag3',
<add> 'description' => 'Yet another one',
<ide> ],
<ide> 'ArticlesTags' => ['article_id' => 2, 'tag_id' => 3]
<ide> ]
<ide> public function testFilteringByBelongsToManyNoHydration()
<ide> 'Tags' => [
<ide> 'id' => 2,
<ide> 'name' => 'tag2',
<add> 'description' => 'Another big description',
<ide> ],
<ide> 'ArticlesTags' => ['article_id' => 1, 'tag_id' => 2]
<ide> ]
<ide> public function testMatchingDotNotation()
<ide> 'tags' => [
<ide> 'id' => 2,
<ide> 'name' => 'tag2',
<add> 'description' => 'Another big description',
<ide> ],
<ide> 'articles' => [
<ide> 'id' => 1,
<ide> public function testMatchingDotNotation()
<ide> 'published' => 'Y'
<ide> ],
<ide> 'ArticlesTags' => [
<del> 'article_id' => 1,
<del> 'tag_id' => 2
<del> ]
<add> 'article_id' => 1,
<add> 'tag_id' => 2
<add> ]
<ide> ]
<ide> ]
<ide> ];
<ide> public function testHydrateBelongsToMany()
<ide> $expected = [
<ide> 'id' => 1,
<ide> 'name' => 'tag1',
<del> '_joinData' => ['article_id' => 1, 'tag_id' => 1]
<add> '_joinData' => ['article_id' => 1, 'tag_id' => 1],
<add> 'description' => 'A big description',
<ide> ];
<ide> $this->assertEquals($expected, $first->tags[0]->toArray());
<ide>
<ide> $expected = [
<ide> 'id' => 2,
<ide> 'name' => 'tag2',
<del> '_joinData' => ['article_id' => 1, 'tag_id' => 2]
<add> '_joinData' => ['article_id' => 1, 'tag_id' => 2],
<add> 'description' => 'Another big description'
<ide> ];
<ide> $this->assertEquals($expected, $first->tags[1]->toArray());
<ide> }
<ide> public function testFormatResultsBelongsToMany()
<ide> $expected = [
<ide> 'id' => 1,
<ide> 'name' => 'tag1',
<del> '_joinData' => ['article_id' => 1, 'tag_id' => 1]
<add> '_joinData' => ['article_id' => 1, 'tag_id' => 1],
<add> 'description' => 'A big description',
<ide> ];
<ide> $this->assertEquals($expected, $first->tags[0]->toArray());
<ide>
<ide> $expected = [
<ide> 'id' => 2,
<ide> 'name' => 'tag2',
<del> '_joinData' => ['article_id' => 1, 'tag_id' => 2]
<add> '_joinData' => ['article_id' => 1, 'tag_id' => 2],
<add> 'description' => 'Another big description'
<ide> ];
<ide> $this->assertEquals($expected, $first->tags[1]->toArray());
<ide> }
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testLinkBelongsToMany()
<ide> ], $options);
<ide>
<ide> $newTag = new \TestApp\Model\Entity\Tag([
<del> 'name' => 'Foo'
<add> 'name' => 'Foo',
<add> 'description' => 'Foo desc'
<ide> ], $source);
<ide> $tags[] = new \TestApp\Model\Entity\Tag([
<ide> 'id' => 3 | 12 |
Mixed | Text | fix some typos | 83880b0f0b26554f321129b834c547b385808c7e | <ide><path>CHANGELOG.md
<ide> * **lang:** Complete the Simplified Chinese translations (zn-CN.json) ([#4827](https://github.com/videojs/video.js/issues/4827)) ([98773dd](https://github.com/videojs/video.js/commit/98773dd))
<ide> * **lang:** Complete the Traditional Chinese translation (zh-CT.json) ([#4828](https://github.com/videojs/video.js/issues/4828)) ([eb4bd9f](https://github.com/videojs/video.js/commit/eb4bd9f))
<ide> * Fix an issue where hookOnce failed for the 'beforesetup' hook. ([#4841](https://github.com/videojs/video.js/issues/4841)) ([a6f4444](https://github.com/videojs/video.js/commit/a6f4444))
<del>* replace with \u00a0 ([#4825](https://github.com/videojs/video.js/issues/4825)) ([98fe49f](https://github.com/videojs/video.js/commit/98fe49f)), closes [#4309](https://github.com/videojs/video.js/issues/4309)
<add>* replace ` ` with `\u00a0` ([#4825](https://github.com/videojs/video.js/issues/4825)) ([98fe49f](https://github.com/videojs/video.js/commit/98fe49f)), closes [#4309](https://github.com/videojs/video.js/issues/4309)
<ide> * wrap audio change handler rather than bind so a player dispose doesn't affect other players ([#4847](https://github.com/videojs/video.js/issues/4847)) ([4eb0047](https://github.com/videojs/video.js/commit/4eb0047))
<ide>
<ide> ### Chores
<ide><path>docs/guides/embeds.md
<ide> # How to Embed the Video.js player
<ide>
<del>Video.js is meant to be an enhacement to the video element in HTML5 so for years, its embed code has been just a `<video>` element.
<add>Video.js is meant to be an enhancement to the video element in HTML5 and for years, its embed code has been just a `<video>` element.
<ide> Video.js then wraps the video element in a div that is used for us to place controls and anything else that's required for the player.
<ide>
<del>For a long time this was enough. In 2016, "div ingest" was added, it allows the developer to give Video.js a player div to use instead of making it's own.
<add>For a long time this was enough. In 2016, "div ingest" was added, and it allows the developer to give Video.js a player div to use instead of making it's own.
<ide> This is partly to help with content reflow but also to help with iOS where you sometimes need to prime the video element and we re-create the video element when we create the player div.
<ide> However, this is kind of weird to have a `<video>` element embed with a `<div>` wrapped around it. So, we built out a new embed, a `<video-js>` embed.
<ide>
<ide> const player = videojs('vid1', {});
<ide> ```
<ide>
<ide> ### Player div ingest
<del>The enhanced classic embed. You can also initialize it via `data-setup` or via `videojs` method.
<add>The enhanced classic embed. You can also initialize it via `data-setup` or via the `videojs` method.
<ide>
<ide> ```html
<ide> <!-- via data-setup -->
<ide> const player = videojs('vid1', {});
<ide> Adding `class="video-js"` with this embed is no longer necessary as it will automatically add the class `video-js` if missing.
<ide>
<ide> #### Custom Elements
<del>Native Custom Elements support is relativly small according to [Can I Use](http://caniuse.com/#feat=custom-elementsv1) and because we didn't want to include a polyfill we're going with just an element called `video-js` rather than a full blown custom element.
<add>Native Custom Elements support is relatively small according to [Can I Use](http://caniuse.com/#feat=custom-elementsv1) and because we didn't want to include a polyfill we're going with just an element called `video-js` rather than a full blown custom element.
<ide>
<ide> #### Browser support
<ide> These all work in all browsers that Video.js supports, though, there are some caveats for some older browsers.
<ide><path>docs/guides/text-tracks.md
<ide> As mentioned [above](#a-note-on-remote-text-tracks), remote text tracks represen
<ide> ```js
<ide> const trackEl = player.addRemoteTextTrack({src: 'en.vtt'}, false);
<ide> trackEl.addEventListener('load', function() {
<del> // your callback go here
<add> // your callback goes here
<ide> });
<ide> ```
<ide>
<ide><path>src/js/button.js
<ide> class Button extends ClickableComponent {
<ide> }
<ide>
<ide> /**
<del> * Enable the `Button` element so that it cannot be activated or clicked. Use this with
<add> * Disable the `Button` element so that it cannot be activated or clicked. Use this with
<ide> * {@link Button#enable}.
<ide> */
<ide> disable() { | 4 |
Python | Python | fix multiple context manages in examples | 2bd78c39e33b90f788b1121b93b3b098c4c4af10 | <ide><path>examples/training/rehearsal.py
<ide> def main(model_name, unlabelled_loc):
<ide> pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
<ide> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> sizes = compounding(1.0, 4.0, 1.001)
<del> with nlp.disable_pipes(*other_pipes) and warnings.catch_warnings():
<add> with nlp.disable_pipes(*other_pipes), warnings.catch_warnings():
<ide> # show warnings for misaligned entity spans once
<ide> warnings.filterwarnings("once", category=UserWarning, module='spacy')
<ide>
<ide><path>examples/training/train_ner.py
<ide> def main(model=None, output_dir=None, n_iter=100):
<ide> pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
<ide> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> # only train NER
<del> with nlp.disable_pipes(*other_pipes) and warnings.catch_warnings():
<add> with nlp.disable_pipes(*other_pipes), warnings.catch_warnings():
<ide> # show warnings for misaligned entity spans once
<ide> warnings.filterwarnings("once", category=UserWarning, module='spacy')
<ide>
<ide><path>examples/training/train_new_entity_type.py
<ide> def main(model=None, new_model_name="animal", output_dir=None, n_iter=30):
<ide> pipe_exceptions = ["ner", "trf_wordpiecer", "trf_tok2vec"]
<ide> other_pipes = [pipe for pipe in nlp.pipe_names if pipe not in pipe_exceptions]
<ide> # only train NER
<del> with nlp.disable_pipes(*other_pipes) and warnings.catch_warnings():
<add> with nlp.disable_pipes(*other_pipes), warnings.catch_warnings():
<ide> # show warnings for misaligned entity spans once
<ide> warnings.filterwarnings("once", category=UserWarning, module='spacy')
<ide> | 3 |
Java | Java | add @requestbody tests | 9cc01fc185a70f56acd5adb5355ae09a44d614a7 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestBodyArgumentResolver.java
<ide> public boolean supportsParameter(MethodParameter parameter) {
<ide> }
<ide>
<ide> @Override
<del> public Mono<Object> resolveArgument(MethodParameter parameter, ModelMap model,
<del> ServerWebExchange exchange) {
<del>
<del> ResolvableType type = ResolvableType.forMethodParameter(parameter);
<add> public Mono<Object> resolveArgument(MethodParameter parameter, ModelMap model, ServerWebExchange exchange) {
<ide>
<ide> TypeDescriptor typeDescriptor = new TypeDescriptor(parameter);
<ide> boolean convertFromMono = getConversionService().canConvert(MONO_TYPE, typeDescriptor);
<ide> boolean convertFromFlux = getConversionService().canConvert(FLUX_TYPE, typeDescriptor);
<ide>
<add> ResolvableType type = ResolvableType.forMethodParameter(parameter);
<ide> ResolvableType elementType = convertFromMono || convertFromFlux ? type.getGeneric(0) : type;
<ide>
<ide> ServerHttpRequest request = exchange.getRequest();
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestBodyArgumentResolverTests.java
<ide> */
<ide> package org.springframework.web.reactive.result.method.annotation;
<ide>
<add>import java.io.Serializable;
<add>import java.lang.reflect.Method;
<ide> import java.net.URI;
<ide> import java.nio.ByteBuffer;
<ide> import java.nio.charset.Charset;
<ide> import javax.xml.bind.annotation.XmlRootElement;
<ide>
<ide> import org.junit.Before;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> public void missingContentType() throws Exception {
<ide> .assertError(UnsupportedMediaTypeStatusException.class);
<ide> }
<ide>
<add> @Test // SPR-9942
<add> public void missingContent() throws Exception {
<add> this.request.writeWith(Flux.empty());
<add> ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
<add> MethodParameter param = this.testMethod.resolveParam(type);
<add> Mono<Object> result = this.resolver.resolveArgument(param, new ExtendedModelMap(), this.exchange);
<add>
<add> TestSubscriber.subscribe(result)
<add> .assertError(UnsupportedMediaTypeStatusException.class);
<add> }
<add>
<ide> @Test @SuppressWarnings("unchecked")
<ide> public void monoTestBean() throws Exception {
<ide> String body = "{\"bar\":\"b1\",\"foo\":\"f1\"}";
<ide> public void list() throws Exception {
<ide> assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), list);
<ide> }
<ide>
<add> @Test
<add> public void monoList() throws Exception {
<add> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]";
<add> ResolvableType type = forClassWithGenerics(Mono.class, forClassWithGenerics(List.class, TestBean.class));
<add> MethodParameter param = this.testMethod.resolveParam(type);
<add> Mono<?> mono = resolveValue(param, Mono.class, body);
<add>
<add> List<?> list = (List<?>) mono.block(Duration.ofSeconds(5));
<add> assertEquals(Arrays.asList(new TestBean("f1", "b1"), new TestBean("f2", "b2")), list);
<add> }
<add>
<ide> @Test
<ide> public void array() throws Exception {
<ide> String body = "[{\"bar\":\"b1\",\"foo\":\"f1\"},{\"bar\":\"b2\",\"foo\":\"f2\"}]";
<ide> public void validateFluxTestBean() throws Exception {
<ide> .assertError(ServerWebInputException.class);
<ide> }
<ide>
<add> @Test // SPR-9964
<add> @Ignore
<add> public void parameterizedMethodArgument() throws Exception {
<add> Class<?> clazz = ConcreteParameterizedController.class;
<add> MethodParameter param = ResolvableMethod.on(clazz).name("handleDto").resolveParam();
<add> SimpleBean simpleBean = resolveValue(param, SimpleBean.class, "{\"name\" : \"Jad\"}");
<add>
<add> assertEquals("Jad", simpleBean.getName());
<add> }
<add>
<add>
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> private <T> T resolveValue(MethodParameter param, Class<T> valueType, String body) {
<ide> private <T> T resolveValue(MethodParameter param, Class<T> valueType, String bod
<ide> Object value = result.block(Duration.ofSeconds(5));
<ide>
<ide> assertNotNull(value);
<del> assertTrue("Actual type: " + value.getClass(), valueType.isAssignableFrom(value.getClass()));
<add> assertTrue("Unexpected return value type: " + value, valueType.isAssignableFrom(value.getClass()));
<ide>
<ide> return (T) value;
<ide> }
<ide> void handle(
<ide> @RequestBody TestBean testBean,
<ide> @RequestBody Map<String, String> map,
<ide> @RequestBody List<TestBean> list,
<add> @RequestBody Mono<List<TestBean>> monoList,
<ide> @RequestBody Set<TestBean> set,
<ide> @RequestBody TestBean[] array,
<ide> TestBean paramWithoutAnnotation) {
<ide> public void validate(Object target, Errors errors) {
<ide> }
<ide> }
<ide> }
<add>
<add> private static abstract class AbstractParameterizedController<DTO extends Identifiable> {
<add>
<add> @SuppressWarnings("unused")
<add> public void handleDto(@RequestBody DTO dto) {}
<add> }
<add>
<add> private static class ConcreteParameterizedController extends AbstractParameterizedController<SimpleBean> {
<add> }
<add>
<add> private interface Identifiable extends Serializable {
<add>
<add> Long getId();
<add>
<add> void setId(Long id);
<add> }
<add>
<add> @SuppressWarnings({ "serial" })
<add> private static class SimpleBean implements Identifiable {
<add>
<add> private Long id;
<add>
<add> private String name;
<add>
<add> @Override
<add> public Long getId() {
<add> return id;
<add> }
<add>
<add> @Override
<add> public void setId(Long id) {
<add> this.id = id;
<add> }
<add>
<add> public String getName() {
<add> return name;
<add> }
<add>
<add> public void setName(String name) {
<add> this.name = name;
<add> }
<add> }
<add>
<ide> } | 2 |
Python | Python | fix distinct for oracle databases | 7813d2fb35cb636116186bddcb58644684ee2723 | <ide><path>rest_framework/filters.py
<ide> from django.core.exceptions import ImproperlyConfigured
<ide> from django.db import models
<ide> from django.utils import six
<add>from django.conf import settings
<ide> from rest_framework.compat import django_filters, guardian, get_model_name
<ide> from rest_framework.settings import api_settings
<ide> from functools import reduce
<ide> def filter_queryset(self, request, queryset, view):
<ide> for search_term in self.get_search_terms(request):
<ide> or_queries = [models.Q(**{orm_lookup: search_term})
<ide> for orm_lookup in orm_lookups]
<del> queryset = queryset.filter(reduce(operator.or_, or_queries)).distinct()
<add> queryset = queryset.filter(reduce(operator.or_, or_queries))
<add> if settings.DATABASES[queryset.db]["ENGINE"] != "django.db.backends.oracle":
<add> queryset = queryset.distinct()
<ide>
<ide> return queryset
<ide> | 1 |
Javascript | Javascript | fix special cases | 0f0062a71c6e6d9f7b29fb30af2880cb7c316318 | <ide><path>src/devtools/views/Components/SearchInput.js
<ide> export default function SearchInput(props: Props) {
<ide> onChange={handleTextChange}
<ide> onKeyDown={handleKeyDown}
<ide> onKeyPress={handleInputKeyPress}
<del> placeholder="Search (text or /regex/)"
<add> placeholder="Search"
<ide> ref={inputRef}
<ide> value={searchText}
<ide> />
<ide><path>src/devtools/views/utils.js
<ide> import { meta } from '../../hydration';
<ide> import type { HooksTree } from 'src/backend/types';
<ide>
<ide> export function createRegExp(string: string): RegExp {
<add> function isLetter(char: string) {
<add> return char.toLowerCase() !== char.toUpperCase();
<add> }
<add>
<add> function matchAnyCase(char: string) {
<add> if (!isLetter(char)) {
<add> // Don't mess with special characters like [.
<add> return char;
<add> }
<add> return '[' + char.toLowerCase() + char.toUpperCase() + ']';
<add> }
<add>
<ide> // 'item' should match 'Item' and 'ListItem', but not 'InviteMom'.
<ide> // To do this, we'll slice off 'tem' and check first letter separately.
<ide> const escaped = escapeStringRegExp(string);
<del> const firstLetter = escaped[0];
<add> const firstChar = escaped[0];
<ide> let restRegex = '';
<ide> // For 'item' input, restRegex becomes '[tT][eE][mM]'
<ide> // We can't simply make it case-insensitive because first letter case matters.
<ide> for (let i = 1; i < escaped.length; i++) {
<del> const char = escaped[i];
<del> restRegex += '[' + char.toLowerCase() + char.toUpperCase() + ']';
<add> restRegex += matchAnyCase(escaped[i]);
<add> }
<add>
<add> if (!isLetter(firstChar)) {
<add> // We can't put a non-character like [ in a group
<add> // so we fall back to the simple case.
<add> return new RegExp(firstChar + restRegex);
<ide> }
<del> // Respect first letter only if it starts a word.
<add>
<add> // Construct a smarter regex.
<ide> return new RegExp(
<ide> // For example:
<ide> // (^[iI]|I)[tT][eE][mM]
<ide> // Matches:
<ide> // 'Item'
<ide> // 'ListItem'
<ide> // but not 'InviteMom'
<del> '(^[' +
<del> firstLetter.toLowerCase() +
<del> firstLetter.toUpperCase() +
<del> ']' +
<add> '(^' +
<add> matchAnyCase(firstChar) +
<ide> '|' +
<del> firstLetter.toUpperCase() +
<add> firstChar.toUpperCase() +
<ide> ')' +
<ide> restRegex
<ide> ); | 2 |
Javascript | Javascript | add deprecated rootelement property | 84c20d95d402cdb9aa9953d50dea863bb1d357a8 | <ide><path>src/text-editor-element.js
<ide> class TextEditorElement extends HTMLElement {
<ide> return this
<ide> }
<ide>
<add> get rootElement () {
<add> Grim.deprecate(dedent`
<add> The contents of \`atom-text-editor\` elements are no longer encapsulated
<add> within a shadow DOM boundary. Please, stop using \`rootElement\` and access
<add> the editor contents directly instead.
<add> `)
<add>
<add> return this
<add> }
<add>
<ide> createdCallback () {
<ide> this.emitter = new Emitter()
<ide> this.initialText = this.textContent | 1 |
PHP | PHP | fix missing return tag | 4786f1bf013fcd0ad45fe6324fdec6abf0b6dfd0 | <ide><path>src/Console/Command.php
<ide> public function execute(Arguments $args, ConsoleIo $io)
<ide> *
<ide> * @param int $code The exit code to use.
<ide> * @throws \Cake\Console\Exception\ConsoleException
<add> * @return void
<ide> */
<ide> public function abort($code = self::CODE_ERROR)
<ide> { | 1 |
Python | Python | allow multiple extra_packages in dataflow | 5d3a7eef30b30fa466d8173f13abe4c356d73aef | <ide><path>airflow/providers/google/cloud/hooks/dataflow.py
<ide> def _build_cmd(variables: Dict, label_formatter: Callable, project_id: str) -> L
<ide> "--runner=DataflowRunner",
<ide> "--project={}".format(project_id),
<ide> ]
<del> if variables is not None:
<del> for attr, value in variables.items():
<del> if attr == 'labels':
<del> command += label_formatter(value)
<del> elif value is None or value.__len__() < 1:
<del> command.append("--" + attr)
<del> else:
<del> command.append("--" + attr + "=" + value)
<add> if variables is None:
<add> return command
<add>
<add> # The logic of this method should be compatible with Apache Beam:
<add> # https://github.com/apache/beam/blob/b56740f0e8cd80c2873412847d0b336837429fb9/sdks/python/
<add> # apache_beam/options/pipeline_options.py#L230-L251
<add> for attr, value in variables.items():
<add> if attr == 'labels':
<add> command += label_formatter(value)
<add> elif value is None:
<add> command.append(f"--{attr}")
<add> elif isinstance(value, bool) and value:
<add> command.append(f"--{attr}")
<add> elif isinstance(value, list):
<add> command.extend([f"--{attr}={v}" for v in value])
<add> else:
<add> command.append(f"--{attr}={value}")
<ide> return command
<ide>
<ide> @_fallback_to_project_id_from_variables
<ide><path>airflow/providers/google/cloud/operators/dataflow.py
<ide> class DataflowCreateJavaJobOperator(BaseOperator):
<ide> :type job_name: str
<ide> :param dataflow_default_options: Map of default job options.
<ide> :type dataflow_default_options: dict
<del> :param options: Map of job specific options.
<add> :param options: Map of job specific options.The key must be a dictionary.
<add> The value can contain different types:
<add>
<add> * If the value is None, the single option - ``--key`` (without value) will be added.
<add> * If the value is False, this option will be skipped
<add> * If the value is True, the single option - ``--key`` (without value) will be added.
<add> * If the value is list, the many options will be added for each key.
<add> If the value is ``['A', 'B']`` and the key is ``key`` then the ``--key=A --key-B`` options
<add> will be left
<add> * Other value types will be replaced with the Python textual representation.
<add>
<add> When defining labels (``labels`` option), you can also provide a dictionary.
<ide> :type options: dict
<ide> :param gcp_conn_id: The connection ID to use connecting to Google Cloud
<ide> Platform.
<ide> class DataflowCreatePythonJobOperator(BaseOperator):
<ide> :type py_options: list[str]
<ide> :param dataflow_default_options: Map of default job options.
<ide> :type dataflow_default_options: dict
<del> :param options: Map of job specific options.
<add> :param options: Map of job specific options.The key must be a dictionary.
<add> The value can contain different types:
<add>
<add> * If the value is None, the single option - ``--key`` (without value) will be added.
<add> * If the value is False, this option will be skipped
<add> * If the value is True, the single option - ``--key`` (without value) will be added.
<add> * If the value is list, the many options will be added for each key.
<add> If the value is ``['A', 'B']`` and the key is ``key`` then the ``--key=A --key-B`` options
<add> will be left
<add> * Other value types will be replaced with the Python textual representation.
<add>
<add> When defining labels (``labels`` option), you can also provide a dictionary.
<ide> :type options: dict
<ide> :param py_interpreter: Python version of the beam pipeline.
<ide> If None, this defaults to the python3.
<ide><path>tests/providers/google/cloud/hooks/test_dataflow.py
<ide>
<ide> import copy
<ide> import unittest
<add>from typing import Any, Dict
<ide>
<ide> import mock
<ide> from mock import MagicMock
<ide> JAR_FILE = 'unitest.jar'
<ide> JOB_CLASS = 'com.example.UnitTest'
<ide> PY_OPTIONS = ['-m']
<del>DATAFLOW_OPTIONS_PY = {
<add>DATAFLOW_VARIABLES_PY = {
<ide> 'project': 'test',
<ide> 'staging_location': 'gs://test/staging',
<ide> 'labels': {'foo': 'bar'}
<ide> }
<del>DATAFLOW_OPTIONS_JAVA = {
<add>DATAFLOW_VARIABLES_JAVA = {
<ide> 'project': 'test',
<ide> 'stagingLocation': 'gs://test/staging',
<ide> 'labels': {'foo': 'bar'}
<ide> }
<del>DATAFLOW_OPTIONS_TEMPLATE = {
<add>DATAFLOW_VARIABLES_TEMPLATE = {
<ide> 'project': 'test',
<ide> 'tempLocation': 'gs://test/temp',
<ide> 'zone': 'us-central1-f'
<ide> def test_start_python_dataflow(
<ide> dataflowjob_instance = mock_dataflowjob.return_value
<ide> dataflowjob_instance.wait_for_done.return_value = None
<ide> self.dataflow_hook.start_python_dataflow( # pylint: disable=no-value-for-parameter
<del> job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_PY,
<add> job_name=JOB_NAME, variables=DATAFLOW_VARIABLES_PY,
<ide> dataflow=PY_FILE, py_options=PY_OPTIONS,
<ide> )
<ide> expected_cmd = ["python3", '-m', PY_FILE,
<ide> def test_start_python_dataflow(
<ide> self.assertListEqual(sorted(mock_dataflow.call_args[1]["cmd"]),
<ide> sorted(expected_cmd))
<ide>
<add> @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'))
<add> @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController'))
<add> @mock.patch(DATAFLOW_STRING.format('_DataflowRunner'))
<add> @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn'))
<add> def test_start_python_dataflow_with_multiple_extra_packages(
<add> self, mock_conn, mock_dataflow, mock_dataflowjob, mock_uuid
<add> ):
<add> mock_uuid.return_value = MOCK_UUID
<add> mock_conn.return_value = None
<add> dataflow_instance = mock_dataflow.return_value
<add> dataflow_instance.wait_for_done.return_value = None
<add> dataflowjob_instance = mock_dataflowjob.return_value
<add> dataflowjob_instance.wait_for_done.return_value = None
<add> variables: Dict[str, Any] = copy.deepcopy(DATAFLOW_VARIABLES_PY)
<add> variables['extra-package'] = ['a.whl', 'b.whl']
<add>
<add> self.dataflow_hook.start_python_dataflow( # pylint: disable=no-value-for-parameter
<add> job_name=JOB_NAME, variables=variables,
<add> dataflow=PY_FILE, py_options=PY_OPTIONS,
<add> )
<add> expected_cmd = ["python3", '-m', PY_FILE,
<add> '--extra-package=a.whl',
<add> '--extra-package=b.whl',
<add> '--region=us-central1',
<add> '--runner=DataflowRunner', '--project=test',
<add> '--labels=foo=bar',
<add> '--staging_location=gs://test/staging',
<add> '--job_name={}-{}'.format(JOB_NAME, MOCK_UUID)]
<add> self.assertListEqual(sorted(mock_dataflow.call_args[1]["cmd"]), sorted(expected_cmd))
<add>
<ide> @parameterized.expand([
<ide> ('default_to_python3', 'python3'),
<ide> ('major_version_2', 'python2'),
<ide> def test_start_python_dataflow_with_custom_interpreter(
<ide> dataflowjob_instance = mock_dataflowjob.return_value
<ide> dataflowjob_instance.wait_for_done.return_value = None
<ide> self.dataflow_hook.start_python_dataflow( # pylint: disable=no-value-for-parameter
<del> job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_PY,
<add> job_name=JOB_NAME, variables=DATAFLOW_VARIABLES_PY,
<ide> dataflow=PY_FILE, py_options=PY_OPTIONS,
<ide> py_interpreter=py_interpreter,
<ide> )
<ide> def test_start_java_dataflow(self, mock_conn,
<ide> dataflowjob_instance = mock_dataflowjob.return_value
<ide> dataflowjob_instance.wait_for_done.return_value = None
<ide> self.dataflow_hook.start_java_dataflow( # pylint: disable=no-value-for-parameter
<del> job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_JAVA,
<add> job_name=JOB_NAME, variables=DATAFLOW_VARIABLES_JAVA,
<add> jar=JAR_FILE)
<add> expected_cmd = ['java', '-jar', JAR_FILE,
<add> '--region=us-central1',
<add> '--runner=DataflowRunner', '--project=test',
<add> '--stagingLocation=gs://test/staging',
<add> '--labels={"foo":"bar"}',
<add> '--jobName={}-{}'.format(JOB_NAME, MOCK_UUID)]
<add> self.assertListEqual(sorted(mock_dataflow.call_args[1]["cmd"]),
<add> sorted(expected_cmd))
<add>
<add> @mock.patch(DATAFLOW_STRING.format('uuid.uuid4'))
<add> @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController'))
<add> @mock.patch(DATAFLOW_STRING.format('_DataflowRunner'))
<add> @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn'))
<add> def test_start_java_dataflow_with_multiple_values_in_variables(
<add> self, mock_conn, mock_dataflow, mock_dataflowjob, mock_uuid
<add> ):
<add> mock_uuid.return_value = MOCK_UUID
<add> mock_conn.return_value = None
<add> dataflow_instance = mock_dataflow.return_value
<add> dataflow_instance.wait_for_done.return_value = None
<add> dataflowjob_instance = mock_dataflowjob.return_value
<add> dataflowjob_instance.wait_for_done.return_value = None
<add> variables: Dict[str, Any] = copy.deepcopy(DATAFLOW_VARIABLES_JAVA)
<add> variables['mock-option'] = ['a.whl', 'b.whl']
<add>
<add> self.dataflow_hook.start_java_dataflow( # pylint: disable=no-value-for-parameter
<add> job_name=JOB_NAME, variables=variables,
<ide> jar=JAR_FILE)
<ide> expected_cmd = ['java', '-jar', JAR_FILE,
<add> '--mock-option=a.whl',
<add> '--mock-option=b.whl',
<ide> '--region=us-central1',
<ide> '--runner=DataflowRunner', '--project=test',
<ide> '--stagingLocation=gs://test/staging',
<ide> def test_start_java_dataflow_with_job_class(
<ide> dataflowjob_instance = mock_dataflowjob.return_value
<ide> dataflowjob_instance.wait_for_done.return_value = None
<ide> self.dataflow_hook.start_java_dataflow( # pylint: disable=no-value-for-parameter
<del> job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_JAVA,
<add> job_name=JOB_NAME, variables=DATAFLOW_VARIABLES_JAVA,
<ide> jar=JAR_FILE, job_class=JOB_CLASS)
<ide> expected_cmd = ['java', '-cp', JAR_FILE, JOB_CLASS,
<ide> '--region=us-central1',
<ide> def test_start_template_dataflow(self, mock_conn, mock_controller, mock_uuid):
<ide> )
<ide> launch_method.return_value.execute.return_value = {"job": {"id": TEST_JOB_ID}}
<ide> self.dataflow_hook.start_template_dataflow( # pylint: disable=no-value-for-parameter
<del> job_name=JOB_NAME, variables=DATAFLOW_OPTIONS_TEMPLATE, parameters=PARAMETERS,
<add> job_name=JOB_NAME, variables=DATAFLOW_VARIABLES_TEMPLATE, parameters=PARAMETERS,
<ide> dataflow_template=TEMPLATE,
<ide> )
<ide> options_with_region = {'region': 'us-central1'}
<del> options_with_region.update(DATAFLOW_OPTIONS_TEMPLATE)
<add> options_with_region.update(DATAFLOW_VARIABLES_TEMPLATE)
<ide> options_with_region_without_project = copy.deepcopy(options_with_region)
<ide> del options_with_region_without_project['project']
<ide>
<ide> def test_start_template_dataflow(self, mock_conn, mock_controller, mock_uuid):
<ide> @mock.patch(DATAFLOW_STRING.format('_DataflowJobsController'))
<ide> @mock.patch(DATAFLOW_STRING.format('DataflowHook.get_conn'))
<ide> def test_start_template_dataflow_with_runtime_env(self, mock_conn, mock_dataflowjob, mock_uuid):
<del> dataflow_options_template = copy.deepcopy(DATAFLOW_OPTIONS_TEMPLATE)
<add> dataflow_options_template = copy.deepcopy(DATAFLOW_VARIABLES_TEMPLATE)
<ide> options_with_runtime_env = copy.deepcopy(RUNTIME_ENV)
<ide> options_with_runtime_env.update(dataflow_options_template)
<ide> | 3 |
Text | Text | remove util.promisify() content in readline.md | 059b8900093f7468a3598eb307b9842247b29ee7 | <ide><path>doc/api/readline.md
<ide> signal.addEventListener('abort', () => {
<ide> setTimeout(() => ac.abort(), 10000);
<ide> ```
<ide>
<del>If this method is invoked as it's util.promisify()ed version, it returns a
<del>Promise that fulfills with the answer. If the question is canceled using
<del>an `AbortController` it will reject with an `AbortError`.
<del>
<del>```js
<del>const util = require('util');
<del>const question = util.promisify(rl.question).bind(rl);
<del>
<del>async function questionExample() {
<del> try {
<del> const answer = await question('What is you favorite food? ');
<del> console.log(`Oh, so your favorite food is ${answer}`);
<del> } catch (err) {
<del> console.error('Question rejected', err);
<del> }
<del>}
<del>questionExample();
<del>```
<del>
<ide> ### `rl.resume()`
<ide>
<ide> <!-- YAML
<ide> signal.addEventListener('abort', () => {
<ide> setTimeout(() => ac.abort(), 10000);
<ide> ```
<ide>
<del>If this method is invoked as it's util.promisify()ed version, it returns a
<del>Promise that fulfills with the answer. If the question is canceled using
<del>an `AbortController` it will reject with an `AbortError`.
<del>
<del>```js
<del>const util = require('util');
<del>const question = util.promisify(rl.question).bind(rl);
<del>
<del>async function questionExample() {
<del> try {
<del> const answer = await question('What is you favorite food? ');
<del> console.log(`Oh, so your favorite food is ${answer}`);
<del> } catch (err) {
<del> console.error('Question rejected', err);
<del> }
<del>}
<del>questionExample();
<del>```
<del>
<ide> ### `readline.clearLine(stream, dir[, callback])`
<ide>
<ide> <!-- YAML | 1 |
Javascript | Javascript | extend spacer api | 73e89a2300a7dc894b98cad41876f8dde94767e2 | <ide><path>client/src/components/helpers/Spacer.js
<ide> import React from 'react';
<add>import PropTypes from 'prop-types';
<ide>
<del>const Spacer = () => (
<del> <div className='spacer' style={{ marginTop: '50px', marginBottom: '50px' }} />
<del>);
<add>const styles = { padding: '15px 0', height: '1px' };
<add>
<add>const Comp = props => <div className='spacer' style={styles} {...props} />;
<add>
<add>const Spacer = ({ size = 1 }) =>
<add> size === 1 ? (
<add> <Comp />
<add> ) : (
<add> '#'
<add> .repeat(size)
<add> .split('')
<add> .map((_, i) => <Comp key={`spacer_${i}`} />)
<add> );
<add>
<add>Spacer.propTypes = {
<add> size: PropTypes.number
<add>};
<ide>
<ide> export default Spacer;
<ide><path>client/src/pages/welcome.js
<ide> function Welcome({
<ide> </Col>
<ide> </Row>
<ide> <Spacer />
<del> <Spacer />
<ide> <Row>
<ide> <Col sm={8} smOffset={2} xs={12}>
<ide> <p className='stats'>
<ide> function Welcome({
<ide> </Col>
<ide> </Row>
<ide> <Spacer />
<del> <Spacer />
<ide> <Row>
<ide> <Col sm={8} smOffset={2} xs={12}>
<ide> <Button block={true} bsStyle='primary' className='btn-cta-big'>
<ide> Go to my next challenge
<ide> </Button>
<ide> </Col>
<ide> </Row>
<del> <Spacer />
<del> <Spacer />
<del> <Spacer />
<del> <Spacer />
<del> <Spacer />
<add> <Spacer size={4}/>
<ide> </Grid>
<ide> </Layout>
<ide> ); | 2 |
Text | Text | update react props guide article | e4ae577cd9f0f93da8eec37af88a669c395f674d | <ide><path>guide/english/react/props/index.md
<ide> title: Props
<ide> ---
<ide> ### What are the props?
<del>Props (short for properties) are the data passed into the component. They are immutable (read-only).
<add>Props (short for properties) are the data or functions passed into a component. They are immutable (read-only).
<ide>\ No newline at end of file | 1 |
Javascript | Javascript | remove typo orginalerror | 4a541e01a59c5d4c01b67e261e83246ed78833c8 | <ide><path>lib/HotModuleReplacement.runtime.js
<ide> module.exports = function() {
<ide> type: "self-accept-error-handler-errored",
<ide> moduleId: moduleId,
<ide> error: err2,
<del> orginalError: err, // TODO remove in webpack 4
<ide> originalError: err
<ide> });
<ide> } | 1 |
Python | Python | add operation that renames tables | 6f667999e1186b8eaa9c86e4cbd80d5c0ba20576 | <ide><path>django/db/backends/schema.py
<ide> def alter_field(self, model, old_field, new_field, strict=False):
<ide> return self._alter_many_to_many(model, old_field, new_field, strict)
<ide> elif old_type is None or new_type is None:
<ide> raise ValueError("Cannot alter field %s into %s - they are not compatible types (probably means only one is an M2M with implicit through model)" % (
<del> old_field,
<del> new_field,
<del> ))
<add> old_field,
<add> new_field,
<add> ))
<ide> # Has unique been removed?
<ide> if old_field.unique and not new_field.unique:
<ide> # Find the unique constraint for this field
<ide><path>django/db/migrations/operations/__init__.py
<del>from .models import CreateModel, DeleteModel
<add>from .models import CreateModel, DeleteModel, AlterModelTable
<ide> from .fields import AddField, RemoveField
<ide><path>django/db/migrations/operations/models.py
<ide> def database_backwards(self, app_label, schema_editor, from_state, to_state):
<ide>
<ide> def describe(self):
<ide> return "Delete model %s" % (self.name, )
<add>
<add>
<add>class AlterModelTable(Operation):
<add> """
<add> Renames a model's table
<add> """
<add>
<add> def __init__(self, name, table):
<add> self.name = name
<add> self.table = table
<add>
<add> def state_forwards(self, app_label, state):
<add> state.models[app_label, self.name.lower()].options["db_table"] = self.table
<add>
<add> def database_forwards(self, app_label, schema_editor, from_state, to_state):
<add> old_app_cache = from_state.render()
<add> new_app_cache = to_state.render()
<add> schema_editor.alter_db_table(
<add> new_app_cache.get_model(app_label, self.name),
<add> old_app_cache.get_model(app_label, self.name)._meta.db_table,
<add> new_app_cache.get_model(app_label, self.name)._meta.db_table,
<add> )
<add>
<add> def database_backwards(self, app_label, schema_editor, from_state, to_state):
<add> return self.database_forwards(app_label, schema_editor, from_state, to_state)
<add>
<add> def describe(self):
<add> return "Rename table for %s to %s" % (self.name, self.table)
<ide><path>tests/migrations/test_autodetector.py
<ide> class AutodetectorTests(TestCase):
<ide> """
<ide>
<ide> author_empty = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))])
<add> author_name = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200))])
<ide> other_pony = ModelState("otherapp", "Pony", [("id", models.AutoField(primary_key=True))])
<ide> other_stable = ModelState("otherapp", "Stable", [("id", models.AutoField(primary_key=True))])
<ide> third_thing = ModelState("thirdapp", "Thing", [("id", models.AutoField(primary_key=True))])
<ide> def test_old_model(self):
<ide> action = migration.operations[0]
<ide> self.assertEqual(action.__class__.__name__, "DeleteModel")
<ide> self.assertEqual(action.name, "Author")
<add>
<add> def test_add_field(self):
<add> "Tests autodetection of new fields"
<add> # Make state
<add> before = self.make_project_state([self.author_empty])
<add> after = self.make_project_state([self.author_name])
<add> autodetector = MigrationAutodetector(before, after)
<add> changes = autodetector.changes()
<add> # Right number of migrations?
<add> self.assertEqual(len(changes['testapp']), 1)
<add> # Right number of actions?
<add> migration = changes['testapp'][0]
<add> self.assertEqual(len(migration.operations), 1)
<add> # Right action?
<add> action = migration.operations[0]
<add> self.assertEqual(action.__class__.__name__, "AddField")
<add> self.assertEqual(action.name, "name")
<add>
<add> def test_remove_field(self):
<add> "Tests autodetection of removed fields"
<add> # Make state
<add> before = self.make_project_state([self.author_name])
<add> after = self.make_project_state([self.author_empty])
<add> autodetector = MigrationAutodetector(before, after)
<add> changes = autodetector.changes()
<add> # Right number of migrations?
<add> self.assertEqual(len(changes['testapp']), 1)
<add> # Right number of actions?
<add> migration = changes['testapp'][0]
<add> self.assertEqual(len(migration.operations), 1)
<add> # Right action?
<add> action = migration.operations[0]
<add> self.assertEqual(action.__class__.__name__, "RemoveField")
<add> self.assertEqual(action.name, "name")
<ide><path>tests/migrations/test_operations.py
<ide> def test_add_field(self):
<ide> with connection.schema_editor() as editor:
<ide> operation.database_backwards("test_adfl", editor, new_state, project_state)
<ide> self.assertColumnNotExists("test_adfl_pony", "height")
<add>
<add> def test_remove_field(self):
<add> """
<add> Tests the RemoveField operation.
<add> """
<add> project_state = self.set_up_test_model("test_rmfl")
<add> # Test the state alteration
<add> operation = migrations.RemoveField("Pony", "pink")
<add> new_state = project_state.clone()
<add> operation.state_forwards("test_rmfl", new_state)
<add> self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 1)
<add> # Test the database alteration
<add> self.assertColumnExists("test_rmfl_pony", "pink")
<add> with connection.schema_editor() as editor:
<add> operation.database_forwards("test_rmfl", editor, project_state, new_state)
<add> self.assertColumnNotExists("test_rmfl_pony", "pink")
<add> # And test reversal
<add> with connection.schema_editor() as editor:
<add> operation.database_backwards("test_rmfl", editor, new_state, project_state)
<add> self.assertColumnExists("test_rmfl_pony", "pink")
<add>
<add> def test_alter_model_table(self):
<add> """
<add> Tests the AlterModelTable operation.
<add> """
<add> project_state = self.set_up_test_model("test_almota")
<add> # Test the state alteration
<add> operation = migrations.AlterModelTable("Pony", "test_almota_pony_2")
<add> new_state = project_state.clone()
<add> operation.state_forwards("test_almota", new_state)
<add> self.assertEqual(new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2")
<add> # Test the database alteration
<add> self.assertTableExists("test_almota_pony")
<add> self.assertTableNotExists("test_almota_pony_2")
<add> with connection.schema_editor() as editor:
<add> operation.database_forwards("test_almota", editor, project_state, new_state)
<add> self.assertTableNotExists("test_almota_pony")
<add> self.assertTableExists("test_almota_pony_2")
<add> # And test reversal
<add> with connection.schema_editor() as editor:
<add> operation.database_backwards("test_almota", editor, new_state, project_state)
<add> self.assertTableExists("test_almota_pony")
<add> self.assertTableNotExists("test_almota_pony_2") | 5 |
Javascript | Javascript | add an example with the two possible arguments | fc05f5e701f77012d54f87facb5a83d56996c7f1 | <ide><path>src/Angular.js
<ide> function isLeafNode (node) {
<ide> * @param {(Object|Array)=} destination Destination into which the source is copied. If
<ide> * provided, must be of the same type as `source`.
<ide> * @returns {*} The copy or updated `destination`, if `destination` was specified.
<add> *
<add> * @example
<add> <doc:example>
<add> <doc:source>
<add> <div ng-controller="Controller">
<add> <form novalidate class="simple-form">
<add> Name: <input type="text" ng-model="user.name" /><br />
<add> E-mail: <input type="email" ng-model="user.email" /><br />
<add> Gender: <input type="radio" ng-model="user.gender" value="male" />male
<add> <input type="radio" ng-model="user.gender" value="female" />female<br />
<add> <button ng-click="reset()">RESET</button>
<add> <button ng-click="update(user)">SAVE</button>
<add> </form>
<add> <pre>form = {{user | json}}</pre>
<add> <pre>master = {{master | json}}</pre>
<add> </div>
<add>
<add> <script>
<add> function Controller($scope) {
<add> $scope.master= {};
<add>
<add> $scope.update = function(user) {
<add> // Example with 1 argument
<add> $scope.master= angular.copy(user);
<add> };
<add>
<add> $scope.reset = function() {
<add> // Example with 2 arguments
<add> angular.copy($scope.master, $scope.user);
<add> };
<add>
<add> $scope.reset();
<add> }
<add> </script>
<add> </doc:source>
<add> </doc:example>
<ide> */
<ide> function copy(source, destination){
<ide> if (isWindow(source) || isScope(source)) { | 1 |
Ruby | Ruby | remove array#sample from core_ext | c52ce1dae2ca8b72732f92c84541a4b6bbc9da77 | <ide><path>activesupport/lib/active_support/core_ext/array.rb
<ide> require 'active_support/core_ext/array/conversions'
<ide> require 'active_support/core_ext/array/extract_options'
<ide> require 'active_support/core_ext/array/grouping'
<del>require 'active_support/core_ext/array/random_access'
<ide> require 'active_support/core_ext/array/prepend_and_append'
<ide><path>activesupport/lib/active_support/core_ext/array/random_access.rb
<del>class Array
<del> # Backport of Array#sample based on Marc-Andre Lafortune's https://github.com/marcandre/backports/
<del> # Returns a random element or +n+ random elements from the array.
<del> # If the array is empty and +n+ is nil, returns <tt>nil</tt>.
<del> # If +n+ is passed and its value is less than 0, it raises an +ArgumentError+ exception.
<del> # If the value of +n+ is equal or greater than 0 it returns <tt>[]</tt>.
<del> #
<del> # [1,2,3,4,5,6].sample # => 4
<del> # [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
<del> # [1,2,3,4,5,6].sample(-3) # => ArgumentError: negative array size
<del> # [].sample # => nil
<del> # [].sample(3) # => []
<del> def sample(n=nil)
<del> return self[Kernel.rand(size)] if n.nil?
<del> n = n.to_int
<del> rescue Exception => e
<del> raise TypeError, "Coercion error: #{n.inspect}.to_int => Integer failed:\n(#{e.message})"
<del> else
<del> raise TypeError, "Coercion error: obj.to_int did NOT return an Integer (was #{n.class})" unless n.kind_of? Integer
<del> raise ArgumentError, "negative array size" if n < 0
<del> n = size if n > size
<del> result = Array.new(self)
<del> n.times do |i|
<del> r = i + Kernel.rand(size - i)
<del> result[i], result[r] = result[r], result[i]
<del> end
<del> result[n..size] = []
<del> result
<del> end unless method_defined? :sample
<del>end
<ide><path>activesupport/test/core_ext/array_ext_test.rb
<ide> def test_uniq_by!
<ide> end
<ide> end
<ide>
<del>class ArrayExtRandomTests < ActiveSupport::TestCase
<del> def test_sample_from_array
<del> assert_nil [].sample
<del> assert_equal [], [].sample(5)
<del> assert_equal 42, [42].sample
<del> assert_equal [42], [42].sample(5)
<del>
<del> a = [:foo, :bar, 42]
<del> s = a.sample(2)
<del> assert_equal 2, s.size
<del> assert_equal 1, (a-s).size
<del> assert_equal [], a-(0..20).sum{a.sample(2)}
<del>
<del> o = Object.new
<del> def o.to_int; 1; end
<del> assert_equal [0], [0].sample(o)
<del>
<del> o = Object.new
<del> assert_raises(TypeError) { [0].sample(o) }
<del>
<del> o = Object.new
<del> def o.to_int; ''; end
<del> assert_raises(TypeError) { [0].sample(o) }
<del>
<del> assert_raises(ArgumentError) { [0].sample(-7) }
<del> end
<del>end
<del>
<ide> class ArrayWrapperTests < Test::Unit::TestCase
<ide> class FakeCollection
<ide> def to_ary | 3 |
Text | Text | fix typo in documentation in flux todo list | 8882f19187df93551cf98a3c516754e3feb44894 | <ide><path>docs/docs/flux-todo-list.md
<ide> At a high level, the React component hierarchy of the app looks like this:
<ide> <TodoItem />
<ide> </ul>
<ide> </MainSection>
<add> </Header>
<ide>
<ide> </TodoApp>
<ide> ``` | 1 |
Javascript | Javascript | check document before shy test | 4c606ac2dc11bb68d28c5e4c10543811e0f89617 | <ide><path>packages/ember-views/lib/system/utils.js
<ide> // Internet Explorer prior to 9 does not allow setting innerHTML if the first element
<ide> // is a "zero-scope" element. This problem can be worked around by making
<ide> // the first node an invisible text node. We, like Modernizr, use ­
<del>var needsShy = (function(){
<add>
<add>var needsShy = this.document && (function(){
<ide> var testEl = document.createElement('div');
<ide> testEl.innerHTML = "<div></div>";
<ide> testEl.firstChild.innerHTML = "<script></script>";
<ide> var needsShy = (function(){
<ide> // IE 8 (and likely earlier) likes to move whitespace preceeding
<ide> // a script tag to appear after it. This means that we can
<ide> // accidentally remove whitespace when updating a morph.
<del>var movesWhitespace = (function() {
<add>var movesWhitespace = this.document && (function() {
<ide> var testEl = document.createElement('div');
<ide> testEl.innerHTML = "Test: <script type='text/x-placeholder'></script>Value";
<ide> return testEl.childNodes[0].nodeValue === 'Test:' &&
<ide><path>packages/metamorph/lib/main.js
<ide> define("metamorph",
<ide>
<ide> var K = function(){},
<ide> guid = 0,
<del> document = window.document,
<add> document = this.document,
<ide>
<ide> // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges
<del> supportsRange = ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment,
<add> supportsRange = document && ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment,
<ide>
<ide> // Internet Explorer prior to 9 does not allow setting innerHTML if the first element
<ide> // is a "zero-scope" element. This problem can be worked around by making
<ide> // the first node an invisible text node. We, like Modernizr, use ­
<del> needsShy = (function(){
<add> needsShy = document && (function(){
<ide> var testEl = document.createElement('div');
<ide> testEl.innerHTML = "<div></div>";
<ide> testEl.firstChild.innerHTML = "<script></script>";
<ide> define("metamorph",
<ide> // IE 8 (and likely earlier) likes to move whitespace preceeding
<ide> // a script tag to appear after it. This means that we can
<ide> // accidentally remove whitespace when updating a morph.
<del> movesWhitespace = (function() {
<add> movesWhitespace = document && (function() {
<ide> var testEl = document.createElement('div');
<ide> testEl.innerHTML = "Test: <script type='text/x-placeholder'></script>Value";
<ide> return testEl.childNodes[0].nodeValue === 'Test:' && | 2 |
Javascript | Javascript | use correct comment format | ca7790158edcf931fc4b6658993efc4e2abf83ea | <ide><path>common/utils/polyvinyl.js
<ide> import castToObservable from '../app/utils/cast-to-observable.js';
<ide>
<ide>
<ide> // createFileStream(
<del>// files: List[ PolyVinyl ]
<add>// files: [...PolyVinyl]
<ide> // ) => Observable[...Observable[...PolyVinyl]]
<ide> export function createFileStream(files = []) {
<ide> return Observable.of( | 1 |
Text | Text | add missing import | e67a38fc77c848ae6d34dfa539c3aaedd68687b2 | <ide><path>docs/templates/getting-started/sequential-model-guide.md
<ide> In the [examples folder](https://github.com/fchollet/keras/tree/master/examples)
<ide> ### Multilayer Perceptron (MLP) for multi-class softmax classification:
<ide>
<ide> ```python
<add>import keras
<ide> from keras.models import Sequential
<ide> from keras.layers import Dense, Dropout, Activation
<ide> from keras.optimizers import SGD | 1 |
Javascript | Javascript | ignore incompatible nodes on find() | 1169b5445691e1495354d235a3badf05240e3904 | <ide><path>src/jqLite.js
<ide> forEach({
<ide> },
<ide>
<ide> find: function(element, selector) {
<del> return element.getElementsByTagName(selector);
<add> if (element.getElementsByTagName) {
<add> return element.getElementsByTagName(selector);
<add> } else {
<add> return [];
<add> }
<ide> },
<ide>
<ide> clone: jqLiteClone,
<ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function() {
<ide> expect(innerDiv.length).toEqual(1);
<ide> expect(innerDiv.html()).toEqual('text');
<ide> });
<add>
<add> it('should find child by name and not care about text nodes', function() {
<add> var divs = jqLite('<div><span>aa</span></div>text<div><span>bb</span></div>');
<add> var innerSpan = divs.find('span');
<add> expect(innerSpan.length).toEqual(2);
<add> });
<ide> });
<ide>
<ide> | 2 |
Text | Text | add solution d3challenges | 17be165d6648a5f069b0c5b2e7b9b63c7ebb06da | <ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/add-a-tooltip-to-a-d3-element.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style>
<add> .bar:hover {
<add> fill: brown;
<add> }
<add></style>
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", (d, i) => h - 3 * d)
<add> .attr("width", 25)
<add> .attr("height", (d, i) => d * 3)
<add> .attr("fill", "navy")
<add> .attr("class", "bar")
<add> .append("title")
<add> .text((d) => d)
<add>
<add>
<add> svg.selectAll("text")
<add> .data(dataset)
<add> .enter()
<add> .append("text")
<add> .text((d) => d)
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", (d, i) => h - (d * 3 + 3))
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/add-attributes-to-the-circle-elements.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [
<add> [ 34, 78 ],
<add> [ 109, 280 ],
<add> [ 310, 120 ],
<add> [ 79, 411 ],
<add> [ 420, 220 ],
<add> [ 233, 145 ],
<add> [ 333, 96 ],
<add> [ 222, 333 ],
<add> [ 78, 320 ],
<add> [ 21, 123 ]
<add> ];
<add>
<add>
<add> const w = 500;
<add> const h = 500;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("circle")
<add> .data(dataset)
<add> .enter()
<add> .append("circle")
<add> .attr("cx", (d) => d[0])
<add> .attr("cy", (d) => h - d[1])
<add> .attr("r", 5)
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/add-axes-to-a-visualization.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [
<add> [ 34, 78 ],
<add> [ 109, 280 ],
<add> [ 310, 120 ],
<add> [ 79, 411 ],
<add> [ 420, 220 ],
<add> [ 233, 145 ],
<add> [ 333, 96 ],
<add> [ 222, 333 ],
<add> [ 78, 320 ],
<add> [ 21, 123 ]
<add> ];
<add>
<add> const w = 500;
<add> const h = 500;
<add> const padding = 60;
<add>
<add> const xScale = d3.scaleLinear()
<add> .domain([0, d3.max(dataset, (d) => d[0])])
<add> .range([padding, w - padding]);
<add>
<add> const yScale = d3.scaleLinear()
<add> .domain([0, d3.max(dataset, (d) => d[1])])
<add> .range([h - padding, padding]);
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("circle")
<add> .data(dataset)
<add> .enter()
<add> .append("circle")
<add> .attr("cx", (d) => xScale(d[0]))
<add> .attr("cy",(d) => yScale(d[1]))
<add> .attr("r", (d) => 5);
<add>
<add> svg.selectAll("text")
<add> .data(dataset)
<add> .enter()
<add> .append("text")
<add> .text((d) => (d[0] + "," + d[1]))
<add> .attr("x", (d) => xScale(d[0] + 10))
<add> .attr("y", (d) => yScale(d[1]))
<add>
<add> const xAxis = d3.axisBottom(xScale);
<add>
<add> const yAxis = d3.axisLeft(yScale);
<add>
<add>
<add> svg.append("g")
<add> .attr("transform", "translate(0," + (h - padding) + ")")
<add> .call(xAxis);
<add>
<add> svg.append("g")
<add> .attr("transform", "translate(" + padding + ",0)")
<add> .call(yAxis)
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/add-document-elements-with-d3.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> d3.select("body")
<add> .append("h1")
<add> .text("Learning D3")
<add> </script>
<add></body>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/add-inline-styling-to-elements.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> d3.select("body").selectAll("h2")
<add> .data(dataset)
<add> .enter()
<add> .append("h2")
<add> .text((d) => (d + " USD"))
<add> .style("font-family", "verdana")
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/add-labels-to-scatter-plot-circles.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [
<add> [ 34, 78 ],
<add> [ 109, 280 ],
<add> [ 310, 120 ],
<add> [ 79, 411 ],
<add> [ 420, 220 ],
<add> [ 233, 145 ],
<add> [ 333, 96 ],
<add> [ 222, 333 ],
<add> [ 78, 320 ],
<add> [ 21, 123 ]
<add> ];
<add>
<add>
<add> const w = 500;
<add> const h = 500;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("circle")
<add> .data(dataset)
<add> .enter()
<add> .append("circle")
<add> .attr("cx", (d, i) => d[0])
<add> .attr("cy", (d, i) => h - d[1])
<add> .attr("r", 5);
<add>
<add> svg.selectAll("text")
<add> .data(dataset)
<add> .enter()
<add> .append("text")
<add> .attr("x", (d) => d[0] + 5)
<add> .attr("y", (d) => h - d[1])
<add> .text((d) => (d[0] + ", " + d[1]))
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/change-styles-based-on-data.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> d3.select("body").selectAll("h2")
<add> .data(dataset)
<add> .enter()
<add> .append("h2")
<add> .text((d) => (d + " USD"))
<add> .style("color", (d) => d < 20 ? "red" : "green")
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/change-the-color-of-an-svg-element.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", (d, i) => h - 3 * d)
<add> .attr("width", 25)
<add> .attr("height", (d, i) => 3 * d)
<add> .attr("fill", "navy");
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/change-the-presentation-of-a-bar-chart.english.md
<ide> tests:
<ide> .enter()
<ide> .append("div")
<ide> .attr("class", "bar")
<del> // Add your code below this line
<del> .style("height", (d) => (d*10 + "px"))
<del>
<del>
<del> // Add your code above this line
<add> .style("height", (d) => (d * 10 + "px"))
<ide> </script>
<ide> </body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/create-a-bar-for-each-data-point-in-the-set.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", 0)
<add> .attr("y", 0)
<add> .attr("width", 25)
<add> .attr("height", 100);
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/create-a-linear-scale-with-d3.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add>
<add> const scale = d3.scaleLinear();
<add> const output = scale(50);
<add>
<add> d3.select("body")
<add> .append("h2")
<add> .text(output);
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/create-a-scatterplot-with-svg-circles.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [
<add> [ 34, 78 ],
<add> [ 109, 280 ],
<add> [ 310, 120 ],
<add> [ 79, 411 ],
<add> [ 420, 220 ],
<add> [ 233, 145 ],
<add> [ 333, 96 ],
<add> [ 222, 333 ],
<add> [ 78, 320 ],
<add> [ 21, 123 ]
<add> ];
<add>
<add>
<add> const w = 500;
<add> const h = 500;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("circle")
<add> .data(dataset)
<add> .enter()
<add> .append("circle")
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/display-shapes-with-svg.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h)
<add> .append("rect")
<add> .attr("width", 25)
<add> .attr("height", 100)
<add> .attr("x", 0)
<add> .attr("y", 0);
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/dynamically-change-the-height-of-each-bar.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", 0)
<add> .attr("width", 25)
<add> .attr("height", (d, i) => {
<add> return d * 3
<add> });
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/dynamically-set-the-coordinates-for-each-bar.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", (d, i) => {
<add> return i * 30
<add> })
<add> .attr("y", 0)
<add> .attr("width", 25)
<add> .attr("height", 100);
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/invert-svg-elements.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", (d, i) => h - 3 * d)
<add> .attr("width", 25)
<add> .attr("height", (d, i) => 3 * d);
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/learn-about-svg-in-d3.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style>
<add> svg {
<add> background-color: pink;
<add> }
<add></style>
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h)
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/select-a-group-of-elements-with-d3.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <ul>
<add> <li>Example</li>
<add> <li>Example</li>
<add> <li>Example</li>
<add> </ul>
<add> <script>
<add> d3.selectAll("li")
<add> .text("list item")
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/set-a-domain-and-a-range-on-a-scale.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const scale = d3.scaleLinear();
<add> scale.domain([250, 500])
<add> scale.range([10, 150])
<add> const output = scale(50);
<add> d3.select("body")
<add> .append("h2")
<add> .text(output);
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/style-d3-labels.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> const w = 500;
<add> const h = 100;
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("rect")
<add> .data(dataset)
<add> .enter()
<add> .append("rect")
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", (d, i) => h - 3 * d)
<add> .attr("width", 25)
<add> .attr("height", (d, i) => d * 3)
<add> .attr("fill", "navy");
<add>
<add> svg.selectAll("text")
<add> .data(dataset)
<add> .enter()
<add> .append("text")
<add> .text((d) => d)
<add> .attr("x", (d, i) => i * 30)
<add> .attr("y", (d, i) => h - (3 * d) - 3)
<add> .style("font-size", 25)
<add> .attr("fill", "red")
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/use-a-pre-defined-scale-to-place-elements.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [
<add> [ 34, 78 ],
<add> [ 109, 280 ],
<add> [ 310, 120 ],
<add> [ 79, 411 ],
<add> [ 420, 220 ],
<add> [ 233, 145 ],
<add> [ 333, 96 ],
<add> [ 222, 333 ],
<add> [ 78, 320 ],
<add> [ 21, 123 ]
<add> ];
<add>
<add> const w = 500;
<add> const h = 500;
<add> const padding = 60;
<add>
<add> const xScale = d3.scaleLinear()
<add> .domain([0, d3.max(dataset, (d) => d[0])])
<add> .range([padding, w - padding]);
<add>
<add> const yScale = d3.scaleLinear()
<add> .domain([0, d3.max(dataset, (d) => d[1])])
<add> .range([h - padding, padding]);
<add>
<add> const svg = d3.select("body")
<add> .append("svg")
<add> .attr("width", w)
<add> .attr("height", h);
<add>
<add> svg.selectAll("circle")
<add> .data(dataset)
<add> .enter()
<add> .append("circle")
<add> .attr("cx", (d) => xScale(d[0]))
<add> .attr("cy", (d) => yScale(d[1]))
<add> .attr("r", 5)
<add>
<add> svg.selectAll("text")
<add> .data(dataset)
<add> .enter()
<add> .append("text")
<add> .text((d) => (d[0] + ", "
<add> + d[1]))
<add> .attr("x", (d) => xScale(d[0] + 10))
<add> .attr("y", (d) => yScale(d[1]))
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/use-dynamic-scales.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [
<add> [ 34, 78 ],
<add> [ 109, 280 ],
<add> [ 310, 120 ],
<add> [ 79, 411 ],
<add> [ 420, 220 ],
<add> [ 233, 145 ],
<add> [ 333, 96 ],
<add> [ 222, 333 ],
<add> [ 78, 320 ],
<add> [ 21, 123 ]
<add> ];
<add>
<add> const w = 500;
<add> const h = 500;
<add>
<add>
<add> const padding = 30;
<add>
<add> const xScale = d3.scaleLinear()
<add> .domain([0, d3.max(dataset, (d) => d[0])])
<add> .range([padding, w - padding]);
<add>
<add>
<add> const yScale = d3.scaleLinear()
<add> .domain([0, d3.max(dataset, (d) => d[1])])
<add> .range([h - padding, padding]);
<add>
<add>
<add> const output = yScale(411);
<add> d3.select("body")
<add> .append("h2")
<add> .text(output)
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/use-the-d3.max-and-d3.min-functions-to-find-minimum-and-maximum-values-in-a-dataset.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const positionData = [[1, 7, -4],[6, 3, 8],[2, 9, 3]]
<add>
<add> const output = d3.max(positionData, (d) => d[2])
<add>
<add> d3.select("body")
<add> .append("h2")
<add> .text(output)
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/work-with-data-in-d3.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> d3.select("body")
<add> .selectAll("h2")
<add> .data(dataset)
<add> .enter()
<add> .append("h2")
<add> .text("New Title")
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section>
<ide><path>curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/work-with-dynamic-data-in-d3.english.md
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><body>
<add> <script>
<add> const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
<add>
<add> d3.select("body").selectAll("h2")
<add> .data(dataset)
<add> .enter()
<add> .append("h2")
<add> .text((d) => `${d} USD`);
<add>
<add> </script>
<add></body>
<add>
<ide> ```
<ide>
<ide> </section> | 25 |
Javascript | Javascript | correct the path in with-electron | a7baeb045e854597db610f6976251c5093560a87 | <ide><path>examples/with-electron/main/index.js
<ide> app.on('ready', async () => {
<ide> const url = isDev
<ide> ? 'http://localhost:8000/start'
<ide> : format({
<del> pathname: join(__dirname, '../renderer/start/index.html'),
<add> pathname: join(__dirname, '../renderer/start.html'),
<ide> protocol: 'file:',
<ide> slashes: true
<ide> }) | 1 |
Python | Python | avoid deprecation warning for f.tanh | b45e65efa0fbff2611ddd68e14fa75cacef3fe08 | <ide><path>src/transformers/modeling_mobilebert.py
<ide> def forward(self, hidden_states):
<ide> return first_token_tensor
<ide> else:
<ide> pooled_output = self.dense(first_token_tensor)
<del> pooled_output = F.tanh(pooled_output)
<add> pooled_output = torch.tanh(pooled_output)
<ide> return pooled_output
<ide>
<ide> | 1 |
Ruby | Ruby | fix deprecation warnings and call super | 570bcdaa65987ac2f5cc84fdf83678cd5c0bb7d8 | <ide><path>actionview/test/template/template_test.rb
<ide> def find_template(*args)
<ide> end
<ide>
<ide> class Context < ActionView::Base
<del> def initialize
<add> def initialize(*)
<ide> super
<ide> @output_buffer = "original"
<ide> @virtual_path = nil
<ide> def render(locals = {})
<ide> end
<ide>
<ide> def setup
<del> @context = Context.with_empty_template_cache.new
<add> @context = Context.with_empty_template_cache.empty
<ide> super
<ide> end
<ide> | 1 |
Ruby | Ruby | fetch artifacts with no-resume strategy | c1ba9975b8349c9eff2bf55bd4319c0bbe45dc73 | <ide><path>Library/Homebrew/dev-cmd/pr-pull.rb
<ide> require "tmpdir"
<ide> require "bintray"
<ide>
<add>class CurlNoResumeDownloadStrategy < CurlDownloadStrategy
<add> private
<add>
<add> def _fetch(url:, resolved_url:)
<add> curl("--location", "--remote-time", "--create-dirs", "--output", temporary_path, resolved_url)
<add> end
<add>end
<add>
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def pr_pull
<ide> if Homebrew.args.dry_run?
<ide> puts "Upload bottles described by these JSON files to Bintray:\n #{Dir["*.json"].join("\n ")}"
<ide> else
<del> bintray.upload_bottle_json Dir["*.json"], publish_package: !args.no_publish?
<add> bintray.upload_bottle_json Dir["*.json"],
<add> publish_package: !args.no_publish?,
<add> strategy: CurlNoResumeDownloadStrategy
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/utils/github.rb
<ide> def dispatch_event(user, repo, event, **payload)
<ide> scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
<ide> end
<ide>
<del> def fetch_artifact(user, repo, pr, dir, workflow_id: "tests.yml", artifact_name: "bottles")
<add> def fetch_artifact(user, repo, pr, dir,
<add> workflow_id: "tests.yml", artifact_name: "bottles", strategy: CurlDownloadStrategy)
<ide> scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
<ide> base_url = "#{API_URL}/repos/#{user}/#{repo}"
<ide> pr_payload = open_api("#{base_url}/pulls/#{pr}", scopes: scopes)
<ide> def fetch_artifact(user, repo, pr, dir, workflow_id: "tests.yml", artifact_name:
<ide> FileUtils.chdir dir do
<ide> curl_args[:cache] = Pathname.new(dir)
<ide> curl_args[:secrets] = [token]
<del> downloader = CurlDownloadStrategy.new(artifact_url, "artifact", pr, **curl_args)
<add> downloader = strategy.new(artifact_url, "artifact", pr, **curl_args)
<ide> downloader.fetch
<ide> downloader.stage
<ide> end | 2 |
Python | Python | remove unicode dash in comment | 241b7ed631c051f15e94b1a421d45f04f6099c20 | <ide><path>keras/preprocessing/sequence.py
<ide> def make_sampling_table(size, sampling_factor=1e-5):
<ide> We assume that the word frequencies follow Zipf's law (s=1) to derive
<ide> a numerical approximation of frequency(rank):
<ide> frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank))
<del> where gamma is the Euler–Mascheroni constant.
<add> where gamma is the Euler-Mascheroni constant.
<ide> '''
<ide> gamma = 0.577
<ide> rank = np.array(list(range(size))) | 1 |
Ruby | Ruby | fix absolute symlink | 5241932b45d8d0897cb1af0f9c6dccf6c2250d29 | <ide><path>Library/Homebrew/keg_relocate.rb
<ide> def fix_install_names(options = {})
<ide> end
<ide> end
<ide> end
<add>
<add> symlink_files.each do |file|
<add> link = file.readlink
<add> # Don't fix relative symlinks
<add> next unless link.absolute?
<add> if link.to_s.start_with?(HOMEBREW_CELLAR.to_s) || link.to_s.start_with?(HOMEBREW_PREFIX.to_s)
<add> FileUtils.ln_sf(link.relative_path_from(file.parent), file)
<add> end
<add> end
<ide> end
<ide>
<ide> def relocate_install_names(old_prefix, new_prefix, old_cellar, new_cellar, options = {})
<ide> def libtool_files
<ide> end if lib.directory?
<ide> libtool_files
<ide> end
<add>
<add> def symlink_files
<add> symlink_files = []
<add> path.find do |pn|
<add> symlink_files << pn if pn.symlink?
<add> end
<add>
<add> symlink_files
<add> end
<ide> end | 1 |
Python | Python | remove special casing of 0d in maskedarray.__str__ | 91b83ac6a9477bfb469e270b6e8634b597a3d1ac | <ide><path>numpy/ma/core.py
<ide> def __str__(self):
<ide>
<ide> """
<ide> if masked_print_option.enabled():
<del> f = masked_print_option
<del> if self is masked:
<del> return str(f)
<del> m = self._mask
<del> if m is nomask:
<add> mask = self._mask
<add> if mask is nomask:
<ide> res = self._data
<ide> else:
<del> if m.shape == () and m.itemsize==len(m.dtype):
<del> if m.dtype.names:
<del> m = m.view((bool, len(m.dtype)))
<del> if m.any():
<del> return str(tuple((f if _m else _d) for _d, _m in
<del> zip(self._data.tolist(), m)))
<del> else:
<del> return str(self._data)
<del> elif m:
<del> return str(f)
<del> else:
<del> return str(self._data)
<ide> # convert to object array to make filled work
<del> names = self.dtype.names
<del> if names is None:
<add> if self.dtype.names is None:
<ide> data = self._data
<del> mask = m
<ide> # For big arrays, to avoid a costly conversion to the
<ide> # object dtype, extract the corners before the conversion.
<ide> print_width = (self._print_width if self.ndim > 1
<ide> def __str__(self):
<ide> arr = np.split(mask, (ind, -ind), axis=axis)
<ide> mask = np.concatenate((arr[0], arr[2]), axis=axis)
<ide> res = data.astype("O")
<del> res.view(ndarray)[mask] = f
<add> res.view(ndarray)[mask] = masked_print_option
<ide> else:
<ide> rdtype = _replace_dtype_fields(self.dtype, "O")
<ide> res = self._data.astype(rdtype)
<del> _recursive_printoption(res, m, f)
<add> _recursive_printoption(res, mask, masked_print_option)
<ide> else:
<ide> res = self.filled(self.fill_value)
<ide> return str(res) | 1 |
Javascript | Javascript | add readline support for meta-d | e49be4768be8c84daca6c98a1aa344bc5065590e | <ide><path>lib/readline.js
<ide> Interface.prototype._ttyWrite = function (b) {
<ide> }
<ide> this.cursor = this.line.length;
<ide> this._refreshLine();
<add> } else if (b[1] === 100 && this.cursor < this.line.length) { // meta-d delete forward word
<add> next_word = this.line.slice(this.cursor, this.line.length)
<add> .search(/\w/);
<add> if (next_word !== -1) {
<add> next_non_word = this.line.slice(this.cursor + next_word, this.line.length)
<add> .search(/\W/);
<add> if (next_non_word !== -1) {
<add> this.line = this.line.slice(this.cursor + next_word + next_non_word);
<add> this.cursor = 0;
<add> this._refreshLine();
<add> break;
<add> }
<add> }
<add> this.line = '';
<add> this.cursor = 0;
<add> this._refreshLine();
<ide> } else if (b[1] === 91 && b[2] === 68) { // left arrow
<ide> if (this.cursor > 0) {
<ide> this.cursor--;
<ide><path>test/simple/test-readline.js
<ide> var key = {
<ide> home: [27, 91, 72],
<ide> end: [27, 91, 70],
<ide> metab: [27, 98],
<del> metaf: [27, 102]
<add> metaf: [27, 102],
<add> metad: [27, 100]
<ide> },
<ide> gnome: {
<ide> home: [27, 79, 72],
<ide> written_bytes_length = rl.written_bytes.length;
<ide> rl.write(key.xterm.metab);
<ide> assert.equal(0, rl.cursor);
<ide> refreshed = written_bytes_length !== rl.written_bytes.length;
<del>assert.equal(true, refreshed);
<ide>\ No newline at end of file
<add>assert.equal(true, refreshed);
<add>
<add>rl = readlineFakeStream();
<add>rl.write('foo bar.hop/zoo');
<add>rl.write(key.xterm.home);
<add>rl.write(key.xterm.metad);
<add>assert.equal(0, rl.cursor);
<add>assert.equal(' bar.hop/zoo', rl.line);
<add>rl.write(key.xterm.metad);
<add>assert.equal(0, rl.cursor);
<add>assert.equal('.hop/zoo', rl.line);
<add>rl.write(key.xterm.metad);
<add>assert.equal(0, rl.cursor);
<add>assert.equal('/zoo', rl.line);
<add>rl.write(key.xterm.metad);
<add>assert.equal(0, rl.cursor);
<add>assert.equal('', rl.line); | 2 |
Text | Text | add graphwrap to third-party-packages.md | c69e2e4eaafd7270565f0ecab7635f8988bc0f6d | <ide><path>docs/community/third-party-packages.md
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> * [drf-action-serializer][drf-action-serializer] - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers.
<ide> * [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
<ide> * [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
<add>* [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API.
<ide>
<ide> ### Serializer fields
<ide>
<ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque
<ide> [django-api-client]: https://github.com/rhenter/django-api-client
<ide> [drf-psq]: https://github.com/drf-psq/drf-psq
<ide> [django-rest-authemail]: https://github.com/celiao/django-rest-authemail
<add>[graphwrap]: https://github.com/PaulGilmartin/graph_wrap | 1 |
Python | Python | drop some else clauses in roll | 8d83ae93706d3486447a9b40908995b406178111 | <ide><path>numpy/core/numeric.py
<ide> def roll(a, shift, axis=None):
<ide> reshape = False
<ide> if n == 0:
<ide> return a
<del> else:
<del> shift %= n
<del> indexes = concatenate((arange(n-shift,n),arange(n-shift)))
<del> res = a.take(indexes, axis)
<del> if reshape:
<del> return res.reshape(a.shape)
<del> else:
<del> return res
<add> shift %= n
<add> indexes = concatenate((arange(n - shift, n), arange(n - shift)))
<add> res = a.take(indexes, axis)
<add> if reshape:
<add> res = res.reshape(a.shape)
<add> return res
<ide>
<ide> def rollaxis(a, axis, start=0):
<ide> """ | 1 |
Text | Text | add v3.16.2 to changelog.md | c279c7a794779349396ef46bb30ba302b1142b04 | <ide><path>CHANGELOG.md
<ide>
<ide> - [#18688](https://github.com/emberjs/ember.js/pull/18688) / [#18621](https://github.com/emberjs/ember.js/pull/18621) Updates Glimmer-VM to v0.46
<ide>
<add>### v3.16.2 (February 10, 2020)
<add>
<add>- [#18721](https://github.com/emberjs/ember.js/pull/18721) [BUGFIX release] Backport autotracking bugfixes
<add>- [#18729](https://github.com/emberjs/ember.js/pull/18729) [BUGFIX] Remove deprecation for instantiation of new singleton instances (e.g. a service) during teardown (originally added in 3.16.1 by [#18717](https://github.com/emberjs/ember.js/pull/18717)).
<add>
<ide> ### v3.16.1 (January 31, 2020)
<ide>
<ide> - [#18691](https://github.com/emberjs/ember.js/pull/18691) [BUGFIX] Updated `component` and `helper` blueprints to use `import { hbs } from 'ember-cli-htmlbars'`. | 1 |
Javascript | Javascript | remove unused variable | 39289c9dece88d87638344da5616c8df0ef4a05c | <ide><path>src/extras/geometries/ParametricGeometry.js
<ide> THREE.ParametricGeometry = function ( func, slices, stacks ) {
<ide> var faces = this.faces;
<ide> var uvs = this.faceVertexUvs[ 0 ];
<ide>
<del> var i, il, j, p;
<add> var i, j, p;
<ide> var u, v;
<ide>
<ide> var stackCount = stacks + 1; | 1 |
Go | Go | remove broken container check from image prune | 3aa4f7f0d71f04c5cc93d5e80cbdd47b0b5fdb7f | <ide><path>daemon/prune.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> timetypes "github.com/docker/docker/api/types/time"
<add> "github.com/docker/docker/errdefs"
<ide> "github.com/docker/docker/image"
<ide> "github.com/docker/docker/layer"
<ide> "github.com/docker/docker/pkg/directory"
<ide> func (daemon *Daemon) ImagesPrune(ctx context.Context, pruneFilters filters.Args
<ide> } else {
<ide> allImages = daemon.imageStore.Map()
<ide> }
<del> allContainers := daemon.List()
<del> imageRefs := map[string]bool{}
<del> for _, c := range allContainers {
<del> select {
<del> case <-ctx.Done():
<del> return nil, ctx.Err()
<del> default:
<del> imageRefs[c.ID] = true
<del> }
<del> }
<ide>
<ide> // Filter intermediary images and get their unique size
<ide> allLayers := make(map[layer.ChainID]layer.Layer)
<ide> deleteImagesLoop:
<ide> default:
<ide> }
<ide>
<del> dgst := digest.Digest(id)
<del> hex := dgst.Hex()
<del> if _, ok := imageRefs[hex]; ok {
<del> continue
<del> }
<del>
<ide> deletedImages := []types.ImageDeleteResponseItem{}
<del> refs := daemon.referenceStore.References(dgst)
<add> refs := daemon.referenceStore.References(id.Digest())
<ide> if len(refs) > 0 {
<ide> shouldDelete := !danglingOnly
<ide> if !shouldDelete {
<ide> deleteImagesLoop:
<ide> if shouldDelete {
<ide> for _, ref := range refs {
<ide> imgDel, err := daemon.ImageDelete(ref.String(), false, true)
<del> if err != nil {
<del> logrus.Warnf("could not delete reference %s: %v", ref.String(), err)
<add> if imageDeleteFailed(ref.String(), err) {
<ide> continue
<ide> }
<ide> deletedImages = append(deletedImages, imgDel...)
<ide> }
<ide> }
<ide> } else {
<add> hex := id.Digest().Hex()
<ide> imgDel, err := daemon.ImageDelete(hex, false, true)
<del> if err != nil {
<del> logrus.Warnf("could not delete image %s: %v", hex, err)
<add> if imageDeleteFailed(hex, err) {
<ide> continue
<ide> }
<ide> deletedImages = append(deletedImages, imgDel...)
<ide> deleteImagesLoop:
<ide> return rep, nil
<ide> }
<ide>
<add>func imageDeleteFailed(ref string, err error) bool {
<add> switch {
<add> case err == nil:
<add> return false
<add> case errdefs.IsConflict(err):
<add> return true
<add> default:
<add> logrus.Warnf("failed to prune image %s: %v", ref, err)
<add> return true
<add> }
<add>}
<add>
<ide> // localNetworksPrune removes unused local networks
<ide> func (daemon *Daemon) localNetworksPrune(ctx context.Context, pruneFilters filters.Args) *types.NetworksPruneReport {
<ide> rep := &types.NetworksPruneReport{} | 1 |
Text | Text | remove reference to using sudo for make files | 9d39c5c3841f459bde91b92eea21b2daa7cdc06e | <ide><path>guide/english/bash/index.md
<ide> That is because it is a convention to let the interactive shell know what kind o
<ide>
<ide> Though it is only executed if you run your script as an executable. For example, when you type `./scriptname.extension`, it will look at the top line to find out the interpreter, whereas, running the script as `bash scriptname.sh`, the first line is ignored.
<ide>
<del>For example, you can use this method to run the script as the root user:
<del>To make the file executable call this command under sudo chmod +x "filename".
<add>Then you could run the script like so:
<add>
<ide> ```
<ide> zach@marigold:~$ ./myBashScript.sh
<ide> Hello world! | 1 |
Javascript | Javascript | add test for selection.empty | 2ed5801e72f8001faef46930ca7ae36778598c32 | <ide><path>test/core/selection-empty-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("selection.empty");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body").html("");
<add> },
<add> "returns true for empty selections": function(body) {
<add> assert.isTrue(body.select("foo").empty());
<add> },
<add> "returns false for non-empty selections": function(body) {
<add> assert.isFalse(body.empty());
<add> },
<add> "ignores null nodes": function(body) {
<add> var some = d3.select("body");
<add> some[0][0] = null;
<add> assert.isTrue(some.empty());
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll(div)": {
<add> topic: function() {
<add> var body = d3.select("body").html("");
<add> body.append("div").append("span");
<add> body.append("div");
<add> return body.selectAll("div");
<add> },
<add> "returns true for empty selections": function(div) {
<add> assert.isTrue(div.select("foo").empty());
<add> },
<add> "returns false for non-empty selections": function(div) {
<add> assert.isFalse(div.empty());
<add> assert.isFalse(div.select("span").empty());
<add> },
<add> "ignores null nodes": function(div) {
<add> var some = d3.selectAll("div");
<add> some[0][0] = null;
<add> assert.isTrue(some.select("span").empty());
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
Text | Text | add example for destructuring nested objects | 172ec835d7ae8c3d4409253d3f39e317b7db5e63 | <ide><path>guide/english/javascript/es6/destructuring/index.md
<ide> The examples above show the benefit of using the ES6 Destructuring Assignment.
<ide> You can also use Destructuring on objects using a similar syntax
<ide>
<ide> ```js
<del>const fullName = { first: "John", last: "Smith"};
<add>const fullName = {first: "John", last: "Smith"};
<ide> const {first, last} = fullName;
<ide>
<ide> console.log(first, last); // John Smith
<ide> console.log(first, last); // John Smith
<ide> Object Destructuring Assignment is a little bit different because the object must have properties with the names you are assigning. Therefore the code below would not work as intended.
<ide>
<ide> ```js
<del>const fullName = { first: "John", last: "Smith"};
<add>const fullName = {first: "John", last: "Smith"};
<ide> const {firstName, lastName} = fullName;
<ide>
<ide> console.log(firstName, lastName); // undefined undefined
<ide> const {propertyName: desiredVariableName} = obj
<ide>
<ide> Our previous example would be rewritten as follows:
<ide> ```js
<del>const fullName = { first: "John", last: "Smith"};
<add>const fullName = {first: "John", last: "Smith"};
<ide> const {first: firstName, last: lastName} = fullName;
<ide>
<ide> console.log(firstName, lastName); // John Smith
<ide> ```
<add>
<add>You can also use Destructuring on nested objects.
<add>
<add>```js
<add>const person = {firstName: "John", lastName: "Smith", address: {city: "Istanbul", country: "Turkey"}};
<add>const {address: {city, country}} = person;
<add>
<add>console.log(city, country); // Istanbul Turkey
<add>```
<add>
<ide> **Array Destructuring with rest**
<ide>
<ide> When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern: | 1 |
Ruby | Ruby | determine llvm location programmatically | 4c6e23c28f66206ea4d5316f4ac0732901bcef60 | <ide><path>Library/Homebrew/brewkit.rb
<ide> end
<ide>
<ide> if MACOS_VERSION >= 10.6 or ENV['HOMEBREW_USE_LLVM']
<del> ENV['PATH'] = "/Developer/usr/llvm-gcc-4.2/bin:#{ENV['PATH']}"
<add> # you can install Xcode wherever you like you know.
<add> prefix = `/usr/bin/xcode-select -print-path`.chomp
<add> prefix = "/Developer" if prefix.to_s.empty?
<add>
<add> ENV['PATH'] = "#{prefix}/usr/llvm-gcc-4.2/bin:#{ENV['PATH']}"
<ide> ENV['CC'] = 'llvm-gcc-4.2'
<ide> ENV['CXX'] = 'llvm-g++-4.2'
<ide> cflags = ['-O4'] # O4 baby! | 1 |
Javascript | Javascript | improve loose assertion message | 1d859ef53224c982aee659d0e17b1e5747b19fa0 | <ide><path>lib/internal/assert.js
<ide> let white = '';
<ide>
<ide> const kReadableOperator = {
<ide> deepStrictEqual: 'Expected inputs to be strictly deep-equal:',
<del> notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:',
<ide> strictEqual: 'Expected inputs to be strictly equal:',
<add> deepEqual: 'Expected inputs to be loosely deep-equal:',
<add> equal: 'Expected inputs to be loosely equal:',
<add> notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:',
<ide> notStrictEqual: 'Expected "actual" to be strictly unequal to:',
<add> notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:',
<add> notEqual: 'Expected "actual" to be loosely unequal to:',
<ide> notIdentical: 'Inputs identical but not reference equal:',
<ide> };
<ide>
<ide> function inspectValue(val) {
<ide> // Assert does not detect proxies currently.
<ide> showProxy: false
<ide> }
<del> ).split('\n');
<add> );
<ide> }
<ide>
<ide> function createErrDiff(actual, expected, operator) {
<ide> function createErrDiff(actual, expected, operator) {
<ide> let lastPos = 0;
<ide> let end = '';
<ide> let skipped = false;
<del> const actualLines = inspectValue(actual);
<del> const expectedLines = inspectValue(expected);
<add> const actualInspected = inspectValue(actual);
<add> const actualLines = actualInspected.split('\n');
<add> const expectedLines = inspectValue(expected).split('\n');
<ide> const msg = kReadableOperator[operator] +
<ide> `\n${green}+ actual${white} ${red}- expected${white}`;
<ide> const skippedMsg = ` ${blue}...${white} Lines skipped`;
<ide> function createErrDiff(actual, expected, operator) {
<ide> // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() })
<ide> if (maxLines === 0) {
<ide> // We have to get the result again. The lines were all removed before.
<del> const actualLines = inspectValue(actual);
<add> const actualLines = actualInspected.split('\n');
<ide>
<ide> // Only remove lines in case it makes sense to collapse those.
<ide> // TODO: Accept env to always show the full error.
<ide> class AssertionError extends Error {
<ide> operator === 'notStrictEqual') {
<ide> // In case the objects are equal but the operator requires unequal, show
<ide> // the first object and say A equals B
<del> const res = inspectValue(actual);
<add> const res = inspectValue(actual).split('\n');
<ide> const base = kReadableOperator[operator];
<ide>
<ide> // Only remove lines in case it makes sense to collapse those.
<ide> class AssertionError extends Error {
<ide> super(`${base}\n\n${res.join('\n')}\n`);
<ide> }
<ide> } else {
<del> let res = inspect(actual);
<del> let other = inspect(expected);
<del> if (res.length > 128)
<del> res = `${res.slice(0, 125)}...`;
<del> if (other.length > 128)
<del> other = `${other.slice(0, 125)}...`;
<del> super(`${res} ${operator} ${other}`);
<add> let res = inspectValue(actual);
<add> let other = '';
<add> const knownOperators = kReadableOperator[operator];
<add> if (operator === 'notDeepEqual' || operator === 'notEqual') {
<add> res = `${kReadableOperator[operator]}\n\n${res}`;
<add> if (res.length > 1024) {
<add> res = `${res.slice(0, 1021)}...`;
<add> }
<add> } else {
<add> other = `${inspectValue(expected)}`;
<add> if (res.length > 512) {
<add> res = `${res.slice(0, 509)}...`;
<add> }
<add> if (other.length > 512) {
<add> other = `${other.slice(0, 509)}...`;
<add> }
<add> if (operator === 'deepEqual' || operator === 'equal') {
<add> res = `${knownOperators}\n\n${res}\n\nshould equal\n\n`;
<add> } else {
<add> other = ` ${operator} ${other}`;
<add> }
<add> }
<add> super(`${res}${other}`);
<ide> }
<ide> }
<ide>
<ide><path>test/parallel/test-assert-deep.js
<ide> 'use strict';
<ide>
<del>const common = require('../common');
<add>require('../common');
<ide> const assert = require('assert');
<ide> const util = require('util');
<ide> const { AssertionError } = assert;
<ide> if (process.stdout.isTTY)
<ide> // Template tag function turning an error message into a RegExp
<ide> // for assert.throws()
<ide> function re(literals, ...values) {
<del> let result = literals[0];
<del> const escapeRE = /[\\^$.*+?()[\]{}|=!<>:-]/g;
<add> let result = 'Expected inputs to be loosely deep-equal:\n\n';
<ide> for (const [i, value] of values.entries()) {
<del> const str = util.inspect(value);
<add> const str = util.inspect(value, {
<add> compact: false,
<add> depth: 1000,
<add> customInspect: false,
<add> maxArrayLength: Infinity,
<add> breakLength: Infinity
<add> });
<ide> // Need to escape special characters.
<del> result += str.replace(escapeRE, '\\$&');
<add> result += str;
<ide> result += literals[i + 1];
<ide> }
<del> return common.expectsError({
<add> return {
<ide> code: 'ERR_ASSERTION',
<del> message: new RegExp(`^${result}$`)
<del> });
<add> message: result
<add> };
<ide> }
<ide>
<ide> // The following deepEqual tests might seem very weird.
<ide> assert.throws(
<ide> }
<ide> }
<ide>
<del>common.expectsError(() => {
<del> assert.deepEqual(new Set([{ a: 0 }]), new Set([{ a: 1 }]));
<del>}, {
<del> code: 'ERR_ASSERTION',
<del> message: /^Set { { a: 0 } } deepEqual Set { { a: 1 } }$/
<del>});
<del>
<ide> function assertDeepAndStrictEqual(a, b) {
<ide> assert.deepEqual(a, b);
<ide> assert.deepStrictEqual(a, b);
<ide> function assertDeepAndStrictEqual(a, b) {
<ide> }
<ide>
<ide> function assertNotDeepOrStrict(a, b, err) {
<del> assert.throws(() => assert.deepEqual(a, b), err || re`${a} deepEqual ${b}`);
<add> assert.throws(
<add> () => assert.deepEqual(a, b),
<add> err || re`${a}\n\nshould equal\n\n${b}`
<add> );
<ide> assert.throws(
<ide> () => assert.deepStrictEqual(a, b),
<ide> err || { code: 'ERR_ASSERTION' }
<ide> );
<ide>
<del> assert.throws(() => assert.deepEqual(b, a), err || re`${b} deepEqual ${a}`);
<add> assert.throws(
<add> () => assert.deepEqual(b, a),
<add> err || re`${b}\n\nshould equal\n\n${a}`
<add> );
<ide> assert.throws(
<ide> () => assert.deepStrictEqual(b, a),
<ide> err || { code: 'ERR_ASSERTION' }
<ide> assertNotDeepOrStrict(new Set([1, 2, 3]), new Set([1, 2, 3, 4]));
<ide> assertNotDeepOrStrict(new Set([1, 2, 3, 4]), new Set([1, 2, 3]));
<ide> assertDeepAndStrictEqual(new Set(['1', '2', '3']), new Set(['1', '2', '3']));
<ide> assertDeepAndStrictEqual(new Set([[1, 2], [3, 4]]), new Set([[3, 4], [1, 2]]));
<add>assertNotDeepOrStrict(new Set([{ a: 0 }]), new Set([{ a: 1 }]));
<ide>
<ide> {
<ide> const a = [ 1, 2 ];
<ide> assert.throws(
<ide>
<ide> assert.notDeepEqual(new Date(), new Date(2000, 3, 14));
<ide>
<del>assert.deepEqual(/a/, /a/);
<del>assert.deepEqual(/a/g, /a/g);
<del>assert.deepEqual(/a/i, /a/i);
<del>assert.deepEqual(/a/m, /a/m);
<del>assert.deepEqual(/a/igm, /a/igm);
<del>assert.throws(() => assert.deepEqual(/ab/, /a/),
<del> {
<del> code: 'ERR_ASSERTION',
<del> name: 'AssertionError [ERR_ASSERTION]',
<del> message: '/ab/ deepEqual /a/'
<del> });
<del>assert.throws(() => assert.deepEqual(/a/g, /a/),
<del> {
<del> code: 'ERR_ASSERTION',
<del> name: 'AssertionError [ERR_ASSERTION]',
<del> message: '/a/g deepEqual /a/'
<del> });
<del>assert.throws(() => assert.deepEqual(/a/i, /a/),
<del> {
<del> code: 'ERR_ASSERTION',
<del> name: 'AssertionError [ERR_ASSERTION]',
<del> message: '/a/i deepEqual /a/'
<del> });
<del>assert.throws(() => assert.deepEqual(/a/m, /a/),
<del> {
<del> code: 'ERR_ASSERTION',
<del> name: 'AssertionError [ERR_ASSERTION]',
<del> message: '/a/m deepEqual /a/'
<del> });
<del>assert.throws(() => assert.deepEqual(/a/igm, /a/im),
<del> {
<del> code: 'ERR_ASSERTION',
<del> name: 'AssertionError [ERR_ASSERTION]',
<del> message: '/a/gim deepEqual /a/im'
<del> });
<add>assertDeepAndStrictEqual(/a/, /a/);
<add>assertDeepAndStrictEqual(/a/g, /a/g);
<add>assertDeepAndStrictEqual(/a/i, /a/i);
<add>assertDeepAndStrictEqual(/a/m, /a/m);
<add>assertDeepAndStrictEqual(/a/igm, /a/igm);
<add>assertNotDeepOrStrict(/ab/, /a/);
<add>assertNotDeepOrStrict(/a/g, /a/);
<add>assertNotDeepOrStrict(/a/i, /a/);
<add>assertNotDeepOrStrict(/a/m, /a/);
<add>assertNotDeepOrStrict(/a/igm, /a/im);
<ide>
<ide> {
<ide> const re1 = /a/g;
<ide> nameBuilder2.prototype = Object;
<ide> nb2 = new nameBuilder2('Ryan', 'Dahl');
<ide> assert.deepEqual(nb1, nb2);
<ide>
<del>// Primitives and object.
<del>assert.throws(() => assert.deepEqual(null, {}), AssertionError);
<del>assert.throws(() => assert.deepEqual(undefined, {}), AssertionError);
<del>assert.throws(() => assert.deepEqual('a', ['a']), AssertionError);
<del>assert.throws(() => assert.deepEqual('a', { 0: 'a' }), AssertionError);
<del>assert.throws(() => assert.deepEqual(1, {}), AssertionError);
<del>assert.throws(() => assert.deepEqual(true, {}), AssertionError);
<del>assert.throws(() => assert.deepEqual(Symbol(), {}), AssertionError);
<add>// Primitives
<add>assertNotDeepOrStrict(null, {});
<add>assertNotDeepOrStrict(undefined, {});
<add>assertNotDeepOrStrict('a', ['a']);
<add>assertNotDeepOrStrict('a', { 0: 'a' });
<add>assertNotDeepOrStrict(1, {});
<add>assertNotDeepOrStrict(true, {});
<add>assertNotDeepOrStrict(Symbol(), {});
<add>assertNotDeepOrStrict(Symbol(), Symbol());
<add>
<add>assertOnlyDeepEqual(4, '4');
<add>assertOnlyDeepEqual(true, 1);
<add>
<add>{
<add> const s = Symbol();
<add> assertDeepAndStrictEqual(s, s);
<add>}
<ide>
<ide> // Primitive wrappers and object.
<del>assert.deepEqual(new String('a'), ['a']);
<del>assert.deepEqual(new String('a'), { 0: 'a' });
<del>assert.deepEqual(new Number(1), {});
<del>assert.deepEqual(new Boolean(true), {});
<add>assertOnlyDeepEqual(new String('a'), ['a']);
<add>assertOnlyDeepEqual(new String('a'), { 0: 'a' });
<add>assertOnlyDeepEqual(new Number(1), {});
<add>assertOnlyDeepEqual(new Boolean(true), {});
<ide>
<ide> // Same number of keys but different key names.
<del>assert.throws(() => assert.deepEqual({ a: 1 }, { b: 1 }), AssertionError);
<add>assertNotDeepOrStrict({ a: 1 }, { b: 1 });
<ide>
<ide> assert.deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14));
<ide>
<ide> assert.throws(
<ide>
<ide> assert.notDeepStrictEqual(new Date(), new Date(2000, 3, 14));
<ide>
<del>assert.deepStrictEqual(/a/, /a/);
<del>assert.deepStrictEqual(/a/g, /a/g);
<del>assert.deepStrictEqual(/a/i, /a/i);
<del>assert.deepStrictEqual(/a/m, /a/m);
<del>assert.deepStrictEqual(/a/igm, /a/igm);
<ide> assert.throws(
<ide> () => assert.deepStrictEqual(/ab/, /a/),
<ide> {
<ide> obj2 = new Constructor2('Ryan', 'Dahl');
<ide>
<ide> assert.deepStrictEqual(obj1, obj2);
<ide>
<del>// primitives
<del>assert.throws(() => assert.deepStrictEqual(4, '4'), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(true, 1), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(Symbol(), Symbol()),
<del> AssertionError);
<del>
<del>const s = Symbol();
<del>assert.deepStrictEqual(s, s);
<del>
<del>// Primitives and object.
<del>assert.throws(() => assert.deepStrictEqual(null, {}), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(undefined, {}), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual('a', ['a']), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual('a', { 0: 'a' }), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(1, {}), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(true, {}), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(Symbol(), {}), AssertionError);
<del>
<del>// Primitive wrappers and object.
<del>assert.throws(() => assert.deepStrictEqual(new String('a'), ['a']),
<del> AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(new String('a'), { 0: 'a' }),
<del> AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(new Number(1), {}), AssertionError);
<del>assert.throws(() => assert.deepStrictEqual(new Boolean(true), {}),
<del> AssertionError);
<del>
<ide> // Check extra properties on errors.
<ide> {
<ide> const a = new TypeError('foo'); | 2 |
Javascript | Javascript | adjust suspenselist cpu bound heuristic | 79572e34d18c67768c93b1a4d60703a5929363a3 | <ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js
<ide> function initSuspenseListRenderState(
<ide> workInProgress.memoizedState = ({
<ide> isBackwards: isBackwards,
<ide> rendering: null,
<add> renderingStartTime: 0,
<ide> last: lastContentRow,
<ide> tail: tail,
<ide> tailExpiration: 0,
<ide> function initSuspenseListRenderState(
<ide> // We can reuse the existing object from previous renders.
<ide> renderState.isBackwards = isBackwards;
<ide> renderState.rendering = null;
<add> renderState.renderingStartTime = 0;
<ide> renderState.last = lastContentRow;
<ide> renderState.tail = tail;
<ide> renderState.tailExpiration = 0;
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js
<ide> function completeWork(
<ide> return null;
<ide> }
<ide> } else if (
<del> now() > renderState.tailExpiration &&
<add> // The time it took to render last row is greater than time until
<add> // the expiration.
<add> now() * 2 - renderState.renderingStartTime >
<add> renderState.tailExpiration &&
<ide> renderExpirationTime > Never
<ide> ) {
<ide> // We have now passed our CPU deadline and we'll just give up further
<ide> function completeWork(
<ide> // until we just give up and show what we have so far.
<ide> const TAIL_EXPIRATION_TIMEOUT_MS = 500;
<ide> renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
<add> // TODO: This is meant to mimic the train model or JND but this
<add> // is a per component value. It should really be since the start
<add> // of the total render or last commit. Consider using something like
<add> // globalMostRecentFallbackTime. That doesn't account for being
<add> // suspended for part of the time or when it's a new render.
<add> // It should probably use a global start time value instead.
<ide> }
<ide> // Pop a row.
<ide> let next = renderState.tail;
<ide> renderState.rendering = next;
<ide> renderState.tail = next.sibling;
<ide> renderState.lastEffect = workInProgress.lastEffect;
<add> renderState.renderingStartTime = now();
<ide> next.sibling = null;
<ide>
<ide> // Restore the context.
<ide><path>packages/react-reconciler/src/ReactFiberSuspenseComponent.js
<ide> export type SuspenseListRenderState = {|
<ide> isBackwards: boolean,
<ide> // The currently rendering tail row.
<ide> rendering: null | Fiber,
<add> // The absolute time when we started rendering the tail row.
<add> renderingStartTime: number,
<ide> // The last of the already rendered children.
<ide> last: null | Fiber,
<ide> // Remaining rows on the tail of the list.
<ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.internal.js
<ide> describe('ReactSuspenseList', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<del> Scheduler.unstable_advanceTime(300);
<del> jest.advanceTimersByTime(300);
<add> Scheduler.unstable_advanceTime(200);
<add> jest.advanceTimersByTime(200);
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['B']);
<ide>
<ide> describe('ReactSuspenseList', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<del> Scheduler.unstable_advanceTime(300);
<del> jest.advanceTimersByTime(300);
<add> Scheduler.unstable_advanceTime(200);
<add> jest.advanceTimersByTime(200);
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['B']);
<ide>
<ide><path>packages/react/src/__tests__/ReactDOMTracing-test.internal.js
<ide> describe('ReactDOMTracing', () => {
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['A']);
<ide>
<del> Scheduler.unstable_advanceTime(300);
<del> jest.advanceTimersByTime(300);
<add> Scheduler.unstable_advanceTime(200);
<add> jest.advanceTimersByTime(200);
<ide>
<ide> expect(Scheduler).toFlushAndYieldThrough(['B']);
<ide> | 5 |
PHP | PHP | add table name as default morph type | 5d58b0fddbe81e6e6589b294c48a71ce095183e3 | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php
<ide> public function getMorphClass()
<ide> return array_search(static::class, $morphMap, true);
<ide> }
<ide>
<add> if (Relation::$tableNameAsMorphType) {
<add> return $this->getTable();
<add> }
<add>
<ide> return static::class;
<ide> }
<ide>
<ide><path>src/Illuminate/Database/Eloquent/Relations/Relation.php
<ide> abstract class Relation
<ide> */
<ide> public static $morphMap = [];
<ide>
<add> /**
<add> * Indicates if the morph relation type should default to table name.
<add> *
<add> * @var bool
<add> */
<add> public static $tableNameAsMorphType = false;
<add>
<ide> /**
<ide> * Create a new relation instance.
<ide> *
<ide> public static function morphMap(array $map = null, $merge = true)
<ide> return static::$morphMap;
<ide> }
<ide>
<add> /**
<add> * Changes the default morph type to table name.
<add> *
<add> * @return void
<add> */
<add> public static function tableNameAsMorphType()
<add> {
<add> self::$tableNameAsMorphType = true;
<add> }
<add>
<ide> /**
<ide> * Builds a table-keyed array from model class names.
<ide> *
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testCorrectMorphClassIsReturned()
<ide> }
<ide> }
<ide>
<add> public function testCorrectMorphClassIsReturnedOnChangingDefault()
<add> {
<add> Relation::tableNameAsMorphType();
<add> Relation::morphMap(['alias' => EloquentModelCamelStub::class]);
<add> Relation::morphMap(['alias2' => 'AnotherModel']);
<add> $model = new EloquentModelStub;
<add> $model2 = new EloquentModelCamelStub;
<add>
<add> try {
<add> $this->assertEquals('stub', $model->getMorphClass());
<add> $this->assertEquals('alias', $model2->getMorphClass());
<add> } finally {
<add> Relation::morphMap([], false);
<add> Relation::$tableNameAsMorphType = false;
<add> }
<add> }
<add>
<ide> public function testHasManyCreatesProperRelation()
<ide> {
<ide> $model = new EloquentModelStub; | 3 |
Text | Text | add example of arrow function with no brackets | 2b265e34046777a78657f4b7b689a7ca0c2ffb47 | <ide><path>guide/english/javascript/es6/arrow-functions/index.md
<ide> let newOneWithOneParam = a => {
<ide> }
<ide> ```
<ide>
<add>When there is only one statement or operation in the function body, braces are optional and the result is returned or undefined.
<add>
<add>```javascript
<add>let a = 10;
<add>let newOneParamWithNoBrackets = b => a + b;
<add>console.log(newOneParamWithNoBrackets(20)); // 30
<add>```
<add>
<ide> An incredible advantage of the arrows function is that you can not rebind an arrow function. It will always be called with the context in which it was defined. Just use a normal function.
<ide> ```javascript
<ide> // Old Syntax | 1 |
Text | Text | fix misleading language in vm docs | 8781e618432a5c5d42a0e898eff0122dd573fa9a | <ide><path>doc/api/vm.md
<ide> let code =
<ide> vm.runInThisContext(code)(require);
<ide> ```
<ide>
<del>*Note*: The `require()` in the above case shares the state with context it is
<del>passed from. This may introduce risks when untrusted code is executed, e.g.
<del>altering objects from the calling thread's context in unwanted ways.
<add>*Note*: The `require()` in the above case shares the state with the context it
<add>is passed from. This may introduce risks when untrusted code is executed, e.g.
<add>altering objects in the context in unwanted ways.
<ide>
<ide> ## What does it mean to "contextify" an object?
<ide> | 1 |
Text | Text | update readme to emphasize 'global batch size' | 841bf60b8bd39d103c723bb99a98686bc280e934 | <ide><path>official/transformer/v2/README.md
<ide> tensorboard --logdir=$MODEL_DIR
<ide> Users need to adjust `batch_size` and `num_gpus` to get good performance
<ide> running multiple GPUs.
<ide>
<add> **Note that:**
<add> when using multiple GPUs or TPUs, this is the global batch size for all
<add> devices. For example, if the batch size is `4096*4` and there are 4 devices,
<add> each device will take 4096 tokens as a batch budget.
<add>
<ide> Command to run:
<ide> ```
<ide> python3 transformer_main.py --data_dir=$DATA_DIR --model_dir=$MODEL_DIR \ | 1 |
Java | Java | clarify beanfactory#containsbean javadoc | 10be0ef9e763d368a24a7ac466da50a2224c5d41 | <ide><path>org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2011 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public interface BeanFactory {
<ide> Object getBean(String name, Object... args) throws BeansException;
<ide>
<ide> /**
<del> * Does this bean factory contain a bean with the given name? More specifically,
<del> * is {@link #getBean} able to obtain a bean instance for the given name?
<del> * <p>Translates aliases back to the corresponding canonical bean name.
<del> * Will ask the parent factory if the bean cannot be found in this factory instance.
<add> * Does this bean factory contain a bean definition or externally registered singleton
<add> * instance with the given name?
<add> * <p>If the given name is an alias, it will be translated back to the corresponding
<add> * canonical bean name.
<add> * <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
<add> * be found in this factory instance.
<add> * <p>If a bean definition or singleton instance matching the given name is found,
<add> * this method will return {@code true} whether the named bean definition is concrete
<add> * or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
<add> * return value from this method does not necessarily indicate that {@link #getBean}
<add> * will be able to obtain an instance for the same name.
<ide> * @param name the name of the bean to query
<del> * @return whether a bean with the given name is defined
<add> * @return whether a bean with the given name is present
<ide> */
<ide> boolean containsBean(String name);
<ide>
<ide><path>org.springframework.beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
<ide>
<ide> package org.springframework.beans.factory;
<ide>
<add>import static org.hamcrest.CoreMatchers.is;
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertFalse;
<ide> import static org.junit.Assert.assertNotNull;
<ide> import static org.junit.Assert.assertNotSame;
<ide> import static org.junit.Assert.assertNull;
<ide> import static org.junit.Assert.assertSame;
<add>import static org.junit.Assert.assertThat;
<ide> import static org.junit.Assert.assertTrue;
<ide> import static org.junit.Assert.fail;
<add>import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
<ide>
<ide> import java.lang.reflect.Field;
<ide> import java.net.MalformedURLException;
<ide> import org.springframework.beans.factory.xml.ConstructorDependenciesBean;
<ide> import org.springframework.beans.factory.xml.DependenciesBean;
<ide> import org.springframework.beans.propertyeditors.CustomNumberEditor;
<del>import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.convert.converter.Converter;
<ide> import org.springframework.core.convert.support.DefaultConversionService;
<ide> public Object run() {
<ide> assertEquals("user1", bean.getUserName());
<ide> }
<ide>
<add> @Test
<add> public void testContainsBeanReturnsTrueEvenForAbstractBeanDefinition() {
<add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<add> bf.registerBeanDefinition("abs",
<add> rootBeanDefinition(TestBean.class).setAbstract(true).getBeanDefinition());
<add> assertThat(bf.containsBean("abs"), is(true));
<add> assertThat(bf.containsBean("bogus"), is(false));
<add> }
<add>
<ide>
<ide> public static class NoDependencies {
<ide> | 2 |
Mixed | Text | add support for unitless tabsize/tab-size | 60e1f5a1032201381da551ed0a6dec8978b2c937 | <ide><path>docs/tips/06-style-props-value-px.ko-KR.md
<ide> React.render(<div style={divStyle}>Hello World!</div>, mountNode);
<ide>
<ide> 개발 하다보면 CSS 속성들이 단위 없이 그대로 유지되어야 할 때가 있을 겁니다. 아래의 프로퍼티들은 자동으로 "px"가 붙지 않는 속성 리스트 입니다:
<ide>
<add>- `boxFlex`
<add>- `boxFlexGroup`
<ide> - `columnCount`
<ide> - `fillOpacity`
<ide> - `flex`
<ide> - `flexGrow`
<add>- `flexPositive`
<ide> - `flexShrink`
<add>- `flexNegative`
<ide> - `fontWeight`
<ide> - `lineClamp`
<ide> - `lineHeight`
<ide> - `opacity`
<ide> - `order`
<ide> - `orphans`
<ide> - `strokeOpacity`
<add>- `tabSize`
<ide> - `widows`
<ide> - `zIndex`
<ide> - `zoom`
<ide><path>docs/tips/06-style-props-value-px.md
<ide> Sometimes you _do_ want to keep the CSS properties unitless. Here's a list of pr
<ide> - `order`
<ide> - `orphans`
<ide> - `strokeOpacity`
<add>- `tabSize`
<ide> - `widows`
<ide> - `zIndex`
<ide> - `zoom`
<ide><path>src/browser/ui/dom/CSSProperty.js
<ide> var isUnitlessNumber = {
<ide> opacity: true,
<ide> order: true,
<ide> orphans: true,
<add> tabSize: true,
<ide> widows: true,
<ide> zIndex: true,
<ide> zoom: true, | 3 |
Python | Python | restore inadvertent change to f2py | 96853238f9a848100ad9e651bb64c8b2c6d1443e | <ide><path>scipy/test/testing.py
<ide> def _get_all_method_names(cls):
<ide> names.append(n)
<ide> return names
<ide>
<add># for debug build--check for memory leaks during the test.
<add>class _SciPyTextTestResult(unittest._TextTestResult):
<add> def startTest(self, test):
<add> unittest._TextTestResult.startTest(self, test)
<add> if self.showAll:
<add> N = len(sys.getobjects(0))
<add> self._totnumobj = N
<add> self._totrefcnt = sys.gettotalrefcount()
<add>
<add> def stopTest(self, test):
<add> if self.showAll:
<add> N = len(sys.getobjects(0))
<add> self.stream.write("objects: %d ===> %d; " % (self._totnumobj, N))
<add> self.stream.write("refcnts: %d ===> %d\n" % (self._totrefcnt,
<add> sys.gettotalrefcount()))
<add>
<add>class SciPyTextTestRunner(unittest.TextTestRunner):
<add> def _makeResult(self):
<add> return _SciPyTextTestResult(self.stream, self.descriptions, self.verbosity)
<add>
<ide> __all__.append('ScipyTest')
<ide> class ScipyTest:
<ide> """ Scipy tests site manager.
<ide> def test(self,level=1,verbosity=1):
<ide> suites.extend(self._get_suite_list(sys.modules[package_name], level))
<ide>
<ide> all_tests = unittest.TestSuite(suites)
<add> #if hasattr(sys,'getobjects'):
<add> # runner = SciPyTextTestRunner(verbosity=verbosity)
<add> #else:
<ide> runner = unittest.TextTestRunner(verbosity=verbosity)
<ide> # Use the builtin displayhook. If the tests are being run
<ide> # under IPython (for instance), any doctest test suites will | 1 |
PHP | PHP | move getconfigloader into application instance | 415d36679d8077f6903db7e3faf2c16d131c96f1 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> use Illuminate\Http\Response;
<ide> use Illuminate\Routing\Route;
<ide> use Illuminate\Routing\Router;
<add>use Illuminate\Config\FileLoader;
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Support\Facades\Facade;
<ide> public function fatal(Closure $callback)
<ide> });
<ide> }
<ide>
<add> /**
<add> * Get the configuration loader instance.
<add> *
<add> * @return \Illuminate\Config\LoaderInterface
<add> */
<add> public function getConfigLoader()
<add> {
<add> return new FileLoader(new Filesystem, $this['path'].'/config');
<add> }
<add>
<ide> /**
<ide> * Set the current application locale.
<ide> *
<ide><path>src/Illuminate/Foundation/start.php
<ide> */
<ide>
<ide> use Illuminate\Http\Request;
<del>use Illuminate\Config\FileLoader;
<ide> use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Support\Facades\Facade;
<ide> use Illuminate\Foundation\AliasLoader;
<ide>
<ide> Facade::setFacadeApplication($app);
<ide>
<del>/*
<del>|--------------------------------------------------------------------------
<del>| Register The Configuration Loader
<del>|--------------------------------------------------------------------------
<del>|
<del>| The configuration loader is responsible for loading the configuration
<del>| options for the application. By default we'll use the "file" loader
<del>| but you are free to use any custom loaders with your application.
<del>|
<del>*/
<del>
<del>$app->bindIf('config.loader', function($app)
<del>{
<del> return new FileLoader(new Filesystem, $app['path'].'/config');
<del>
<del>}, true);
<del>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Register The Configuration Repository
<ide> |
<ide> */
<ide>
<del>$config = new Config($app['config.loader'], $env);
<add>$config = new Config($app->getConfigLoader(), $env);
<ide>
<ide> $app->instance('config', $config);
<ide> | 2 |
Go | Go | remove solaris build-tag, simplify and gofumpt | de705907a54f6c20ec1fd2ea2f7c56d94d24dbcb | <ide><path>client/client_unix.go
<del>//go:build linux || freebsd || openbsd || netbsd || darwin || solaris || illumos || dragonfly
<del>// +build linux freebsd openbsd netbsd darwin solaris illumos dragonfly
<add>//go:build !windows
<add>// +build !windows
<ide>
<ide> package client // import "github.com/docker/docker/client"
<ide> | 1 |
Javascript | Javascript | use a getter for candefineproperty check | d95a2239a88440bbaa3ba33817ea91e0bd0c958a | <ide><path>src/shared/utils/canDefineProperty.js
<ide> var canDefineProperty = false;
<ide> if (__DEV__) {
<ide> try {
<del> Object.defineProperty({}, 'x', {});
<add> Object.defineProperty({}, 'x', {get: function() {}});
<ide> canDefineProperty = true;
<ide> } catch (x) {
<ide> // IE will fail on defineProperty | 1 |
Python | Python | fix failing tests from | 2c18a3f3b3208e7e7bfa0bdd4496dd6e727918a3 | <ide><path>airflow/www/views.py
<ide> def recurse_nodes(task, visited):
<ide>
<ide> # avoid spaces to reduce payload size
<ide> data = htmlsafe_json_dumps(data, separators=(',', ':'))
<del> # escape slashes to avoid JSON parse error in JS
<del> data = data.replace('\\', '\\\\')
<ide>
<ide> return self.render_template(
<ide> 'airflow/tree.html',
<ide><path>tests/www/test_views.py
<ide> def test_view_uses_existing_dagbag(self, endpoint, mock_get_dag):
<ide> self.check_content_in_response('example_bash_operator', resp)
<ide>
<ide> @parameterized.expand([
<del> ("hello\nworld", "hello\\\\nworld"),
<del> ("hello'world", "hello\\\\u0027world"),
<del> ("<script>", "\\\\u003cscript\\\\u003e"),
<add> ("hello\nworld", r'\"conf\":{\"abc\":\"hello\\nworld\"}}'),
<add> ("hello'world", r'\"conf\":{\"abc\":\"hello\\u0027world\"}}'),
<add> ("<script>", r'\"conf\":{\"abc\":\"\\u003cscript\\u003e\"}}'),
<add> ("\"", r'\"conf\":{\"abc\":\"\\\"\"}}'),
<ide> ])
<del> def test_escape_in_tree_view(self, test_str, seralized_test_str):
<add> def test_escape_in_tree_view(self, test_str, expected_text):
<ide> dag = self.dagbag.dags['test_tree_view']
<ide> dag.create_dagrun(
<ide> execution_date=self.EXAMPLE_DAG_DEFAULT_DATE,
<ide> def test_escape_in_tree_view(self, test_str, seralized_test_str):
<ide>
<ide> url = 'tree?dag_id=test_tree_view'
<ide> resp = self.client.get(url, follow_redirects=True)
<del> self.check_content_in_response(f'"conf":{{"abc":"{seralized_test_str}"}}', resp)
<add> self.check_content_in_response(expected_text, resp)
<ide>
<ide> def test_dag_details_trigger_origin_tree_view(self):
<ide> dag = self.dagbag.dags['test_tree_view'] | 2 |
Ruby | Ruby | prefer keg curl over system on 10.6 | aa49da260082deb6d3ec3492d6c836e6ad709ba7 | <ide><path>Library/Homebrew/utils.rb
<ide> def quiet_system cmd, *args
<ide> end
<ide>
<ide> def curl *args
<del> curl = Pathname.new '/usr/bin/curl'
<add> brewed_curl = HOMEBREW_PREFIX/"opt/curl/bin/curl"
<add> curl = if MacOS.version <= "10.6" && brewed_curl.exist?
<add> brewed_curl
<add> else
<add> Pathname.new '/usr/bin/curl'
<add> end
<ide> raise "#{curl} is not executable" unless curl.exist? and curl.executable?
<ide>
<ide> flags = HOMEBREW_CURL_ARGS | 1 |
Text | Text | fix typo in changelog | dde78060742506a89cf4b106400abd12bc78545e | <ide><path>CHANGELOG.md
<ide> Below is a summary of the user-facing changes to be found in the io.js v1.0.0 re
<ide> current _stable_ Node.js release, v0.10.35. At the time of the v1.0.0 release, the latest _unstable_
<ide> Node.js release is v0.11.14 with much progress made towards a v0.11.15 release. The io.js codebase inherits
<ide> the majority of the changes found in the v0.11 branch of the [joyent/node](https://github.com/joyent/node)
<del>repository and therefore can be seen as an xteension to v0.11.
<add>repository and therefore can be seen as an extension to v0.11.
<ide>
<ide> ## Summary of changes from Node.js v0.10.35 to io.js v1.0.0
<ide> | 1 |
Ruby | Ruby | fix unscope for less than | c6e05d68400361921c4ba6f0888979e92a4a801b | <ide><path>activerecord/lib/active_record/relation/where_clause.rb
<ide> def invert_predicate(node)
<ide> def predicates_except(columns)
<ide> predicates.reject do |node|
<ide> case node
<del> when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThanOrEqual
<add> when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual
<ide> subrelation = (node.left.kind_of?(Arel::Attributes::Attribute) ? node.left : node.right)
<ide> columns.include?(subrelation.name.to_s)
<ide> end
<ide><path>activerecord/test/cases/scoping/default_scoping_test.rb
<ide> def test_unscope_with_where_attributes
<ide> assert_equal expected_7, received_7
<ide> end
<ide>
<add> def test_unscope_comparison_where_clauses
<add> # unscoped for WHERE (`developers`.`id` <= 2)
<add> expected = Developer.order('salary DESC').collect(&:name)
<add> received = DeveloperOrderedBySalary.where(id: -Float::INFINITY..2).unscope(where: :id).collect { |dev| dev.name }
<add> assert_equal expected, received
<add>
<add> # unscoped for WHERE (`developers`.`id` < 2)
<add> expected = Developer.order('salary DESC').collect(&:name)
<add> received = DeveloperOrderedBySalary.where(id: -Float::INFINITY...2).unscope(where: :id).collect { |dev| dev.name }
<add> assert_equal expected, received
<add> end
<add>
<ide> def test_unscope_multiple_where_clauses
<ide> expected = Developer.order('salary DESC').collect(&:name)
<ide> received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect(&:name) | 2 |
Javascript | Javascript | add number for schema info | f18989c712894bba13ebfb6dfb3f50fc44b0d12a | <ide><path>lib/WebpackOptionsValidationError.js
<ide> function formatSchema(schema, prevSchemas) {
<ide> return "string";
<ide> case "boolean":
<ide> return "boolean";
<add> case "number":
<add> return "number";
<ide> case "object":
<ide> if(schema.properties) {
<ide> var required = schema.required || []; | 1 |
Text | Text | add digitalocean logo | b2995be4453e8d2d7367dac1d573258f2a59148f | <ide><path>README.md
<ide> Our Xserve ESXi boxes for CI are hosted by [MacStadium](https://www.macstadium.c
<ide>
<ide> Our Jenkins CI installation is hosted by [DigitalOcean](https://m.do.co/c/7e39c35d5581).
<ide>
<add>
<add>
<ide> Our bottles (binary packages) are hosted by [Bintray](https://bintray.com/homebrew).
<ide>
<ide> [](https://bintray.com/homebrew) | 1 |
Python | Python | fix doc strings on default activations | b574263adefccc6aea5a3770edd80bbb9f170f41 | <ide><path>keras/layers/recurrent.py
<ide> class SimpleRNNCell(Layer):
<ide> units: Positive integer, dimensionality of the output space.
<ide> activation: Activation function to use
<ide> (see [activations](../activations.md)).
<del> If you pass None, no activation is applied
<add> Default: hyperbolic tangent (`tanh`).
<add> If you pass `None`, no activation is applied
<ide> (ie. "linear" activation: `a(x) = x`).
<ide> use_bias: Boolean, whether the layer uses a bias vector.
<ide> kernel_initializer: Initializer for the `kernel` weights matrix,
<ide> class SimpleRNN(RNN):
<ide> units: Positive integer, dimensionality of the output space.
<ide> activation: Activation function to use
<ide> (see [activations](../activations.md)).
<del> If you pass None, no activation is applied
<add> Default: hyperbolic tangent (`tanh`).
<add> If you pass `None`, no activation is applied
<ide> (ie. "linear" activation: `a(x) = x`).
<ide> use_bias: Boolean, whether the layer uses a bias vector.
<ide> kernel_initializer: Initializer for the `kernel` weights matrix,
<ide> class GRUCell(Layer):
<ide> units: Positive integer, dimensionality of the output space.
<ide> activation: Activation function to use
<ide> (see [activations](../activations.md)).
<del> If you pass None, no activation is applied
<add> Default: hyperbolic tangent (`tanh`).
<add> If you pass `None`, no activation is applied
<ide> (ie. "linear" activation: `a(x) = x`).
<ide> recurrent_activation: Activation function to use
<ide> for the recurrent step
<ide> (see [activations](../activations.md)).
<add> Default: hard sigmoid (`hard_sigmoid`).
<add> If you pass `None`, no activation is applied
<add> (ie. "linear" activation: `a(x) = x`).
<ide> use_bias: Boolean, whether the layer uses a bias vector.
<ide> kernel_initializer: Initializer for the `kernel` weights matrix,
<ide> used for the linear transformation of the inputs
<ide> class GRU(RNN):
<ide> units: Positive integer, dimensionality of the output space.
<ide> activation: Activation function to use
<ide> (see [activations](../activations.md)).
<del> If you pass None, no activation is applied
<add> Default: hyperbolic tangent (`tanh`).
<add> If you pass `None`, no activation is applied
<ide> (ie. "linear" activation: `a(x) = x`).
<ide> recurrent_activation: Activation function to use
<ide> for the recurrent step
<ide> (see [activations](../activations.md)).
<add> Default: hard sigmoid (`hard_sigmoid`).
<add> If you pass `None`, no activation is applied
<add> (ie. "linear" activation: `a(x) = x`).
<ide> use_bias: Boolean, whether the layer uses a bias vector.
<ide> kernel_initializer: Initializer for the `kernel` weights matrix,
<ide> used for the linear transformation of the inputs
<ide> class LSTMCell(Layer):
<ide> units: Positive integer, dimensionality of the output space.
<ide> activation: Activation function to use
<ide> (see [activations](../activations.md)).
<del> If you pass None, no activation is applied
<add> Default: hyperbolic tangent (`tanh`).
<add> If you pass `None`, no activation is applied
<ide> (ie. "linear" activation: `a(x) = x`).
<ide> recurrent_activation: Activation function to use
<ide> for the recurrent step
<ide> (see [activations](../activations.md)).
<add> Default: hard sigmoid (`hard_sigmoid`).
<add> If you pass `None`, no activation is applied
<add> (ie. "linear" activation: `a(x) = x`).x
<ide> use_bias: Boolean, whether the layer uses a bias vector.
<ide> kernel_initializer: Initializer for the `kernel` weights matrix,
<ide> used for the linear transformation of the inputs
<ide> class LSTM(RNN):
<ide> units: Positive integer, dimensionality of the output space.
<ide> activation: Activation function to use
<ide> (see [activations](../activations.md)).
<del> If you pass None, no activation is applied
<add> Default: hyperbolic tangent (`tanh`).
<add> If you pass `None`, no activation is applied
<ide> (ie. "linear" activation: `a(x) = x`).
<ide> recurrent_activation: Activation function to use
<ide> for the recurrent step
<ide> (see [activations](../activations.md)).
<add> Default: hard sigmoid (`hard_sigmoid`).
<add> If you pass `None`, no activation is applied
<add> (ie. "linear" activation: `a(x) = x`).
<ide> use_bias: Boolean, whether the layer uses a bias vector.
<ide> kernel_initializer: Initializer for the `kernel` weights matrix,
<ide> used for the linear transformation of the inputs. | 1 |
Text | Text | remove outdated vagrant docs | 45eb4e0d80a7ccc97746c36a0bd308e5b5135af0 | <ide><path>contrib/vagrant-docker/README.md
<del># Vagrant integration
<del>
<del>Currently there are at least 4 different projects that we are aware of that deals
<del>with integration with [Vagrant](http://vagrantup.com/) at different levels. One
<del>approach is to use Docker as a [provisioner](http://docs.vagrantup.com/v2/provisioning/index.html)
<del>which means you can create containers and pull base images on VMs using Docker's
<del>CLI and the other is to use Docker as a [provider](http://docs.vagrantup.com/v2/providers/index.html),
<del>meaning you can use Vagrant to control Docker containers.
<del>
<del>
<del>### Provisioners
<del>
<del>* [Vocker](https://github.com/fgrehm/vocker)
<del>* [Ventriloquist](https://github.com/fgrehm/ventriloquist)
<del>
<del>### Providers
<del>
<del>* [docker-provider](https://github.com/fgrehm/docker-provider)
<del>* [vagrant-shell](https://github.com/destructuring/vagrant-shell)
<del>
<del>## Setting up Vagrant-docker with the Engine API
<del>
<del>The initial Docker upstart script will not work because it runs on `127.0.0.1`, which is not accessible to the host machine. Instead, we need to change the script to connect to `0.0.0.0`. To do this, modify `/etc/init/docker.conf` to look like this:
<del>
<del>```
<del>description "Docker daemon"
<del>
<del>start on filesystem
<del>stop on runlevel [!2345]
<del>
<del>respawn
<del>
<del>script
<del> /usr/bin/dockerd -H=tcp://0.0.0.0:2375
<del>end script
<del>```
<del>
<del>Once that's done, you need to set up an SSH tunnel between your host machine and the vagrant machine that's running Docker. This can be done by running the following command in a host terminal:
<del>
<del>```
<del>ssh -L 2375:localhost:2375 -p 2222 vagrant@localhost
<del>```
<del>
<del>(The first 2375 is what your host can connect to, the second 2375 is what port Docker is running on in the vagrant machine, and the 2222 is the port Vagrant is providing for SSH. If VirtualBox is the VM you're using, you can see what value "2222" should be by going to: Network > Adapter 1 > Advanced > Port Forwarding in the VirtualBox GUI.)
<del>
<del>Note that because the port has been changed, to run docker commands from within the command line you must run them like this:
<del>
<del>```
<del>sudo docker -H 0.0.0.0:2375 < commands for docker >
<del>``` | 1 |
PHP | PHP | reference the correct interface method | 2399dabe64136ccb851a4e0f1370c32fda0100d2 | <ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> protected function replaceRouteableParameters($parameters = array())
<ide> {
<ide> if ($parameter instanceof RouteableInterface)
<ide> {
<del> $parameter = $parameter->getRouteParameter();
<add> $parameter = $parameter->getRouteKey();
<ide> }
<ide> }
<ide> | 1 |
Python | Python | update train_ner_standalone example | 027a5d8b75c74fe2ae27d21ecb1d4ca36ec23cb3 | <ide><path>examples/training/train_ner_standalone.py
<ide> https://www.lt.informatik.tu-darmstadt.de/fileadmin/user_upload/Group_LangTech/data/GermEval2014_complete_data.zip
<ide>
<ide> Developed for: spaCy 1.7.1
<del>Last tested for: spaCy 1.7.1
<add>Last tested for: spaCy 2.0.0a13
<ide> '''
<ide> from __future__ import unicode_literals, print_function
<ide> import plac
<ide> from pathlib import Path
<ide> import random
<ide> import json
<add>from thinc.neural.optimizers import Adam
<add>from thinc.neural.ops import NumpyOps
<add>import tqdm
<ide>
<del>import spacy.orth as orth_funcs
<ide> from spacy.vocab import Vocab
<del>from spacy.pipeline import BeamEntityRecognizer
<del>from spacy.pipeline import EntityRecognizer
<add>from spacy.pipeline import TokenVectorEncoder, NeuralEntityRecognizer
<ide> from spacy.tokenizer import Tokenizer
<ide> from spacy.tokens import Doc
<ide> from spacy.attrs import *
<ide> from spacy.gold import GoldParse
<del>from spacy.gold import _iob_to_biluo as iob_to_biluo
<add>from spacy.gold import iob_to_biluo
<add>from spacy.gold import minibatch
<ide> from spacy.scorer import Scorer
<add>import spacy.util
<ide>
<ide> try:
<ide> unicode
<ide> except NameError:
<ide> unicode = str
<ide>
<ide>
<add>spacy.util.set_env_log(True)
<add>
<add>
<ide> def init_vocab():
<ide> return Vocab(
<ide> lex_attr_getters={
<ide> LOWER: lambda string: string.lower(),
<del> SHAPE: orth_funcs.word_shape,
<add> NORM: lambda string: string.lower(),
<ide> PREFIX: lambda string: string[0],
<ide> SUFFIX: lambda string: string[-3:],
<del> CLUSTER: lambda string: 0,
<del> IS_ALPHA: orth_funcs.is_alpha,
<del> IS_ASCII: orth_funcs.is_ascii,
<del> IS_DIGIT: lambda string: string.isdigit(),
<del> IS_LOWER: orth_funcs.is_lower,
<del> IS_PUNCT: orth_funcs.is_punct,
<del> IS_SPACE: lambda string: string.isspace(),
<del> IS_TITLE: orth_funcs.is_title,
<del> IS_UPPER: orth_funcs.is_upper,
<del> IS_STOP: lambda string: False,
<del> IS_OOV: lambda string: True
<ide> })
<ide>
<ide>
<del>def save_vocab(vocab, path):
<del> path = Path(path)
<del> if not path.exists():
<del> path.mkdir()
<del> elif not path.is_dir():
<del> raise IOError("Can't save vocab to %s\nNot a directory" % path)
<del> with (path / 'strings.json').open('w') as file_:
<del> vocab.strings.dump(file_)
<del> vocab.dump((path / 'lexemes.bin').as_posix())
<del>
<del>
<del>def load_vocab(path):
<del> path = Path(path)
<del> if not path.exists():
<del> raise IOError("Cannot load vocab from %s\nDoes not exist" % path)
<del> if not path.is_dir():
<del> raise IOError("Cannot load vocab from %s\nNot a directory" % path)
<del> return Vocab.load(path)
<del>
<del>
<del>def init_ner_model(vocab, features=None):
<del> if features is None:
<del> features = tuple(EntityRecognizer.feature_templates)
<del> return EntityRecognizer(vocab, features=features)
<del>
<del>
<del>def save_ner_model(model, path):
<del> path = Path(path)
<del> if not path.exists():
<del> path.mkdir()
<del> if not path.is_dir():
<del> raise IOError("Can't save model to %s\nNot a directory" % path)
<del> model.model.dump((path / 'model').as_posix())
<del> with (path / 'config.json').open('w') as file_:
<del> data = json.dumps(model.cfg)
<del> if not isinstance(data, unicode):
<del> data = data.decode('utf8')
<del> file_.write(data)
<del>
<del>
<del>def load_ner_model(vocab, path):
<del> return EntityRecognizer.load(path, vocab)
<del>
<del>
<ide> class Pipeline(object):
<del> @classmethod
<del> def load(cls, path):
<del> path = Path(path)
<del> if not path.exists():
<del> raise IOError("Cannot load pipeline from %s\nDoes not exist" % path)
<del> if not path.is_dir():
<del> raise IOError("Cannot load pipeline from %s\nNot a directory" % path)
<del> vocab = load_vocab(path)
<del> tokenizer = Tokenizer(vocab, {}, None, None, None)
<del> ner_model = load_ner_model(vocab, path / 'ner')
<del> return cls(vocab, tokenizer, ner_model)
<del>
<del> def __init__(self, vocab=None, tokenizer=None, entity=None):
<add> def __init__(self, vocab=None, tokenizer=None, tensorizer=None, entity=None):
<ide> if vocab is None:
<ide> vocab = init_vocab()
<ide> if tokenizer is None:
<ide> tokenizer = Tokenizer(vocab, {}, None, None, None)
<add> if tensorizer is None:
<add> tensorizer = TokenVectorEncoder(vocab)
<ide> if entity is None:
<del> entity = init_ner_model(self.vocab)
<add> entity = NeuralEntityRecognizer(vocab)
<ide> self.vocab = vocab
<ide> self.tokenizer = tokenizer
<add> self.tensorizer = tensorizer
<ide> self.entity = entity
<del> self.pipeline = [self.entity]
<add> self.pipeline = [tensorizer, self.entity]
<add>
<add> def begin_training(self):
<add> for model in self.pipeline:
<add> model.begin_training([])
<add> optimizer = Adam(NumpyOps(), 0.001)
<add> return optimizer
<ide>
<ide> def __call__(self, input_):
<ide> doc = self.make_doc(input_)
<ide> def make_gold(self, input_, annotations):
<ide> gold = GoldParse(doc, entities=annotations)
<ide> return gold
<ide>
<del> def update(self, input_, annot):
<del> doc = self.make_doc(input_)
<del> gold = self.make_gold(input_, annot)
<del> for ner in gold.ner:
<del> if ner not in (None, '-', 'O'):
<del> action, label = ner.split('-', 1)
<del> self.entity.add_label(label)
<del> return self.entity.update(doc, gold)
<add> def update(self, inputs, annots, sgd, losses=None, drop=0.):
<add> if losses is None:
<add> losses = {}
<add> docs = [self.make_doc(input_) for input_ in inputs]
<add> golds = [self.make_gold(input_, annot) for input_, annot in
<add> zip(inputs, annots)]
<add>
<add> tensors, bp_tensors = self.tensorizer.update(docs, golds, drop=drop)
<add> d_tensors = self.entity.update((docs, tensors), golds, drop=drop,
<add> sgd=sgd, losses=losses)
<add> bp_tensors(d_tensors, sgd=sgd)
<add> return losses
<ide>
<ide> def evaluate(self, examples):
<ide> scorer = Scorer()
<ide> def evaluate(self, examples):
<ide> scorer.score(doc, gold)
<ide> return scorer.scores
<ide>
<del> def average_weights(self):
<del> self.entity.model.end_training()
<del>
<del> def save(self, path):
<add> def to_disk(self, path):
<ide> path = Path(path)
<ide> if not path.exists():
<ide> path.mkdir()
<ide> elif not path.is_dir():
<ide> raise IOError("Can't save pipeline to %s\nNot a directory" % path)
<del> save_vocab(self.vocab, path / 'vocab')
<del> save_ner_model(self.entity, path / 'ner')
<add> self.vocab.to_disk(path / 'vocab')
<add> self.tensorizer.to_disk(path / 'tensorizer')
<add> self.entity.to_disk(path / 'ner')
<add>
<add> def from_disk(self, path):
<add> path = Path(path)
<add> if not path.exists():
<add> raise IOError("Cannot load pipeline from %s\nDoes not exist" % path)
<add> if not path.is_dir():
<add> raise IOError("Cannot load pipeline from %s\nNot a directory" % path)
<add> self.vocab = self.vocab.from_disk(path / 'vocab')
<add> self.tensorizer = self.tensorizer.from_disk(path / 'tensorizer')
<add> self.entity = self.entity.from_disk(path / 'ner')
<ide>
<ide>
<del>def train(nlp, train_examples, dev_examples, ctx, nr_epoch=5):
<del> next_epoch = train_examples
<add>def train(nlp, train_examples, dev_examples, nr_epoch=5):
<add> sgd = nlp.begin_training()
<ide> print("Iter", "Loss", "P", "R", "F")
<ide> for i in range(nr_epoch):
<del> this_epoch = next_epoch
<del> next_epoch = []
<del> loss = 0
<del> for input_, annot in this_epoch:
<del> loss += nlp.update(input_, annot)
<del> if (i+1) < nr_epoch:
<del> next_epoch.append((input_, annot))
<del> random.shuffle(next_epoch)
<add> random.shuffle(train_examples)
<add> losses = {}
<add> for batch in minibatch(tqdm.tqdm(train_examples, leave=False), size=8):
<add> inputs, annots = zip(*batch)
<add> nlp.update(list(inputs), list(annots), sgd, losses=losses)
<ide> scores = nlp.evaluate(dev_examples)
<del> report_scores(i, loss, scores)
<del> nlp.average_weights()
<add> report_scores(i, losses['ner'], scores)
<ide> scores = nlp.evaluate(dev_examples)
<ide> report_scores(channels, i+1, loss, scores)
<ide>
<ide> def read_examples(path):
<ide> with path.open() as file_:
<ide> sents = file_.read().strip().split('\n\n')
<ide> for sent in sents:
<del> if not sent.strip():
<add> sent = sent.strip()
<add> if not sent:
<ide> continue
<ide> tokens = sent.split('\n')
<ide> while tokens and tokens[0].startswith('#'):
<ide> def read_examples(path):
<ide> iob = []
<ide> for token in tokens:
<ide> if token.strip():
<del> pieces = token.split()
<add> pieces = token.split('\t')
<ide> words.append(pieces[1])
<ide> iob.append(pieces[2])
<ide> yield words, iob_to_biluo(iob)
<ide>
<ide>
<add>def get_labels(examples):
<add> labels = set()
<add> for words, tags in examples:
<add> for tag in tags:
<add> if '-' in tag:
<add> labels.add(tag.split('-')[1])
<add> return sorted(labels)
<add>
<add>
<ide> @plac.annotations(
<ide> model_dir=("Path to save the model", "positional", None, Path),
<ide> train_loc=("Path to your training data", "positional", None, Path),
<ide> dev_loc=("Path to your development data", "positional", None, Path),
<ide> )
<del>def main(model_dir=Path('/home/matt/repos/spaCy/spacy/data/de-1.0.0'),
<del> train_loc=None, dev_loc=None, nr_epoch=30):
<del>
<del> train_examples = read_examples(train_loc)
<add>def main(model_dir, train_loc, dev_loc, nr_epoch=30):
<add> print(model_dir, train_loc, dev_loc)
<add> train_examples = list(read_examples(train_loc))
<ide> dev_examples = read_examples(dev_loc)
<del> nlp = Pipeline.load(model_dir)
<add> nlp = Pipeline()
<add> for label in get_labels(train_examples):
<add> nlp.entity.add_label(label)
<add> print("Add label", label)
<ide>
<del> train(nlp, train_examples, list(dev_examples), ctx, nr_epoch)
<add> train(nlp, train_examples, list(dev_examples), nr_epoch)
<ide>
<del> nlp.save(model_dir)
<add> nlp.to_disk(model_dir)
<ide>
<ide>
<ide> if __name__ == '__main__':
<del> main()
<add> plac.call(main) | 1 |
Ruby | Ruby | use the reflection name instead of the accessor | d300256ca4dd8b6f921afe8ef2de05d7e9c084e7 | <ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> def self.define_callbacks(model, reflection)
<ide> # Post.first.comments and Post.first.comments= methods are defined by this method...
<ide> def define_accessors(model, reflection)
<ide> mixin = model.generated_feature_methods
<add> name = reflection.name
<ide> self.class.define_readers(mixin, name)
<ide> self.class.define_writers(mixin, name)
<ide> end
<ide><path>activerecord/lib/active_record/associations/builder/singular_association.rb
<ide> def valid_options
<ide>
<ide> def define_accessors(model, reflection)
<ide> super
<del> self.class.define_constructors(model.generated_feature_methods, name) if reflection.constructable?
<add> self.class.define_constructors(model.generated_feature_methods, reflection.name) if reflection.constructable?
<ide> end
<ide>
<ide> # Defines the (build|create)_association methods for belongs_to or has_one association | 2 |
PHP | PHP | move null casting tests to main model tests file | 11813cc991ae4871afdd08ee8b4e864740a230f0 | <ide><path>tests/Database/DatabaseEloquentCastingSupportsNullableTest.php
<del><?php
<del>
<del>use Illuminate\Database\Eloquent\Model;
<del>
<del>class DatabaseEloquentCastingSupportsNullableTest extends PHPUnit_Framework_TestCase {
<del>
<del> public function testCastingStringToInteger()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('integer', $model->getAttribute('string_to_integer_field'));
<del> }
<del>
<del>
<del> public function testCastingStringToFloat()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('float', $model->getAttribute('string_to_float_field'));
<del> }
<del>
<del>
<del> public function testCastingStringToBoolean()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('boolean', $model->getAttribute('string_to_boolean_field'));
<del> }
<del>
<del>
<del> public function testCastingStringToArray()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('array', $model->getAttribute('json_string_to_array_field'));
<del> }
<del>
<del>
<del> public function testCastIntegerToString()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('string', $model->getAttribute('integer_to_string_field'));
<del> }
<del>
<del>
<del> public function testCastIntegerToBoolean()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('boolean', $model->getAttribute('integer_to_boolean_field'));
<del> }
<del>
<del>
<del> public function testCastFloatToString()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('string', $model->getAttribute('float_to_string_field'));
<del> }
<del>
<del>
<del> public function testCastNullableToString()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('null', $model->getAttribute('nullable_to_string'));
<del> }
<del>
<del>
<del> public function testCastNullableToInteger()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('null', $model->getAttribute('nullable_to_integer'));
<del> }
<del>
<del>
<del> public function testCastNullableToFloat()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('null', $model->getAttribute('nullable_to_float'));
<del> }
<del>
<del>
<del> public function testCastNullableToBoolean()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('null', $model->getAttribute('nullable_to_boolean'));
<del> }
<del>
<del>
<del> public function testCastNullableToArray()
<del> {
<del> $model = new EloquentModelCastingNullableStub();
<del>
<del> $this->assertInternalType('null', $model->getAttribute('nullable_to_array'));
<del> }
<del>
<del>}
<del>
<del>
<del>class EloquentModelCastingNullableStub extends Model {
<del>
<del> protected $table = 'stub';
<del>
<del> protected $guarded = array();
<del>
<del> protected $attributes = array(
<del> 'string_to_integer_field' => '1',
<del> 'string_to_float_field' => '1.0',
<del> 'string_to_boolean_field' => '1',
<del> 'json_string_to_array_field' => '{"foo": "bar"}',
<del> 'integer_to_string_field' => 1,
<del> 'integer_to_boolean_field' => 1,
<del> 'float_to_string_field' => 1.2,
<del> 'nullable_to_string' => null,
<del> 'nullable_to_integer' => null,
<del> 'nullable_to_float' => null,
<del> 'nullable_to_boolean' => null,
<del> 'nullable_to_array' => null,
<del> );
<del>
<del> protected $casts = array(
<del> 'string_to_integer_field' => 'integer',
<del> 'string_to_float_field' => 'float',
<del> 'string_to_boolean_field' => 'boolean',
<del> 'json_string_to_array_field' => 'array',
<del> 'integer_to_string_field' => 'string',
<del> 'integer_to_boolean_field' => 'boolean',
<del> 'float_to_string_field' => 'string',
<del> 'nullable_to_string' => 'string',
<del> 'nullable_to_integer' => 'integer',
<del> 'nullable_to_float' => 'float',
<del> 'nullable_to_boolean' => 'boolean',
<del> 'nullable_to_array' => 'array',
<del> );
<del>
<del>}
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testModelAttributesAreCastedWhenPresentInCastsArray()
<ide> }
<ide>
<ide>
<add> public function testModelAttributeCastingPreservesNull()
<add> {
<add> $model = new EloquentModelCastingStub;
<add> $model->first = null;
<add> $model->second = null;
<add> $model->third = null;
<add> $model->fourth = null;
<add> $model->fifth = null;
<add> $model->sixth = null;
<add> $model->seventh = null;
<add> $model->eighth = null;
<add>
<add> $this->assertNull($model->first);
<add> $this->assertNull($model->second);
<add> $this->assertNull($model->third);
<add> $this->assertNull($model->fourth);
<add> $this->assertNull($model->fifth);
<add> $this->assertNull($model->sixth);
<add> $this->assertNull($model->seventh);
<add> $this->assertNull($model->eighth);
<add>
<add> $array = $model->toArray();
<add>
<add> $this->assertNull($array['first']);
<add> $this->assertNull($array['second']);
<add> $this->assertNull($array['third']);
<add> $this->assertNull($array['fourth']);
<add> $this->assertNull($array['fifth']);
<add> $this->assertNull($array['sixth']);
<add> $this->assertNull($array['seventh']);
<add> $this->assertNull($array['eighth']);
<add> }
<add>
<add>
<ide> protected function addMockConnection($model)
<ide> {
<ide> $model->setConnectionResolver($resolver = m::mock('Illuminate\Database\ConnectionResolverInterface')); | 2 |
Ruby | Ruby | create variable only in the test that uses it | af31cf067242757b2005197b10a2dfbe6bb89184 | <ide><path>actionpack/test/template/form_helper_test.rb
<ide> def @post.to_param; '123'; end
<ide> @post.tags = []
<ide> @post.tags << Tag.new
<ide>
<del> @blog_post = Blog::Post.new("And his name will be forty and four.", 44)
<del>
<ide> @car = Car.new("#000FFF")
<ide> end
<ide>
<ide> def test_form_for_with_format
<ide> end
<ide>
<ide> def test_form_for_with_model_using_relative_model_naming
<del> form_for(@blog_post) do |f|
<add> blog_post = Blog::Post.new("And his name will be forty and four.", 44)
<add>
<add> form_for(blog_post) do |f|
<ide> concat f.text_field :title
<ide> concat f.submit('Edit post')
<ide> end | 1 |
Javascript | Javascript | add a few querystring benchmarks | 35ed79932c0d5adccb80ff7e734da41691a3cd00 | <ide><path>benchmark/querystring/querystring-parse.js
<add>var common = require('../common.js');
<add>var querystring = require('querystring');
<add>var v8 = require('v8');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['noencode', 'encodemany', 'encodelast'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var type = conf.type;
<add> var n = conf.n | 0;
<add>
<add> var inputs = {
<add> noencode: 'foo=bar&baz=quux&xyzzy=thud',
<add> encodemany: '%66%6F%6F=bar&%62%61%7A=quux&xyzzy=%74h%75d',
<add> encodelast: 'foo=bar&baz=quux&xyzzy=thu%64'
<add> };
<add> var input = inputs[type];
<add>
<add> // Force-optimize querystring.parse() so that the benchmark doesn't get
<add> // disrupted by the optimizer kicking in halfway through.
<add> for (var name in inputs)
<add> querystring.parse(inputs[name]);
<add>
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(querystring.parse)');
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i += 1)
<add> querystring.parse(input);
<add> bench.end(n);
<add>}
<ide><path>benchmark/querystring/querystring-stringify.js
<add>var common = require('../common.js');
<add>var querystring = require('querystring');
<add>var v8 = require('v8');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['noencode', 'encodemany', 'encodelast'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var type = conf.type;
<add> var n = conf.n | 0;
<add>
<add> var inputs = {
<add> noencode: {
<add> foo: 'bar',
<add> baz: 'quux',
<add> xyzzy: 'thud'
<add> },
<add> encodemany: {
<add> '\u0080\u0083\u0089': 'bar',
<add> '\u008C\u008E\u0099': 'quux',
<add> xyzzy: '\u00A5q\u00A3r'
<add> },
<add> encodelast: {
<add> foo: 'bar',
<add> baz: 'quux',
<add> xyzzy: 'thu\u00AC'
<add> }
<add> };
<add> var input = inputs[type];
<add>
<add> // Force-optimize querystring.stringify() so that the benchmark doesn't get
<add> // disrupted by the optimizer kicking in halfway through.
<add> for (var name in inputs)
<add> querystring.stringify(inputs[name]);
<add>
<add> v8.setFlagsFromString('--allow_natives_syntax');
<add> eval('%OptimizeFunctionOnNextCall(querystring.stringify)');
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i += 1)
<add> querystring.stringify(input);
<add> bench.end(n);
<add>} | 2 |
Ruby | Ruby | improve docs for ar relation | 2c050e1808b996e6a0ff2e26981087d8c080fc48 | <ide><path>activerecord/lib/active_record/relation.rb
<ide> def explain
<ide> exec_explain(queries)
<ide> end
<ide>
<add> # Converts relation objects to Array.
<ide> def to_a
<ide> # We monitor here the entire execution rather than individual SELECTs
<ide> # because from the point of view of the user fetching the records of a
<ide> def empty?
<ide> c.respond_to?(:zero?) ? c.zero? : c.empty?
<ide> end
<ide>
<add> # Returns true if there are any records.
<ide> def any?
<ide> if block_given?
<ide> to_a.any? { |*block_args| yield(*block_args) }
<ide> def any?
<ide> end
<ide> end
<ide>
<add> # Returns true if there are more than one records.
<ide> def many?
<ide> if block_given?
<ide> to_a.many? { |*block_args| yield(*block_args) }
<ide> def scoping
<ide> # ==== Parameters
<ide> #
<ide> # * +updates+ - A string, array, or hash representing the SET part of an SQL statement.
<del> # * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement.
<del> # See conditions in the intro.
<del> # * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage.
<ide> #
<ide> # ==== Examples
<ide> #
<ide> # # Update all customers with the given attributes
<del> # Customer.update_all :wants_email => true
<add> # Customer.update_all wants_email: true
<ide> #
<ide> # # Update all books with 'Rails' in their title
<del> # Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David')
<add> # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
<ide> #
<ide> # # Update all books that match conditions, but limit it to 5 ordered by date
<ide> # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
<ide> def update_all(updates)
<ide> # ==== Examples
<ide> #
<ide> # # Updates one record
<del> # Person.update(15, :user_name => 'Samuel', :group => 'expert')
<add> # Person.update(15, user_name: 'Samuel', group: 'expert')
<ide> #
<ide> # # Updates multiple records
<ide> # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
<ide> def update(id, attributes)
<ide> # ==== Examples
<ide> #
<ide> # Person.destroy_all("last_login < '2004-04-04'")
<del> # Person.destroy_all(:status => "inactive")
<add> # Person.destroy_all(status: "inactive")
<ide> # Person.where(:age => 0..18).destroy_all
<ide> def destroy_all(conditions = nil)
<ide> if conditions
<ide> def delete(id_or_array)
<ide> where(primary_key => id_or_array).delete_all
<ide> end
<ide>
<add> # Forces reloading of relation.
<ide> def reload
<ide> reset
<ide> to_a # force reload
<ide> def reset
<ide> self
<ide> end
<ide>
<add> # Returns sql statement for the relation.
<add> #
<add> # Users.where(name: 'Oscar').to_sql
<add> # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar'
<ide> def to_sql
<ide> @to_sql ||= klass.connection.to_sql(arel, bind_values.dup)
<ide> end
<ide>
<add> # Returns an hash of where conditions
<add> #
<add> # Users.where(name: 'Oscar').to_sql
<add> # # => {:name=>"oscar"}
<ide> def where_values_hash
<ide> equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
<ide> node.left.relation.name == table_name
<ide> def scope_for_create
<ide> @scope_for_create ||= where_values_hash.merge(create_with_value)
<ide> end
<ide>
<add> # Returns true if relation needs eager loading.
<ide> def eager_loading?
<ide> @should_eager_load ||=
<ide> eager_load_values.any? ||
<ide> def joined_includes_values
<ide> includes_values & joins_values
<ide> end
<ide>
<add> # Compares two relations for equality.
<ide> def ==(other)
<ide> case other
<ide> when Relation
<ide> def with_default_scope #:nodoc:
<ide> end
<ide> end
<ide>
<add> # Returns true if relation is blank>
<ide> def blank?
<ide> to_a.blank?
<ide> end | 1 |
PHP | PHP | apply fixes from styleci | fb8d38c41cd68bafc2b34ade348935e7380bf958 | <ide><path>src/Illuminate/Collections/Enumerable.php
<ide> public function whereNotInStrict($key, $values);
<ide> * Filter the items, removing any items that don't match the given type(s).
<ide> *
<ide> * @template TWhereInstanceOf
<add> *
<ide> * @param class-string<TWhereInstanceOf>|array<array-key, class-string<TWhereInstanceOf>> $type
<ide> * @return static<TKey, TWhereInstanceOf>
<ide> */
<ide><path>src/Illuminate/Collections/Traits/EnumeratesValues.php
<ide> public function whereNotInStrict($key, $values)
<ide> * Filter the items, removing any items that don't match the given type(s).
<ide> *
<ide> * @template TWhereInstanceOf
<add> *
<ide> * @param class-string<TWhereInstanceOf>|array<array-key, class-string<TWhereInstanceOf>> $type
<ide> * @return static<TKey, TWhereInstanceOf>
<ide> */ | 2 |
Javascript | Javascript | add first pass at shader | 2131b112e74e04c764b5a6960b4a5760b4fb49bc | <ide><path>examples/js/loaders/LDrawLoader.js
<ide>
<ide> THREE.LDrawLoader = ( function () {
<ide>
<add> var optionalLineVertShader = /* glsl */`
<add> attribute vec3 optionalControl0;
<add> attribute vec3 optionalControl1;
<add> attribute vec3 point0;
<add> attribute vec3 point1;
<add>
<add> varying vec4 controlOut0;
<add> varying vec4 controlOut1;
<add> varying vec4 pointOut0;
<add> varying vec4 pointOut1;
<add> #include <common>
<add> #include <color_pars_vertex>
<add> #include <fog_pars_vertex>
<add> #include <logdepthbuf_pars_vertex>
<add> #include <clipping_planes_pars_vertex>
<add> void main() {
<add> #include <color_vertex>
<add> vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
<add> gl_Position = projectionMatrix * mvPosition;
<add>
<add> controlOut0 = projectionMatrix * modelViewMatrix * vec4( optionalControl0, 1.0 );
<add> controlOut1 = projectionMatrix * modelViewMatrix * vec4( optionalControl1, 1.0 );
<add> pointOut0 = projectionMatrix * modelViewMatrix * vec4( point0, 1.0 );
<add> pointOut1 = projectionMatrix * modelViewMatrix * vec4( point1, 1.0 );
<add>
<add> #include <logdepthbuf_vertex>
<add> #include <clipping_planes_vertex>
<add> #include <fog_vertex>
<add> }
<add> `;
<add>
<add> var optionalLineFragShader = /* glsl */`
<add> uniform vec3 diffuse;
<add> uniform float opacity;
<add> varying vec4 controlOut0;
<add> varying vec4 controlOut1;
<add> varying vec4 pointOut0;
<add> varying vec4 pointOut1;
<add>
<add> #include <common>
<add> #include <color_pars_fragment>
<add> #include <fog_pars_fragment>
<add> #include <logdepthbuf_pars_fragment>
<add> #include <clipping_planes_pars_fragment>
<add> void main() {
<add>
<add> vec2 c0 = controlOut0.xy / controlOut0.w;
<add> vec2 c1 = controlOut1.xy / controlOut1.w;
<add> vec2 p0 = pointOut0.xy / pointOut0.w;
<add> vec2 p1 = pointOut1.xy / pointOut1.w;
<add> vec2 dir = p1 - p0;
<add> vec2 norm = vec2( -dir.y, dir.x );
<add>
<add> vec2 c0dir = c0 - p1;
<add> vec2 c1dir = c1 - p1;
<add>
<add> float d0 = dot( normalize( norm ), normalize( c0dir ) );
<add> float d1 = dot( normalize( norm ), normalize( c1dir ) );
<add>
<add> if ( sign( d0 ) != sign( d1 ) ) discard;
<add>
<add> #include <clipping_planes_fragment>
<add> vec3 outgoingLight = vec3( 0.0 );
<add> vec4 diffuseColor = vec4( diffuse, opacity );
<add> #include <logdepthbuf_fragment>
<add> #include <color_fragment>
<add> outgoingLight = diffuseColor.rgb; // simple shader
<add> gl_FragColor = vec4( outgoingLight, diffuseColor.a );
<add> #include <premultiplied_alpha_fragment>
<add> #include <tonemapping_fragment>
<add> #include <encodings_fragment>
<add> #include <fog_fragment>
<add> }
<add> `;
<add>
<add>
<add>
<ide> var tempVec0 = new THREE.Vector3();
<ide> var tempVec1 = new THREE.Vector3();
<ide> function smoothNormals( triangles, lineSegments ) {
<ide> THREE.LDrawLoader = ( function () {
<ide>
<ide> if ( parseScope.conditionalSegments.length > 0 ) {
<ide>
<del> var lines = createObject( parseScope.conditionalSegments, 2 );
<add> var conditionalSegments = parseScope.conditionalSegments;
<add> var lines = createObject( conditionalSegments, 2 );
<ide> lines.isConditionalLine = true;
<ide> lines.visible = false;
<add>
<add> var controlArray0 = new Float32Array( conditionalSegments.length * 3 * 2 );
<add> var controlArray1 = new Float32Array( conditionalSegments.length * 3 * 2 );
<add> var pointArray0 = new Float32Array( conditionalSegments.length * 3 * 2 );
<add> var pointArray1 = new Float32Array( conditionalSegments.length * 3 * 2 );
<add> for ( var i = 0, l = conditionalSegments.length; i < l; i ++ ) {
<add>
<add> var os = conditionalSegments[ i ];
<add> var c0 = os.c0;
<add> var c1 = os.c1;
<add> var v0 = os.v0;
<add> var v1 = os.v1;
<add> var index = i * 3 * 2;
<add> controlArray0[ index + 0 ] = c0.x;
<add> controlArray0[ index + 1 ] = c0.y;
<add> controlArray0[ index + 2 ] = c0.z;
<add> controlArray0[ index + 3 ] = c0.x;
<add> controlArray0[ index + 4 ] = c0.y;
<add> controlArray0[ index + 5 ] = c0.z;
<add>
<add> controlArray1[ index + 0 ] = c1.x;
<add> controlArray1[ index + 1 ] = c1.y;
<add> controlArray1[ index + 2 ] = c1.z;
<add> controlArray1[ index + 3 ] = c1.x;
<add> controlArray1[ index + 4 ] = c1.y;
<add> controlArray1[ index + 5 ] = c1.z;
<add>
<add> pointArray0[ index + 0 ] = v0.x;
<add> pointArray0[ index + 1 ] = v0.y;
<add> pointArray0[ index + 2 ] = v0.z;
<add> pointArray0[ index + 3 ] = v0.x;
<add> pointArray0[ index + 4 ] = v0.y;
<add> pointArray0[ index + 5 ] = v0.z;
<add>
<add> pointArray1[ index + 0 ] = v1.x;
<add> pointArray1[ index + 1 ] = v1.y;
<add> pointArray1[ index + 2 ] = v1.z;
<add> pointArray1[ index + 3 ] = v1.x;
<add> pointArray1[ index + 4 ] = v1.y;
<add> pointArray1[ index + 5 ] = v1.z;
<add>
<add> }
<add>
<add> lines.geometry.addAttribute( 'optionalControl0', new THREE.BufferAttribute( controlArray0, 3, false ) );
<add> lines.geometry.addAttribute( 'optionalControl1', new THREE.BufferAttribute( controlArray1, 3, false ) );
<add> lines.geometry.addAttribute( 'point0', new THREE.BufferAttribute( pointArray0, 3, false ) );
<add> lines.geometry.addAttribute( 'point1', new THREE.BufferAttribute( pointArray1, 3, false ) );
<add>
<add> lines.material = lines.material.map( mat => {
<add>
<add> return new THREE.ShaderMaterial( {
<add> vertexShader: optionalLineVertShader,
<add> fragmentShader: optionalLineFragShader,
<add> uniforms: {
<add> diffuse: {
<add> value: mat.color
<add> },
<add> opacity: {
<add> value: mat.opacity
<add> }
<add> }
<add> } );
<add>
<add> } );
<add>
<add>
<ide> objGroup.add( lines );
<ide>
<ide> }
<ide> THREE.LDrawLoader = ( function () {
<ide>
<ide> os.v0.applyMatrix4( parseScope.matrix );
<ide> os.v1.applyMatrix4( parseScope.matrix );
<add> os.c0.applyMatrix4( parseScope.matrix );
<add> os.c1.applyMatrix4( parseScope.matrix );
<ide>
<ide> }
<ide> parentConditionalSegments.push( os );
<ide> THREE.LDrawLoader = ( function () {
<ide> var material = parseColourCode( lp, true );
<ide> var arr = lineType === '2' ? lineSegments : conditionalSegments;
<ide>
<del> arr.push( {
<add> var segment = {
<ide> material: material.userData.edgeMaterial,
<ide> colourCode: material.userData.code,
<ide> v0: parseVector( lp ),
<ide> v1: parseVector( lp )
<del> } );
<add> };
<add>
<add> if ( lineType === '5' ) {
<add>
<add> segment.c0 = parseVector( lp );
<add> segment.c1 = parseVector( lp );
<add>
<add> }
<add>
<add> arr.push( segment );
<ide>
<ide> break;
<ide> | 1 |
Python | Python | add param_name to size_dict logs & tidy | 55ba31908a1216c1767463e3333aa94a6414e6d6 | <ide><path>src/transformers/image_processing_utils.py
<ide> def preprocess(self, images, **kwargs) -> BatchFeature:
<ide> raise NotImplementedError("Each image processor must implement its own preprocess method")
<ide>
<ide>
<add>VALID_SIZE_DICT_KEYS = ({"height", "width"}, {"shortest_edge"}, {"shortest_edge", "longest_edge"})
<add>
<add>
<add>def is_valid_size_dict(size_dict):
<add> if not isinstance(size_dict, dict):
<add> return False
<add>
<add> size_dict_keys = set(size_dict.keys())
<add> for allowed_keys in VALID_SIZE_DICT_KEYS:
<add> if size_dict_keys == allowed_keys:
<add> return True
<add> return False
<add>
<add>
<add>def convert_to_size_dict(
<add> size, max_size: Optional[int] = None, default_to_square: bool = True, height_width_order: bool = True
<add>):
<add> # By default, if size is an int we assume it represents a tuple of (size, size).
<add> if isinstance(size, int) and default_to_square:
<add> if max_size is not None:
<add> raise ValueError("Cannot specify both size as an int, with default_to_square=True and max_size")
<add> return {"height": size, "width": size}
<add> # In other configs, if size is an int and default_to_square is False, size represents the length of
<add> # the shortest edge after resizing.
<add> elif isinstance(size, int) and not default_to_square:
<add> size_dict = {"shortest_edge": size}
<add> if max_size is not None:
<add> size_dict["longest_edge"] = max_size
<add> return size_dict
<add> # Otherwise, if size is a tuple it's either (height, width) or (width, height)
<add> elif isinstance(size, (tuple, list)) and height_width_order:
<add> return {"height": size[0], "width": size[1]}
<add> elif isinstance(size, (tuple, list)) and not height_width_order:
<add> return {"height": size[1], "width": size[0]}
<add>
<add> raise ValueError(f"Could not convert size input to size dict: {size}")
<add>
<add>
<ide> def get_size_dict(
<ide> size: Union[int, Iterable[int], Dict[str, int]] = None,
<ide> max_size: Optional[int] = None,
<ide> height_width_order: bool = True,
<ide> default_to_square: bool = True,
<add> param_name="size",
<ide> ) -> dict:
<ide> """
<ide> Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards
<ide> def get_size_dict(
<ide> default_to_square (`bool`, *optional*, defaults to `True`):
<ide> If `size` is an int, whether to default to a square image or not.
<ide> """
<del> # If a dict is passed, we check if it's a valid size dict and then return it.
<del> if isinstance(size, dict):
<del> size_keys = set(size.keys())
<del> if (
<del> size_keys != set(["height", "width"])
<del> and size_keys != set(["shortest_edge"])
<del> and size_keys != set(["shortest_edge", "longest_edge"])
<del> ):
<del> raise ValueError(
<del> "The size dict must contain either the keys ('height', 'width') or ('shortest_edge')"
<del> f"or ('shortest_edge', 'longest_edge') but got {size_keys}"
<del> )
<del> return size
<del>
<del> # By default, if size is an int we assume it represents a tuple of (size, size).
<del> elif isinstance(size, int) and default_to_square:
<del> if max_size is not None:
<del> raise ValueError("Cannot specify both size as an int, with default_to_square=True and max_size")
<del> size_dict = {"height": size, "width": size}
<del> # In other configs, if size is an int and default_to_square is False, size represents the length of the shortest edge after resizing.
<del> elif isinstance(size, int) and not default_to_square:
<del> if max_size is not None:
<del> size_dict = {"shortest_edge": size, "longest_edge": max_size}
<del> else:
<del> size_dict = {"shortest_edge": size}
<del> elif isinstance(size, (tuple, list)) and height_width_order:
<del> size_dict = {"height": size[0], "width": size[1]}
<del> elif isinstance(size, (tuple, list)) and not height_width_order:
<del> size_dict = {"height": size[1], "width": size[0]}
<add> if not isinstance(size, dict):
<add> size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)
<add> logger.info(
<add> "{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}."
<add> " Converted to {size_dict}.",
<add> )
<add> else:
<add> size_dict = size
<ide>
<del> logger.info(
<del> "The size parameter should be a dictionary with keys ('height', 'width'), ('shortest_edge', 'longest_edge')"
<del> f" or ('shortest_edge',) got {size}. Setting as {size_dict}.",
<del> )
<add> if not is_valid_size_dict(size_dict):
<add> raise ValueError(
<add> f"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}"
<add> )
<ide> return size_dict
<ide>
<ide>
<ide><path>src/transformers/models/beit/image_processing_beit.py
<ide> def __init__(
<ide> size = size if size is not None else {"height": 256, "width": 256}
<ide> size = get_size_dict(size)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> self.resample = resample
<ide> def resize(
<ide> data_format (`str` or `ChannelDimension`, *optional*):
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<del> size = get_size_dict(size)
<add> size = get_size_dict(size, default_to_square=True, param_name="size")
<ide> if "height" not in size or "width" not in size:
<ide> raise ValueError(f"The `size` argument must contain `height` and `width` keys. Got {size.keys()}")
<ide> return resize(
<ide> def center_crop(
<ide> data_format (`str` or `ChannelDimension`, *optional*):
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<del> size = get_size_dict(size)
<add> size = get_size_dict(size, default_to_square=True, param_name="size")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> """
<ide> do_resize = do_resize if do_resize is not None else self.do_resize
<ide> size = size if size is not None else self.size
<del> size = get_size_dict(size)
<add> size = get_size_dict(size, default_to_square=True, param_name="size")
<ide> resample = resample if resample is not None else self.resample
<ide> do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
<ide> do_rescale = do_rescale if do_rescale is not None else self.do_rescale
<ide> rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
<ide> do_normalize = do_normalize if do_normalize is not None else self.do_normalize
<ide><path>src/transformers/models/clip/image_processing_clip.py
<ide> def __init__(
<ide> size = size if size is not None else {"shortest_edge": 224}
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> """
<ide> do_resize = do_resize if do_resize is not None else self.do_resize
<ide> size = size if size is not None else self.size
<del> size = get_size_dict(size, default_to_square=False)
<add> size = get_size_dict(size, param_name="size", default_to_square=False)
<ide> resample = resample if resample is not None else self.resample
<ide> do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
<ide> do_rescale = do_rescale if do_rescale is not None else self.do_rescale
<ide> rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
<ide> do_normalize = do_normalize if do_normalize is not None else self.do_normalize
<ide><path>src/transformers/models/deit/image_processing_deit.py
<ide> def __init__(
<ide> size = size if size is not None else {"height": 256, "width": 256}
<ide> size = get_size_dict(size)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> size = size if size is not None else self.size
<ide> size = get_size_dict(size)
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> if not is_batched(images):
<ide> images = [images]
<ide><path>src/transformers/models/flava/image_processing_flava.py
<ide> def __init__(
<ide> size = size if size is not None else {"height": 224, "width": 224}
<ide> size = get_size_dict(size)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> codebook_size = codebook_size if codebook_size is not None else {"height": 112, "width": 112}
<del> codebook_size = get_size_dict(codebook_size)
<add> codebook_size = get_size_dict(codebook_size, param_name="codebook_size")
<ide> codebook_crop_size = codebook_crop_size if codebook_crop_size is not None else {"height": 112, "width": 112}
<del> codebook_crop_size = get_size_dict(codebook_crop_size)
<add> codebook_crop_size = get_size_dict(codebook_crop_size, param_name="codebook_crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"The size dictionary must contain 'height' and 'width' keys. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> resample = resample if resample is not None else self.resample
<ide> do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide> do_rescale = do_rescale if do_rescale is not None else self.do_rescale
<ide> rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
<ide> do_normalize = do_normalize if do_normalize is not None else self.do_normalize
<ide> def preprocess(
<ide> )
<ide> codebook_do_resize = codebook_do_resize if codebook_do_resize is not None else self.codebook_do_resize
<ide> codebook_size = codebook_size if codebook_size is not None else self.codebook_size
<del> codebook_size = get_size_dict(codebook_size)
<add> codebook_size = get_size_dict(codebook_size, param_name="codebook_size")
<ide> codebook_resample = codebook_resample if codebook_resample is not None else self.codebook_resample
<ide> codebook_do_rescale = codebook_do_rescale if codebook_do_rescale is not None else self.codebook_do_rescale
<ide> codebook_rescale_factor = (
<ide> def preprocess(
<ide> codebook_do_center_crop if codebook_do_center_crop is not None else self.codebook_do_center_crop
<ide> )
<ide> codebook_crop_size = codebook_crop_size if codebook_crop_size is not None else self.codebook_crop_size
<del> codebook_crop_size = get_size_dict(codebook_crop_size)
<add> codebook_crop_size = get_size_dict(codebook_crop_size, param_name="codebook_crop_size")
<ide> codebook_do_map_pixels = (
<ide> codebook_do_map_pixels if codebook_do_map_pixels is not None else self.codebook_do_map_pixels
<ide> )
<ide><path>src/transformers/models/levit/image_processing_levit.py
<ide> def __init__(
<ide> size = size if size is not None else {"shortest_edge": 224}
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"Size dict must have keys 'height' and 'width'. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> size = size if size is not None else self.size
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> if not is_batched(images):
<ide> images = [images]
<ide><path>src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py
<ide> def __init__(
<ide> size = size if size is not None else {"shortest_edge": 256}
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> self.resample = resample
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> resample = resample if resample is not None else self.resample
<ide> do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide> do_rescale = do_rescale if do_rescale is not None else self.do_rescale
<ide> rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
<ide> do_normalize = do_normalize if do_normalize is not None else self.do_normalize
<ide><path>src/transformers/models/mobilevit/image_processing_mobilevit.py
<ide> def __init__(
<ide> size = size if size is not None else {"shortest_edge": 224}
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else {"height": 256, "width": 256}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> size = size if size is not None else self.size
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> if not is_batched(images):
<ide> images = [images]
<ide><path>src/transformers/models/perceiver/image_processing_perceiver.py
<ide> def __init__(
<ide> ) -> None:
<ide> super().__init__(**kwargs)
<ide> crop_size = crop_size if crop_size is not None else {"height": 256, "width": 256}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide> size = size if size is not None else {"height": 224, "width": 224}
<ide> size = get_size_dict(size)
<ide>
<ide> def center_crop(
<ide> """
<ide> size = self.size if size is None else size
<ide> size = get_size_dict(size)
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> height, width = get_image_size(image)
<ide> min_dim = min(height, width)
<ide> def preprocess(
<ide> """
<ide> do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide> do_resize = do_resize if do_resize is not None else self.do_resize
<ide> size = size if size is not None else self.size
<ide> size = get_size_dict(size)
<ide><path>src/transformers/models/poolformer/image_processing_poolformer.py
<ide> def __init__(
<ide> size = size if size is not None else {"shortest_edge": 224}
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"size must contain 'height' and 'width' as keys. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> size = size if size is not None else self.size
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> if not is_batched(images):
<ide> images = [images]
<ide><path>src/transformers/models/segformer/image_processing_segformer.py
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide><path>src/transformers/models/videomae/image_processing_videomae.py
<ide> def __init__(
<ide> size = size if size is not None else {"shortest_edge": 224}
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> self.do_resize = do_resize
<ide> self.size = size
<ide> def resize(
<ide> data_format (`str` or `ChannelDimension`, *optional*):
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<del> size = get_size_dict(size)
<add> size = get_size_dict(size, default_to_square=False)
<ide> if "shortest_edge" in size:
<ide> output_size = get_resize_output_image_size(image, size["shortest_edge"], default_to_square=False)
<ide> elif "height" in size and "width" in size:
<ide> def center_crop(
<ide> The channel dimension format of the image. If not provided, it will be the same as the input image.
<ide> """
<ide> size = get_size_dict(size)
<add> if "height" not in size or "width" not in size:
<add> raise ValueError(f"Size must have 'height' and 'width' as keys. Got {size.keys()}")
<ide> return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
<ide>
<ide> def rescale(
<ide> def preprocess(
<ide> size = size if size is not None else self.size
<ide> size = get_size_dict(size, default_to_square=False)
<ide> crop_size = crop_size if crop_size is not None else self.crop_size
<del> crop_size = get_size_dict(crop_size)
<add> crop_size = get_size_dict(crop_size, param_name="crop_size")
<ide>
<ide> if not valid_images(videos):
<ide> raise ValueError( | 12 |
Ruby | Ruby | remove redundant tests method | 77e25a777a074bc77c7aefed914ff3dd5e667ab1 | <ide><path>actionpack/test/controller/send_file_test.rb
<ide> def test_send_file_without_content_disposition_header
<ide> end
<ide> end
<ide>
<del> tests SendFileWithActionControllerLive
<del>
<ide> def test_send_file_with_action_controller_live
<ide> @controller = SendFileWithActionControllerLive.new
<ide> @controller.options = { :content_type => "application/x-ruby" } | 1 |
Java | Java | refine sourcefile record to class conversion | afac8dd8af1ed06e48bb79c5eb334a4d797ba1ae | <ide><path>spring-core-test/src/main/java/org/springframework/core/test/tools/SourceFile.java
<ide> import java.io.InputStreamReader;
<ide> import java.io.StringReader;
<ide> import java.nio.charset.StandardCharsets;
<add>import java.util.regex.Matcher;
<add>import java.util.regex.Pattern;
<ide>
<ide> import com.thoughtworks.qdox.JavaProjectBuilder;
<ide> import com.thoughtworks.qdox.model.JavaClass;
<ide> private static String getClassName(String content) {
<ide> }
<ide>
<ide> private static String makeRecordsLookLikeClasses(String content) {
<del> return content.replaceAll("record\\s(\\S+)\\(\\X+?\\)", "class $1");
<add> Pattern pattern = Pattern.compile("record\\s(\\S+)\\(");
<add> Matcher matcher = pattern.matcher(content);
<add> if (matcher.find()) {
<add> StringBuilder result = new StringBuilder();
<add> result.append(content.substring(0, matcher.start()) + "class");
<add> result.append(content.substring(matcher.start() + 6, matcher.end() - 1));
<add> int parenthesesCount = 1;
<add> for (int i = matcher.end(); i < content.length(); i++) {
<add> char ch = content.charAt(i);
<add> if (parenthesesCount > 0) {
<add> if (ch == '(') {
<add> parenthesesCount++;
<add> }
<add> else if (ch == ')') {
<add> parenthesesCount--;
<add> }
<add> }
<add> else {
<add> result.append(ch);
<add> }
<add> }
<add> return makeRecordsLookLikeClasses(result.toString());
<add> }
<add> return content;
<ide> }
<ide>
<ide> /**
<ide><path>spring-core-test/src/test/java/org/springframework/core/test/tools/SourceFileTests.java
<ide> String getFoo() {
<ide> assertThat(sourceFile.getClassName()).isEqualTo("com.example.helloworld.HelloWorld");
<ide> }
<ide>
<add> @Test
<add> void getClassNameFromAnnotatedRecord() {
<add> SourceFile sourceFile = SourceFile.of("""
<add> package com.example;
<add>
<add> public record RecordProperties(
<add> @org.springframework.boot.context.properties.bind.DefaultValue("default-value-1") String property1,
<add> @org.springframework.boot.context.properties.bind.DefaultValue("default-value-2") String property2) {
<add> }
<add> """);
<add> assertThat(sourceFile.getClassName()).isEqualTo("com.example.RecordProperties");
<add> }
<add>
<ide> /**
<ide> * JavaPoet style API with a {@code writeTo} method.
<ide> */ | 2 |
Python | Python | update gyp to 828ce09 | 96dffb12177570a1311e97df501142e56b606c02 | <ide><path>tools/gyp/pylib/gyp/common.py
<ide> def close(self):
<ide> return Writer()
<ide>
<ide>
<add>def EnsureDirExists(path):
<add> """Make sure the directory for |path| exists."""
<add> try:
<add> os.makedirs(os.path.dirname(path))
<add> except OSError:
<add> pass
<add>
<add>
<ide> def GetFlavor(params):
<ide> """Returns |params.flavor| if it's set, the system's default flavor else."""
<ide> flavors = {
<ide><path>tools/gyp/pylib/gyp/generator/android.py
<ide> def Write(self, qualified_target, relative_target, base_path, output_filename,
<ide> spec, configs: gyp info
<ide> part_of_all: flag indicating this target is part of 'all'
<ide> """
<del> make.ensure_directory_exists(output_filename)
<add> gyp.common.EnsureDirExists(output_filename)
<ide>
<ide> self.fp = open(output_filename, 'w')
<ide>
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> makefile_path = os.path.join(options.toplevel_dir, makefile_name)
<ide> assert not options.generator_output, (
<ide> 'The Android backend does not support options.generator_output.')
<del> make.ensure_directory_exists(makefile_path)
<add> gyp.common.EnsureDirExists(makefile_path)
<ide> root_makefile = open(makefile_path, 'w')
<ide>
<ide> root_makefile.write(header)
<ide><path>tools/gyp/pylib/gyp/generator/cmake.py
<ide> def NormjoinPath(base_path, rel_path):
<ide> return os.path.normpath(os.path.join(base_path, rel_path))
<ide>
<ide>
<del>def EnsureDirectoryExists(path):
<del> """Python version of 'mkdir -p'."""
<del> dirPath = os.path.dirname(path)
<del> if dirPath and not os.path.exists(dirPath):
<del> os.makedirs(dirPath)
<del>
<del>
<ide> def CMakeStringEscape(a):
<ide> """Escapes the string 'a' for use inside a CMake string.
<ide>
<ide> def GenerateOutputForConfig(target_list, target_dicts, data,
<ide> toplevel_build = os.path.join(options.toplevel_dir, build_dir)
<ide>
<ide> output_file = os.path.join(toplevel_build, 'CMakeLists.txt')
<del> EnsureDirectoryExists(output_file)
<add> gyp.common.EnsureDirExists(output_file)
<ide>
<ide> output = open(output_file, 'w')
<ide> output.write('cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR)\n')
<ide><path>tools/gyp/pylib/gyp/generator/eclipse.py
<ide> def GenerateOutputForConfig(target_list, target_dicts, data, params,
<ide> shared_intermediate_dirs = [os.path.join(toplevel_build, 'obj', 'gen'),
<ide> os.path.join(toplevel_build, 'gen')]
<ide>
<del> if not os.path.exists(toplevel_build):
<del> os.makedirs(toplevel_build)
<del> out = open(os.path.join(toplevel_build, 'eclipse-cdt-settings.xml'), 'w')
<add> out_name = os.path.join(toplevel_build, 'eclipse-cdt-settings.xml')
<add> gyp.common.EnsureDirExists(out_name)
<add> out = open(out_name, 'w')
<ide>
<ide> out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
<ide> out.write('<cdtprojectproperties>\n')
<ide><path>tools/gyp/pylib/gyp/generator/make.py
<ide> def CalculateGeneratorInputInfo(params):
<ide> }
<ide>
<ide>
<del>def ensure_directory_exists(path):
<del> dir = os.path.dirname(path)
<del> if dir and not os.path.exists(dir):
<del> os.makedirs(dir)
<del>
<del>
<ide> # The .d checking code below uses these functions:
<ide> # wildcard, sort, foreach, shell, wordlist
<ide> # wildcard can handle spaces, the rest can't.
<ide> def Write(self, qualified_target, base_path, output_filename, spec, configs,
<ide> spec, configs: gyp info
<ide> part_of_all: flag indicating this target is part of 'all'
<ide> """
<del> ensure_directory_exists(output_filename)
<add> gyp.common.EnsureDirExists(output_filename)
<ide>
<ide> self.fp = open(output_filename, 'w')
<ide>
<ide> def WriteSubMake(self, output_filename, makefile_path, targets, build_dir):
<ide> targets: list of "all" targets for this sub-project
<ide> build_dir: build output directory, relative to the sub-project
<ide> """
<del> ensure_directory_exists(output_filename)
<add> gyp.common.EnsureDirExists(output_filename)
<ide> self.fp = open(output_filename, 'w')
<ide> self.fp.write(header)
<ide> # For consistency with other builders, put sub-project build output in the
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> make_global_settings += (
<ide> 'ifneq (,$(filter $(origin %s), undefined default))\n' % key)
<ide> # Let gyp-time envvars win over global settings.
<del> if key in os.environ:
<del> value = os.environ[key]
<add> env_key = key.replace('.', '_') # CC.host -> CC_host
<add> if env_key in os.environ:
<add> value = os.environ[env_key]
<ide> make_global_settings += ' %s = %s\n' % (key, value)
<ide> make_global_settings += 'endif\n'
<ide> else:
<ide> def CalculateMakefilePath(build_file, base_name):
<ide>
<ide> header_params['make_global_settings'] = make_global_settings
<ide>
<del> ensure_directory_exists(makefile_path)
<add> gyp.common.EnsureDirExists(makefile_path)
<ide> root_makefile = open(makefile_path, 'w')
<ide> root_makefile.write(SHARED_HEADER % header_params)
<ide> # Currently any versions have the same effect, but in future the behavior
<ide><path>tools/gyp/pylib/gyp/generator/msvs.py
<ide> import gyp.MSVSVersion as MSVSVersion
<ide> from gyp.common import GypError
<ide>
<add># TODO: Remove once bots are on 2.7, http://crbug.com/241769
<add>def _import_OrderedDict():
<add> import collections
<add> try:
<add> return collections.OrderedDict
<add> except AttributeError:
<add> import gyp.ordered_dict
<add> return gyp.ordered_dict.OrderedDict
<add>OrderedDict = _import_OrderedDict()
<add>
<ide>
<ide> # Regular expression for validating Visual Studio GUIDs. If the GUID
<ide> # contains lowercase hex letters, MSVS will be fine. However,
<ide> def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
<ide> if not prefix: prefix = []
<ide> result = []
<ide> excluded_result = []
<del> folders = collections.OrderedDict()
<ide> # Gather files into the final result, excluded, or folders.
<ide> for s in sources:
<ide> if len(s) == 1:
<ide> def _ConvertSourcesToFilterHierarchy(sources, prefix=None, excluded=None,
<ide> else:
<ide> result.append(filename)
<ide> else:
<del> if not folders.get(s[0]):
<del> folders[s[0]] = []
<del> folders[s[0]].append(s[1:])
<add> contents = _ConvertSourcesToFilterHierarchy([s[1:]], prefix + [s[0]],
<add> excluded=excluded,
<add> list_excluded=list_excluded)
<add> contents = MSVSProject.Filter(s[0], contents=contents)
<add> result.append(contents)
<ide> # Add a folder for excluded files.
<ide> if excluded_result and list_excluded:
<ide> excluded_folder = MSVSProject.Filter('_excluded_files',
<ide> contents=excluded_result)
<ide> result.append(excluded_folder)
<del> # Populate all the folders.
<del> for f in folders:
<del> contents = _ConvertSourcesToFilterHierarchy(folders[f], prefix=prefix + [f],
<del> excluded=excluded,
<del> list_excluded=list_excluded)
<del> contents = MSVSProject.Filter(f, contents=contents)
<del> result.append(contents)
<del>
<ide> return result
<ide>
<ide>
<ide> def _GenerateMSVSProject(project, options, version, generator_flags):
<ide> generator_flags: dict of generator-specific flags.
<ide> """
<ide> spec = project.spec
<del> vcproj_dir = os.path.dirname(project.path)
<del> if vcproj_dir and not os.path.exists(vcproj_dir):
<del> os.makedirs(vcproj_dir)
<add> gyp.common.EnsureDirExists(project.path)
<ide>
<ide> platforms = _GetUniquePlatforms(spec)
<ide> p = MSVSProject.Writer(project.path, version, spec['target_name'],
<ide> def _GenerateMSBuildProject(project, options, version, generator_flags):
<ide> spec = project.spec
<ide> configurations = spec['configurations']
<ide> project_dir, project_file_name = os.path.split(project.path)
<del> msbuildproj_dir = os.path.dirname(project.path)
<del> if msbuildproj_dir and not os.path.exists(msbuildproj_dir):
<del> os.makedirs(msbuildproj_dir)
<add> gyp.common.EnsureDirExists(project.path)
<ide> # Prepare list of sources and excluded sources.
<ide> gyp_path = _NormalizedSource(project.build_file)
<ide> relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir)
<ide><path>tools/gyp/pylib/gyp/generator/ninja.py
<ide> def WriteLinkForArch(self, ninja_file, spec, config_name, config,
<ide> elif self.flavor == 'win':
<ide> manifest_name = self.GypPathToUniqueOutput(
<ide> self.ComputeOutputFileName(spec))
<del> ldflags, manifest_files = self.msvs_settings.GetLdflags(config_name,
<del> self.GypPathToNinja, self.ExpandSpecial, manifest_name, is_executable)
<add> ldflags, intermediate_manifest, manifest_files = \
<add> self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja,
<add> self.ExpandSpecial, manifest_name,
<add> is_executable, self.toplevel_build)
<ide> ldflags = env_ldflags + ldflags
<ide> self.WriteVariableList(ninja_file, 'manifests', manifest_files)
<add> implicit_deps = implicit_deps.union(manifest_files)
<add> if intermediate_manifest:
<add> self.WriteVariableList(
<add> ninja_file, 'intermediatemanifest', [intermediate_manifest])
<ide> command_suffix = _GetWinLinkRuleNameSuffix(
<del> self.msvs_settings.IsEmbedManifest(config_name),
<del> self.msvs_settings.IsLinkIncremental(config_name))
<add> self.msvs_settings.IsEmbedManifest(config_name))
<ide> def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja)
<ide> if def_file:
<ide> implicit_deps.add(def_file)
<ide> def CalculateGeneratorInputInfo(params):
<ide>
<ide> def OpenOutput(path, mode='w'):
<ide> """Open |path| for writing, creating directories if necessary."""
<del> try:
<del> os.makedirs(os.path.dirname(path))
<del> except OSError:
<del> pass
<add> gyp.common.EnsureDirExists(path)
<ide> return open(path, mode)
<ide>
<ide>
<ide> class MEMORYSTATUSEX(ctypes.Structure):
<ide> return 1
<ide>
<ide>
<del>def _GetWinLinkRuleNameSuffix(embed_manifest, link_incremental):
<add>def _GetWinLinkRuleNameSuffix(embed_manifest):
<ide> """Returns the suffix used to select an appropriate linking rule depending on
<del> whether the manifest embedding and/or incremental linking is enabled."""
<del> suffix = ''
<del> if embed_manifest:
<del> suffix += '_embed'
<del> if link_incremental:
<del> suffix += '_inc'
<del> return suffix
<add> whether the manifest embedding is enabled."""
<add> return '_embed' if embed_manifest else ''
<ide>
<ide>
<del>def _AddWinLinkRules(master_ninja, embed_manifest, link_incremental):
<add>def _AddWinLinkRules(master_ninja, embed_manifest):
<ide> """Adds link rules for Windows platform to |master_ninja|."""
<ide> def FullLinkCommand(ldcmd, out, binary_type):
<del> """Returns a one-liner written for cmd.exe to handle multiphase linker
<del> operations including manifest file generation. The command will be
<del> structured as follows:
<del> cmd /c (linkcmd1 a b) && (linkcmd2 x y) && ... &&
<del> if not "$manifests"=="" ((manifestcmd1 a b) && (manifestcmd2 x y) && ... )
<del> Note that $manifests becomes empty when no manifest file is generated."""
<del> link_commands = ['%(ldcmd)s',
<del> 'if exist %(out)s.manifest del %(out)s.manifest']
<del> mt_cmd = ('%(python)s gyp-win-tool manifest-wrapper'
<del> ' $arch $mt -nologo -manifest $manifests')
<del> if embed_manifest and not link_incremental:
<del> # Embed manifest into a binary. If incremental linking is enabled,
<del> # embedding is postponed to the re-linking stage (see below).
<del> mt_cmd += ' -outputresource:%(out)s;%(resname)s'
<del> else:
<del> # Save manifest as an external file.
<del> mt_cmd += ' -out:%(out)s.manifest'
<del> manifest_commands = [mt_cmd]
<del> if link_incremental:
<del> # There is no point in generating separate rule for the case when
<del> # incremental linking is enabled, but manifest embedding is disabled.
<del> # In that case the basic rule should be used (e.g. 'link').
<del> # See also implementation of _GetWinLinkRuleNameSuffix().
<del> assert embed_manifest
<del> # Make .rc file out of manifest, compile it to .res file and re-link.
<del> manifest_commands += [
<del> ('%(python)s gyp-win-tool manifest-to-rc $arch %(out)s.manifest'
<del> ' %(out)s.manifest.rc %(resname)s'),
<del> '%(python)s gyp-win-tool rc-wrapper $arch $rc %(out)s.manifest.rc',
<del> '%(ldcmd)s %(out)s.manifest.res']
<del> cmd = 'cmd /c %s && if not "$manifests"=="" (%s)' % (
<del> ' && '.join(['(%s)' % c for c in link_commands]),
<del> ' && '.join(['(%s)' % c for c in manifest_commands]))
<ide> resource_name = {
<ide> 'exe': '1',
<ide> 'dll': '2',
<ide> }[binary_type]
<del> return cmd % {'python': sys.executable,
<del> 'out': out,
<del> 'ldcmd': ldcmd,
<del> 'resname': resource_name}
<del>
<del> rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest, link_incremental)
<add> return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \
<add> '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \
<add> '$manifests' % {
<add> 'python': sys.executable,
<add> 'out': out,
<add> 'ldcmd': ldcmd,
<add> 'resname': resource_name,
<add> 'embed': embed_manifest }
<add> rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest)
<ide> dlldesc = 'LINK%s(DLL) $dll' % rule_name_suffix.upper()
<ide> dllcmd = ('%s gyp-win-tool link-wrapper $arch '
<ide> '$ld /nologo $implibflag /DLL /OUT:$dll '
<ide> def GenerateOutputForConfig(target_list, target_dicts, data, params,
<ide> sys.executable),
<ide> rspfile='$out.rsp',
<ide> rspfile_content='$in_newline $libflags')
<del> _AddWinLinkRules(master_ninja, embed_manifest=True, link_incremental=True)
<del> _AddWinLinkRules(master_ninja, embed_manifest=True, link_incremental=False)
<del> _AddWinLinkRules(master_ninja, embed_manifest=False, link_incremental=False)
<del> # Do not generate rules for embed_manifest=False and link_incremental=True
<del> # because in that case rules for (False, False) should be used (see
<del> # implementation of _GetWinLinkRuleNameSuffix()).
<add> _AddWinLinkRules(master_ninja, embed_manifest=True)
<add> _AddWinLinkRules(master_ninja, embed_manifest=False)
<ide> else:
<ide> master_ninja.rule(
<ide> 'objc',
<ide><path>tools/gyp/pylib/gyp/input.py
<ide> def ExpandVariables(input, phase, variables, build_file):
<ide> rel_build_file_dir = build_file_dir
<ide> qualified_out_dir = generator_filelist_paths['qualified_out_dir']
<ide> path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement)
<del> if not os.path.isdir(os.path.dirname(path)):
<del> os.makedirs(os.path.dirname(path))
<add> gyp.common.EnsureDirExists(path)
<ide>
<ide> replacement = gyp.common.RelativePath(path, build_file_dir)
<ide> f = gyp.common.WriteOnDiff(path)
<ide><path>tools/gyp/pylib/gyp/msvs_emulation.py
<ide> def GetPGDName(self, config, expand_special):
<ide> return output_file
<ide>
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<del> manifest_base_name, is_executable):
<add> manifest_base_name, is_executable, build_dir):
<ide> """Returns the flags that need to be added to link commands, and the
<ide> manifest files."""
<ide> config = self._TargetConfig(config)
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<ide> ld('DataExecutionPrevention',
<ide> map={'1': ':NO', '2': ''}, prefix='/NXCOMPAT')
<ide> ld('OptimizeReferences', map={'1': 'NOREF', '2': 'REF'}, prefix='/OPT:')
<add> ld('ForceSymbolReferences', prefix='/INCLUDE:')
<ide> ld('EnableCOMDATFolding', map={'1': 'NOICF', '2': 'ICF'}, prefix='/OPT:')
<ide> ld('LinkTimeCodeGeneration',
<ide> map={'1': '', '2': ':PGINSTRUMENT', '3': ':PGOPTIMIZE',
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<ide> ldflags.append('/NXCOMPAT')
<ide>
<ide> have_def_file = filter(lambda x: x.startswith('/DEF:'), ldflags)
<del> manifest_flags, manifest_files = self._GetLdManifestFlags(
<del> config, manifest_base_name, gyp_to_build_path,
<del> is_executable and not have_def_file)
<add> manifest_flags, intermediate_manifest, manifest_files = \
<add> self._GetLdManifestFlags(config, manifest_base_name, gyp_to_build_path,
<add> is_executable and not have_def_file, build_dir)
<ide> ldflags.extend(manifest_flags)
<del> return ldflags, manifest_files
<add> return ldflags, intermediate_manifest, manifest_files
<ide>
<ide> def _GetLdManifestFlags(self, config, name, gyp_to_build_path,
<del> allow_isolation):
<del> """Returns the set of flags that need to be added to the link to generate
<del> a default manifest, as well as the list of all the manifest files to be
<del> merged by the manifest tool."""
<add> allow_isolation, build_dir):
<add> """Returns a 3-tuple:
<add> - the set of flags that need to be added to the link to generate
<add> a default manifest
<add> - the intermediate manifest that the linker will generate that should be
<add> used to assert it doesn't add anything to the merged one.
<add> - the list of all the manifest files to be merged by the manifest tool and
<add> included into the link."""
<ide> generate_manifest = self._Setting(('VCLinkerTool', 'GenerateManifest'),
<ide> config,
<ide> default='true')
<ide> if generate_manifest != 'true':
<ide> # This means not only that the linker should not generate the intermediate
<ide> # manifest but also that the manifest tool should do nothing even when
<ide> # additional manifests are specified.
<del> return ['/MANIFEST:NO'], []
<add> return ['/MANIFEST:NO'], [], []
<ide>
<ide> output_name = name + '.intermediate.manifest'
<ide> flags = [
<ide> '/MANIFEST',
<ide> '/ManifestFile:' + output_name,
<ide> ]
<ide>
<add> # Instead of using the MANIFESTUAC flags, we generate a .manifest to
<add> # include into the list of manifests. This allows us to avoid the need to
<add> # do two passes during linking. The /MANIFEST flag and /ManifestFile are
<add> # still used, and the intermediate manifest is used to assert that the
<add> # final manifest we get from merging all the additional manifest files
<add> # (plus the one we generate here) isn't modified by merging the
<add> # intermediate into it.
<add>
<add> # Always NO, because we generate a manifest file that has what we want.
<add> flags.append('/MANIFESTUAC:NO')
<add>
<ide> config = self._TargetConfig(config)
<ide> enable_uac = self._Setting(('VCLinkerTool', 'EnableUAC'), config,
<ide> default='true')
<add> manifest_files = []
<add> generated_manifest_outer = \
<add>"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" \
<add>"<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>%s" \
<add>"</assembly>"
<ide> if enable_uac == 'true':
<ide> execution_level = self._Setting(('VCLinkerTool', 'UACExecutionLevel'),
<ide> config, default='0')
<ide> def _GetLdManifestFlags(self, config, name, gyp_to_build_path,
<ide>
<ide> ui_access = self._Setting(('VCLinkerTool', 'UACUIAccess'), config,
<ide> default='false')
<del> flags.append('''/MANIFESTUAC:"level='%s' uiAccess='%s'"''' %
<del> (execution_level_map[execution_level], ui_access))
<add>
<add> inner = '''
<add><trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<add> <security>
<add> <requestedPrivileges>
<add> <requestedExecutionLevel level='%s' uiAccess='%s' />
<add> </requestedPrivileges>
<add> </security>
<add></trustInfo>''' % (execution_level_map[execution_level], ui_access)
<ide> else:
<del> flags.append('/MANIFESTUAC:NO')
<add> inner = ''
<add>
<add> generated_manifest_contents = generated_manifest_outer % inner
<add> generated_name = name + '.generated.manifest'
<add> # Need to join with the build_dir here as we're writing it during
<add> # generation time, but we return the un-joined version because the build
<add> # will occur in that directory. We only write the file if the contents
<add> # have changed so that simply regenerating the project files doesn't
<add> # cause a relink.
<add> build_dir_generated_name = os.path.join(build_dir, generated_name)
<add> gyp.common.EnsureDirExists(build_dir_generated_name)
<add> f = gyp.common.WriteOnDiff(build_dir_generated_name)
<add> f.write(generated_manifest_contents)
<add> f.close()
<add> manifest_files = [generated_name]
<ide>
<ide> if allow_isolation:
<ide> flags.append('/ALLOWISOLATION')
<ide>
<del> manifest_files = [output_name]
<ide> manifest_files += self._GetAdditionalManifestFiles(config,
<ide> gyp_to_build_path)
<del> return flags, manifest_files
<add> return flags, output_name, manifest_files
<ide>
<ide> def _GetAdditionalManifestFiles(self, config, gyp_to_build_path):
<ide> """Gets additional manifest files that are added to the default one
<ide> def IsUseLibraryDependencyInputs(self, config):
<ide> def IsEmbedManifest(self, config):
<ide> """Returns whether manifest should be linked into binary."""
<ide> config = self._TargetConfig(config)
<del> embed = self._Setting(('VCManifestTool', 'EmbedManifest'), config)
<add> embed = self._Setting(('VCManifestTool', 'EmbedManifest'), config,
<add> default='true')
<ide> return embed == 'true'
<ide>
<ide> def IsLinkIncremental(self, config):
<ide><path>tools/gyp/pylib/gyp/ordered_dict.py
<add># Unmodified from http://code.activestate.com/recipes/576693/
<add># other than to add MIT license header (as specified on page, but not in code).
<add># Linked from Python documentation here:
<add># http://docs.python.org/2/library/collections.html#collections.OrderedDict
<add>#
<add># This should be deleted once Py2.7 is available on all bots, see
<add># http://crbug.com/241769.
<add>#
<add># Copyright (c) 2009 Raymond Hettinger.
<add>#
<add># Permission is hereby granted, free of charge, to any person obtaining a copy
<add># of this software and associated documentation files (the "Software"), to deal
<add># in the Software without restriction, including without limitation the rights
<add># to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<add># copies of the Software, and to permit persons to whom the Software is
<add># furnished to do so, subject to the following conditions:
<add>#
<add># The above copyright notice and this permission notice shall be included in
<add># all copies or substantial portions of the Software.
<add>#
<add># THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add># IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add># FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<add># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<add># LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<add># OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
<add># THE SOFTWARE.
<add>
<add># Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
<add># Passes Python2.7's test suite and incorporates all the latest updates.
<add>
<add>try:
<add> from thread import get_ident as _get_ident
<add>except ImportError:
<add> from dummy_thread import get_ident as _get_ident
<add>
<add>try:
<add> from _abcoll import KeysView, ValuesView, ItemsView
<add>except ImportError:
<add> pass
<add>
<add>
<add>class OrderedDict(dict):
<add> 'Dictionary that remembers insertion order'
<add> # An inherited dict maps keys to values.
<add> # The inherited dict provides __getitem__, __len__, __contains__, and get.
<add> # The remaining methods are order-aware.
<add> # Big-O running times for all methods are the same as for regular dictionaries.
<add>
<add> # The internal self.__map dictionary maps keys to links in a doubly linked list.
<add> # The circular doubly linked list starts and ends with a sentinel element.
<add> # The sentinel element never gets deleted (this simplifies the algorithm).
<add> # Each link is stored as a list of length three: [PREV, NEXT, KEY].
<add>
<add> def __init__(self, *args, **kwds):
<add> '''Initialize an ordered dictionary. Signature is the same as for
<add> regular dictionaries, but keyword arguments are not recommended
<add> because their insertion order is arbitrary.
<add>
<add> '''
<add> if len(args) > 1:
<add> raise TypeError('expected at most 1 arguments, got %d' % len(args))
<add> try:
<add> self.__root
<add> except AttributeError:
<add> self.__root = root = [] # sentinel node
<add> root[:] = [root, root, None]
<add> self.__map = {}
<add> self.__update(*args, **kwds)
<add>
<add> def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
<add> 'od.__setitem__(i, y) <==> od[i]=y'
<add> # Setting a new item creates a new link which goes at the end of the linked
<add> # list, and the inherited dictionary is updated with the new key/value pair.
<add> if key not in self:
<add> root = self.__root
<add> last = root[0]
<add> last[1] = root[0] = self.__map[key] = [last, root, key]
<add> dict_setitem(self, key, value)
<add>
<add> def __delitem__(self, key, dict_delitem=dict.__delitem__):
<add> 'od.__delitem__(y) <==> del od[y]'
<add> # Deleting an existing item uses self.__map to find the link which is
<add> # then removed by updating the links in the predecessor and successor nodes.
<add> dict_delitem(self, key)
<add> link_prev, link_next, key = self.__map.pop(key)
<add> link_prev[1] = link_next
<add> link_next[0] = link_prev
<add>
<add> def __iter__(self):
<add> 'od.__iter__() <==> iter(od)'
<add> root = self.__root
<add> curr = root[1]
<add> while curr is not root:
<add> yield curr[2]
<add> curr = curr[1]
<add>
<add> def __reversed__(self):
<add> 'od.__reversed__() <==> reversed(od)'
<add> root = self.__root
<add> curr = root[0]
<add> while curr is not root:
<add> yield curr[2]
<add> curr = curr[0]
<add>
<add> def clear(self):
<add> 'od.clear() -> None. Remove all items from od.'
<add> try:
<add> for node in self.__map.itervalues():
<add> del node[:]
<add> root = self.__root
<add> root[:] = [root, root, None]
<add> self.__map.clear()
<add> except AttributeError:
<add> pass
<add> dict.clear(self)
<add>
<add> def popitem(self, last=True):
<add> '''od.popitem() -> (k, v), return and remove a (key, value) pair.
<add> Pairs are returned in LIFO order if last is true or FIFO order if false.
<add>
<add> '''
<add> if not self:
<add> raise KeyError('dictionary is empty')
<add> root = self.__root
<add> if last:
<add> link = root[0]
<add> link_prev = link[0]
<add> link_prev[1] = root
<add> root[0] = link_prev
<add> else:
<add> link = root[1]
<add> link_next = link[1]
<add> root[1] = link_next
<add> link_next[0] = root
<add> key = link[2]
<add> del self.__map[key]
<add> value = dict.pop(self, key)
<add> return key, value
<add>
<add> # -- the following methods do not depend on the internal structure --
<add>
<add> def keys(self):
<add> 'od.keys() -> list of keys in od'
<add> return list(self)
<add>
<add> def values(self):
<add> 'od.values() -> list of values in od'
<add> return [self[key] for key in self]
<add>
<add> def items(self):
<add> 'od.items() -> list of (key, value) pairs in od'
<add> return [(key, self[key]) for key in self]
<add>
<add> def iterkeys(self):
<add> 'od.iterkeys() -> an iterator over the keys in od'
<add> return iter(self)
<add>
<add> def itervalues(self):
<add> 'od.itervalues -> an iterator over the values in od'
<add> for k in self:
<add> yield self[k]
<add>
<add> def iteritems(self):
<add> 'od.iteritems -> an iterator over the (key, value) items in od'
<add> for k in self:
<add> yield (k, self[k])
<add>
<add> def update(*args, **kwds):
<add> '''od.update(E, **F) -> None. Update od from dict/iterable E and F.
<add>
<add> If E is a dict instance, does: for k in E: od[k] = E[k]
<add> If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
<add> Or if E is an iterable of items, does: for k, v in E: od[k] = v
<add> In either case, this is followed by: for k, v in F.items(): od[k] = v
<add>
<add> '''
<add> if len(args) > 2:
<add> raise TypeError('update() takes at most 2 positional '
<add> 'arguments (%d given)' % (len(args),))
<add> elif not args:
<add> raise TypeError('update() takes at least 1 argument (0 given)')
<add> self = args[0]
<add> # Make progressively weaker assumptions about "other"
<add> other = ()
<add> if len(args) == 2:
<add> other = args[1]
<add> if isinstance(other, dict):
<add> for key in other:
<add> self[key] = other[key]
<add> elif hasattr(other, 'keys'):
<add> for key in other.keys():
<add> self[key] = other[key]
<add> else:
<add> for key, value in other:
<add> self[key] = value
<add> for key, value in kwds.items():
<add> self[key] = value
<add>
<add> __update = update # let subclasses override update without breaking __init__
<add>
<add> __marker = object()
<add>
<add> def pop(self, key, default=__marker):
<add> '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
<add> If key is not found, d is returned if given, otherwise KeyError is raised.
<add>
<add> '''
<add> if key in self:
<add> result = self[key]
<add> del self[key]
<add> return result
<add> if default is self.__marker:
<add> raise KeyError(key)
<add> return default
<add>
<add> def setdefault(self, key, default=None):
<add> 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
<add> if key in self:
<add> return self[key]
<add> self[key] = default
<add> return default
<add>
<add> def __repr__(self, _repr_running={}):
<add> 'od.__repr__() <==> repr(od)'
<add> call_key = id(self), _get_ident()
<add> if call_key in _repr_running:
<add> return '...'
<add> _repr_running[call_key] = 1
<add> try:
<add> if not self:
<add> return '%s()' % (self.__class__.__name__,)
<add> return '%s(%r)' % (self.__class__.__name__, self.items())
<add> finally:
<add> del _repr_running[call_key]
<add>
<add> def __reduce__(self):
<add> 'Return state information for pickling'
<add> items = [[k, self[k]] for k in self]
<add> inst_dict = vars(self).copy()
<add> for k in vars(OrderedDict()):
<add> inst_dict.pop(k, None)
<add> if inst_dict:
<add> return (self.__class__, (items,), inst_dict)
<add> return self.__class__, (items,)
<add>
<add> def copy(self):
<add> 'od.copy() -> a shallow copy of od'
<add> return self.__class__(self)
<add>
<add> @classmethod
<add> def fromkeys(cls, iterable, value=None):
<add> '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
<add> and values equal to v (which defaults to None).
<add>
<add> '''
<add> d = cls()
<add> for key in iterable:
<add> d[key] = value
<add> return d
<add>
<add> def __eq__(self, other):
<add> '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
<add> while comparison to a regular mapping is order-insensitive.
<add>
<add> '''
<add> if isinstance(other, OrderedDict):
<add> return len(self)==len(other) and self.items() == other.items()
<add> return dict.__eq__(self, other)
<add>
<add> def __ne__(self, other):
<add> return not self == other
<add>
<add> # -- the following methods are only used in Python 2.7 --
<add>
<add> def viewkeys(self):
<add> "od.viewkeys() -> a set-like object providing a view on od's keys"
<add> return KeysView(self)
<add>
<add> def viewvalues(self):
<add> "od.viewvalues() -> an object providing a view on od's values"
<add> return ValuesView(self)
<add>
<add> def viewitems(self):
<add> "od.viewitems() -> a set-like object providing a view on od's items"
<add> return ItemsView(self)
<add>
<ide><path>tools/gyp/pylib/gyp/win_tool.py
<ide> import re
<ide> import shutil
<ide> import subprocess
<add>import string
<ide> import sys
<ide>
<ide> BASE_DIR = os.path.dirname(os.path.abspath(__file__))
<ide> def ExecLinkWrapper(self, arch, *args):
<ide> print line
<ide> return link.returncode
<ide>
<add> def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname,
<add> mt, rc, intermediate_manifest, *manifests):
<add> """A wrapper for handling creating a manifest resource and then executing
<add> a link command."""
<add> # The 'normal' way to do manifests is to have link generate a manifest
<add> # based on gathering dependencies from the object files, then merge that
<add> # manifest with other manifests supplied as sources, convert the merged
<add> # manifest to a resource, and then *relink*, including the compiled
<add> # version of the manifest resource. This breaks incremental linking, and
<add> # is generally overly complicated. Instead, we merge all the manifests
<add> # provided (along with one that includes what would normally be in the
<add> # linker-generated one, see msvs_emulation.py), and include that into the
<add> # first and only link. We still tell link to generate a manifest, but we
<add> # only use that to assert that our simpler process did not miss anything.
<add> variables = {
<add> 'python': sys.executable,
<add> 'arch': arch,
<add> 'out': out,
<add> 'ldcmd': ldcmd,
<add> 'resname': resname,
<add> 'mt': mt,
<add> 'rc': rc,
<add> 'intermediate_manifest': intermediate_manifest,
<add> 'manifests': ' '.join(manifests),
<add> }
<add> add_to_ld = ''
<add> if manifests:
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
<add> '-manifest %(manifests)s -out:%(out)s.manifest' % variables)
<add> if embed_manifest == 'True':
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'
<add> ' %(out)s.manifest.rc %(resname)s' % variables)
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '
<add> '%(out)s.manifest.rc' % variables)
<add> add_to_ld = ' %(out)s.manifest.res' % variables
<add> subprocess.check_call(ldcmd + add_to_ld)
<add>
<add> # Run mt.exe on the theoretically complete manifest we generated, merging
<add> # it with the one the linker generated to confirm that the linker
<add> # generated one does not add anything. This is strictly unnecessary for
<add> # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not
<add> # used in a #pragma comment.
<add> if manifests:
<add> # Merge the intermediate one with ours to .assert.manifest, then check
<add> # that .assert.manifest is identical to ours.
<add> subprocess.check_call(
<add> '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '
<add> '-manifest %(out)s.manifest %(intermediate_manifest)s '
<add> '-out:%(out)s.assert.manifest' % variables)
<add> assert_manifest = '%(out)s.assert.manifest' % variables
<add> our_manifest = '%(out)s.manifest' % variables
<add> # Load and normalize the manifests. mt.exe sometimes removes whitespace,
<add> # and sometimes doesn't unfortunately.
<add> with open(our_manifest, 'rb') as our_f:
<add> with open(assert_manifest, 'rb') as assert_f:
<add> our_data = our_f.read().translate(None, string.whitespace)
<add> assert_data = assert_f.read().translate(None, string.whitespace)
<add> if our_data != assert_data:
<add> os.unlink(out)
<add> def dump(filename):
<add> sys.stderr.write('%s\n-----\n' % filename)
<add> with open(filename, 'rb') as f:
<add> sys.stderr.write(f.read() + '\n-----\n')
<add> dump(intermediate_manifest)
<add> dump(our_manifest)
<add> dump(assert_manifest)
<add> sys.stderr.write(
<add> 'Linker generated manifest "%s" added to final manifest "%s" '
<add> '(result in "%s"). '
<add> 'Were /MANIFEST switches used in #pragma statements? ' % (
<add> intermediate_manifest, our_manifest, assert_manifest))
<add> return 1
<add>
<ide> def ExecManifestWrapper(self, arch, *args):
<ide> """Run manifest tool with environment set. Strip out undesirable warning
<ide> (some XML blocks are recognized by the OS loader, but not the manifest
<ide><path>tools/gyp/pylib/gyp/xcode_emulation.py
<ide> def _GetStdout(self, cmdlist):
<ide> return out.rstrip('\n')
<ide>
<ide> def _GetSdkVersionInfoItem(self, sdk, infoitem):
<del> return self._GetStdout(['xcodebuild', '-version', '-sdk', sdk, infoitem])
<add> # xcodebuild requires Xcode and can't run on Command Line Tools-only
<add> # systems from 10.7 onward.
<add> # Since the CLT has no SDK paths anyway, returning None is the
<add> # most sensible route and should still do the right thing.
<add> try:
<add> return self._GetStdout(['xcodebuild', '-version', '-sdk', sdk, infoitem])
<add> except:
<add> pass
<ide>
<ide> def _SdkRoot(self, configname):
<ide> if configname is None:
<ide> def GetCflags(self, configname, arch=None):
<ide> cflags = []
<ide>
<ide> sdk_root = self._SdkPath()
<del> if 'SDKROOT' in self._Settings():
<add> if 'SDKROOT' in self._Settings() and sdk_root:
<ide> cflags.append('-isysroot %s' % sdk_root)
<ide>
<ide> if self._Test('CLANG_WARN_CONSTANT_CONVERSION', 'YES', default='NO'):
<ide> def GetCflags(self, configname, arch=None):
<ide>
<ide> cflags += self._Settings().get('WARNING_CFLAGS', [])
<ide>
<add> if sdk_root:
<add> framework_root = sdk_root
<add> else:
<add> framework_root = ''
<ide> config = self.spec['configurations'][self.configname]
<ide> framework_dirs = config.get('mac_framework_dirs', [])
<ide> for directory in framework_dirs:
<del> cflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root))
<add> cflags.append('-F' + directory.replace('$(SDKROOT)', framework_root))
<ide>
<ide> self.configname = None
<ide> return cflags
<ide> def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
<ide>
<ide> self._AppendPlatformVersionMinFlags(ldflags)
<ide>
<del> if 'SDKROOT' in self._Settings():
<add> if 'SDKROOT' in self._Settings() and self._SdkPath():
<ide> ldflags.append('-isysroot ' + self._SdkPath())
<ide>
<ide> for library_path in self._Settings().get('LIBRARY_SEARCH_PATHS', []):
<ide> def GetLdflags(self, configname, product_dir, gyp_to_build_path, arch=None):
<ide> for rpath in self._Settings().get('LD_RUNPATH_SEARCH_PATHS', []):
<ide> ldflags.append('-Wl,-rpath,' + rpath)
<ide>
<add> sdk_root = self._SdkPath()
<add> if not sdk_root:
<add> sdk_root = ''
<ide> config = self.spec['configurations'][self.configname]
<ide> framework_dirs = config.get('mac_framework_dirs', [])
<ide> for directory in framework_dirs:
<del> ldflags.append('-F' + directory.replace('$(SDKROOT)', self._SdkPath()))
<add> ldflags.append('-F' + directory.replace('$(SDKROOT)', sdk_root))
<ide>
<ide> self.configname = None
<ide> return ldflags
<ide> def _GetIOSCodeSignIdentityKey(self, settings):
<ide> ['security', 'find-identity', '-p', 'codesigning', '-v'])
<ide> for line in output.splitlines():
<ide> if identity in line:
<del> assert identity not in XcodeSettings._codesigning_key_cache, (
<del> "Multiple codesigning identities for identity: %s" % identity)
<del> XcodeSettings._codesigning_key_cache[identity] = line.split()[1]
<add> fingerprint = line.split()[1]
<add> cache = XcodeSettings._codesigning_key_cache
<add> assert identity not in cache or fingerprint == cache[identity], (
<add> "Multiple codesigning fingerprints for identity: %s" % identity)
<add> XcodeSettings._codesigning_key_cache[identity] = fingerprint
<ide> return XcodeSettings._codesigning_key_cache.get(identity, '')
<ide>
<ide> def AddImplicitPostbuilds(self, configname, output, output_binary,
<ide> def _AdjustLibrary(self, library, config_name=None):
<ide> l = '-l' + m.group(1)
<ide> else:
<ide> l = library
<del> return l.replace('$(SDKROOT)', self._SdkPath(config_name))
<add>
<add> sdk_root = self._SdkPath(config_name)
<add> if not sdk_root:
<add> sdk_root = ''
<add> return l.replace('$(SDKROOT)', sdk_root)
<ide>
<ide> def AdjustLibraries(self, libraries, config_name=None):
<ide> """Transforms entries like 'Cocoa.framework' in libraries into entries like
<ide> def AdjustLibraries(self, libraries, config_name=None):
<ide> def _BuildMachineOSBuild(self):
<ide> return self._GetStdout(['sw_vers', '-buildVersion'])
<ide>
<add> # This method ported from the logic in Homebrew's CLT version check
<add> def _CLTVersion(self):
<add> # pkgutil output looks like
<add> # package-id: com.apple.pkg.CLTools_Executables
<add> # version: 5.0.1.0.1.1382131676
<add> # volume: /
<add> # location: /
<add> # install-time: 1382544035
<add> # groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group
<add> STANDALONE_PKG_ID = "com.apple.pkg.DeveloperToolsCLILeo"
<add> FROM_XCODE_PKG_ID = "com.apple.pkg.DeveloperToolsCLI"
<add> MAVERICKS_PKG_ID = "com.apple.pkg.CLTools_Executables"
<add>
<add> regex = re.compile('version: (?P<version>.+)')
<add> for key in [MAVERICKS_PKG_ID, STANDALONE_PKG_ID, FROM_XCODE_PKG_ID]:
<add> try:
<add> output = self._GetStdout(['/usr/sbin/pkgutil', '--pkg-info', key])
<add> return re.search(regex, output).groupdict()['version']
<add> except:
<add> continue
<add>
<ide> def _XcodeVersion(self):
<ide> # `xcodebuild -version` output looks like
<ide> # Xcode 4.6.3
<ide> def _XcodeVersion(self):
<ide> # BuildVersion: 10M2518
<ide> # Convert that to '0463', '4H1503'.
<ide> if len(XcodeSettings._xcode_version_cache) == 0:
<del> version_list = self._GetStdout(['xcodebuild', '-version']).splitlines()
<add> try:
<add> version_list = self._GetStdout(['xcodebuild', '-version']).splitlines()
<add> # In some circumstances xcodebuild exits 0 but doesn't return
<add> # the right results; for example, a user on 10.7 or 10.8 with
<add> # a bogus path set via xcode-select
<add> # In that case this may be a CLT-only install so fall back to
<add> # checking that version.
<add> if len(version_list) < 2:
<add> raise GypError, "xcodebuild returned unexpected results"
<add> except:
<add> version = self._CLTVersion()
<add> if version:
<add> version = re.match('(\d\.\d\.?\d*)', version).groups()[0]
<add> else:
<add> raise GypError, "No Xcode or CLT version detected!"
<add> # The CLT has no build information, so we return an empty string.
<add> version_list = [version, '']
<ide> version = version_list[0]
<ide> build = version_list[-1]
<ide> # Be careful to convert "4.2" to "0420":
<ide> version = version.split()[-1].replace('.', '')
<ide> version = (version + '0' * (3 - len(version))).zfill(4)
<del> build = build.split()[-1]
<add> if build:
<add> build = build.split()[-1]
<ide> XcodeSettings._xcode_version_cache = (version, build)
<ide> return XcodeSettings._xcode_version_cache
<ide>
<ide> def _DefaultSdkRoot(self):
<ide> default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path)
<ide> if default_sdk_root:
<ide> return default_sdk_root
<del> all_sdks = self._GetStdout(['xcodebuild', '-showsdks'])
<add> try:
<add> all_sdks = self._GetStdout(['xcodebuild', '-showsdks'])
<add> except:
<add> # If xcodebuild fails, there will be no valid SDKs
<add> return ''
<ide> for line in all_sdks.splitlines():
<ide> items = line.split()
<ide> if len(items) >= 3 and items[-2] == '-sdk': | 12 |
Ruby | Ruby | remove whitespaces from empty line | 360b98f0618873e5c0a41f0a5e029868b8deadf9 | <ide><path>railties/test/generators/plugin_new_generator_test.rb
<ide> def test_passing_dummy_path_as_a_parameter
<ide> assert_file "spec/dummy/config/application.rb"
<ide> assert_no_file "test/dummy"
<ide> end
<del>
<add>
<ide> def test_creating_dummy_without_tests_but_with_dummy_path
<ide> run_generator [destination_root, "--dummy_path", "spec/dummy", "--skip-test-unit"]
<ide> assert_file "spec/dummy" | 1 |
Javascript | Javascript | fix directive usage | 03d4bbc16f620d13ac509ab93cabbc77bbfc3f59 | <ide><path>src/Angular.js
<ide> var csp = function() {
<ide> * @name ngJq
<ide> *
<ide> * @element ANY
<del> * @param {string=} the name of the library available under `window`
<add> * @param {string=} ngJq the name of the library available under `window`
<ide> * to be used for angular.element
<ide> * @description
<ide> * Use this directive to force the angular.element library. This should be | 1 |
Python | Python | fix error when last shard is not assigned a batch | bf29843973dbe9d073f12ccd7cb8e5de9cc8423c | <ide><path>official/recommendation/data_async_generation.py
<ide> def _construct_records(
<ide> num_workers: Number of multiprocessing workers to use for negative
<ide> generation.
<ide> cache_paths: Paths object with information of where to write files.
<del> num_readers: The number of reader datasets in the input_fn.
<add> num_readers: The number of reader datasets in the input_fn. This number is
<add> approximate; fewer shards will be created if not all shards are assigned
<add> batches. This can occur due to discretization in the assignment process.
<ide> num_neg: The number of false negatives per positive example.
<ide> num_positives: The number of positive examples. This value is used
<ide> to pre-allocate arrays while the imap is still running. (NumPy does not
<ide> def _construct_records(
<ide> break
<ide> batches_by_file[current_file_id].append(current_batch_id)
<ide>
<add> # Drop shards which were not assigned batches
<add> batches_by_file = [i for i in batches_by_file if i]
<add> num_readers = len(batches_by_file)
<add>
<ide> if is_training:
<ide> # Empirically it is observed that placing the batch with repeated values at
<ide> # the start rather than the end improves convergence. | 1 |
Text | Text | complete the webui readme with more infos | 6cbf768c97e7a46984f4c24a19788e1b520096ad | <ide><path>glances/outputs/static/README.md
<ide> static
<ide> |
<ide> |--- templates (bottle)
<ide> ```
<add>
<add>## Data
<add>
<add>Each plugin receives the data in the following format:
<add>
<add>* stats
<add>* views
<add>* isBsd
<add>* isLinux
<add>* isMac
<add>* isWindows | 1 |
PHP | PHP | fix docblock for metadatabag namespace | 2d7c8c8bc29ca32c0fd474f82be3f48b97e6d153 | <ide><path>src/Illuminate/Session/Store.php
<ide> class Store implements SessionInterface {
<ide> /**
<ide> * The meta-data bag instance.
<ide> *
<del> * @var \Symfony\Component\Session\Storage\MetadataBag
<add> * @var \Symfony\Component\HttpFoundation\Session\Storage\MetadataBag
<ide> */
<ide> protected $metaBag;
<ide> | 1 |
Java | Java | remove all layout index adjustments | d3b93f75787267629c4033a5aa61b62d623f3c08 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyManager.java
<ide> import android.graphics.RectF;
<ide> import android.util.SparseArray;
<ide> import android.util.SparseBooleanArray;
<del>import android.util.SparseIntArray;
<ide> import android.view.Menu;
<ide> import android.view.MenuItem;
<ide> import android.view.View;
<ide> public class NativeViewHierarchyManager {
<ide> private final JSResponderHandler mJSResponderHandler = new JSResponderHandler();
<ide> private final RootViewManager mRootViewManager;
<ide> private final LayoutAnimationController mLayoutAnimator = new LayoutAnimationController();
<del> private final SparseArray<SparseIntArray> mTagsToPendingIndicesToDelete = new SparseArray<>();
<ide> private final int[] mDroppedViewArray = new int[100];
<ide> private final RectF mBoundingBox = new RectF();
<ide>
<ide> private static String constructManageChildrenErrorMessage(
<ide> return stringBuilder.toString();
<ide> }
<ide>
<del> /**
<del> * Given an index to action on under synchronous deletes, return an updated index factoring in
<del> * asynchronous deletes (where the async delete operations have not yet been performed)
<del> */
<del> private int normalizeIndex(int index, SparseIntArray pendingIndices) {
<del> int normalizedIndex = index;
<del> for (int i = 0; i <= index; i++) {
<del> normalizedIndex += pendingIndices.get(i);
<del> }
<del> return normalizedIndex;
<del> }
<del>
<del> /**
<del> * Given React tag, return sparse array of direct child indices that are pending deletion (due to
<del> * async view deletion)
<del> */
<del> private SparseIntArray getOrCreatePendingIndicesToDelete(int tag) {
<del> SparseIntArray pendingIndicesToDelete = mTagsToPendingIndicesToDelete.get(tag);
<del> if (pendingIndicesToDelete == null) {
<del> pendingIndicesToDelete = new SparseIntArray();
<del> mTagsToPendingIndicesToDelete.put(tag, pendingIndicesToDelete);
<del> }
<del> return pendingIndicesToDelete;
<del> }
<del>
<ide> /**
<ide> * @param tag react tag of the node we want to manage
<ide> * @param indicesToRemove ordered (asc) list of indicies at which view should be removed
<ide> * @param viewsToAdd ordered (asc based on mIndex property) list of tag-index pairs that represent
<ide> * a view which should be added at the specified index
<ide> * @param tagsToDelete list of tags corresponding to views that should be removed
<del> * @param indicesToDelete parallel list to tagsToDelete, list of indices of those tags
<ide> */
<ide> public synchronized void manageChildren(
<ide> int tag,
<ide> @Nullable int[] indicesToRemove,
<ide> @Nullable ViewAtIndex[] viewsToAdd,
<del> @Nullable int[] tagsToDelete,
<del> @Nullable int[] indicesToDelete) {
<add> @Nullable int[] tagsToDelete) {
<ide> UiThreadUtil.assertOnUiThread();
<ide>
<del> final SparseIntArray pendingIndicesToDelete = getOrCreatePendingIndicesToDelete(tag);
<del>
<ide> final ViewGroup viewToManage = (ViewGroup) mTagsToViews.get(tag);
<ide> final ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(tag);
<ide> if (viewToManage == null) {
<ide> public synchronized void manageChildren(
<ide> viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
<ide> }
<ide>
<del> int normalizedIndexToRemove = normalizeIndex(indexToRemove, pendingIndicesToDelete);
<del> View viewToRemove = viewManager.getChildAt(viewToManage, normalizedIndexToRemove);
<add> View viewToRemove = viewManager.getChildAt(viewToManage, indexToRemove);
<ide>
<ide> if (mLayoutAnimationEnabled
<ide> && mLayoutAnimator.shouldAnimateLayout(viewToRemove)
<ide> && arrayContains(tagsToDelete, viewToRemove.getId())) {
<ide> // The view will be removed and dropped by the 'delete' layout animation
<ide> // instead, so do nothing
<ide> } else {
<del> viewManager.removeViewAt(viewToManage, normalizedIndexToRemove);
<add> viewManager.removeViewAt(viewToManage, indexToRemove);
<ide> }
<ide>
<ide> lastIndexToRemove = indexToRemove;
<ide> && arrayContains(tagsToDelete, viewToRemove.getId())) {
<ide> if (tagsToDelete != null) {
<ide> for (int i = 0; i < tagsToDelete.length; i++) {
<ide> int tagToDelete = tagsToDelete[i];
<del> final int indexToDelete = indicesToDelete[i];
<ide> final View viewToDestroy = mTagsToViews.get(tagToDelete);
<ide> if (viewToDestroy == null) {
<ide> throw new IllegalViewOperationException(
<ide> && arrayContains(tagsToDelete, viewToRemove.getId())) {
<ide> }
<ide>
<ide> if (mLayoutAnimationEnabled && mLayoutAnimator.shouldAnimateLayout(viewToDestroy)) {
<del> int updatedCount = pendingIndicesToDelete.get(indexToDelete, 0) + 1;
<del> pendingIndicesToDelete.put(indexToDelete, updatedCount);
<ide> mLayoutAnimator.deleteView(
<ide> viewToDestroy,
<ide> new LayoutAnimationListener() {
<ide> public void onAnimationEnd() {
<ide>
<ide> viewManager.removeView(viewToManage, viewToDestroy);
<ide> dropView(viewToDestroy);
<del>
<del> int count = pendingIndicesToDelete.get(indexToDelete, 0);
<del> pendingIndicesToDelete.put(indexToDelete, Math.max(0, count - 1));
<ide> }
<ide> });
<ide> } else {
<ide> public void onAnimationEnd() {
<ide> + constructManageChildrenErrorMessage(
<ide> viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
<ide> }
<del> int normalizedIndexToAdd = normalizeIndex(viewAtIndex.mIndex, pendingIndicesToDelete);
<del> viewManager.addView(viewToManage, viewToAdd, normalizedIndexToAdd);
<add> viewManager.addView(viewToManage, viewToAdd, viewAtIndex.mIndex);
<ide> }
<ide> }
<ide> }
<ide> protected synchronized void dropView(View view) {
<ide> }
<ide> viewGroupManager.removeAllViews(viewGroup);
<ide> }
<del> mTagsToPendingIndicesToDelete.remove(view.getId());
<ide> mTagsToViews.remove(view.getId());
<ide> mTagsToViewManagers.remove(view.getId());
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/NativeViewHierarchyOptimizer.java
<ide> public void handleManageChildren(
<ide> int[] indicesToRemove,
<ide> int[] tagsToRemove,
<ide> ViewAtIndex[] viewsToAdd,
<del> int[] tagsToDelete,
<del> int[] indicesToDelete) {
<add> int[] tagsToDelete) {
<ide> if (!ENABLED) {
<ide> assertNodeSupportedWithoutOptimizer(nodeToManage);
<ide> mUIViewOperationQueue.enqueueManageChildren(
<del> nodeToManage.getReactTag(), indicesToRemove, viewsToAdd, tagsToDelete, indicesToDelete);
<add> nodeToManage.getReactTag(), indicesToRemove, viewsToAdd, tagsToDelete);
<ide> return;
<ide> }
<ide>
<ide> private void removeNodeFromParent(ReactShadowNode nodeToRemove, boolean shouldDe
<ide> nativeNodeToRemoveFrom.getReactTag(),
<ide> new int[] {index},
<ide> null,
<del> shouldDelete ? new int[] {nodeToRemove.getReactTag()} : null,
<del> shouldDelete ? new int[] {index} : null);
<add> shouldDelete ? new int[] {nodeToRemove.getReactTag()} : null);
<ide> }
<ide> }
<ide>
<ide> private void addNativeChild(ReactShadowNode parent, ReactShadowNode child, int i
<ide> parent.getReactTag(),
<ide> null,
<ide> new ViewAtIndex[] {new ViewAtIndex(child.getReactTag(), index)},
<del> null,
<ide> null);
<ide>
<ide> if (child.getNativeKind() != NativeKind.PARENT) {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIImplementation.java
<ide> public void manageChildren(
<ide> int[] indicesToRemove = new int[numToMove + numToRemove];
<ide> int[] tagsToRemove = new int[indicesToRemove.length];
<ide> int[] tagsToDelete = new int[numToRemove];
<del> int[] indicesToDelete = new int[numToRemove];
<ide>
<ide> if (numToMove > 0) {
<ide> Assertions.assertNotNull(moveFrom);
<ide> public void manageChildren(
<ide> indicesToRemove[numToMove + i] = indexToRemove;
<ide> tagsToRemove[numToMove + i] = tagToRemove;
<ide> tagsToDelete[i] = tagToRemove;
<del> indicesToDelete[i] = indexToRemove;
<ide> }
<ide> }
<ide>
<ide> public void manageChildren(
<ide> }
<ide>
<ide> mNativeViewHierarchyOptimizer.handleManageChildren(
<del> cssNodeToManage,
<del> indicesToRemove,
<del> tagsToRemove,
<del> viewsToAdd,
<del> tagsToDelete,
<del> indicesToDelete);
<add> cssNodeToManage, indicesToRemove, tagsToRemove, viewsToAdd, tagsToDelete);
<ide>
<ide> for (int i = 0; i < tagsToDelete.length; i++) {
<ide> removeShadowNode(mShadowNodeRegistry.getNode(tagsToDelete[i]));
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIViewOperationQueue.java
<ide> private final class ManageChildrenOperation extends ViewOperation {
<ide> private final @Nullable int[] mIndicesToRemove;
<ide> private final @Nullable ViewAtIndex[] mViewsToAdd;
<ide> private final @Nullable int[] mTagsToDelete;
<del> private final @Nullable int[] mIndicesToDelete;
<ide>
<ide> public ManageChildrenOperation(
<ide> int tag,
<ide> @Nullable int[] indicesToRemove,
<ide> @Nullable ViewAtIndex[] viewsToAdd,
<del> @Nullable int[] tagsToDelete,
<del> @Nullable int[] indicesToDelete) {
<add> @Nullable int[] tagsToDelete) {
<ide> super(tag);
<ide> mIndicesToRemove = indicesToRemove;
<ide> mViewsToAdd = viewsToAdd;
<ide> mTagsToDelete = tagsToDelete;
<del> mIndicesToDelete = indicesToDelete;
<ide> }
<ide>
<ide> @Override
<ide> public void execute() {
<ide> mNativeViewHierarchyManager.manageChildren(
<del> mTag, mIndicesToRemove, mViewsToAdd, mTagsToDelete, mIndicesToDelete);
<add> mTag, mIndicesToRemove, mViewsToAdd, mTagsToDelete);
<ide> }
<ide> }
<ide>
<ide> public void enqueueManageChildren(
<ide> int reactTag,
<ide> @Nullable int[] indicesToRemove,
<ide> @Nullable ViewAtIndex[] viewsToAdd,
<del> @Nullable int[] tagsToDelete,
<del> @Nullable int[] indicesToDelete) {
<add> @Nullable int[] tagsToDelete) {
<ide> mOperations.add(
<del> new ManageChildrenOperation(
<del> reactTag, indicesToRemove, viewsToAdd, tagsToDelete, indicesToDelete));
<add> new ManageChildrenOperation(reactTag, indicesToRemove, viewsToAdd, tagsToDelete));
<ide> }
<ide>
<ide> public void enqueueSetChildren(int reactTag, ReadableArray childrenTags) { | 4 |
Javascript | Javascript | add more examples | a82a62e5a674c3a229a304844905ea758dc7461e | <ide><path>src/ngMessageFormat/messageFormatService.js
<ide> * For more information, see:
<ide> * https://docs.google.com/a/google.com/document/d/1pbtW2yvtmFBikfRrJd8VAsabiFkKezmYZ_PbgdjQOVU/edit
<ide> *
<del> * ## Example
<add> * @example
<add> * ## Gender
<ide> *
<del> * <example name="ngMessageFormat-example" module="msgFmtExample" deps="angular-message-format.min.js">
<add> * This example uses the "select" keyword to specify the message based on gender.
<add> *
<add> * <example name="ngMessageFormat-example-gender" module="msgFmtExample" deps="angular-message-format.min.js">
<add> * <file name="index.html">
<add> * <div ng-controller="AppController">
<add> * Select Recipient:<br>
<add> <select ng-model="recipient" ng-options="person as person.name for person in recipients">
<add> </select>
<add> <p>{{recipient.gender, select,
<add> male {{{recipient.name}} unwrapped his gift. }
<add> female {{{recipient.name}} unwrapped her gift. }
<add> other {{{recipient.name}} unwrapped their gift. }
<add> }}</p>
<add> * </div>
<add> * </file>
<add> * <file name="script.js">
<add> * function Person(name, gender) {
<add> * this.name = name;
<add> * this.gender = gender;
<add> * }
<add> *
<add> * var alice = new Person("Alice", "female"),
<add> * bob = new Person("Bob", "male"),
<add> * ashley = new Person("Ashley", "");
<add> *
<add> * angular.module('msgFmtExample', ['ngMessageFormat'])
<add> * .controller('AppController', ['$scope', function($scope) {
<add> * $scope.recipients = [alice, bob, ashley];
<add> * $scope.recipient = $scope.recipients[0];
<add> * }]);
<add> * </file>
<add> * </example>
<add> *
<add> * @example
<add> * ## Plural
<add> *
<add> * This example shows how the "plural" keyword is used to account for a variable number of entities.
<add> * The "#" variable holds the current number and can be embedded in the message.
<add> *
<add> * Note that "=1" takes precedence over "one".
<add> *
<add> * The example also shows the "offset" keyword, which allows you to offset the value of the "#" variable.
<add> *
<add> * <example name="ngMessageFormat-example-plural" module="msgFmtExample" deps="angular-message-format.min.js">
<ide> * <file name="index.html">
<ide> * <div ng-controller="AppController">
<del> * <button ng-click="decreaseRecipients()" id="decreaseRecipients">decreaseRecipients</button><br>
<del> * <span>{{recipients.length, plural, offset:1
<add> Select recipients:<br>
<add> <select multiple size=5 ng-model="recipients" ng-options="person as person.name for person in people">
<add> </select><br>
<add> * <p>{{recipients.length, plural, offset:1
<ide> * =0 {{{sender.name}} gave no gifts (\#=#)}
<del> * =1 {{{sender.name}} gave one gift to {{recipients[0].name}} (\#=#)}
<add> * =1 {{{sender.name}} gave a gift to {{recipients[0].name}} (\#=#)}
<ide> * one {{{sender.name}} gave {{recipients[0].name}} and one other person a gift (\#=#)}
<ide> * other {{{sender.name}} gave {{recipients[0].name}} and # other people a gift (\#=#)}
<del> * }}</span>
<add> * }}</p>
<ide> * </div>
<ide> * </file>
<ide> *
<ide> *
<ide> * var alice = new Person("Alice", "female"),
<ide> * bob = new Person("Bob", "male"),
<del> * charlie = new Person("Charlie", "male"),
<del> * harry = new Person("Harry Potter", "male");
<add> * sarah = new Person("Sarah", "female"),
<add> * harry = new Person("Harry Potter", "male"),
<add> * ashley = new Person("Ashley", "");
<ide> *
<ide> * angular.module('msgFmtExample', ['ngMessageFormat'])
<ide> * .controller('AppController', ['$scope', function($scope) {
<del> * $scope.recipients = [alice, bob, charlie];
<add> * $scope.people = [alice, bob, sarah, ashley];
<add> * $scope.recipients = [alice, bob, sarah];
<ide> * $scope.sender = harry;
<del> * $scope.decreaseRecipients = function() {
<del> * --$scope.recipients.length;
<del> * };
<ide> * }]);
<ide> * </file>
<ide> *
<ide> * <file name="protractor.js" type="protractor">
<ide> * describe('MessageFormat plural', function() {
<add> * function clickOptionCtrl(select, index) {
<add> * element.all(by.css('select option')).then(function(arr) {
<add> browser.actions()
<add> .mouseMove(arr[index])
<add> .keyDown(protractor.Key.CONTROL)
<add> .click()
<add> .keyUp(protractor.Key.CONTROL)
<add> .perform();
<add> });
<add> * }
<add> *
<ide> * it('should pluralize initial values', function() {
<del> * var messageElem = element(by.binding('recipients.length')), decreaseRecipientsBtn = element(by.id('decreaseRecipients'));
<add> * var messageElem = element(by.binding('recipients.length')),
<add> * select = element(by.css('select'));
<add> *
<ide> * expect(messageElem.getText()).toEqual('Harry Potter gave Alice and 2 other people a gift (#=2)');
<del> * decreaseRecipientsBtn.click();
<add> clickOptionCtrl(select, 2);
<ide> * expect(messageElem.getText()).toEqual('Harry Potter gave Alice and one other person a gift (#=1)');
<del> * decreaseRecipientsBtn.click();
<del> * expect(messageElem.getText()).toEqual('Harry Potter gave one gift to Alice (#=0)');
<del> * decreaseRecipientsBtn.click();
<add> clickOptionCtrl(select, 1);
<add> * expect(messageElem.getText()).toEqual('Harry Potter gave a gift to Alice (#=0)');
<add> clickOptionCtrl(select, 0);
<ide> * expect(messageElem.getText()).toEqual('Harry Potter gave no gifts (#=-1)');
<ide> * });
<ide> * });
<ide> * </file>
<ide> * </example>
<add> *
<add> * @example
<add> * ## Plural and Gender
<add> *
<add> * This example shows how you can specify gender rules for specific plural matches - in this case,
<add> * =1 is special cased for gender.
<add> * <example name="ngMessageFormat-example-plural-gender" module="msgFmtExample" deps="angular-message-format.min.js">
<add> * <file name="index.html">
<add> * <div ng-controller="AppController">
<add> Select recipients:<br>
<add> <select multiple size=5 ng-model="recipients" ng-options="person as person.name for person in people">
<add> </select><br>
<add> <p>{{recipients.length, plural,
<add> =0 {{{sender.name}} has not given any gifts to anyone.}
<add> =1 { {{recipients[0].gender, select,
<add> female { {{sender.name}} gave {{recipients[0].name}} her gift.}
<add> male { {{sender.name}} gave {{recipients[0].name}} his gift.}
<add> other { {{sender.name}} gave {{recipients[0].name}} their gift.}
<add> }}
<add> }
<add> other {{{sender.name}} gave {{recipients.length}} people gifts.}
<add> }}</p>
<add> </file>
<add> * <file name="script.js">
<add> * function Person(name, gender) {
<add> * this.name = name;
<add> * this.gender = gender;
<add> * }
<add> *
<add> * var alice = new Person("Alice", "female"),
<add> * bob = new Person("Bob", "male"),
<add> * harry = new Person("Harry Potter", "male"),
<add> * ashley = new Person("Ashley", "");
<add> *
<add> * angular.module('msgFmtExample', ['ngMessageFormat'])
<add> * .controller('AppController', ['$scope', function($scope) {
<add> * $scope.people = [alice, bob, ashley];
<add> * $scope.recipients = [alice];
<add> * $scope.sender = harry;
<add> * }]);
<add> * </file>
<add> </example>
<ide> */
<ide> var $$MessageFormatFactory = ['$parse', '$locale', '$sce', '$exceptionHandler', function $$messageFormat(
<ide> $parse, $locale, $sce, $exceptionHandler) { | 1 |
Ruby | Ruby | add guard to broadcast | 711d232f9344173d6a3f63d5239fe9a41f10e9bc | <ide><path>actioncable/lib/action_cable/subscription_adapter/subscriber_map.rb
<ide> def remove_subscriber(channel, subscriber)
<ide> end
<ide>
<ide> def broadcast(channel, message)
<del> list = @sync.synchronize { @subscribers[channel].dup }
<add> list = @sync.synchronize do
<add> return if !@subscribers.key?(channel)
<add> @subscribers[channel].dup
<add> end
<add>
<ide> list.each do |subscriber|
<ide> invoke_callback(subscriber, message)
<ide> end
<ide><path>actioncable/test/subscription_adapter/subscriber_map_test.rb
<add>require 'test_helper'
<add>
<add>class SubscriberMapTest < ActionCable::TestCase
<add> test "broadcast should not change subscribers" do
<add> setup_subscription_map
<add> origin = @subscription_map.instance_variable_get(:@subscribers).dup
<add>
<add> @subscription_map.broadcast('not_exist_channel', '')
<add>
<add> assert_equal origin, @subscription_map.instance_variable_get(:@subscribers)
<add> end
<add>
<add> private
<add> def setup_subscription_map
<add> @subscription_map = ActionCable::SubscriptionAdapter::SubscriberMap.new
<add> end
<add>end | 2 |
Ruby | Ruby | exclude order by clause for exists? | 24ac36be7150f97ac0a61cf7cbe7d212097ef1a6 | <ide><path>activerecord/lib/active_record/relation/finder_methods.rb
<ide> def find_with_associations
<ide> end
<ide>
<ide> def construct_relation_for_exists(relation, conditions)
<del> relation = relation.except(:select, :distinct)._select!(ONE_AS_ONE).limit!(1)
<add> relation = relation.except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1)
<ide>
<ide> case conditions
<ide> when Array, Hash
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_exists_with_order_and_distinct
<ide> assert_equal true, Topic.order(:id).distinct.exists?
<ide> end
<ide>
<add> # Ensure +exists?+ runs without an error by excluding order value.
<add> def test_exists_with_order
<add> assert_equal true, Topic.order("invalid sql here").exists?
<add> end
<add>
<ide> def test_exists_with_joins
<ide> assert_equal true, Topic.joins(:replies).where(replies_topics: { approved: true }).order("replies_topics.created_at DESC").exists?
<ide> end | 2 |
Javascript | Javascript | implement meridiemparse and ispm in russian | 1c86ed64f45c231a708be658fbfb3bc68a71af3c | <ide><path>lang/ru.js
<ide> yy : relativeTimeWithPlural
<ide> },
<ide>
<del> // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason
<add> meridiemParse: /ночи|утра|дня|вечера/i,
<add> isPM : function (input) {
<add> return /^(дня|вечера)$/.test(input);
<add> },
<ide>
<ide> meridiem : function (hour, minute, isLower) {
<ide> if (hour < 4) { | 1 |
Javascript | Javascript | fix a markdown format typo | 29c8d46ea1c9b9d14a7f334b9c51fb219e614059 | <ide><path>Libraries/vendor/react/browser/eventPlugins/PanResponder.js
<ide> var PanResponder = {
<ide> * - `onPanResponderMove: (e, gestureState) => {...}`
<ide> * - `onPanResponderTerminate: (e, gestureState) => {...}`
<ide> * - `onPanResponderTerminationRequest: (e, gestureState) => {...}`
<del> * - 'onShouldBlockNativeResponder: (e, gestureState) => {...}'
<add> * - `onShouldBlockNativeResponder: (e, gestureState) => {...}`
<ide> *
<ide> * In general, for events that have capture equivalents, we update the
<ide> * gestureState once in the capture phase and can use it in the bubble phase | 1 |
PHP | PHP | apply fixes from styleci | 4861b82bd1395fdcddd2fab1ae728c05ba2aba55 | <ide><path>src/Illuminate/Foundation/Providers/FoundationServiceProvider.php
<ide>
<ide> namespace Illuminate\Foundation\Providers;
<ide>
<del>use Illuminate\Support\Str;
<ide> use Illuminate\Http\Request;
<ide> use Illuminate\Support\Facades\URL;
<ide> use Illuminate\Support\AggregateServiceProvider; | 1 |
Go | Go | add progressbar and time | ebc36b879d4197a9455b325b529da212539e180c | <ide><path>utils/jsonmessage.go
<ide> import (
<ide> "encoding/json"
<ide> "fmt"
<ide> "io"
<add> "strings"
<ide> "time"
<ide> )
<ide>
<ide> func (e *JSONError) Error() string {
<ide> }
<ide>
<ide> type JSONProgress struct {
<del> Current int `json:"current,omitempty"`
<del> Total int `json:"total,omitempty"`
<add> Current int `json:"current,omitempty"`
<add> Total int `json:"total,omitempty"`
<add> Start int64 `json:"start,omitempty"`
<ide> }
<ide>
<ide> func (p *JSONProgress) String() string {
<ide> func (p *JSONProgress) String() string {
<ide> return fmt.Sprintf("%8v/?", current)
<ide> }
<ide> total := HumanSize(int64(p.Total))
<del> percentage := float64(p.Current) / float64(p.Total) * 100
<del> return fmt.Sprintf("%8v/%v (%.0f%%)", current, total, percentage)
<add> percentage := int(float64(p.Current)/float64(p.Total)*100) / 2
<add>
<add> fromStart := time.Now().UTC().Sub(time.Unix(int64(p.Start), 0))
<add> perEntry := fromStart / time.Duration(p.Current)
<add> left := time.Duration(p.Total-p.Current) * perEntry
<add> left = (left / time.Second) * time.Second
<add> return fmt.Sprintf("[%s>%s] %8v/%v %s", strings.Repeat("=", percentage), strings.Repeat(" ", 50-percentage), current, total, left.String())
<ide> }
<ide>
<ide> type JSONMessage struct {
<ide><path>utils/progressreader.go
<ide> package utils
<ide>
<ide> import (
<ide> "io"
<add> "time"
<ide> )
<ide>
<ide> // Reader with progress bar
<ide> func ProgressReader(r io.ReadCloser, size int, output io.Writer, sf *StreamForma
<ide> output: NewWriteFlusher(output),
<ide> ID: ID,
<ide> action: action,
<del> progress: JSONProgress{Total: size},
<add> progress: JSONProgress{Total: size, Start: time.Now().UTC().Unix()},
<ide> sf: sf,
<ide> newLine: newline,
<ide> } | 2 |
Javascript | Javascript | fix relative path | 822e0af79af5a8fbc20fc0347fac2090719351bd | <ide><path>index.js
<ide> var fs = require("fs"),
<add> path = require("path"),
<ide> document = require("jsdom").jsdom("<html><head></head><body></body></html>"),
<ide> window = document.createWindow();
<ide>
<ide> CSSStyleDeclaration_prototype.setProperty = function(name, value, priority) {
<ide> };
<ide>
<ide> module.exports = (new Function("window", "document",
<del> "return " + fs.readFileSync("./d3.js", "utf-8"))
<add> "return " + fs.readFileSync(path.join(__dirname, "d3.js"), "utf-8"))
<ide> )(window, document); | 1 |
Javascript | Javascript | remove unneeded comma in list.js | e496dd255b259a256d89100f731632b9d04fe4e1 | <ide><path>docs/list.js
<ide> var list = {
<ide> [ "Loader", "api/loaders/Loader" ],
<ide> [ "MaterialLoader", "api/loaders/MaterialLoader" ],
<ide> [ "ObjectLoader", "api/loaders/ObjectLoader" ],
<del> [ "TextureLoader", "api/loaders/TextureLoader" ],
<add> [ "TextureLoader", "api/loaders/TextureLoader" ]
<ide> ],
<ide>
<ide> "Loaders / Managers": [
<ide> var list = {
<ide> [ "CanvasRenderer", "examples/renderers/CanvasRenderer" ]
<ide> ]
<ide>
<del> },
<add> }
<ide>
<ide> };
<ide> | 1 |
Text | Text | remove stray comma in url.md | 77364b04565415fddad38a66347aa1c231c0b949 | <ide><path>doc/api/url.md
<ide> myURL.hostname = 'example.com:82';
<ide> console.log(myURL.href);
<ide> // Prints https://example.com:81/foo
<ide>
<del>// Use, myURL.host to change the hostname and port
<add>// Use myURL.host to change the hostname and port
<ide> myURL.host = 'example.org:82';
<ide> console.log(myURL.href);
<ide> // Prints https://example.org:82/foo | 1 |
PHP | PHP | add support for checking checkboxes | 770bc7c471ab367168bb29462c89cc2ff1ee59f6 | <ide><path>src/View/Input/MultiCheckbox.php
<ide> public function render($data) {
<ide> $checkbox['escape'] = $data['escape'];
<ide>
<ide> if ($this->_isSelected($key, $data['val'])) {
<del> $checkbox['selected'] = true;
<add> $checkbox['checked'] = true;
<ide> }
<ide> if ($this->_isDisabled($key, $data['disabled'])) {
<ide> $checkbox['disabled'] = true;
<ide><path>tests/TestCase/View/Input/MultiCheckboxTest.php
<ide> public function testRenderComplex() {
<ide> * @return void
<ide> */
<ide> public function testRenderSelected() {
<del> $this->markTestIncomplete();
<add> $input = new MultiCheckbox($this->templates);
<add> $data = [
<add> 'name' => 'Tags[id]',
<add> 'options' => [
<add> 1 => 'CakePHP',
<add> '1x' => 'Development',
<add> ],
<add> 'val' => [1]
<add> ];
<add> $result = $input->render($data);
<add> $expected = [
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => 1,
<add> 'id' => 'tags-id-1',
<add> 'checked' => 'checked'
<add> ]],
<add> ['label' => ['for' => 'tags-id-1']],
<add> 'CakePHP',
<add> '/label',
<add> '/div',
<add> ['div' => ['class' => 'checkbox']],
<add> ['input' => [
<add> 'type' => 'checkbox',
<add> 'name' => 'Tags[id][]',
<add> 'value' => '1x',
<add> 'id' => 'tags-id-1x',
<add> ]],
<add> ['label' => ['for' => 'tags-id-1x']],
<add> 'Development',
<add> '/label',
<add> '/div',
<add> ];
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = 1;
<add> $result = $input->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = '1';
<add> $result = $input->render($data);
<add> $this->assertTags($result, $expected);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | emit ipc messages on next tick | 87d682b69a2ed1d6b74215ee8fbf9af9d6674ee9 | <ide><path>lib/internal/child_process.js
<ide> function setupChannel(target, channel) {
<ide> }
<ide> chunks[0] = jsonBuffer + chunks[0];
<ide>
<del> var nextTick = false;
<ide> for (var i = 0; i < numCompleteChunks; i++) {
<ide> var message = JSON.parse(chunks[i]);
<ide>
<ide> function setupChannel(target, channel) {
<ide> // that we deliver the handle with the right message however.
<ide> if (isInternal(message)) {
<ide> if (message.cmd === 'NODE_HANDLE')
<del> handleMessage(message, recvHandle, true, false);
<add> handleMessage(message, recvHandle, true);
<ide> else
<del> handleMessage(message, undefined, true, false);
<add> handleMessage(message, undefined, true);
<ide> } else {
<del> handleMessage(message, undefined, false, nextTick);
<del> nextTick = true;
<add> handleMessage(message, undefined, false);
<ide> }
<ide> }
<ide> jsonBuffer = incompleteChunk;
<ide> function setupChannel(target, channel) {
<ide>
<ide> // Convert handle object
<ide> obj.got.call(this, message, handle, function(handle) {
<del> handleMessage(message.msg, handle, isInternal(message.msg), false);
<add> handleMessage(message.msg, handle, isInternal(message.msg));
<ide> });
<ide> });
<ide>
<ide> function setupChannel(target, channel) {
<ide> target.emit(event, message, handle);
<ide> }
<ide>
<del> function handleMessage(message, handle, internal, nextTick) {
<add> function handleMessage(message, handle, internal) {
<ide> if (!target.channel)
<ide> return;
<ide>
<ide> var eventName = (internal ? 'internalMessage' : 'message');
<del> if (nextTick)
<del> process.nextTick(emit, eventName, message, handle);
<del> else
<del> target.emit(eventName, message, handle);
<add>
<add> process.nextTick(emit, eventName, message, handle);
<ide> }
<ide>
<ide> channel.readStart();
<ide><path>test/parallel/test-child-process-ipc-next-tick.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const cp = require('child_process');
<add>const NUM_MESSAGES = 10;
<add>const values = [];
<add>
<add>for (let i = 0; i < NUM_MESSAGES; ++i) {
<add> values[i] = i;
<add>}
<add>
<add>if (process.argv[2] === 'child') {
<add> const received = values.map(() => { return false; });
<add>
<add> process.on('uncaughtException', common.mustCall((err) => {
<add> received[err] = true;
<add> const done = received.every((element) => { return element === true; });
<add>
<add> if (done)
<add> process.disconnect();
<add> }, NUM_MESSAGES));
<add>
<add> process.on('message', (msg) => {
<add> // If messages are handled synchronously, throwing should break the IPC
<add> // message processing.
<add> throw msg;
<add> });
<add>
<add> process.send('ready');
<add>} else {
<add> const child = cp.fork(__filename, ['child']);
<add>
<add> child.on('message', common.mustCall((msg) => {
<add> assert.strictEqual(msg, 'ready');
<add> values.forEach((value) => {
<add> child.send(value);
<add> });
<add> }));
<add>} | 2 |
Javascript | Javascript | replace `sanity` language in combinereducers | 7e745ce543baecb835173220e7bb51f17b19c875 | <ide><path>src/combineReducers.js
<ide> function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, une
<ide> }
<ide> }
<ide>
<del>function assertReducerSanity(reducers) {
<add>function assertReducerShape(reducers) {
<ide> Object.keys(reducers).forEach(key => {
<ide> const reducer = reducers[key]
<ide> const initialState = reducer(undefined, { type: ActionTypes.INIT })
<ide> export default function combineReducers(reducers) {
<ide> unexpectedKeyCache = {}
<ide> }
<ide>
<del> let sanityError
<add> let shapeAssertionError
<ide> try {
<del> assertReducerSanity(finalReducers)
<add> assertReducerShape(finalReducers)
<ide> } catch (e) {
<del> sanityError = e
<add> shapeAssertionError = e
<ide> }
<ide>
<ide> return function combination(state = {}, action) {
<del> if (sanityError) {
<del> throw sanityError
<add> if (shapeAssertionError) {
<add> throw shapeAssertionError
<ide> }
<ide>
<ide> if (process.env.NODE_ENV !== 'production') { | 1 |
Javascript | Javascript | eliminate multicast test freebsd flakiness | b3313aa6039dd20034206f755bee88d06022514e | <ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> 'use strict';
<del>var common = require('../common'),
<del> assert = require('assert'),
<del> dgram = require('dgram'),
<del> util = require('util'),
<del> Buffer = require('buffer').Buffer,
<del> fork = require('child_process').fork,
<del> LOCAL_BROADCAST_HOST = '224.0.0.114',
<del> TIMEOUT = common.platformTimeout(5000),
<del> messages = [
<del> new Buffer('First message to send'),
<del> new Buffer('Second message to send'),
<del> new Buffer('Third message to send'),
<del> new Buffer('Fourth message to send')
<del> ];
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const dgram = require('dgram');
<add>const fork = require('child_process').fork;
<add>const LOCAL_BROADCAST_HOST = '224.0.0.114';
<add>const TIMEOUT = common.platformTimeout(5000);
<add>const messages = [
<add> new Buffer('First message to send'),
<add> new Buffer('Second message to send'),
<add> new Buffer('Third message to send'),
<add> new Buffer('Fourth message to send')
<add>];
<add>const workers = {};
<add>const listeners = 3;
<add>
<add>
<add>// Skip test in FreeBSD jails.
<add>if (common.inFreeBSDJail) {
<add> console.log('1..0 # Skipped: In a FreeBSD jail');
<add> return;
<add>}
<add>
<add>function launchChildProcess(index) {
<add> const worker = fork(__filename, ['child']);
<add> workers[worker.pid] = worker;
<add>
<add> worker.messagesReceived = [];
<add>
<add> // Handle the death of workers.
<add> worker.on('exit', function(code, signal) {
<add> // Don't consider this the true death if the worker has finished
<add> // successfully or if the exit code is 0.
<add> if (worker.isDone || code === 0) {
<add> return;
<add> }
<add>
<add> dead += 1;
<add> console.error('[PARENT] Worker %d died. %d dead of %d',
<add> worker.pid,
<add> dead,
<add> listeners);
<add>
<add> if (dead === listeners) {
<add> console.error('[PARENT] All workers have died.');
<add> console.error('[PARENT] Fail');
<add> process.exit(1);
<add> }
<add> });
<add>
<add> worker.on('message', function(msg) {
<add> if (msg.listening) {
<add> listening += 1;
<add>
<add> if (listening === listeners) {
<add> // All child process are listening, so start sending.
<add> sendSocket.sendNext();
<add> }
<add> return;
<add> }
<add> if (msg.message) {
<add> worker.messagesReceived.push(msg.message);
<add>
<add> if (worker.messagesReceived.length === messages.length) {
<add> done += 1;
<add> worker.isDone = true;
<add> console.error('[PARENT] %d received %d messages total.',
<add> worker.pid,
<add> worker.messagesReceived.length);
<add> }
<add>
<add> if (done === listeners) {
<add> console.error('[PARENT] All workers have received the ' +
<add> 'required number of messages. Will now compare.');
<add>
<add> Object.keys(workers).forEach(function(pid) {
<add> const worker = workers[pid];
<add>
<add> var count = 0;
<add>
<add> worker.messagesReceived.forEach(function(buf) {
<add> for (var i = 0; i < messages.length; ++i) {
<add> if (buf.toString() === messages[i].toString()) {
<add> count++;
<add> break;
<add> }
<add> }
<add> });
<add>
<add> console.error('[PARENT] %d received %d matching messages.',
<add> worker.pid, count);
<add>
<add> assert.strictEqual(count, messages.length,
<add> 'A worker received an invalid multicast message');
<add> });
<add>
<add> clearTimeout(timer);
<add> console.error('[PARENT] Success');
<add> killChildren(workers);
<add> }
<add> }
<add> });
<add>}
<add>
<add>function killChildren(children) {
<add> Object.keys(children).forEach(function(key) {
<add> const child = children[key];
<add> child.kill();
<add> });
<add>}
<ide>
<ide> if (process.argv[2] !== 'child') {
<del> var workers = {},
<del> listeners = 3,
<del> listening = 0,
<del> dead = 0,
<del> i = 0,
<del> done = 0,
<del> timer = null;
<del>
<del> //exit the test if it doesn't succeed within TIMEOUT
<del> timer = setTimeout(function() {
<add> var listening = 0;
<add> var dead = 0;
<add> var i = 0;
<add> var done = 0;
<add>
<add> // Exit the test if it doesn't succeed within TIMEOUT.
<add> var timer = setTimeout(function() {
<ide> console.error('[PARENT] Responses were not received within %d ms.',
<ide> TIMEOUT);
<ide> console.error('[PARENT] Fail');
<ide> if (process.argv[2] !== 'child') {
<ide> process.exit(1);
<ide> }, TIMEOUT);
<ide>
<del> //launch child processes
<add> // Launch child processes.
<ide> for (var x = 0; x < listeners; x++) {
<del> (function() {
<del> var worker = fork(process.argv[1], ['child']);
<del> workers[worker.pid] = worker;
<del>
<del> worker.messagesReceived = [];
<del>
<del> //handle the death of workers
<del> worker.on('exit', function(code, signal) {
<del> // don't consider this the true death if the
<del> // worker has finished successfully
<del>
<del> // or if the exit code is 0
<del> if (worker.isDone || code === 0) {
<del> return;
<del> }
<del>
<del> dead += 1;
<del> console.error('[PARENT] Worker %d died. %d dead of %d',
<del> worker.pid,
<del> dead,
<del> listeners);
<del>
<del> if (dead === listeners) {
<del> console.error('[PARENT] All workers have died.');
<del> console.error('[PARENT] Fail');
<del>
<del> killChildren(workers);
<del>
<del> process.exit(1);
<del> }
<del> });
<del>
<del> worker.on('message', function(msg) {
<del> if (msg.listening) {
<del> listening += 1;
<del>
<del> if (listening === listeners) {
<del> //all child process are listening, so start sending
<del> sendSocket.sendNext();
<del> }
<del> }
<del> else if (msg.message) {
<del> worker.messagesReceived.push(msg.message);
<del>
<del> if (worker.messagesReceived.length === messages.length) {
<del> done += 1;
<del> worker.isDone = true;
<del> console.error('[PARENT] %d received %d messages total.',
<del> worker.pid,
<del> worker.messagesReceived.length);
<del> }
<del>
<del> if (done === listeners) {
<del> console.error('[PARENT] All workers have received the ' +
<del> 'required number of messages. Will now compare.');
<del>
<del> Object.keys(workers).forEach(function(pid) {
<del> var worker = workers[pid];
<del>
<del> var count = 0;
<del>
<del> worker.messagesReceived.forEach(function(buf) {
<del> for (var i = 0; i < messages.length; ++i) {
<del> if (buf.toString() === messages[i].toString()) {
<del> count++;
<del> break;
<del> }
<del> }
<del> });
<del>
<del> console.error('[PARENT] %d received %d matching messages.',
<del> worker.pid, count);
<del>
<del> assert.equal(count, messages.length,
<del> 'A worker received an invalid multicast message');
<del> });
<del>
<del> clearTimeout(timer);
<del> console.error('[PARENT] Success');
<del> killChildren(workers);
<del> }
<del> }
<del> });
<del> })(x);
<add> launchChildProcess(x);
<ide> }
<ide>
<ide> var sendSocket = dgram.createSocket('udp4');
<del> // FIXME a libuv limitation makes it necessary to bind()
<del> // before calling any of the set*() functions - the bind()
<del> // call is what creates the actual socket...
<add> // FIXME: a libuv limitation makes it necessary to bind()
<add> // before calling any of the set*() functions. The bind()
<add> // call is what creates the actual socket.
<ide> sendSocket.bind();
<ide>
<del> // The socket is actually created async now
<add> // The socket is actually created async now.
<ide> sendSocket.on('listening', function() {
<ide> sendSocket.setTTL(1);
<ide> sendSocket.setBroadcast(true);
<ide> if (process.argv[2] !== 'child') {
<ide> });
<ide>
<ide> sendSocket.sendNext = function() {
<del> var buf = messages[i++];
<add> const buf = messages[i++];
<ide>
<ide> if (!buf) {
<ide> try { sendSocket.close(); } catch (e) {}
<ide> if (process.argv[2] !== 'child') {
<ide> sendSocket.send(buf, 0, buf.length,
<ide> common.PORT, LOCAL_BROADCAST_HOST, function(err) {
<ide> if (err) throw err;
<del> console.error('[PARENT] sent %s to %s:%s',
<del> util.inspect(buf.toString()),
<add> console.error('[PARENT] sent "%s" to %s:%s',
<add> buf.toString(),
<ide> LOCAL_BROADCAST_HOST, common.PORT);
<ide> process.nextTick(sendSocket.sendNext);
<ide> });
<ide> };
<del>
<del> function killChildren(children) {
<del> Object.keys(children).forEach(function(key) {
<del> var child = children[key];
<del> child.kill();
<del> });
<del> }
<ide> }
<ide>
<ide> if (process.argv[2] === 'child') {
<del> var receivedMessages = [];
<del> var listenSocket = dgram.createSocket({
<add> const receivedMessages = [];
<add> const listenSocket = dgram.createSocket({
<ide> type: 'udp4',
<ide> reuseAddr: true
<ide> });
<ide>
<del> listenSocket.on('message', function(buf, rinfo) {
<del> console.error('[CHILD] %s received %s from %j', process.pid,
<del> util.inspect(buf.toString()), rinfo);
<add> listenSocket.on('listening', function() {
<add> listenSocket.addMembership(LOCAL_BROADCAST_HOST);
<ide>
<del> receivedMessages.push(buf);
<add> listenSocket.on('message', function(buf, rinfo) {
<add> console.error('[CHILD] %s received "%s" from %j', process.pid,
<add> buf.toString(), rinfo);
<ide>
<del> process.send({ message: buf.toString() });
<add> receivedMessages.push(buf);
<ide>
<del> if (receivedMessages.length == messages.length) {
<del> // .dropMembership() not strictly needed but here as a sanity check
<del> listenSocket.dropMembership(LOCAL_BROADCAST_HOST);
<del> process.nextTick(function() {
<del> listenSocket.close();
<del> });
<del> }
<del> });
<add> process.send({ message: buf.toString() });
<ide>
<del> listenSocket.on('close', function() {
<del> //HACK: Wait to exit the process to ensure that the parent
<del> //process has had time to receive all messages via process.send()
<del> //This may be indicitave of some other issue.
<del> setTimeout(function() {
<del> process.exit();
<del> }, 1000);
<del> });
<add> if (receivedMessages.length == messages.length) {
<add> // .dropMembership() not strictly needed but here as a sanity check.
<add> listenSocket.dropMembership(LOCAL_BROADCAST_HOST);
<add> process.nextTick(function() {
<add> listenSocket.close();
<add> });
<add> }
<add> });
<ide>
<del> listenSocket.on('listening', function() {
<add> listenSocket.on('close', function() {
<add> // HACK: Wait to exit the process to ensure that the parent
<add> // process has had time to receive all messages via process.send()
<add> // This may be indicative of some other issue.
<add> setTimeout(function() {
<add> process.exit();
<add> }, common.platformTimeout(1000));
<add> });
<ide> process.send({ listening: true });
<ide> });
<ide>
<ide> listenSocket.bind(common.PORT);
<del>
<del> listenSocket.on('listening', function() {
<del> listenSocket.addMembership(LOCAL_BROADCAST_HOST);
<del> });
<ide> } | 1 |
PHP | PHP | remove ref to jshelper | bd0d13cb23ead62d28d1405fe169c1d7dd533de5 | <ide><path>src/Controller/Controller.php
<ide> class Controller implements EventListener {
<ide> * An array containing the names of helpers this controller uses. The array elements should
<ide> * not contain the "Helper" part of the class name.
<ide> *
<del> * Example: `public $helpers = array('Html', 'Js', 'Time', 'Ajax');`
<add> * Example: `public $helpers = ['Form', 'Html', 'Time'];`
<ide> *
<ide> * @var mixed
<ide> * @link http://book.cakephp.org/2.0/en/controllers.html#components-helpers-and-uses | 1 |
Text | Text | add returned values and options to stream.md | a2c0fcc0d8bc9bd4559089f1182b13a2ae7bb318 | <ide><path>doc/api/stream.md
<ide> added: v0.9.4
<ide> * `destination` {stream.Writable} The destination for writing data
<ide> * `options` {Object} Pipe options
<ide> * `end` {boolean} End the writer when the reader ends. Defaults to `true`.
<add>* Returns: {stream.Writable} making it possible to set up chains of piped
<add> streams
<ide>
<ide> The `readable.pipe()` method attaches a [Writable][] stream to the `readable`,
<ide> causing it to switch automatically into flowing mode and push all of its data
<ide> closed until the Node.js process exits, regardless of the specified options.
<ide> added: v9.3.0
<ide> -->
<ide>
<del>Return the value of `highWaterMark` passed when constructing this
<add>* Returns: {number}
<add>
<add>Returns the value of `highWaterMark` passed when constructing this
<ide> `Readable`.
<ide>
<ide> ##### readable.read([size])
<ide> added: v0.9.4
<ide> -->
<ide>
<ide> * `size` {number} Optional argument to specify how much data to read.
<del>* Return {string|Buffer|null}
<add>* Returns: {string|Buffer|null}
<ide>
<ide> The `readable.read()` method pulls some data out of the internal buffer and
<ide> returns it. If no data available to be read, `null` is returned. By default,
<ide> been emitted will return `null`. No runtime error will be raised.
<ide> added: v9.4.0
<ide> -->
<ide>
<add>* Returns: {number}
<add>
<ide> This property contains the number of bytes (or objects) in the queue
<ide> ready to be read. The value provides introspection data regarding
<ide> the status of the `highWaterMark`.
<ide> added: v0.9.4
<ide> -->
<ide>
<ide> * `destination` {stream.Writable} Optional specific stream to unpipe
<add>* Returns: {this}
<ide>
<ide> The `readable.unpipe()` method detaches a Writable stream previously attached
<ide> using the [`stream.pipe()`][] method.
<ide> added: v0.9.4
<ide> -->
<ide>
<ide> * `stream` {Stream} An "old style" readable stream
<add>* Returns: {this}
<ide>
<ide> Versions of Node.js prior to v0.10 had streams that did not implement the
<ide> entire `stream` module API as it is currently defined. (See [Compatibility][]
<ide> myReader.on('readable', () => {
<ide> added: v8.0.0
<ide> -->
<ide>
<add>* `error` {Error} Error which will be passed as payload in `'error'` event
<add>* Returns: {this}
<add>
<ide> Destroy the stream, and emit `'error'` and `close`. After this call, the
<ide> readable stream will release any internal resources and subsequent calls
<ide> to `push` will be ignored. | 1 |
Text | Text | fix some translate error | 1859bc2eabfb2caa44d585ffaa0d78f4feb0d40f | <ide><path>guide/chinese/javascript/es6/let-and-const/index.md
<ide> ---
<ide> title: Let and Const
<del>localeTitle: 让和Const
<add>localeTitle: let 和 const
<ide> ---
<del>## 让
<add>## let
<ide>
<del>let类似于var但是有范围。 let只能在定义的块级别中访问。
<add>let类似于var,但是let有作用域。 let只能在定义的块级作用域中访问。
<ide> ```
<ide> if (true) {
<ide> let a = 40;
<ide> let a = 50;
<ide> console.log(a); // 50
<ide> ```
<ide>
<del>## 常量
<add>## const
<ide>
<del>Const用于为变量赋值常量。价值无法改变。这是固定的。
<add>const声明一个常量。常量的值不能修改。
<ide> ```
<ide> const a = 50;
<ide> a = 60; // shows error. You cannot change the value of const.
<ide> const b = "Constant variable";
<ide> b = "Assigning new value"; // shows error.
<ide> ```
<ide>
<del>考虑另一个例子。
<add>看另一个例子。
<ide> ```
<ide> const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];
<ide> LANGUAGES = "Javascript"; // shows error.
<ide> LANGUAGES.push('Java'); // Works fine.
<ide> console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']
<ide> ```
<ide>
<del>这可能有点混乱。
<add>可能会有点迷惑。
<ide>
<del>以这种方式考虑。无论何时定义const变量,Javascript都会将值的地址引用给变量。在我们的示例中,变量'LANGUAGES'实际上引用了分配给数组的内存。因此,您无法在以后更改变量以引用其他内存位置。在整个程序中它只引用数组。
<ide>\ No newline at end of file
<add>换一种方式想。无论何时定义const变量,Javascript都会将值的地址引用给变量。在我们的示例中,变量'LANGUAGES'实际上引用了分配给数组的内存。因此,您无法更改变量以引用其他内存位置。在整个程序中它只引用数组。 | 1 |
Java | Java | update documentation todos | 0bb24f2922c57e6ba8869a2a443044c3670e1fba | <ide><path>spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericWebContextLoader.java
<ide> import org.springframework.web.context.support.GenericWebApplicationContext;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document AbstractGenericWebContextLoader.
<add> * TODO [SPR-9864] Document AbstractGenericWebContextLoader.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide> public abstract class AbstractGenericWebContextLoader extends AbstractContextLoa
<ide> // --- SmartContextLoader -----------------------------------------------
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document overridden loadContext(MergedContextConfiguration).
<add> * TODO [SPR-9864] Document overridden loadContext(MergedContextConfiguration).
<ide> *
<ide> * @see org.springframework.test.context.SmartContextLoader#loadContext(org.springframework.test.context.MergedContextConfiguration)
<ide> */
<ide> public final ConfigurableApplicationContext loadContext(MergedContextConfigurati
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document configureWebResources().
<add> * TODO [SPR-9864] Document configureWebResources().
<ide> */
<ide> protected void configureWebResources(GenericWebApplicationContext context,
<ide> WebMergedContextConfiguration webMergedConfig) {
<ide> protected void configureWebResources(GenericWebApplicationContext context,
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document customizeBeanFactory().
<add> * TODO [SPR-9864] Document customizeBeanFactory().
<ide> */
<ide> protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory,
<ide> WebMergedContextConfiguration webMergedConfig) {
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document loadBeanDefinitions().
<add> * TODO [SPR-9864] Document loadBeanDefinitions().
<ide> */
<ide> protected abstract void loadBeanDefinitions(GenericWebApplicationContext context,
<ide> WebMergedContextConfiguration webMergedConfig);
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document customizeContext().
<add> * TODO [SPR-9864] Document customizeContext().
<ide> */
<ide> protected void customizeContext(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) {
<ide> }
<ide>
<ide> // --- ContextLoader -------------------------------------------------------
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document overridden loadContext(String...).
<add> * TODO [SPR-9864] Document overridden loadContext(String...).
<ide> *
<ide> * @see org.springframework.test.context.ContextLoader#loadContext(java.lang.String[])
<ide> */
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtils.java
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document AnnotationConfigContextLoaderUtils.
<add> * TODO [SPR-9864] Document AnnotationConfigContextLoaderUtils.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigWebContextLoader.java
<ide> import org.springframework.web.context.support.GenericWebApplicationContext;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document AnnotationConfigWebContextLoader.
<add> * TODO [SPR-9864] Document AnnotationConfigWebContextLoader.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/XmlWebContextLoader.java
<ide> import org.springframework.web.context.support.GenericWebApplicationContext;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document XmlWebContextLoader.
<add> * TODO [SPR-9864] Document XmlWebContextLoader.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide> protected String getResourceSuffix() {
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document overridden loadBeanDefinitions().
<add> * TODO [SPR-9864] Document overridden loadBeanDefinitions().
<ide> *
<ide> * @see org.springframework.test.context.support.AbstractGenericWebContextLoader#loadBeanDefinitions(org.springframework.web.context.support.GenericWebApplicationContext, org.springframework.test.context.web.WebMergedContextConfiguration)
<ide> */
<ide><path>spring-test/src/main/java/org/springframework/test/context/web/WebAppConfiguration.java
<ide> import java.lang.annotation.Target;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document WebAppConfiguration.
<add> * TODO [SPR-9864] Document WebAppConfiguration.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide><path>spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document WebMergedContextConfiguration.
<add> * TODO [SPR-9864] Document WebMergedContextConfiguration.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide> public class WebMergedContextConfiguration extends MergedContextConfiguration {
<ide>
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document WebMergedContextConfiguration constructor.
<add> * TODO [SPR-9864] Document WebMergedContextConfiguration constructor.
<ide> */
<ide> public WebMergedContextConfiguration(
<ide> Class<?> testClass,
<ide> public WebMergedContextConfiguration(
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document getResourceBasePath().
<add> * TODO [SPR-9864] Document getResourceBasePath().
<ide> */
<ide> public String getResourceBasePath() {
<ide> return this.resourceBasePath;
<ide><path>spring-test/src/main/java/org/springframework/test/context/web/WebTestExecutionListener.java
<ide> import org.springframework.web.context.request.ServletWebRequest;
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document WebTestExecutionListener.
<add> * TODO [SPR-9864] Document WebTestExecutionListener.
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 3.2
<ide> public class WebTestExecutionListener extends AbstractTestExecutionListener {
<ide>
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document overridden prepareTestInstance().
<add> * TODO [SPR-9864] Document overridden prepareTestInstance().
<ide> *
<ide> * @see org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext)
<ide> */
<ide> public void prepareTestInstance(TestContext testContext) throws Exception {
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document overridden beforeTestMethod().
<add> * TODO [SPR-9864] Document overridden beforeTestMethod().
<ide> *
<ide> * @see org.springframework.test.context.support.AbstractTestExecutionListener#beforeTestMethod(org.springframework.test.context.TestContext)
<ide> */
<ide> public void beforeTestMethod(TestContext testContext) throws Exception {
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document setUpRequestContext().
<add> * TODO [SPR-9864] Document setUpRequestContext().
<ide> *
<ide> * @param testContext
<ide> * @param servletContext
<ide> private void setUpRequestContextIfNecessary(TestContext testContext) {
<ide> }
<ide>
<ide> /**
<del> * TODO [SPR-5243] Document overridden afterTestMethod().
<add> * TODO [SPR-9864] Document overridden afterTestMethod().
<ide> *
<ide> * @see org.springframework.test.context.support.AbstractTestExecutionListener#afterTestMethod(org.springframework.test.context.TestContext)
<ide> */ | 7 |
Text | Text | add v4.0.0-beta.10 to changelog | d320f79978c929c221d8224ec492400d176297e6 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.0.0-beta.10 (November 15, 2021)
<add>
<add>- [#19833](https://github.com/emberjs/ember.js/pull/19833) [CLEANUP] Remove deprecated array observers
<add>- [#19836](https://github.com/emberjs/ember.js/pull/19836) [CLEANUP] Turn `template-only-glimmer-components` deprecation into an error
<add>- [#19843](https://github.com/emberjs/ember.js/pull/19843) [CLEANUP] Turn `argument-less-helper-paren-less-invocation` deprecation into an error
<add>
<ide> ### v4.0.0-beta.9 (November 10, 2021)
<ide>
<ide> - [#19749](https://github.com/emberjs/ember.js/pull/19749) [CLEANUP] Remove `deprecate-router-events` support code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.