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
|
|---|---|---|---|---|---|
Go
|
Go
|
move authconfig to api/types
|
5b321e328769cc93c3454e82ec3fe07672156f2e
|
<ide><path>api/client/client.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/client/lib"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/runconfig"
<ide> type apiClient interface {
<ide> NetworkInspect(networkID string) (types.NetworkResource, error)
<ide> NetworkList() ([]types.NetworkResource, error)
<ide> NetworkRemove(networkID string) error
<del> RegistryLogin(auth cliconfig.AuthConfig) (types.AuthResponse, error)
<add> RegistryLogin(auth types.AuthConfig) (types.AuthResponse, error)
<ide> ServerVersion() (types.Version, error)
<ide> VolumeCreate(options types.VolumeCreateRequest) (types.Volume, error)
<ide> VolumeInspect(volumeID string) (types.Volume, error)
<ide><path>api/client/lib/login.go
<ide> import (
<ide> "net/url"
<ide>
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/cliconfig"
<ide> )
<ide>
<ide> // RegistryLogin authenticates the docker server with a given docker registry.
<ide> // It returns UnauthorizerError when the authentication fails.
<del>func (cli *Client) RegistryLogin(auth cliconfig.AuthConfig) (types.AuthResponse, error) {
<add>func (cli *Client) RegistryLogin(auth types.AuthConfig) (types.AuthResponse, error) {
<ide> resp, err := cli.post("/auth", url.Values{}, auth, nil)
<ide>
<ide> if resp != nil && resp.statusCode == http.StatusUnauthorized {
<ide><path>api/client/login.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/client/lib"
<ide> Cli "github.com/docker/docker/cli"
<del> "github.com/docker/docker/cliconfig"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/term"
<ide> "github.com/docker/docker/registry"
<ide> func (cli *DockerCli) CmdLogin(args ...string) error {
<ide>
<ide> authconfig, ok := cli.configFile.AuthConfigs[serverAddress]
<ide> if !ok {
<del> authconfig = cliconfig.AuthConfig{}
<add> authconfig = types.AuthConfig{}
<ide> }
<ide>
<ide> if username == "" {
<ide><path>api/client/pull.go
<ide> func (cli *DockerCli) CmdPull(args ...string) error {
<ide> return cli.imagePullPrivileged(authConfig, distributionRef.String(), "", requestPrivilege)
<ide> }
<ide>
<del>func (cli *DockerCli) imagePullPrivileged(authConfig cliconfig.AuthConfig, imageID, tag string, requestPrivilege lib.RequestPrivilegeFunc) error {
<add>func (cli *DockerCli) imagePullPrivileged(authConfig types.AuthConfig, imageID, tag string, requestPrivilege lib.RequestPrivilegeFunc) error {
<ide>
<del> encodedAuth, err := authConfig.EncodeToBase64()
<add> encodedAuth, err := cliconfig.EncodeAuthToBase64(authConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>api/client/push.go
<ide> func (cli *DockerCli) CmdPush(args ...string) error {
<ide> return cli.imagePushPrivileged(authConfig, ref.Name(), tag, cli.out, requestPrivilege)
<ide> }
<ide>
<del>func (cli *DockerCli) imagePushPrivileged(authConfig cliconfig.AuthConfig, imageID, tag string, outputStream io.Writer, requestPrivilege lib.RequestPrivilegeFunc) error {
<del> encodedAuth, err := authConfig.EncodeToBase64()
<add>func (cli *DockerCli) imagePushPrivileged(authConfig types.AuthConfig, imageID, tag string, outputStream io.Writer, requestPrivilege lib.RequestPrivilegeFunc) error {
<add> encodedAuth, err := cliconfig.EncodeAuthToBase64(authConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>api/client/search.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> Cli "github.com/docker/docker/cli"
<add> "github.com/docker/docker/cliconfig"
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/docker/docker/registry"
<ide> func (cli *DockerCli) CmdSearch(args ...string) error {
<ide> authConfig := registry.ResolveAuthConfig(cli.configFile.AuthConfigs, indexInfo)
<ide> requestPrivilege := cli.registryAuthenticationPrivilegedFunc(indexInfo, "search")
<ide>
<del> encodedAuth, err := authConfig.EncodeToBase64()
<add> encodedAuth, err := cliconfig.EncodeAuthToBase64(authConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>api/client/trust.go
<ide> func trustServer(index *registry.IndexInfo) (string, error) {
<ide> }
<ide>
<ide> type simpleCredentialStore struct {
<del> auth cliconfig.AuthConfig
<add> auth types.AuthConfig
<ide> }
<ide>
<ide> func (scs simpleCredentialStore) Basic(u *url.URL) (string, string) {
<ide> return scs.auth.Username, scs.auth.Password
<ide> }
<ide>
<del>func (cli *DockerCli) getNotaryRepository(repoInfo *registry.RepositoryInfo, authConfig cliconfig.AuthConfig) (*client.NotaryRepository, error) {
<add>func (cli *DockerCli) getNotaryRepository(repoInfo *registry.RepositoryInfo, authConfig types.AuthConfig) (*client.NotaryRepository, error) {
<ide> server, err := trustServer(repoInfo.Index)
<ide> if err != nil {
<ide> return nil, err
<ide> func notaryError(err error) error {
<ide> return err
<ide> }
<ide>
<del>func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig cliconfig.AuthConfig, requestPrivilege lib.RequestPrivilegeFunc) error {
<add>func (cli *DockerCli) trustedPull(repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig types.AuthConfig, requestPrivilege lib.RequestPrivilegeFunc) error {
<ide> var refs []target
<ide>
<ide> notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig)
<ide> func targetStream(in io.Writer) (io.WriteCloser, <-chan []target) {
<ide> return ioutils.NewWriteCloserWrapper(out, w.Close), targetChan
<ide> }
<ide>
<del>func (cli *DockerCli) trustedPush(repoInfo *registry.RepositoryInfo, tag string, authConfig cliconfig.AuthConfig, requestPrivilege lib.RequestPrivilegeFunc) error {
<add>func (cli *DockerCli) trustedPush(repoInfo *registry.RepositoryInfo, tag string, authConfig types.AuthConfig, requestPrivilege lib.RequestPrivilegeFunc) error {
<ide> streamOut, targetChan := targetStream(cli.out)
<ide>
<ide> reqError := cli.imagePushPrivileged(authConfig, repoInfo.LocalName.Name(), tag, streamOut, requestPrivilege)
<ide><path>api/client/utils.go
<ide> package client
<ide>
<ide> import (
<add> "encoding/base64"
<add> "encoding/json"
<ide> "fmt"
<ide> "os"
<ide> gosignal "os/signal"
<ide> import (
<ide> "github.com/docker/docker/registry"
<ide> )
<ide>
<add>// encodeAuthToBase64 serializes the auth configuration as JSON base64 payload
<add>func encodeAuthToBase64(authConfig AuthConfig) (string, error) {
<add> buf, err := json.Marshal(authConfig)
<add> if err != nil {
<add> return "", err
<add> }
<add> return base64.URLEncoding.EncodeToString(buf), nil
<add>}
<add>
<ide> func (cli *DockerCli) encodeRegistryAuth(index *registry.IndexInfo) (string, error) {
<ide> authConfig := registry.ResolveAuthConfig(cli.configFile.AuthConfigs, index)
<del> return authConfig.EncodeToBase64()
<add> return cliconfig.EncodeAuthToBase64(authConfig)
<ide> }
<ide>
<ide> func (cli *DockerCli) registryAuthenticationPrivilegedFunc(index *registry.IndexInfo, cmdName string) lib.RequestPrivilegeFunc {
<ide><path>api/server/router/local/image.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/builder"
<ide> "github.com/docker/docker/builder/dockerfile"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/daemon/daemonbuilder"
<ide> derr "github.com/docker/docker/errors"
<ide> "github.com/docker/docker/pkg/archive"
<ide> func (s *router) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
<ide> message = r.Form.Get("message")
<ide> )
<ide> authEncoded := r.Header.Get("X-Registry-Auth")
<del> authConfig := &cliconfig.AuthConfig{}
<add> authConfig := &types.AuthConfig{}
<ide> if authEncoded != "" {
<ide> authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
<ide> if err := json.NewDecoder(authJSON).Decode(authConfig); err != nil {
<ide> // for a pull it is not an error if no auth was given
<ide> // to increase compatibility with the existing api it is defaulting to be empty
<del> authConfig = &cliconfig.AuthConfig{}
<add> authConfig = &types.AuthConfig{}
<ide> }
<ide> }
<ide>
<ide> func (s *router) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h
<ide> if err := httputils.ParseForm(r); err != nil {
<ide> return err
<ide> }
<del> authConfig := &cliconfig.AuthConfig{}
<add> authConfig := &types.AuthConfig{}
<ide>
<ide> authEncoded := r.Header.Get("X-Registry-Auth")
<ide> if authEncoded != "" {
<ide> // the new format is to handle the authConfig as a header
<ide> authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
<ide> if err := json.NewDecoder(authJSON).Decode(authConfig); err != nil {
<ide> // to increase compatibility to existing api it is defaulting to be empty
<del> authConfig = &cliconfig.AuthConfig{}
<add> authConfig = &types.AuthConfig{}
<ide> }
<ide> } else {
<ide> // the old format is supported for compatibility if there was no authConfig header
<ide> func (s *router) getImagesByName(ctx context.Context, w http.ResponseWriter, r *
<ide>
<ide> func (s *router) postBuild(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> var (
<del> authConfigs = map[string]cliconfig.AuthConfig{}
<add> authConfigs = map[string]types.AuthConfig{}
<ide> authConfigsEncoded = r.Header.Get("X-Registry-Config")
<ide> buildConfig = &dockerfile.Config{}
<ide> )
<ide> func (s *router) getImagesSearch(ctx context.Context, w http.ResponseWriter, r *
<ide> return err
<ide> }
<ide> var (
<del> config *cliconfig.AuthConfig
<add> config *types.AuthConfig
<ide> authEncoded = r.Header.Get("X-Registry-Auth")
<ide> headers = map[string][]string{}
<ide> )
<ide> func (s *router) getImagesSearch(ctx context.Context, w http.ResponseWriter, r *
<ide> if err := json.NewDecoder(authJSON).Decode(&config); err != nil {
<ide> // for a search it is not an error if no auth was given
<ide> // to increase compatibility with the existing api it is defaulting to be empty
<del> config = &cliconfig.AuthConfig{}
<add> config = &types.AuthConfig{}
<ide> }
<ide> }
<ide> for k, v := range r.Header {
<ide><path>api/server/router/system/backend.go
<ide> package system
<ide>
<ide> import (
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> )
<ide> type Backend interface {
<ide> SystemVersion() types.Version
<ide> SubscribeToEvents(since, sinceNano int64, ef filters.Args) ([]*jsonmessage.JSONMessage, chan interface{})
<ide> UnsubscribeFromEvents(chan interface{})
<del> AuthenticateToRegistry(authConfig *cliconfig.AuthConfig) (string, error)
<add> AuthenticateToRegistry(authConfig *types.AuthConfig) (string, error)
<ide> }
<ide><path>api/server/router/system/system_routes.go
<ide> import (
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/server/httputils"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/jsonmessage"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> func (s *systemRouter) getEvents(ctx context.Context, w http.ResponseWriter, r *
<ide> }
<ide>
<ide> func (s *systemRouter) postAuth(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> var config *cliconfig.AuthConfig
<add> var config *types.AuthConfig
<ide> err := json.NewDecoder(r.Body).Decode(&config)
<ide> r.Body.Close()
<ide> if err != nil {
<ide><path>api/types/auth.go
<add>package types
<add>
<add>// AuthConfig contains authorization information for connecting to a Registry
<add>type AuthConfig struct {
<add> Username string `json:"username,omitempty"`
<add> Password string `json:"password,omitempty"`
<add> Auth string `json:"auth"`
<add> Email string `json:"email"`
<add> ServerAddress string `json:"serveraddress,omitempty"`
<add> RegistryToken string `json:"registrytoken,omitempty"`
<add>}
<ide><path>api/types/client.go
<ide> import (
<ide> "io"
<ide> "net"
<ide>
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/parsers/filters"
<ide> "github.com/docker/docker/pkg/ulimit"
<ide> "github.com/docker/docker/runconfig"
<ide> type ImageBuildOptions struct {
<ide> Dockerfile string
<ide> Ulimits []*ulimit.Ulimit
<ide> BuildArgs []string
<del> AuthConfigs map[string]cliconfig.AuthConfig
<add> AuthConfigs map[string]types.AuthConfig
<ide> Context io.Reader
<ide> }
<ide>
<ide><path>cliconfig/config.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/pkg/homedir"
<ide> )
<ide>
<ide> func SetConfigDir(dir string) {
<ide> configDir = dir
<ide> }
<ide>
<del>// AuthConfig contains authorization information for connecting to a Registry
<del>type AuthConfig struct {
<del> Username string `json:"username,omitempty"`
<del> Password string `json:"password,omitempty"`
<del> Auth string `json:"auth"`
<del> Email string `json:"email"`
<del> ServerAddress string `json:"serveraddress,omitempty"`
<del> RegistryToken string `json:"registrytoken,omitempty"`
<del>}
<del>
<del>// EncodeToBase64 serializes the auth configuration as JSON base64 payload
<del>func (a AuthConfig) EncodeToBase64() (string, error) {
<del> buf, err := json.Marshal(a)
<add>// EncodeAuthToBase64 serializes the auth configuration as JSON base64 payload
<add>func EncodeAuthToBase64(authConfig AuthConfig) (string, error) {
<add> buf, err := json.Marshal(authConfig)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func (a AuthConfig) EncodeToBase64() (string, error) {
<ide>
<ide> // ConfigFile ~/.docker/config.json file info
<ide> type ConfigFile struct {
<del> AuthConfigs map[string]AuthConfig `json:"auths"`
<del> HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
<del> PsFormat string `json:"psFormat,omitempty"`
<del> filename string // Note: not serialized - for internal use only
<add> AuthConfigs map[string]types.AuthConfig `json:"auths"`
<add> HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
<add> PsFormat string `json:"psFormat,omitempty"`
<add> filename string // Note: not serialized - for internal use only
<ide> }
<ide>
<ide> // NewConfigFile initializes an empty configuration file for the given filename 'fn'
<ide> func NewConfigFile(fn string) *ConfigFile {
<ide> return &ConfigFile{
<del> AuthConfigs: make(map[string]AuthConfig),
<add> AuthConfigs: make(map[string]types.AuthConfig),
<ide> HTTPHeaders: make(map[string]string),
<ide> filename: fn,
<ide> }
<ide> func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error {
<ide> if len(arr) < 2 {
<ide> return fmt.Errorf("The Auth config file is empty")
<ide> }
<del> authConfig := AuthConfig{}
<add> authConfig := types.AuthConfig{}
<ide> origAuth := strings.Split(arr[0], " = ")
<ide> if len(origAuth) != 2 {
<ide> return fmt.Errorf("Invalid Auth config file")
<ide> func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error {
<ide> // a non-nested reader
<ide> func LegacyLoadFromReader(configData io.Reader) (*ConfigFile, error) {
<ide> configFile := ConfigFile{
<del> AuthConfigs: make(map[string]AuthConfig),
<add> AuthConfigs: make(map[string]types.AuthConfig),
<ide> }
<ide> err := configFile.LegacyLoadFromReader(configData)
<ide> return &configFile, err
<ide> func LegacyLoadFromReader(configData io.Reader) (*ConfigFile, error) {
<ide> // a reader
<ide> func LoadFromReader(configData io.Reader) (*ConfigFile, error) {
<ide> configFile := ConfigFile{
<del> AuthConfigs: make(map[string]AuthConfig),
<add> AuthConfigs: make(map[string]types.AuthConfig),
<ide> }
<ide> err := configFile.LoadFromReader(configData)
<ide> return &configFile, err
<ide> func Load(configDir string) (*ConfigFile, error) {
<ide> }
<ide>
<ide> configFile := ConfigFile{
<del> AuthConfigs: make(map[string]AuthConfig),
<add> AuthConfigs: make(map[string]types.AuthConfig),
<ide> filename: filepath.Join(configDir, ConfigFileName),
<ide> }
<ide>
<ide> func Load(configDir string) (*ConfigFile, error) {
<ide> // the given writer
<ide> func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error {
<ide> // Encode sensitive data into a new/temp struct
<del> tmpAuthConfigs := make(map[string]AuthConfig, len(configFile.AuthConfigs))
<add> tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs))
<ide> for k, authConfig := range configFile.AuthConfigs {
<ide> authCopy := authConfig
<ide> // encode and save the authstring, while blanking out the original fields
<ide> func (configFile *ConfigFile) Filename() string {
<ide> }
<ide>
<ide> // EncodeAuth creates a base64 encoded string to containing authorization information
<del>func EncodeAuth(authConfig *AuthConfig) string {
<add>func EncodeAuth(authConfig *types.AuthConfig) string {
<ide> authStr := authConfig.Username + ":" + authConfig.Password
<ide> msg := []byte(authStr)
<ide> encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/api/types"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/daemon/exec"
<ide> func writeDistributionProgress(cancelFunc func(), outStream io.Writer, progressC
<ide>
<ide> // PullImage initiates a pull operation. image is the repository name to pull, and
<ide> // tag may be either empty, or indicate a specific tag to pull.
<del>func (daemon *Daemon) PullImage(ref reference.Named, metaHeaders map[string][]string, authConfig *cliconfig.AuthConfig, outStream io.Writer) error {
<add>func (daemon *Daemon) PullImage(ref reference.Named, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> // Include a buffer so that slow client connections don't affect
<ide> // transfer performance.
<ide> progressChan := make(chan progress.Progress, 100)
<ide> func (daemon *Daemon) ExportImage(names []string, outStream io.Writer) error {
<ide> }
<ide>
<ide> // PushImage initiates a push operation on the repository named localName.
<del>func (daemon *Daemon) PushImage(ref reference.Named, metaHeaders map[string][]string, authConfig *cliconfig.AuthConfig, outStream io.Writer) error {
<add>func (daemon *Daemon) PushImage(ref reference.Named, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
<ide> // Include a buffer so that slow client connections don't affect
<ide> // transfer performance.
<ide> progressChan := make(chan progress.Progress, 100)
<ide> func configureVolumes(config *Config, rootUID, rootGID int) (*store.VolumeStore,
<ide> }
<ide>
<ide> // AuthenticateToRegistry checks the validity of credentials in authConfig
<del>func (daemon *Daemon) AuthenticateToRegistry(authConfig *cliconfig.AuthConfig) (string, error) {
<add>func (daemon *Daemon) AuthenticateToRegistry(authConfig *types.AuthConfig) (string, error) {
<ide> return daemon.RegistryService.Auth(authConfig)
<ide> }
<ide>
<ide> // SearchRegistryForImages queries the registry for images matching
<ide> // term. authConfig is used to login.
<ide> func (daemon *Daemon) SearchRegistryForImages(term string,
<del> authConfig *cliconfig.AuthConfig,
<add> authConfig *types.AuthConfig,
<ide> headers map[string][]string) (*registry.SearchResults, error) {
<ide> return daemon.RegistryService.Search(term, authConfig, headers)
<ide> }
<ide><path>daemon/daemonbuilder/builder.go
<ide> import (
<ide> type Docker struct {
<ide> Daemon *daemon.Daemon
<ide> OutOld io.Writer
<del> AuthConfigs map[string]cliconfig.AuthConfig
<add> AuthConfigs map[string]types.AuthConfig
<ide> Archiver *archive.Archiver
<ide> }
<ide>
<ide> func (d Docker) Pull(name string) (*image.Image, error) {
<ide> }
<ide> }
<ide>
<del> pullRegistryAuth := &cliconfig.AuthConfig{}
<add> pullRegistryAuth := &types.AuthConfig{}
<ide> if len(d.AuthConfigs) > 0 {
<ide> // The request came with a full auth config file, we prefer to use that
<ide> repoInfo, err := d.Daemon.RegistryService.ResolveRepository(ref)
<ide><path>distribution/pull.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> type ImagePullConfig struct {
<ide> MetaHeaders map[string][]string
<ide> // AuthConfig holds authentication credentials for authenticating with
<ide> // the registry.
<del> AuthConfig *cliconfig.AuthConfig
<add> AuthConfig *types.AuthConfig
<ide> // ProgressOutput is the interface for showing the status of the pull
<ide> // operation.
<ide> ProgressOutput progress.Output
<ide><path>distribution/push.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/digest"
<ide> "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/daemon/events"
<ide> "github.com/docker/docker/distribution/metadata"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> type ImagePushConfig struct {
<ide> MetaHeaders map[string][]string
<ide> // AuthConfig holds authentication credentials for authenticating with
<ide> // the registry.
<del> AuthConfig *cliconfig.AuthConfig
<add> AuthConfig *types.AuthConfig
<ide> // ProgressOutput is the interface for showing the status of the push
<ide> // operation.
<ide> ProgressOutput progress.Output
<ide><path>distribution/registry.go
<ide> import (
<ide> "github.com/docker/distribution/registry/client"
<ide> "github.com/docker/distribution/registry/client/auth"
<ide> "github.com/docker/distribution/registry/client/transport"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/distribution/xfer"
<ide> "github.com/docker/docker/registry"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> type dumbCredentialStore struct {
<del> auth *cliconfig.AuthConfig
<add> auth *types.AuthConfig
<ide> }
<ide>
<ide> func (dcs dumbCredentialStore) Basic(*url.URL) (string, string) {
<ide> func (dcs dumbCredentialStore) Basic(*url.URL) (string, string) {
<ide> // NewV2Repository returns a repository (v2 only). It creates a HTTP transport
<ide> // providing timeout settings and authentication support, and also verifies the
<ide> // remote API version.
<del>func NewV2Repository(repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint, metaHeaders http.Header, authConfig *cliconfig.AuthConfig, actions ...string) (distribution.Repository, error) {
<add>func NewV2Repository(repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint, metaHeaders http.Header, authConfig *types.AuthConfig, actions ...string) (distribution.Repository, error) {
<ide> ctx := context.Background()
<ide>
<ide> repoName := repoInfo.CanonicalName
<ide><path>distribution/registry_unit_test.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client/auth"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/registry"
<ide> "github.com/docker/docker/utils"
<ide> "golang.org/x/net/context"
<ide> )
<ide>
<ide> func TestTokenPassThru(t *testing.T) {
<del> authConfig := &cliconfig.AuthConfig{
<add> authConfig := &types.AuthConfig{
<ide> RegistryToken: "mysecrettoken",
<ide> }
<ide> gotToken := false
<ide><path>registry/auth.go
<ide> import (
<ide> )
<ide>
<ide> // Login tries to register/login to the registry server.
<del>func Login(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (string, error) {
<add>func Login(authConfig *types.AuthConfig, registryEndpoint *Endpoint) (string, error) {
<ide> // Separates the v2 registry login logic from the v1 logic.
<ide> if registryEndpoint.Version == APIVersion2 {
<ide> return loginV2(authConfig, registryEndpoint, "" /* scope */)
<ide> func Login(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (string
<ide> }
<ide>
<ide> // loginV1 tries to register/login to the v1 registry server.
<del>func loginV1(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (string, error) {
<add>func loginV1(authConfig *types.AuthConfig, registryEndpoint *Endpoint) (string, error) {
<ide> var (
<ide> status string
<ide> respBody []byte
<ide> func loginV1(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (stri
<ide> // now, users should create their account through other means like directly from a web page
<ide> // served by the v2 registry service provider. Whether this will be supported in the future
<ide> // is to be determined.
<del>func loginV2(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint, scope string) (string, error) {
<add>func loginV2(authConfig *types.AuthConfig, registryEndpoint *Endpoint, scope string) (string, error) {
<ide> logrus.Debugf("attempting v2 login to registry endpoint %s", registryEndpoint)
<ide> var (
<ide> err error
<ide> func loginV2(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint, scope
<ide> return "", fmt.Errorf("no successful auth challenge for %s - errors: %s", registryEndpoint, allErrors)
<ide> }
<ide>
<del>func tryV2BasicAuthLogin(authConfig *cliconfig.AuthConfig, params map[string]string, registryEndpoint *Endpoint) error {
<add>func tryV2BasicAuthLogin(authConfig *types.AuthConfig, params map[string]string, registryEndpoint *Endpoint) error {
<ide> req, err := http.NewRequest("GET", registryEndpoint.Path(""), nil)
<ide> if err != nil {
<ide> return err
<ide> func tryV2BasicAuthLogin(authConfig *cliconfig.AuthConfig, params map[string]str
<ide> return nil
<ide> }
<ide>
<del>func tryV2TokenAuthLogin(authConfig *cliconfig.AuthConfig, params map[string]string, registryEndpoint *Endpoint) error {
<add>func tryV2TokenAuthLogin(authConfig *types.AuthConfig, params map[string]string, registryEndpoint *Endpoint) error {
<ide> token, err := getToken(authConfig.Username, authConfig.Password, params, registryEndpoint)
<ide> if err != nil {
<ide> return err
<ide> func tryV2TokenAuthLogin(authConfig *cliconfig.AuthConfig, params map[string]str
<ide> }
<ide>
<ide> // ResolveAuthConfig matches an auth configuration to a server address or a URL
<del>func ResolveAuthConfig(authConfigs map[string]cliconfig.AuthConfig, index *IndexInfo) cliconfig.AuthConfig {
<add>func ResolveAuthConfig(authConfigs map[string]types.AuthConfig, index *IndexInfo) types.AuthConfig {
<ide> configKey := index.GetAuthConfigKey()
<ide> // First try the happy case
<ide> if c, found := authConfigs[configKey]; found || index.Official {
<ide> func ResolveAuthConfig(authConfigs map[string]cliconfig.AuthConfig, index *Index
<ide> }
<ide>
<ide> // When all else fails, return an empty auth config
<del> return cliconfig.AuthConfig{}
<add> return types.AuthConfig{}
<ide> }
<ide><path>registry/auth_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestEncodeAuth(t *testing.T) {
<del> newAuthConfig := &cliconfig.AuthConfig{Username: "ken", Password: "test", Email: "test@example.com"}
<add> newAuthConfig := &types.AuthConfig{Username: "ken", Password: "test", Email: "test@example.com"}
<ide> authStr := cliconfig.EncodeAuth(newAuthConfig)
<del> decAuthConfig := &cliconfig.AuthConfig{}
<add> decAuthConfig := &types.AuthConfig{}
<ide> var err error
<ide> decAuthConfig.Username, decAuthConfig.Password, err = cliconfig.DecodeAuth(authStr)
<ide> if err != nil {
<ide> func buildAuthConfigs() map[string]cliconfig.AuthConfig {
<ide> authConfigs := map[string]cliconfig.AuthConfig{}
<ide>
<ide> for _, registry := range []string{"testIndex", IndexServer} {
<del> authConfigs[registry] = cliconfig.AuthConfig{
<add> authConfigs[registry] = types.AuthConfig{
<ide> Username: "docker-user",
<ide> Password: "docker-pass",
<ide> Email: "docker@docker.io",
<ide> func TestResolveAuthConfigIndexServer(t *testing.T) {
<ide> func TestResolveAuthConfigFullURL(t *testing.T) {
<ide> authConfigs := buildAuthConfigs()
<ide>
<del> registryAuth := cliconfig.AuthConfig{
<add> registryAuth := types.AuthConfig{
<ide> Username: "foo-user",
<ide> Password: "foo-pass",
<ide> Email: "foo@example.com",
<ide> }
<del> localAuth := cliconfig.AuthConfig{
<add> localAuth := types.AuthConfig{
<ide> Username: "bar-user",
<ide> Password: "bar-pass",
<ide> Email: "bar@example.com",
<ide> }
<del> officialAuth := cliconfig.AuthConfig{
<add> officialAuth := types.AuthConfig{
<ide> Username: "baz-user",
<ide> Password: "baz-pass",
<ide> Email: "baz@example.com",
<ide> }
<ide> authConfigs[IndexServer] = officialAuth
<ide>
<del> expectedAuths := map[string]cliconfig.AuthConfig{
<add> expectedAuths := map[string]types.AuthConfig{
<ide> "registry.example.com": registryAuth,
<ide> "localhost:8000": localAuth,
<ide> "registry.com": localAuth,
<ide><path>registry/registry_test.go
<ide> import (
<ide>
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client/transport"
<del> "github.com/docker/docker/cliconfig"
<ide> )
<ide>
<ide> var (
<ide> const (
<ide> )
<ide>
<ide> func spawnTestRegistrySession(t *testing.T) *Session {
<del> authConfig := &cliconfig.AuthConfig{}
<add> authConfig := &types.AuthConfig{}
<ide> endpoint, err := NewEndpoint(makeIndex("/v1/"), nil, APIVersionUnknown)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide><path>registry/service.go
<ide> import (
<ide>
<ide> "github.com/docker/distribution/reference"
<ide> "github.com/docker/distribution/registry/client/auth"
<del> "github.com/docker/docker/cliconfig"
<ide> )
<ide>
<ide> // Service is a registry service. It tracks configuration data such as a list
<ide> func NewService(options *Options) *Service {
<ide> // Auth contacts the public registry with the provided credentials,
<ide> // and returns OK if authentication was successful.
<ide> // It can be used to verify the validity of a client's credentials.
<del>func (s *Service) Auth(authConfig *cliconfig.AuthConfig) (string, error) {
<add>func (s *Service) Auth(authConfig *types.AuthConfig) (string, error) {
<ide> addr := authConfig.ServerAddress
<ide> if addr == "" {
<ide> // Use the official registry address if not specified.
<ide> func splitReposSearchTerm(reposName string) (string, string) {
<ide>
<ide> // Search queries the public registry for images matching the specified
<ide> // search terms, and returns the results.
<del>func (s *Service) Search(term string, authConfig *cliconfig.AuthConfig, headers map[string][]string) (*SearchResults, error) {
<add>func (s *Service) Search(term string, authConfig *types.AuthConfig, headers map[string][]string) (*SearchResults, error) {
<ide> if err := validateNoSchema(term); err != nil {
<ide> return nil, err
<ide> }
<ide><path>registry/session.go
<ide> import (
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/reference"
<del> "github.com/docker/docker/cliconfig"
<ide> "github.com/docker/docker/pkg/httputils"
<ide> "github.com/docker/docker/pkg/ioutils"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> type Session struct {
<ide> indexEndpoint *Endpoint
<ide> client *http.Client
<ide> // TODO(tiborvass): remove authConfig
<del> authConfig *cliconfig.AuthConfig
<add> authConfig *types.AuthConfig
<ide> id string
<ide> }
<ide>
<ide> type authTransport struct {
<ide> http.RoundTripper
<del> *cliconfig.AuthConfig
<add> *types.AuthConfig
<ide>
<ide> alwaysSetBasicAuth bool
<ide> token []string
<ide> type authTransport struct {
<ide> // If the server sends a token without the client having requested it, it is ignored.
<ide> //
<ide> // This RoundTripper also has a CancelRequest method important for correct timeout handling.
<del>func AuthTransport(base http.RoundTripper, authConfig *cliconfig.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper {
<add>func AuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper {
<ide> if base == nil {
<ide> base = http.DefaultTransport
<ide> }
<ide> func (tr *authTransport) CancelRequest(req *http.Request) {
<ide>
<ide> // NewSession creates a new session
<ide> // TODO(tiborvass): remove authConfig param once registry client v2 is vendored
<del>func NewSession(client *http.Client, authConfig *cliconfig.AuthConfig, endpoint *Endpoint) (r *Session, err error) {
<add>func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *Endpoint) (r *Session, err error) {
<ide> r = &Session{
<ide> authConfig: authConfig,
<ide> client: client,
<ide> func (r *Session) SearchRepositories(term string) (*SearchResults, error) {
<ide>
<ide> // GetAuthConfig returns the authentication settings for a session
<ide> // TODO(tiborvass): remove this once registry client v2 is vendored
<del>func (r *Session) GetAuthConfig(withPasswd bool) *cliconfig.AuthConfig {
<add>func (r *Session) GetAuthConfig(withPasswd bool) *types.AuthConfig {
<ide> password := ""
<ide> if withPasswd {
<ide> password = r.authConfig.Password
<ide> }
<del> return &cliconfig.AuthConfig{
<add> return &types.AuthConfig{
<ide> Username: r.authConfig.Username,
<ide> Password: password,
<ide> Email: r.authConfig.Email,
| 25
|
Javascript
|
Javascript
|
improve test coverage for
|
db76b9fb39d7ca29873739571ea09035ad7603e3
|
<ide><path>spec/tokenized-buffer-iterator-spec.js
<ide> import {Point} from 'text-buffer'
<ide>
<ide> describe('TokenizedBufferIterator', () => {
<ide> describe('seek(position)', function () {
<del> it('seeks to the leftmost tag boundary at the given position, returning the containing tags', function () {
<add> it('seeks to the leftmost tag boundary greater than or equal to the given position and returns the containing tags', function () {
<ide> const tokenizedBuffer = {
<ide> tokenizedLineForRow (row) {
<ide> if (row === 0) {
<ide> return {
<del> tags: [-1, -2, -3, -4, -5, 3, -3, -4, -6, 4],
<add> tags: [-1, -2, -3, -4, -5, 3, -3, -4, -6, -5, 4, -6, -3, -4],
<ide> text: 'foo bar',
<ide> openScopes: []
<ide> }
<ide> describe('TokenizedBufferIterator', () => {
<ide> iterator.moveToSuccessor()
<ide> expect(iterator.getPosition()).toEqual(Point(0, 3))
<ide> expect(iterator.getCloseTags()).toEqual(['bar', 'baz'])
<del> expect(iterator.getOpenTags()).toEqual([])
<add> expect(iterator.getOpenTags()).toEqual(['baz'])
<ide>
<ide> expect(iterator.seek(Point(0, 3))).toEqual(['baz'])
<ide> expect(iterator.getPosition()).toEqual(Point(0, 3))
<ide> describe('TokenizedBufferIterator', () => {
<ide> iterator.moveToSuccessor()
<ide> expect(iterator.getPosition()).toEqual(Point(0, 3))
<ide> expect(iterator.getCloseTags()).toEqual(['bar', 'baz'])
<add> expect(iterator.getOpenTags()).toEqual(['baz'])
<add>
<add> iterator.moveToSuccessor()
<add> expect(iterator.getPosition()).toEqual(Point(0, 7))
<add> expect(iterator.getCloseTags()).toEqual(['baz'])
<add> expect(iterator.getOpenTags()).toEqual(['bar'])
<add>
<add> iterator.moveToSuccessor()
<add> expect(iterator.getPosition()).toEqual(Point(0, 7))
<add> expect(iterator.getCloseTags()).toEqual(['bar'])
<ide> expect(iterator.getOpenTags()).toEqual([])
<ide>
<ide> iterator.moveToSuccessor()
<ide> expect(iterator.getPosition()).toEqual(Point(1, 0))
<ide> expect(iterator.getCloseTags()).toEqual([])
<ide> expect(iterator.getOpenTags()).toEqual([])
<add>
<add> expect(iterator.seek(Point(0, 5))).toEqual(['baz'])
<add> expect(iterator.getPosition()).toEqual(Point(0, 7))
<add> expect(iterator.getCloseTags()).toEqual(['baz'])
<add> expect(iterator.getOpenTags()).toEqual(['bar'])
<add>
<add> iterator.moveToSuccessor()
<add> expect(iterator.getPosition()).toEqual(Point(0, 7))
<add> expect(iterator.getCloseTags()).toEqual(['bar'])
<add> expect(iterator.getOpenTags()).toEqual([])
<ide> })
<ide> })
<ide>
| 1
|
Javascript
|
Javascript
|
check isavailable key on simulator object
|
1031872784e9373082797e5bf5c815816af2105b
|
<ide><path>local-cli/runIOS/__tests__/findMatchingSimulator-test.js
<ide> describe('findMatchingSimulator', () => {
<ide> });
<ide> });
<ide>
<add> it('should find simulator with new xcrun format', () => {
<add> expect(
<add> findMatchingSimulator(
<add> {
<add> devices: {
<add> 'iOS 12.1': [
<add> {
<add> state: 'Shutdown',
<add> isAvailable: 'YES',
<add> name: 'iPhone 6s',
<add> udid: 'D0F29BE7-CC3C-4976-888D-C739B4F50508',
<add> },
<add> {
<add> state: 'Shutdown',
<add> isAvailable: 'YES',
<add> name: 'iPhone 6',
<add> udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C',
<add> },
<add> {
<add> state: 'Shutdown',
<add> isAvailable: 'YES',
<add> name: 'iPhone XS Max',
<add> udid: 'B9B5E161-416B-43C4-A78F-729CB96CC8C6',
<add> availabilityError: '',
<add> },
<add> {
<add> state: 'Shutdown',
<add> isAvailable: 'YES',
<add> name: 'iPad Air',
<add> udid: '1CCBBF8B-5773-4EA6-BD6F-C308C87A1ADB',
<add> availabilityError: '',
<add> },
<add> {
<add> state: 'Shutdown',
<add> isAvailable: 'YES',
<add> name: 'iPad (5th generation)',
<add> udid: '9564ABEE-9EC2-4B4A-B443-D3710929A45A',
<add> availabilityError: '',
<add> },
<add> ],
<add> },
<add> },
<add> 'iPhone 6',
<add> ),
<add> ).toEqual({
<add> udid: 'BA0D93BD-07E6-4182-9B0A-F60A2474139C',
<add> name: 'iPhone 6',
<add> booted: false,
<add> version: 'iOS 12.1',
<add> });
<add> });
<add>
<ide> it('should return null if no simulators available', () => {
<ide> expect(
<ide> findMatchingSimulator(
<ide><path>local-cli/runIOS/findMatchingSimulator.js
<ide> function findMatchingSimulator(simulators, simulatorName) {
<ide> for (let i in devices[version]) {
<ide> let simulator = devices[version][i];
<ide> // Skipping non-available simulator
<del> if (simulator.availability !== '(available)') {
<add> if (
<add> simulator.availability !== '(available)' &&
<add> simulator.isAvailable !== 'YES'
<add> ) {
<ide> continue;
<ide> }
<ide> let booted = simulator.state === 'Booted';
| 2
|
Javascript
|
Javascript
|
fix lint issue
|
134a3a52e8357884d2ad14ba10db145832b94093
|
<ide><path>server/services/user.js
<ide> const protectedUserFields = {
<ide> profiles: censor
<ide> };
<ide>
<del>export default function userServices(/* app */) {
<add>export default function userServices() {
<ide> return {
<ide> name: 'user',
<ide> read: (req, resource, params, config, cb) => {
| 1
|
Javascript
|
Javascript
|
replace tls-fragmentation with tls/throughput
|
0a406869df990d030d2383abc7f1388aead57d0c
|
<ide><path>benchmark/tls-fragmentation.js
<del>// Copyright Joyent, Inc. and other Node contributors.
<del>//
<del>// Permission is hereby granted, free of charge, to any person obtaining a
<del>// copy of this software and associated documentation files (the
<del>// "Software"), to deal in the Software without restriction, including
<del>// without limitation the rights to use, copy, modify, merge, publish,
<del>// distribute, sublicense, and/or sell copies of the Software, and to permit
<del>// persons to whom the Software is furnished to do so, subject to the
<del>// following conditions:
<del>//
<del>// The above copyright notice and this permission notice shall be included
<del>// in all copies or substantial portions of the Software.
<del>//
<del>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<del>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<del>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<del>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<del>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<del>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>if (!process.versions.openssl) {
<del> console.error('Skipping because node compiled without OpenSSL.');
<del> process.exit(0);
<del>}
<del>
<del>var common = require('../common');
<del>var assert = require('assert');
<del>var tls = require('tls');
<del>var fs = require('fs');
<del>var path = require('path');
<del>
<del>var options = {
<del> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')),
<del> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))
<del>};
<del>
<del>var fragment = 'fr';
<del>var dataSize = 1024 * 1024;
<del>var sent = 0;
<del>var received = 0;
<del>
<del>var server = tls.createServer(options, function (stream) {
<del> for (sent = 0; sent <= dataSize; sent += fragment.length) {
<del> stream.write(fragment);
<del> }
<del> stream.end();
<del>});
<del>
<del>server.listen(common.PORT, function () {
<del> var client = tls.connect(common.PORT, function () {
<del> client.on('data', function (data) {
<del> received += data.length;
<del> });
<del> client.on('end', function () {
<del> server.close();
<del> });
<del> });
<del>});
<del>
<del>process.on('exit', function () {
<del> assert.equal(sent, received);
<del>});
<ide><path>benchmark/tls/throughput.js
<add>var common = require('../common.js');
<add>var bench = common.createBenchmark(main, {
<add> dur: [1, 3],
<add> type: ['buf', 'asc', 'utf'],
<add> size: [2, 1024, 1024 * 1024]
<add>});
<add>
<add>var dur, type, encoding, size;
<add>var server;
<add>
<add>var path = require('path');
<add>var fs = require('fs');
<add>var cert_dir = path.resolve(__dirname, '../../test/fixtures');
<add>var options;
<add>var tls = require('tls');
<add>
<add>function main(conf) {
<add> dur = +conf.dur;
<add> type = conf.type;
<add> size = +conf.size;
<add>
<add> var chunk;
<add> switch (type) {
<add> case 'buf':
<add> chunk = new Buffer(size);
<add> chunk.fill('b');
<add> break;
<add> case 'asc':
<add> chunk = new Array(size + 1).join('a');
<add> encoding = 'ascii';
<add> break;
<add> case 'utf':
<add> chunk = new Array(size/2 + 1).join('ü');
<add> encoding = 'utf8';
<add> break;
<add> default:
<add> throw new Error('invalid type');
<add> }
<add>
<add> options = { key: fs.readFileSync(cert_dir + '/test_key.pem'),
<add> cert: fs.readFileSync(cert_dir + '/test_cert.pem'),
<add> ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ] };
<add>
<add> server = tls.createServer(options, onConnection);
<add> setTimeout(done, dur * 1000);
<add> server.listen(common.PORT, function() {
<add> var opt = { port: common.PORT, rejectUnauthorized: false };
<add> var conn = tls.connect(opt, function() {
<add> bench.start();
<add> conn.on('drain', write);
<add> write();
<add> });
<add>
<add> function write() {
<add> var i = 0;
<add> while (false !== conn.write(chunk, encoding));
<add> }
<add> });
<add>
<add> var received = 0;
<add> function onConnection(conn) {
<add> conn.on('data', function(chunk) {
<add> received += chunk.length;
<add> });
<add> }
<add>
<add> function done() {
<add> var mbits = (received * 8) / (1024 * 1024);
<add> bench.end(mbits);
<add> conn.destroy();
<add> server.close();
<add> }
<add>}
<add>
| 2
|
PHP
|
PHP
|
add hasscope function to the base model
|
2a922bc0d83ebdf4199ff8fa75088b27c9c41083
|
<ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function __call($method, $parameters)
<ide> return call_user_func_array(static::$macros[$method], $parameters);
<ide> }
<ide>
<del> if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
<del> return $this->callScope([$this->model, $scope], $parameters);
<add> if ($this->model->hasScope($method)) {
<add> return $this->callScope([$this->model, 'scope' . ucfirst($method)], $parameters);
<ide> }
<ide>
<ide> if (in_array($method, $this->passthru)) {
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function isIgnoringTouch($class = null)
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * Determine if the given model has a scope.
<add> *
<add> * @param string $method
<add> * @return bool
<add> */
<add> public function hasScope(string $method)
<add> {
<add> return method_exists($this, 'scope' . ucfirst($method));
<add> }
<add>
<ide> /**
<ide> * Fill the model with an array of attributes.
<ide> *
<ide><path>tests/Integration/Database/EloquentModelScopeTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Database;
<add>
<add>use Illuminate\Database\Eloquent\Model;
<add>
<add>/**
<add> * @group integration
<add> */
<add>class EloquentModelScopeTest extends DatabaseTestCase
<add>{
<add> public function testModelHasScope()
<add> {
<add> $model = new TestModel1;
<add>
<add> $this->assertTrue($model->hasScope("exists"));
<add> }
<add>
<add> public function testModelDoesNotHaveScope()
<add> {
<add> $model = new TestModel1;
<add>
<add> $this->assertFalse($model->hasScope("doesNotExist"));
<add> }
<add>}
<add>
<add>class TestModel1 extends Model
<add>{
<add> public function scopeExists()
<add> {
<add> return true;
<add> }
<add>}
| 3
|
Python
|
Python
|
add python 3.7 to setup.py (resolves )
|
83e88553d4cb18dd876c5abe1fe1651034b09e8e
|
<ide><path>setup.py
<ide> def setup_package():
<ide> 'Programming Language :: Python :: 3.4',
<ide> 'Programming Language :: Python :: 3.5',
<ide> 'Programming Language :: Python :: 3.6',
<add> 'Programming Language :: Python :: 3.7',
<ide> 'Topic :: Scientific/Engineering'],
<ide> cmdclass = {
<ide> 'build_ext': build_ext_subclass},
| 1
|
Javascript
|
Javascript
|
use only public api for changeeventplugin-test.js
|
a67757e11540936677b0a5d89d623b3e38b5fe69
|
<ide><path>packages/react-dom/src/events/__tests__/ChangeEventPlugin-test.internal.js
<del>/**
<del> * Copyright (c) 2013-present, Facebook, Inc.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @emails react-core
<del> */
<del>
<del>'use strict';
<del>
<del>var React = require('react');
<del>var ReactDOM = require('react-dom');
<del>var ReactTestUtils = require('react-dom/test-utils');
<del>// TODO: can we express this test with only public API?
<del>var ChangeEventPlugin = require('../ChangeEventPlugin').default;
<del>var inputValueTracking = require('../../client/inputValueTracking');
<del>
<del>function getTrackedValue(elem) {
<del> var tracker = inputValueTracking._getTrackerFromNode(elem);
<del> return tracker.getValue();
<del>}
<del>
<del>function setTrackedValue(elem, value) {
<del> var tracker = inputValueTracking._getTrackerFromNode(elem);
<del> tracker.setValue(value);
<del>}
<del>
<del>function setUntrackedValue(elem, value) {
<del> var tracker = inputValueTracking._getTrackerFromNode(elem);
<del> var current = tracker.getValue();
<del>
<del> if (elem.type === 'checkbox' || elem.type === 'radio') {
<del> elem.checked = value;
<del> } else {
<del> elem.value = value;
<del> }
<del> tracker.setValue(current);
<del>}
<del>
<del>describe('ChangeEventPlugin', () => {
<del> it('should fire change for checkbox input', () => {
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called = 1;
<del> expect(e.type).toBe('change');
<del> }
<del>
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="checkbox" onChange={cb} />,
<del> );
<del>
<del> setUntrackedValue(input, true);
<del> ReactTestUtils.SimulateNative.click(input);
<del>
<del> expect(called).toBe(1);
<del> });
<del>
<del> it('should catch setting the value programmatically', () => {
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="text" defaultValue="foo" />,
<del> );
<del>
<del> input.value = 'bar';
<del> expect(getTrackedValue(input)).toBe('bar');
<del> });
<del>
<del> it('should not fire change when setting the value programmatically', () => {
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called += 1;
<del> expect(e.type).toBe('change');
<del> }
<del>
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="text" onChange={cb} defaultValue="foo" />,
<del> );
<del>
<del> input.value = 'bar';
<del> ReactTestUtils.SimulateNative.change(input);
<del> expect(called).toBe(0);
<del>
<del> setUntrackedValue(input, 'foo');
<del> ReactTestUtils.SimulateNative.change(input);
<del>
<del> expect(called).toBe(1);
<del> });
<del>
<del> it('should not fire change when setting checked programmatically', () => {
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called += 1;
<del> expect(e.type).toBe('change');
<del> }
<del>
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="checkbox" onChange={cb} defaultChecked={true} />,
<del> );
<del>
<del> input.checked = true;
<del> ReactTestUtils.SimulateNative.click(input);
<del> expect(called).toBe(0);
<del>
<del> input.checked = false;
<del> setTrackedValue(input, undefined);
<del> ReactTestUtils.SimulateNative.click(input);
<del>
<del> expect(called).toBe(1);
<del> });
<del>
<del> it('should unmount', () => {
<del> var container = document.createElement('div');
<del> var input = ReactDOM.render(<input />, container);
<del>
<del> ReactDOM.unmountComponentAtNode(container);
<del> });
<del>
<del> it('should only fire change for checked radio button once', () => {
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called += 1;
<del> }
<del>
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="radio" onChange={cb} />,
<del> );
<del> setUntrackedValue(input, true);
<del> ReactTestUtils.SimulateNative.click(input);
<del> ReactTestUtils.SimulateNative.click(input);
<del> expect(called).toBe(1);
<del> });
<del>
<del> it('should deduplicate input value change events', () => {
<del> var input;
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called += 1;
<del> expect(e.type).toBe('change');
<del> }
<del>
<del> [
<del> <input type="text" onChange={cb} />,
<del> <input type="number" onChange={cb} />,
<del> <input type="range" onChange={cb} />,
<del> ].forEach(function(element) {
<del> called = 0;
<del> input = ReactTestUtils.renderIntoDocument(element);
<del>
<del> setUntrackedValue(input, '40');
<del> ReactTestUtils.SimulateNative.change(input);
<del> ReactTestUtils.SimulateNative.change(input);
<del> expect(called).toBe(1);
<del>
<del> called = 0;
<del> input = ReactTestUtils.renderIntoDocument(element);
<del> setUntrackedValue(input, '40');
<del> ReactTestUtils.SimulateNative.input(input);
<del> ReactTestUtils.SimulateNative.input(input);
<del> expect(called).toBe(1);
<del>
<del> called = 0;
<del> input = ReactTestUtils.renderIntoDocument(element);
<del> setUntrackedValue(input, '40');
<del> ReactTestUtils.SimulateNative.input(input);
<del> ReactTestUtils.SimulateNative.change(input);
<del> expect(called).toBe(1);
<del> });
<del> });
<del>
<del> it('should listen for both change and input events when supported', () => {
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called += 1;
<del> expect(e.type).toBe('change');
<del> }
<del>
<del> if (!ChangeEventPlugin._isInputEventSupported) {
<del> return;
<del> }
<del>
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="range" onChange={cb} />,
<del> );
<del> setUntrackedValue(input, 'bar');
<del>
<del> ReactTestUtils.SimulateNative.input(input);
<del>
<del> setUntrackedValue(input, 'foo');
<del>
<del> ReactTestUtils.SimulateNative.change(input);
<del>
<del> expect(called).toBe(2);
<del> });
<del>
<del> it('should only fire events when the value changes for range inputs', () => {
<del> var called = 0;
<del>
<del> function cb(e) {
<del> called += 1;
<del> expect(e.type).toBe('change');
<del> }
<del>
<del> var input = ReactTestUtils.renderIntoDocument(
<del> <input type="range" onChange={cb} />,
<del> );
<del> setUntrackedValue(input, '40');
<del> ReactTestUtils.SimulateNative.input(input);
<del> ReactTestUtils.SimulateNative.change(input);
<del>
<del> setUntrackedValue(input, 'foo');
<del>
<del> ReactTestUtils.SimulateNative.input(input);
<del> ReactTestUtils.SimulateNative.change(input);
<del> expect(called).toBe(2);
<del> });
<del>});
<ide><path>packages/react-dom/src/events/__tests__/ChangeEventPlugin-test.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>'use strict';
<add>
<add>var React = require('react');
<add>var ReactDOM = require('react-dom');
<add>
<add>var setUntrackedChecked = Object.getOwnPropertyDescriptor(
<add> HTMLInputElement.prototype,
<add> 'checked',
<add>).set;
<add>
<add>var setUntrackedValue = Object.getOwnPropertyDescriptor(
<add> HTMLInputElement.prototype,
<add> 'value',
<add>).set;
<add>
<add>describe('ChangeEventPlugin', () => {
<add> var container;
<add>
<add> beforeEach(() => {
<add> container = document.createElement('div');
<add> document.body.appendChild(container);
<add> });
<add>
<add> afterEach(() => {
<add> document.body.removeChild(container);
<add> container = null;
<add> });
<add>
<add> it('should fire change for checkbox input', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var node = ReactDOM.render(
<add> <input type="checkbox" onChange={cb} />,
<add> container,
<add> );
<add>
<add> expect(node.checked).toBe(false);
<add> node.dispatchEvent(
<add> new MouseEvent('click', {bubbles: true, cancelable: true}),
<add> );
<add> // Note: unlike with text input events, dispatching `click` actually
<add> // toggles the checkbox and updates its `checked` value.
<add> expect(node.checked).toBe(true);
<add> expect(called).toBe(1);
<add>
<add> expect(node.checked).toBe(true);
<add> node.dispatchEvent(
<add> new MouseEvent('click', {bubbles: true, cancelable: true}),
<add> );
<add> expect(node.checked).toBe(false);
<add> expect(called).toBe(2);
<add> });
<add>
<add> it('should not fire change setting the value programmatically', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var input = ReactDOM.render(
<add> <input type="text" defaultValue="foo" onChange={cb} />,
<add> container,
<add> );
<add>
<add> // We try to avoid firing "duplicate" React change events.
<add> // However, to tell which events are duplicates and should be ignored,
<add> // we are tracking the "current" input value, and only respect events
<add> // that occur after it changes. In this test, we verify that we can
<add> // keep track of the "current" value even if it is set programatically.
<add>
<add> // Set it programmatically.
<add> input.value = 'bar';
<add> // Even if a DOM input event fires, React sees that the real input value now
<add> // ('bar') is the same as the "current" one we already recorded.
<add> input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
<add> expect(input.value).toBe('bar');
<add> // In this case we don't expect to get a React event.
<add> expect(called).toBe(0);
<add>
<add> // However, we can simulate user typing by calling the underlying setter.
<add> setUntrackedValue.call(input, 'foo');
<add> // Now, when the event fires, the real input value ('foo') differs from the
<add> // "current" one we previously recorded ('bar').
<add> input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
<add> expect(input.value).toBe('foo');
<add> // In this case React should fire an event for it.
<add> expect(called).toBe(1);
<add>
<add> // Verify again that extra events without real changes are ignored.
<add> input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
<add> expect(called).toBe(1);
<add> });
<add>
<add> // See a similar input test above for a detailed description of why.
<add> it('should not fire change when setting checked programmatically', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var input = ReactDOM.render(
<add> <input type="checkbox" onChange={cb} defaultChecked={false} />,
<add> container,
<add> );
<add>
<add> // Set the value, updating the "current" value that React tracks to true.
<add> input.checked = true;
<add> // Under the hood, uncheck the box so that the click will "check" it again.
<add> setUntrackedChecked.call(input, false);
<add> input.dispatchEvent(
<add> new MouseEvent('click', {bubbles: true, cancelable: true}),
<add> );
<add> expect(input.checked).toBe(true);
<add> // We don't expect a React event because at the time of the click, the real
<add> // checked value (true) was the same as the last recorded "current" value
<add> // (also true).
<add> expect(called).toBe(0);
<add>
<add> // However, simulating a normal click should fire a React event because the
<add> // real value (false) would have changed from the last tracked value (true).
<add> input.dispatchEvent(new Event('click', {bubbles: true, cancelable: true}));
<add> expect(called).toBe(1);
<add> });
<add>
<add> it('should unmount', () => {
<add> var input = ReactDOM.render(<input />, container);
<add>
<add> ReactDOM.unmountComponentAtNode(container);
<add> });
<add>
<add> it('should only fire change for checked radio button once', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var input = ReactDOM.render(
<add> <input type="radio" onChange={cb} />,
<add> container,
<add> );
<add>
<add> setUntrackedChecked.call(input, true);
<add> input.dispatchEvent(new Event('click', {bubbles: true, cancelable: true}));
<add> input.dispatchEvent(new Event('click', {bubbles: true, cancelable: true}));
<add> expect(called).toBe(1);
<add> });
<add>
<add> it('should deduplicate input value change events', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var input;
<add> ['text', 'number', 'range'].forEach(type => {
<add> called = 0;
<add> input = ReactDOM.render(<input type={type} onChange={cb} />, container);
<add> setUntrackedValue.call(input, '42');
<add> input.dispatchEvent(
<add> new Event('change', {bubbles: true, cancelable: true}),
<add> );
<add> input.dispatchEvent(
<add> new Event('change', {bubbles: true, cancelable: true}),
<add> );
<add> expect(called).toBe(1);
<add> ReactDOM.unmountComponentAtNode(container);
<add>
<add> called = 0;
<add> input = ReactDOM.render(<input type={type} onChange={cb} />, container);
<add> setUntrackedValue.call(input, '42');
<add> input.dispatchEvent(
<add> new Event('input', {bubbles: true, cancelable: true}),
<add> );
<add> input.dispatchEvent(
<add> new Event('input', {bubbles: true, cancelable: true}),
<add> );
<add> expect(called).toBe(1);
<add> ReactDOM.unmountComponentAtNode(container);
<add>
<add> called = 0;
<add> input = ReactDOM.render(<input type={type} onChange={cb} />, container);
<add> setUntrackedValue.call(input, '42');
<add> input.dispatchEvent(
<add> new Event('input', {bubbles: true, cancelable: true}),
<add> );
<add> input.dispatchEvent(
<add> new Event('change', {bubbles: true, cancelable: true}),
<add> );
<add> expect(called).toBe(1);
<add> ReactDOM.unmountComponentAtNode(container);
<add> });
<add> });
<add>
<add> it('should listen for both change and input events when supported', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var input = ReactDOM.render(
<add> <input type="range" onChange={cb} />,
<add> container,
<add> );
<add>
<add> setUntrackedValue.call(input, 'foo');
<add> input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
<add>
<add> setUntrackedValue.call(input, 'bar');
<add> input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
<add>
<add> expect(called).toBe(2);
<add> });
<add>
<add> it('should only fire events when the value changes for range inputs', () => {
<add> var called = 0;
<add>
<add> function cb(e) {
<add> called++;
<add> expect(e.type).toBe('change');
<add> }
<add>
<add> var input = ReactDOM.render(
<add> <input type="range" onChange={cb} />,
<add> container,
<add> );
<add> setUntrackedValue.call(input, '40');
<add> input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
<add> input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
<add>
<add> setUntrackedValue.call(input, 'foo');
<add> input.dispatchEvent(new Event('input', {bubbles: true, cancelable: true}));
<add> input.dispatchEvent(new Event('change', {bubbles: true, cancelable: true}));
<add>
<add> expect(called).toBe(2);
<add> });
<add>});
| 2
|
Javascript
|
Javascript
|
remove duplicate import declarations
|
595b4f945b703128af7e65750726c0cbf073ca58
|
<ide><path>packages/react-reconciler/src/ReactFiberScheduler.js
<ide> import {
<ide> scheduleDeferredCallback,
<ide> cancelDeferredCallback,
<ide> shouldYield,
<del> scheduleTimeout,
<del> cancelTimeout,
<del> noTimeout,
<ide> prepareForCommit,
<ide> resetAfterCommit,
<ide> scheduleTimeout,
| 1
|
Python
|
Python
|
add missing teardown in deprecation test case
|
78d7cc4f3422826954b067a5b030f0807f85f294
|
<ide><path>numpy/core/tests/test_deprecations.py
<ide> def foo():
<ide> warnings.warn("foo", category=DeprecationWarning)
<ide>
<ide> test_case_instance.assert_deprecated(foo)
<add> test_case_instance.tearDown()
<add>
<ide>
<ide> if __name__ == "__main__":
<ide> run_module_suite()
| 1
|
PHP
|
PHP
|
add test covering reading old data
|
e97b65c70d19d36ed9704d1ea2001ce5384c2010
|
<ide><path>tests/TestCase/Http/Cookie/CookieTest.php
<ide> public function testReadComplexData()
<ide> $this->assertEquals('developer', $result);
<ide> }
<ide>
<add> /**
<add> * Test reading complex data serialized in 1.x and early 2.x
<add> *
<add> * @return void
<add> */
<add> public function testReadLegacyComplexData()
<add> {
<add> $data = 'key|value,key2|value2';
<add> $cookie = new Cookie('cakephp', $data);
<add> $this->assertEquals('value', $cookie->read('key'));
<add> $this->assertNull($cookie->read('nope'));
<add> }
<add>
<ide> /**
<ide> * Test that toHeaderValue() collapses data.
<ide> *
| 1
|
Javascript
|
Javascript
|
fix https with fs.openreadstream hangs
|
5451ba3aa8f3061851a1618374374f2f0f0e3275
|
<ide><path>lib/tls.js
<ide> CryptoStream.prototype._pull = function() {
<ide> paused = this.pair.cleartext._paused;
<ide> }
<ide> if (!paused) {
<del> debug('drain');
<del> process.nextTick(this.emit.bind(this, 'drain'));
<add> debug('drain ' + (this === this.pair.cleartext ? 'clear' : 'encrypted'));
<add> var self = this;
<add> process.nextTick(function() {
<add> if (typeof self.ondrain === 'function') {
<add> self.ondrain();
<add> }
<add> self.emit('drain');
<add> });
<ide> this._needDrain = false;
<ide> if (this.__destroyOnDrain) this.end();
<ide> }
<ide><path>test/simple/test-https-drain.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>if (!process.versions.openssl) {
<add> console.error('Skipping because node compiled without OpenSSL.');
<add> process.exit(0);
<add>}
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var https = require('https');
<add>var fs = require('fs');
<add>var path = require('path');
<add>
<add>var options = {
<add> key: fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')),
<add> cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'))
<add>};
<add>
<add>var bufSize = 1024 * 1024;
<add>var sent = 0;
<add>var received = 0;
<add>
<add>var server = https.createServer(options, function(req, res) {
<add> res.writeHead(200);
<add> req.pipe(res);
<add>});
<add>
<add>server.listen(common.PORT, function() {
<add> var resumed = false;
<add> var req = https.request({
<add> port: common.PORT,
<add> method: 'POST'
<add> }, function(res) {
<add> var timer;
<add> res.pause();
<add> common.debug('paused');
<add> send();
<add> function send() {
<add> if (req.write(new Buffer(bufSize))) {
<add> sent += bufSize;
<add> assert.ok(sent < 100 * 1024 * 1024); // max 100MB
<add> return process.nextTick(send);
<add> }
<add> sent += bufSize;
<add> common.debug('sent: ' + sent);
<add> resumed = true;
<add> res.resume();
<add> common.debug('resumed');
<add> timer = setTimeout(function() {
<add> process.exit(1);
<add> }, 1000);
<add> }
<add>
<add> res.on('data', function(data) {
<add> assert.ok(resumed);
<add> if (timer) {
<add> clearTimeout(timer);
<add> timer = null;
<add> }
<add> received += data.length;
<add> if (received >= sent) {
<add> common.debug('received: ' + received);
<add> req.end();
<add> server.close();
<add> }
<add> });
<add> });
<add> req.write('a');
<add> ++sent;
<add>});
<add>
<add>process.on('exit', function() {
<add> assert.equal(sent, received);
<add>});
| 2
|
Javascript
|
Javascript
|
fix coding style in test/unit/crypto_spec.js
|
9e3f7e4d6d8d6a29bee4cd37b4eb593fe74b5062
|
<ide><path>test/unit/crypto_spec.js
<ide> describe('crypto', function() {
<ide> function string2binary(s) {
<ide> var n = s.length, i;
<ide> var result = new Uint8Array(n);
<del> for (i = 0; i < n; ++i)
<add> for (i = 0; i < n; ++i) {
<ide> result[i] = s.charCodeAt(i) % 0xFF;
<add> }
<ide> return result;
<ide> }
<ide>
<ide> describe('CipherTransformFactory', function() {
<ide> describe('#ctor', function() {
<ide> it('should accept user password', function() {
<ide> var factory = new CipherTransformFactory(new DictMock(map1), fileID1,
<del> '123456');
<add> '123456');
<ide> });
<ide>
<ide> it('should accept owner password', function() {
<ide> var factory = new CipherTransformFactory(new DictMock(map1), fileID1,
<del> '654321');
<add> '654321');
<ide> });
<ide>
<ide> it('should not accept wrong password', function() {
<ide> var thrown = false;
<ide> try {
<ide> var factory = new CipherTransformFactory(new DictMock(map1), fileID1,
<del> 'wrong');
<add> 'wrong');
<ide> } catch (e) {
<ide> thrown = true;
<ide> }
| 1
|
PHP
|
PHP
|
fix null when calling explode
|
5d8d5545a40e8360a8b0ef9aaa3e514308ab99fd
|
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function requestedWith($type = null)
<ide> return false;
<ide> }
<ide>
<del> list($contentType) = explode(';', $request->contentType());
<add> list($contentType) = explode(';', $request->contentType() ?? '');
<ide> if ($type === null) {
<ide> return $response->mapType($contentType);
<ide> }
| 1
|
Go
|
Go
|
check supplied hostname before using it
|
412324cfbe9b5e256d9af31b21e6ae142d39612c
|
<ide><path>pkg/libcontainer/nsinit/init.go
<ide> func Init(container *libcontainer.Container, uncleanRootfs, consolePath string,
<ide> if err := mount.InitializeMountNamespace(rootfs, consolePath, container); err != nil {
<ide> return fmt.Errorf("setup mount namespace %s", err)
<ide> }
<del> if err := system.Sethostname(container.Hostname); err != nil {
<del> return fmt.Errorf("sethostname %s", err)
<add> if container.Hostname != "" {
<add> if err := system.Sethostname(container.Hostname); err != nil {
<add> return fmt.Errorf("sethostname %s", err)
<add> }
<ide> }
<ide> if err := FinalizeNamespace(container); err != nil {
<ide> return fmt.Errorf("finalize namespace %s", err)
| 1
|
Text
|
Text
|
add security.md to readme.md
|
472a3d890bcd1c6799658d72bb813626a16d0adc
|
<ide><path>README.md
<ide> source and a list of supported platforms.
<ide>
<ide> ## Security
<ide>
<del>If you find a security vulnerability in Node.js, please report it to
<del>security@nodejs.org. Please withhold public disclosure until after the security
<del>team has addressed the vulnerability.
<del>
<del>The security team will acknowledge your email within 24 hours. You will receive
<del>a more detailed response within 48 hours.
<del>
<del>There are no hard and fast rules to determine if a bug is worth reporting as a
<del>security issue. Here are some examples of past issues and what the Security
<del>Response Team thinks of them. When in doubt, please do send us a report
<del>nonetheless.
<del>
<del>
<del>### Public disclosure preferred
<del>
<del>- [#14519](https://github.com/nodejs/node/issues/14519): _Internal domain
<del> function can be used to cause segfaults_. Requires the ability to execute
<del> arbitrary JavaScript code. That is already the highest level of privilege
<del> possible.
<del>
<del>### Private disclosure preferred
<del>
<del>- [CVE-2016-7099](https://nodejs.org/en/blog/vulnerability/september-2016-security-releases/):
<del> _Fix invalid wildcard certificate validation check_. This was a high-severity
<del> defect. It caused Node.js TLS clients to accept invalid wildcard certificates.
<del>
<del>- [#5507](https://github.com/nodejs/node/pull/5507): _Fix a defect that makes
<del> the CacheBleed Attack possible_. Many, though not all, OpenSSL vulnerabilities
<del> in the TLS/SSL protocols also affect Node.js.
<del>
<del>- [CVE-2016-2216](https://nodejs.org/en/blog/vulnerability/february-2016-security-releases/):
<del> _Fix defects in HTTP header parsing for requests and responses that can allow
<del> response splitting_. This was a remotely-exploitable defect in the Node.js
<del> HTTP implementation.
<del>
<del>When in doubt, please do send us a report.
<del>
<add>For information on reporting security vulnerabilities in Node.js, see
<add>[SECURITY.md](./SECURITY.md).
<ide>
<ide> ## Current Project Team Members
<ide>
<ide><path>SECURITY.md
<add># Security
<add>
<add>If you find a security vulnerability in Node.js, please report it to
<add>security@nodejs.org. Please withhold public disclosure until after the security
<add>team has addressed the vulnerability.
<add>
<add>The security team will acknowledge your email within 24 hours. You will receive
<add>a more detailed response within 48 hours.
<add>
<add>There are no hard and fast rules to determine if a bug is worth reporting as a
<add>security issue. Here are some examples of past issues and what the Security
<add>Response Team thinks of them. When in doubt, please do send us a report
<add>nonetheless.
<add>
<add>## Public disclosure preferred
<add>
<add>- [#14519](https://github.com/nodejs/node/issues/14519): _Internal domain
<add> function can be used to cause segfaults_. Requires the ability to execute
<add> arbitrary JavaScript code. That is already the highest level of privilege
<add> possible.
<add>
<add>## Private disclosure preferred
<add>
<add>- [CVE-2016-7099](https://nodejs.org/en/blog/vulnerability/september-2016-security-releases/):
<add> _Fix invalid wildcard certificate validation check_. This was a high-severity
<add> defect. It caused Node.js TLS clients to accept invalid wildcard certificates.
<add>
<add>- [#5507](https://github.com/nodejs/node/pull/5507): _Fix a defect that makes
<add> the CacheBleed Attack possible_. Many, though not all, OpenSSL vulnerabilities
<add> in the TLS/SSL protocols also affect Node.js.
<add>
<add>- [CVE-2016-2216](https://nodejs.org/en/blog/vulnerability/february-2016-security-releases/):
<add> _Fix defects in HTTP header parsing for requests and responses that can allow
<add> response splitting_. This was a remotely-exploitable defect in the Node.js
<add> HTTP implementation.
<add>
<add>When in doubt, please do send us a report.
| 2
|
Text
|
Text
|
fix typo in esm example
|
4bd8e0efa05112d29de241142ccca3c2dcfb8175
|
<ide><path>doc/api/esm.md
<ide> async function getPackageType(url) {
<ide> // Compose a file path to a package.json in the same directory,
<ide> // which may or may not exist
<ide> const packagePath = resolvePath(dir, 'package.json');
<del> // Try to read the possibly non-existant package.json
<add> // Try to read the possibly nonexistent package.json
<ide> const type = await readFile(packagePath, { encoding: 'utf8' })
<ide> .then((filestring) => JSON.parse(filestring).type)
<ide> .catch((err) => {
| 1
|
Ruby
|
Ruby
|
remove dead code
|
598e7010f98c261df7c0a17c79dea554aebd1334
|
<ide><path>Library/Homebrew/download_strategy.rb
<ide> def initialize name, resource
<ide> @url = "#{@url}?use_mirror=#{mirror}" if mirror
<ide> end
<ide>
<del> def tarball_path
<del> @tarball_path ||= HOMEBREW_CACHE/"#{name}-#{resource.version}#{ext}"
<del> end
<del>
<ide> def stage
<ide> ohai "Pouring #{tarball_path.basename}"
<ide> super
| 1
|
Javascript
|
Javascript
|
apply css on server rendering
|
3e721b6878bcaad7a68256ac9643305bff478fcf
|
<ide><path>client/next.js
<ide> import { createElement } from 'react'
<ide> import { render } from 'react-dom'
<ide> import HeadManager from './head-manager'
<add>import { StyleSheet } from '../lib/css'
<ide> import Router from '../lib/router'
<ide> import DefaultApp from '../lib/app'
<ide> import evalScript from '../lib/eval-script'
<ide>
<ide> const {
<del> __NEXT_DATA__: { app, component, props }
<add> __NEXT_DATA__: { app, component, props, classNames }
<ide> } = window
<ide>
<ide> const App = app ? evalScript(app).default : DefaultApp
<ide> const headManager = new HeadManager()
<ide> const container = document.getElementById('__next')
<ide> const appProps = { Component, props, router, headManager }
<ide>
<add>StyleSheet.rehydrate(classNames)
<ide> render(createElement(App, { ...appProps }), container)
<ide><path>lib/document.js
<ide> export function Head (props, context) {
<ide> .map((h, i) => React.cloneElement(h, { key: '_next' + i }))
<ide> return <head>
<ide> {h}
<del> <style data-aphrodite>{css.content}</style>
<add> <style data-aphrodite dangerouslySetInnerHTML={{ __html: css.content }} />
<ide> </head>
<ide> }
<ide>
<ide> export function Main (props, context) {
<ide> const { html, data } = context._documentProps;
<ide> return <div>
<ide> <div id='__next' dangerouslySetInnerHTML={{ __html: html }} />
<del> <script dangerouslySetInnerHTML={{ __html: '__NEXT_DATA__ = ' + htmlescape(data) }}></script>
<add> <script dangerouslySetInnerHTML={{ __html: '__NEXT_DATA__ = ' + htmlescape(data) }} />
<ide> </div>
<ide> }
<ide>
<ide><path>server/render.js
<ide> export async function render (path, ctx, { dir = process.cwd(), dev = false } =
<ide> html,
<ide> head,
<ide> css,
<del> data: { component, props },
<add> data: {
<add> component,
<add> props,
<add> classNames: css.renderedClassNames
<add> },
<ide> hotReload: false,
<ide> dev
<ide> })
| 3
|
Go
|
Go
|
enable multiple cli build tests
|
bb4b31585c19b5d20a536c615e54b2fe48f8054c
|
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> testRequires(c, SameHostDaemon)
<ide>
<ide> name := "testbuildcontextcleanup"
<ide> func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
<ide> c.Fatalf("failed to list contents of tmp dir: %s", err)
<ide> }
<ide> _, err = buildImage(name,
<del> `FROM scratch
<add> `FROM `+minimalBaseImage()+`
<ide> RUN /non/existing/command`,
<ide> true)
<ide> if err == nil {
<ide> func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // TODO Windows: This test passes on Windows,
<del> // but currently adds a disproportionate amount of time for the value it has.
<del> // Removing it from Windows CI for now, but this will be revisited in the
<del> // TP5 timeframe when perf is better.
<ide> name := "testbuilddockerignore"
<ide> dockerfile := `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // TODO Windows: This test passes on Windows,
<del> // but currently adds a disproportionate amount of time for the value it has.
<del> // Removing it from Windows CI for now, but this will be revisited in the
<del> // TP5 timeframe when perf is better.
<ide> name := "testbuilddockerignoreexceptions"
<ide> dockerfile := `
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildDockerignoringWildDirs(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // TODO Windows: Fix this test; also perf
<del>
<ide> dockerfile := `
<ide> FROM busybox
<ide> COPY . /
<ide> func (s *DockerSuite) TestBuildFromGITwithF(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> name := "testbuildfromremotetarball"
<ide>
<ide> buffer := new(bytes.Buffer)
<ide> RUN echo from Dockerfile`,
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<del>
<ide> server, err := fakeStorage(map[string]string{"baz": `FROM busybox
<ide> RUN echo from baz
<ide> COPY * /tmp/
<ide> func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support ARG
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> envVal := "bar"
<ide> func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support ARG
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> envVal := "bar"
<ide> func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support ARG
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> envVal := "bar"
<ide> func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support ARG
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> envVal := "bar"
<ide> func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> envVal := "bar"
<ide> func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support ARG
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> envKey1 := "foo1"
<ide> func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildBuildTimeArgDefintionWithNoEnvInjection(c *check.C) {
<del> testRequires(c, DaemonIsLinux) // Windows does not support ARG
<ide> imgName := "bldargtest"
<ide> envKey := "foo"
<ide> args := []string{}
<ide> func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
<ide>
<ide> // #17290
<ide> func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> name := "testbuildbrokensymlink"
<ide> ctx, err := fakeContext(`
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> name := "testbuildbrokensymlink"
<ide> ctx, err := fakeContext(`
<ide> FROM busybox
<ide> func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
<del> testRequires(c, DaemonIsLinux)
<ide> name := "testbuildbrokensymlink"
<ide> ctx, err := fakeContext(`
<ide> FROM busybox
| 1
|
PHP
|
PHP
|
update php8 string function
|
ab5fd4bfc2a93283c26a4bfbc63f48355694bca4
|
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
<ide> protected function serializeClassCastableAttribute($key, $value)
<ide> */
<ide> protected function isCustomDateTimeCast($cast)
<ide> {
<del> return strncmp($cast, 'date:', 5) === 0 ||
<del> strncmp($cast, 'datetime:', 9) === 0;
<add> return str_starts_with($cast, 'date:') ||
<add> str_starts_with($cast, 'datetime:');
<ide> }
<ide>
<ide> /**
<ide> protected function isCustomDateTimeCast($cast)
<ide> */
<ide> protected function isDecimalCast($cast)
<ide> {
<del> return strncmp($cast, 'decimal:', 8) === 0;
<add> return str_starts_with($cast, 'decimal:');
<ide> }
<ide>
<ide> /**
| 1
|
PHP
|
PHP
|
remove strange test
|
2a728804ccc1ef63fcf4fae3b4d5d73eda04dbba
|
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testClassesCanBeInjectedIntoRoutes()
<ide> unset($_SERVER['__test.route_inject']);
<ide> }
<ide>
<del> public function testClassesAndVariablesCanBeInjectedIntoRoutes()
<del> {
<del> unset($_SERVER['__test.route_inject']);
<del> $router = $this->getRouter();
<del> $router->get('foo/{var}/{bar?}/{baz?}', function (stdClass $foo, $var, $bar = 'test', Request $baz = null) {
<del> $_SERVER['__test.route_inject'] = func_get_args();
<del>
<del> return 'hello';
<del> });
<del> $this->assertEquals('hello', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());
<del> $this->assertInstanceOf('stdClass', $_SERVER['__test.route_inject'][0]);
<del> $this->assertEquals('bar', $_SERVER['__test.route_inject'][1]);
<del> $this->assertEquals('test', $_SERVER['__test.route_inject'][2]);
<del> $this->assertArrayHasKey(3, $_SERVER['__test.route_inject']);
<del> $this->assertInstanceOf('Illuminate\Http\Request', $_SERVER['__test.route_inject'][3]);
<del> unset($_SERVER['__test.route_inject']);
<del> }
<del>
<ide> public function testOptionsResponsesAreGeneratedByDefault()
<ide> {
<ide> $router = $this->getRouter();
| 1
|
Ruby
|
Ruby
|
remove more flaky tests
|
fb0fa419abc750bf33695a396244b9cffbea1554
|
<ide><path>Library/Homebrew/test/cask/cmd/upgrade_spec.rb
<ide> end
<ide> end
<ide>
<del> context "dry run upgrade" do
<del> let(:installed) {
<del> [
<del> "outdated/local-caffeine",
<del> "outdated/local-transmission",
<del> "outdated/auto-updates",
<del> "outdated/version-latest",
<del> ]
<del> }
<del>
<del> before do
<del> installed.each { |cask| Cask::Cmd::Install.run(cask) }
<del>
<del> allow_any_instance_of(described_class).to receive(:verbose?).and_return(true)
<del> end
<del>
<del> describe 'without --greedy it ignores the Casks with "version latest" or "auto_updates true"' do
<del> it "would update all the installed Casks when no token is provided" do
<del> local_caffeine = Cask::CaskLoader.load("local-caffeine")
<del> local_caffeine_path = Cask::Config.global.appdir.join("Caffeine.app")
<del> local_transmission = Cask::CaskLoader.load("local-transmission")
<del> local_transmission_path = Cask::Config.global.appdir.join("Transmission.app")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del>
<del> described_class.run("--dry-run")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del> expect(local_caffeine.versions).not_to include("1.2.3")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del> expect(local_transmission.versions).not_to include("2.61")
<del> end
<del>
<del> it "would update only the Casks specified in the command line" do
<del> local_caffeine = Cask::CaskLoader.load("local-caffeine")
<del> local_caffeine_path = Cask::Config.global.appdir.join("Caffeine.app")
<del> local_transmission = Cask::CaskLoader.load("local-transmission")
<del> local_transmission_path = Cask::Config.global.appdir.join("Transmission.app")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del>
<del> described_class.run("--dry-run", "local-caffeine")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del> expect(local_caffeine.versions).not_to include("1.2.3")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del> expect(local_transmission.versions).not_to include("2.61")
<del> end
<del> end
<del>
<del> describe "with --greedy it checks additional Casks" do
<del> it 'would include the Casks with "auto_updates true" or "version latest"' do
<del> local_caffeine = Cask::CaskLoader.load("local-caffeine")
<del> local_caffeine_path = Cask::Config.global.appdir.join("Caffeine.app")
<del> auto_updates = Cask::CaskLoader.load("auto-updates")
<del> auto_updates_path = Cask::Config.global.appdir.join("MyFancyApp.app")
<del> local_transmission = Cask::CaskLoader.load("local-transmission")
<del> local_transmission_path = Cask::Config.global.appdir.join("Transmission.app")
<del> version_latest = Cask::CaskLoader.load("version-latest")
<del> version_latest_path_1 = Cask::Config.global.appdir.join("Caffeine Mini.app")
<del> version_latest_path_2 = Cask::Config.global.appdir.join("Caffeine Pro.app")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.57")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del>
<del> expect(version_latest).to be_installed
<del> expect(version_latest_path_1).to be_a_directory
<del> expect(version_latest.versions).to include("latest")
<del>
<del> described_class.run("--greedy", "--dry-run")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del> expect(local_caffeine.versions).not_to include("1.2.3")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.57")
<del> expect(auto_updates.versions).not_to include("2.61")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del> expect(local_transmission.versions).not_to include("2.61")
<del>
<del> expect(version_latest).to be_installed
<del> expect(version_latest_path_2).to be_a_directory
<del> end
<del>
<del> it 'does not include the Casks with "auto_updates true" when the version did not change' do
<del> cask = Cask::CaskLoader.load("auto-updates")
<del> cask_path = cask.config.appdir.join("MyFancyApp.app")
<del>
<del> expect(cask).to be_installed
<del> expect(cask_path).to be_a_directory
<del> expect(cask.versions).to include("2.57")
<del>
<del> described_class.run("--dry-run", "auto-updates", "--greedy")
<del>
<del> expect(cask).to be_installed
<del> expect(cask_path).to be_a_directory
<del> expect(cask.versions).to include("2.57")
<del> expect(cask.versions).not_to include("2.61")
<del>
<del> described_class.run("--dry-run", "auto-updates", "--greedy")
<del>
<del> expect(cask).to be_installed
<del> expect(cask_path).to be_a_directory
<del> expect(cask.versions).to include("2.57")
<del> expect(cask.versions).not_to include("2.61")
<del> end
<del> end
<del> end
<del>
<ide> context "failed upgrade" do
<ide> let(:installed) {
<ide> [
| 1
|
Java
|
Java
|
add tests for importselector meta-data
|
e142fd11e08261de16f79e23081e02cab3d9f628
|
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java
<ide> import java.lang.annotation.Retention;
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<add>import java.util.HashMap;
<add>import java.util.Map;
<ide>
<add>import org.hamcrest.Matcher;
<add>import org.junit.BeforeClass;
<ide> import org.junit.Test;
<ide> import org.mockito.InOrder;
<ide> import org.springframework.beans.BeansException;
<ide>
<ide> import static org.hamcrest.CoreMatchers.*;
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.Matchers.*;
<ide> import static org.mockito.Mockito.*;
<ide>
<ide> /**
<ide> */
<ide> public class ImportSelectorTests {
<ide>
<add> static Map<Class<?>, String> importFrom = new HashMap<Class<?>, String>();
<add>
<add> @BeforeClass
<add> public static void clearImportFrom() {
<add> ImportSelectorTests.importFrom.clear();
<add> }
<add>
<ide> @Test
<ide> public void importSelectors() {
<ide> DefaultListableBeanFactory beanFactory = spy(new DefaultListableBeanFactory());
<ide> public void importSelectors() {
<ide>
<ide> @Test
<ide> public void invokeAwareMethodsInImportSelector() {
<del>
<ide> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
<ide> context.getBean(MessageSource.class);
<del>
<ide> assertThat(SampleRegistrar.beanFactory, is((BeanFactory) context.getBeanFactory()));
<ide> assertThat(SampleRegistrar.classLoader, is(context.getBeanFactory().getBeanClassLoader()));
<ide> assertThat(SampleRegistrar.resourceLoader, is(notNullValue()));
<ide> assertThat(SampleRegistrar.environment, is((Environment) context.getEnvironment()));
<ide> }
<ide>
<add> @Test
<add> public void correctMetaDataOnIndirectImports() throws Exception {
<add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IndirectConfig.class);
<add> Matcher<String> isFromIndirect = equalTo(IndirectImport.class.getName());
<add> System.out.println(importFrom);
<add> assertThat(importFrom.get(ImportSelector1.class), isFromIndirect);
<add> assertThat(importFrom.get(ImportSelector2.class), isFromIndirect);
<add> assertThat(importFrom.get(DeferredImportSelector1.class), isFromIndirect);
<add> assertThat(importFrom.get(DeferredImportSelector2.class), isFromIndirect);
<add> }
<add>
<ide> @Configuration
<ide> @Import(SampleImportSelector.class)
<ide> static class AwareConfig {
<ide> public static class ImportSelector1 implements ImportSelector {
<ide>
<ide> @Override
<ide> public String[] selectImports(AnnotationMetadata importingClassMetadata) {
<add> ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
<ide> return new String[] { ImportedSelector1.class.getName() };
<ide> }
<ide> }
<ide> public static class ImportSelector2 implements ImportSelector {
<ide>
<ide> @Override
<ide> public String[] selectImports(AnnotationMetadata importingClassMetadata) {
<add> ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
<ide> return new String[] { ImportedSelector2.class.getName() };
<ide> }
<ide> }
<ide> public static class DeferredImportSelector1 implements DeferredImportSelector, O
<ide>
<ide> @Override
<ide> public String[] selectImports(AnnotationMetadata importingClassMetadata) {
<add> ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
<ide> return new String[] { DeferredImportedSelector1.class.getName() };
<ide> }
<ide>
<ide> public static class DeferredImportSelector2 implements DeferredImportSelector {
<ide>
<ide> @Override
<ide> public String[] selectImports(AnnotationMetadata importingClassMetadata) {
<add> ImportSelectorTests.importFrom.put(getClass(), importingClassMetadata.getClassName());
<ide> return new String[] { DeferredImportedSelector2.class.getName() };
<ide> }
<ide>
<ide> public String d() {
<ide> }
<ide> }
<ide>
<add> @Configuration
<add> @Import(IndirectImportSelector.class)
<add> public static class IndirectConfig {
<add>
<add> }
<add>
<add> public static class IndirectImportSelector implements ImportSelector {
<add> @Override
<add> public String[] selectImports(AnnotationMetadata importingClassMetadata) {
<add> return new String[] { IndirectImport.class.getName()};
<add> }
<add> }
<add>
<add> @Sample
<add> public static class IndirectImport {
<add>
<add> }
<add>
<ide> }
| 1
|
Python
|
Python
|
add accuracy monitoring, verbose eval/predict
|
616537f3085aa00c41871a2226c4fdd4d6e8c669
|
<ide><path>keras/models.py
<ide> def standardize_y(y):
<ide> y = np.reshape(y, (len(y), 1))
<ide> return y
<ide>
<add>def make_batches(size, batch_size):
<add> nb_batch = int(np.ceil(size/float(batch_size)))
<add> return [(i*batch_size, min(size, (i+1)*batch_size)) for i in range(0, nb_batch)]
<add>
<ide> class Sequential(object):
<ide> def __init__(self):
<ide> self.layers = []
<ide> def add(self, layer):
<ide> self.layers[-1].connect(self.layers[-2])
<ide> self.params += [p for p in layer.params]
<ide>
<del> def compile(self, optimizer, loss):
<add> def compile(self, optimizer, loss, class_mode="categorical"):
<ide> self.optimizer = optimizers.get(optimizer)
<ide> self.loss = objectives.get(loss)
<ide>
<ide> def compile(self, optimizer, loss):
<ide> self.y_test = self.layers[-1].output(train=False)
<ide>
<ide> # output of model
<del> self.Y = T.matrix() # TODO: support for custom output shapes
<add> self.y = T.matrix() # TODO: support for custom output shapes
<add>
<add> train_loss = self.loss(self.y, self.y_train)
<add> test_score = self.loss(self.y, self.y_test)
<add>
<add> if class_mode == "categorical":
<add> train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))
<add> test_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_test, axis=-1)))
<add>
<add> elif class_mode == "binary":
<add> train_accuracy = T.mean(T.eq(self.y, T.round(self.y_train)))
<add> test_accuracy = T.mean(T.eq(self.y, T.round(self.y_test)))
<add> else:
<add> raise Exception("Invalid class mode:" + str(class_mode))
<add> self.class_mode = class_mode
<ide>
<del> train_loss = self.loss(self.Y, self.y_train)
<del> test_score = self.loss(self.Y, self.y_test)
<ide> updates = self.optimizer.get_updates(self.params, train_loss)
<ide>
<del> self._train = theano.function([self.X, self.Y], train_loss,
<add> self._train = theano.function([self.X, self.y], train_loss,
<add> updates=updates, allow_input_downcast=True)
<add> self._train_with_acc = theano.function([self.X, self.y], [train_loss, train_accuracy],
<ide> updates=updates, allow_input_downcast=True)
<ide> self._predict = theano.function([self.X], self.y_test,
<ide> allow_input_downcast=True)
<del> self._test = theano.function([self.X, self.Y], test_score,
<add> self._test = theano.function([self.X, self.y], test_score,
<add> allow_input_downcast=True)
<add> self._test_with_acc = theano.function([self.X, self.y], [test_score, test_accuracy],
<ide> allow_input_downcast=True)
<ide>
<del> def train(self, X, y):
<add> def train(self, X, y, accuracy=False):
<ide> y = standardize_y(y)
<del> loss = self._train(X, y)
<del> return loss
<add> if accuracy:
<add> return self._train_with_acc(X, y)
<add> else:
<add> return self._train(X, y)
<add>
<ide>
<del> def test(self, X, y):
<add> def test(self, X, y, accuracy=False):
<ide> y = standardize_y(y)
<del> score = self._test(X, y)
<del> return score
<add> if accuracy:
<add> return self._test_with_acc(X, y)
<add> else:
<add> return self._test(X, y)
<add>
<ide>
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1,
<del> validation_split=0., shuffle=True):
<del> # If a validation split size is given (e.g. validation_split=0.2)
<del> # then split X into smaller X and X_val,
<del> # and split y into smaller y and y_val.
<add> validation_split=0., validation_data=None, shuffle=True, show_accuracy=False):
<ide> y = standardize_y(y)
<ide>
<ide> do_validation = False
<del> if validation_split > 0 and validation_split < 1:
<add> if validation_data:
<add> try:
<add> X_val, y_val = validation_data
<add> except:
<add> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val).")
<ide> do_validation = True
<del> split_at = int(len(X) * (1 - validation_split))
<del> (X, X_val) = (X[0:split_at], X[split_at:])
<del> (y, y_val) = (y[0:split_at], y[split_at:])
<add> y_val = standardize_y(y_val)
<ide> if verbose:
<ide> print "Train on %d samples, validate on %d samples" % (len(y), len(y_val))
<add> else:
<add> if 0 < validation_split < 1:
<add> # If a validation split size is given (e.g. validation_split=0.2)
<add> # then split X into smaller X and X_val,
<add> # and split y into smaller y and y_val.
<add> do_validation = True
<add> split_at = int(len(X) * (1 - validation_split))
<add> (X, X_val) = (X[0:split_at], X[split_at:])
<add> (y, y_val) = (y[0:split_at], y[split_at:])
<add> if verbose:
<add> print "Train on %d samples, validate on %d samples" % (len(y), len(y_val))
<ide>
<ide> index_array = np.arange(len(X))
<ide> for epoch in range(nb_epoch):
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1,
<ide> if shuffle:
<ide> np.random.shuffle(index_array)
<ide>
<del> nb_batch = int(np.ceil(len(X)/float(batch_size)))
<add> batches = make_batches(len(X), batch_size)
<ide> progbar = Progbar(target=len(X))
<del> for batch_index in range(0, nb_batch):
<del> batch_start = batch_index*batch_size
<del> batch_end = min(len(X), (batch_index+1)*batch_size)
<add> for batch_index, (batch_start, batch_end) in enumerate(batches):
<ide> batch_ids = index_array[batch_start:batch_end]
<del>
<ide> X_batch = X[batch_ids]
<ide> y_batch = y[batch_ids]
<del> loss = self._train(X_batch, y_batch)
<add>
<add> if show_accuracy:
<add> loss, acc = self._train_with_acc(X_batch, y_batch)
<add> else:
<add> loss = self._train(X_batch, y_batch)
<ide>
<add> # logging
<ide> if verbose:
<del> is_last_batch = (batch_index == nb_batch - 1)
<add> is_last_batch = (batch_index == len(batches) - 1)
<ide> if not is_last_batch or not do_validation:
<del> progbar.update(batch_end, [('loss', loss)])
<add> if show_accuracy:
<add> progbar.update(batch_end, [('loss', loss), ('acc.', acc)])
<add> else:
<add> progbar.update(batch_end, [('loss', loss)])
<ide> else:
<del> progbar.update(batch_end, [('loss', loss), ('val. loss', self.test(X_val, y_val))])
<add> if show_accuracy:
<add> val_loss, val_acc = self.test(X_val, y_val, accuracy=True)
<add> progbar.update(batch_end, [('loss', loss), ('acc.', acc), ('val. loss', val_loss), ('val. acc.', val_acc)])
<add> else:
<add> val_loss = self.test(X_val, y_val, accuracy=False)
<add> progbar.update(batch_end, [('loss', loss), ('val. loss', val_loss)])
<add>
<ide>
<del> def predict_proba(self, X, batch_size=128):
<del> for batch_index in range(0, len(X)/batch_size+1):
<del> batch = range(batch_index*batch_size, min(len(X), (batch_index+1)*batch_size))
<del> if not batch:
<del> break
<del> batch_preds = self._predict(X[batch])
<add> def predict_proba(self, X, batch_size=128, verbose=1):
<add> batches = make_batches(len(X), batch_size)
<add> if verbose:
<add> progbar = Progbar(target=len(X))
<add> for batch_index, (batch_start, batch_end) in enumerate(batches):
<add> X_batch = X[batch_start:batch_end]
<add> batch_preds = self._predict(X_batch)
<ide>
<ide> if batch_index == 0:
<ide> shape = (len(X),) + batch_preds.shape[1:]
<ide> preds = np.zeros(shape)
<del> preds[batch] = batch_preds
<add> preds[batch_start:batch_end] = batch_preds
<add>
<add> if verbose:
<add> progbar.update(batch_end)
<ide> return preds
<ide>
<del> def predict_classes(self, X, batch_size=128):
<del> proba = self.predict_proba(X, batch_size=batch_size)
<del> # The last dimension is the one containing the class probas
<del> classes_dim = proba.ndim - 1
<del> if proba.shape[classes_dim] > 1:
<del> return proba.argmax(axis=classes_dim)
<add>
<add> def predict_classes(self, X, batch_size=128, verbose=1):
<add> proba = self.predict_proba(X, batch_size=batch_size, verbose=verbose)
<add> if self.class_mode == "categorical":
<add> return proba.argmax(axis=-1)
<ide> else:
<ide> return (proba>0.5).astype('int32')
<ide>
<del> def evaluate(self, X, y, batch_size=128):
<add>
<add> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<ide> y = standardize_y(y)
<del> av_score = 0.
<del> samples = 0
<del> for batch_index in range(0, len(X)/batch_size+1):
<del> batch = range(batch_index*batch_size, min(len(X), (batch_index+1)*batch_size))
<del> if not batch:
<del> break
<del> score = self._test(X[batch], y[batch])
<del> av_score += len(batch)*score
<del> samples += len(batch)
<del> return av_score/samples
<add>
<add> if show_accuracy:
<add> tot_acc = 0.
<add> tot_score = 0.
<add>
<add> batches = make_batches(len(X), batch_size)
<add> progbar = Progbar(target=len(X))
<add> for batch_index, (batch_start, batch_end) in enumerate(batches):
<add> X_batch = X[batch_start:batch_end]
<add> y_batch = y[batch_start:batch_end]
<add>
<add> if show_accuracy:
<add> loss, acc = self._test_with_acc(X_batch, y_batch)
<add> tot_acc += acc
<add> else:
<add> loss = self._test(X_batch, y_batch)
<add> tot_score += loss
<add>
<add> if verbose:
<add> if show_accuracy:
<add> progbar.update(batch_end, [('loss', loss), ('acc.', acc)])
<add> else:
<add> progbar.update(batch_end, [('loss', loss)])
<add>
<add> if show_accuracy:
<add> return tot_score/len(batches), tot_acc/len(batches)
<add> else:
<add> return tot_score/len(batches)
<add>
<add>
<ide>
<ide>
| 1
|
Python
|
Python
|
add proth number to maths
|
618f9ca885a6f4e0c2f7dfcf1768ef7b0f717ba6
|
<ide><path>maths/proth_number.py
<add>"""
<add>Calculate the nth Proth number
<add>
<add>Source:
<add> https://handwiki.org/wiki/Proth_number
<add>"""
<add>
<add>import math
<add>
<add>
<add>def proth(number: int) -> int:
<add> """
<add> :param number: nth number to calculate in the sequence
<add> :return: the nth number in Proth number
<add>
<add> Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3
<add>
<add> >>> proth(6)
<add> 25
<add>
<add> >>> proth(0)
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Input value of [number=0] must be > 0
<add>
<add> >>> proth(-1)
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Input value of [number=-1] must be > 0
<add>
<add> >>> proth(6.0)
<add> Traceback (most recent call last):
<add> ...
<add> TypeError: Input value of [number=6.0] must be an integer
<add> """
<add>
<add> if not isinstance(number, int):
<add> raise TypeError(f"Input value of [number={number}] must be an integer")
<add>
<add> if number < 1:
<add> raise ValueError(f"Input value of [number={number}] must be > 0")
<add> elif number == 1:
<add> return 3
<add> elif number == 2:
<add> return 5
<add> else:
<add> block_index = number // 3
<add> """
<add> +1 for binary starting at 0 i.e. 2^0, 2^1, etc.
<add> +1 to start the sequence at the 3rd Proth number
<add> Hence, we have a +2 in the below statement
<add> """
<add> block_index = math.log(block_index, 2) + 2
<add> block_index = int(block_index)
<add>
<add> proth_list = [3, 5]
<add> proth_index = 2
<add> increment = 3
<add> for block in range(1, block_index):
<add> for move in range(increment):
<add> proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
<add> proth_index += 1
<add> increment *= 2
<add>
<add> return proth_list[number - 1]
<add>
<add>
<add>if __name__ == "__main__":
<add> for number in range(11):
<add> value = 0
<add> try:
<add> value = proth(number)
<add> except ValueError:
<add> print(f"ValueError: there is no {number}th Proth number")
<add> continue
<add>
<add> print(f"The {number}th Proth number: {value}")
| 1
|
Python
|
Python
|
fix typo in all model docs
|
13c185771847370d695b8eee3cbf12f4edc2111c
|
<ide><path>src/transformers/modeling_albert.py
<ide> class AlbertForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_bart.py
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_bert_generation.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide> def forward(
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide> labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide> Labels for computing the left-to-right language modeling loss (next word prediction).
<ide> Indices should be in ``[-100, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)
<ide><path>src/transformers/modeling_ctrl.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_distilbert.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
<ide><path>src/transformers/modeling_dpr.py
<ide> def init_weights(self):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide> def init_weights(self):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(n_passages, sequence_length, hidden_size)`, `optional`):
<ide><path>src/transformers/modeling_electra.py
<ide> class ElectraForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_encoder_decoder.py
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_flaubert.py
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_fsmt.py
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_funnel.py
<ide> class FunnelForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_gpt2.py
<ide> class GPT2DoubleHeadsModelOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`, `optional`):
<ide><path>src/transformers/modeling_longformer.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> global_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_lxmert.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> visual_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):
<ide> Mask to avoid performing attention on padding token indices.
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_mmbt.py
<ide> def forward(self, input_modal, start_token=None, end_token=None, position_ids=No
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:
<ide> def forward(self, input_modal, start_token=None, end_token=None, position_ids=No
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> output_attentions (:obj:`bool`, `optional`):
<ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
<ide><path>src/transformers/modeling_mobilebert.py
<ide> class MobileBertForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide> class MobileBertForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> output_attentions (:obj:`bool`, `optional`):
<ide> Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
<ide><path>src/transformers/modeling_openai.py
<ide> class OpenAIGPTDoubleHeadsModelOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_rag.py
<ide> def from_pretrained_question_encoder_generator(
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> encoder_outputs (:obj:`tuple(tuple(torch.FloatTensor)`, `optional`)
<ide> def generate(
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> context_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size * config.n_docs, config.max_combined_length)`, `optional`, returned when `output_retrieved=True`):
<ide> def generate(
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> context_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size * config.n_docs, config.max_combined_length)`, `optional`, returned when `output_retrieved=True`):
<ide><path>src/transformers/modeling_reformer.py
<ide> class ReformerModelWithLMHeadOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_retribert.py
<ide> def forward(
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> input_ids_doc (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):
<ide><path>src/transformers/modeling_roberta.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_squeezebert.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_t5.py
<ide> def forward(
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> decoder_input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, target_sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_tf_albert.py
<ide> class TFAlbertForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_bert.py
<ide> class TFBertForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_ctrl.py
<ide> class TFCTRLPreTrainedModel(TFPreTrainedModel):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_tf_distilbert.py
<ide> class TFDistilBertPreTrainedModel(TFPreTrainedModel):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> head_mask (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
<ide><path>src/transformers/modeling_tf_electra.py
<ide> class TFElectraForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> position_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_flaubert.py
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - ``1`` for tokens that are **not masked**,
<del> - ``0`` for tokens that are **maked**.
<add> - ``0`` for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> langs (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_tf_funnel.py
<ide> class TFFunnelForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_gpt2.py
<ide> class TFGPT2DoubleHeadsModelOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_tf_longformer.py
<ide> def dummy_inputs(self):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> global_attention_mask (:obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_lxmert.py
<ide> def dummy_inputs(self) -> Dict[str, tf.Tensor]:
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> visual_attention_mask (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide> MMask to avoid performing attention on padding token indices.
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`tf.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_tf_mobilebert.py
<ide> class TFMobileBertForPreTrainingOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_openai.py
<ide> class TFOpenAIGPTDoubleHeadsModelOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`):
<ide><path>src/transformers/modeling_tf_roberta.py
<ide> class TFRobertaPreTrainedModel(TFPreTrainedModel):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_t5.py
<ide> def _shift_right(self, input_ids):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> decoder_attention_mask (:obj:`tf.Tensor` of shape :obj:`(batch_size, tgt_seq_len)`, `optional`):
<ide><path>src/transformers/modeling_tf_xlm.py
<ide> class TFXLMWithLMHeadModelOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> langs (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_tf_xlnet.py
<ide> class TFXLNetForQuestionAnsweringSimpleOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> mems (:obj:`List[torch.FloatTensor]` of length :obj:`config.n_layers`):
<ide><path>src/transformers/modeling_xlm.py
<ide> class XLMForQuestionAnsweringOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> langs (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
<ide><path>src/transformers/modeling_xlnet.py
<ide> class XLNetForQuestionAnsweringOutput(ModelOutput):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> mems (:obj:`List[torch.FloatTensor]` of length :obj:`config.n_layers`):
<ide><path>templates/adding_a_new_model/modeling_tf_xxx.py
<ide> class TFXxxPreTrainedModel(TFPreTrainedModel):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`Numpy array` or :obj:`tf.Tensor` of shape :obj:`({0})`, `optional`):
<ide><path>templates/adding_a_new_model/modeling_xxx.py
<ide> def _init_weights(self, module):
<ide> Mask values selected in ``[0, 1]``:
<ide>
<ide> - 1 for tokens that are **not masked**,
<del> - 0 for tokens that are **maked**.
<add> - 0 for tokens that are **masked**.
<ide>
<ide> `What are attention masks? <../glossary.html#attention-mask>`__
<ide> token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
| 43
|
Ruby
|
Ruby
|
remove audit whitelist
|
09d53f4fc567dfafb6d9c71742f4633762f55d7c
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_line(line, lineno)
<ide> end
<ide>
<ide> if line =~ /ARGV\.(?!(debug\?|verbose\?|value[\(\s]))/
<del> # Python formulae need ARGV for Requirements
<del> problem "Use build instead of ARGV to check options",
<del> :whitelist => %w{pygobject3 qscintilla2}
<add> problem "Use build instead of ARGV to check options"
<ide> end
<ide>
<ide> if line =~ /def options/
<ide> def audit
<ide>
<ide> private
<ide>
<del> def problem p, options={}
<del> return if options[:whitelist].to_a.include? f.name
<add> def problem p
<ide> @problems << p
<ide> end
<ide> end
| 1
|
Ruby
|
Ruby
|
add more docs comment context
|
59747144539a3c394b6c4e5e27948df41bec22d2
|
<ide><path>Library/Homebrew/dev-cmd/pull.rb
<ide> def merge_commit?(url)
<ide>
<ide> # Use `homebrew` remote if HOMEBREW_FORCE_HOMEBREW_ON_LINUX env variable is set.
<ide> # The `homebrew` remote points to homebrew-core tap and is used by Linux maintainers.
<add> # See https://docs.brew.sh/Homebrew-linuxbrew-core-Maintainer-Guide#preparation
<ide> remote = ENV["HOMEBREW_FORCE_HOMEBREW_ON_LINUX"] ? "homebrew" : "origin"
<ide> safe_system "git", "fetch", "--quiet", remote, "pull/#{pr_number}/head"
<ide> Utils.popen_read("git", "rev-list", "--parents", "-n1", "FETCH_HEAD").count(" ") > 1
| 1
|
PHP
|
PHP
|
check disable_functions before set_time_limit
|
52685b3f2ca3055ce3c6418f9a943cab06cc085a
|
<ide><path>src/Http/Response.php
<ide> protected function _sendFile($file, $range)
<ide> }
<ide>
<ide> $bufferSize = 8192;
<del> set_time_limit(0);
<add> if (array_search('set_time_limit', explode(',', ini_get('disable_functions'))) === false) {
<add> set_time_limit(0);
<add> }
<ide> session_write_close();
<ide> while (!feof($file->handle)) {
<ide> if (!$this->_isActive()) {
| 1
|
Mixed
|
Javascript
|
handle errors properly with deep*equal
|
204d94fc756218bfeee921905c8be488027f9627
|
<ide><path>doc/api/assert.md
<ide> Only [enumerable "own" properties][] are considered. The
<ide> non-enumerable properties — for such checks, consider using
<ide> [`assert.deepStrictEqual()`][] instead. This can lead to some
<ide> potentially surprising results. For example, the following example does not
<del>throw an `AssertionError` because the properties on the [`Error`][] object are
<add>throw an `AssertionError` because the properties on the [`RegExp`][] object are
<ide> not enumerable:
<ide>
<ide> ```js
<ide> // WARNING: This does not throw an AssertionError!
<del>assert.deepEqual(Error('a'), Error('b'));
<add>assert.deepEqual(/a/gi, new Date());
<ide> ```
<ide>
<ide> An exception is made for [`Map`][] and [`Set`][]. Maps and Sets have their
<ide> parameter is undefined, a default error message is assigned.
<ide> <!-- YAML
<ide> added: v1.2.0
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/12142
<add> description: Error names and messages are now properly compared
<ide> - version: v8.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/12142
<ide> description: Set and Map content is also compared
<ide><path>lib/assert.js
<ide> function strictDeepEqual(actual, expected) {
<ide> if (!areSimilarRegExps(actual, expected)) {
<ide> return false;
<ide> }
<add> } else if (actualTag === '[object Error]') {
<add> // Do not compare the stack as it might differ even though the error itself
<add> // is otherwise identical. The non-enumerable name should be identical as
<add> // the prototype is also identical. Otherwise this is caught later on.
<add> if (actual.message !== expected.message) {
<add> return false;
<add> }
<ide> } else if (!isFloatTypedArrayTag(actualTag) && ArrayBuffer.isView(actual)) {
<ide> if (!areSimilarTypedArrays(actual, expected)) {
<ide> return false;
<ide> function looseDeepEqual(actual, expected) {
<ide> if (isRegExp(actual) && isRegExp(expected)) {
<ide> return areSimilarRegExps(actual, expected);
<ide> }
<add> if (actual instanceof Error && expected instanceof Error) {
<add> if (actual.message !== expected.message || actual.name !== expected.name)
<add> return false;
<add> }
<ide> const actualTag = objectToString(actual);
<ide> const expectedTag = objectToString(expected);
<ide> if (actualTag === expectedTag) {
<ide><path>test/parallel/test-assert-deep.js
<ide> function assertDeepAndStrictEqual(a, b) {
<ide> assert.deepStrictEqual(b, a);
<ide> }
<ide>
<del>function assertNotDeepOrStrict(a, b) {
<del> assert.throws(() => assert.deepEqual(a, b), re`${a} deepEqual ${b}`);
<del> assert.throws(() => assert.deepStrictEqual(a, b),
<add>function assertNotDeepOrStrict(a, b, err) {
<add> assert.throws(() => assert.deepEqual(a, b), err || re`${a} deepEqual ${b}`);
<add> assert.throws(() => assert.deepStrictEqual(a, b), err ||
<ide> re`${a} deepStrictEqual ${b}`);
<ide>
<del> assert.throws(() => assert.deepEqual(b, a), re`${b} deepEqual ${a}`);
<del> assert.throws(() => assert.deepStrictEqual(b, a),
<add> assert.throws(() => assert.deepEqual(b, a), err || re`${b} deepEqual ${a}`);
<add> assert.throws(() => assert.deepStrictEqual(b, a), err ||
<ide> re`${b} deepStrictEqual ${a}`);
<ide> }
<ide>
<del>function assertOnlyDeepEqual(a, b) {
<add>function assertOnlyDeepEqual(a, b, err) {
<ide> assert.doesNotThrow(() => assert.deepEqual(a, b));
<del> assert.throws(() => assert.deepStrictEqual(a, b),
<add> assert.throws(() => assert.deepStrictEqual(a, b), err ||
<ide> re`${a} deepStrictEqual ${b}`);
<ide>
<ide> assert.doesNotThrow(() => assert.deepEqual(b, a));
<del> assert.throws(() => assert.deepStrictEqual(b, a),
<add> assert.throws(() => assert.deepStrictEqual(b, a), err ||
<ide> re`${b} deepStrictEqual ${a}`);
<ide> }
<ide>
<ide> assertOnlyDeepEqual(
<ide> assertDeepAndStrictEqual([1, , , 3], [1, , , 3]);
<ide> assertOnlyDeepEqual([1, , , 3], [1, , , 3, , , ]);
<ide>
<add>// Handle different error messages
<add>{
<add> const err1 = new Error('foo1');
<add> const err2 = new Error('foo2');
<add> const err3 = new TypeError('foo1');
<add> assertNotDeepOrStrict(err1, err2, assert.AssertionError);
<add> assertNotDeepOrStrict(err1, err3, assert.AssertionError);
<add> // TODO: evaluate if this should throw or not. The same applies for RegExp
<add> // Date and any object that has the same keys but not the same prototype.
<add> assertOnlyDeepEqual(err1, {}, assert.AssertionError);
<add>}
<add>
<ide> /* eslint-enable */
| 3
|
Ruby
|
Ruby
|
use file.open instead of kernel.open
|
0304545d0cb334c5f24be63e1c639ff8989f7226
|
<ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit
<ide> style_results = Style.check_style_json(style_files, options) if style_files
<ide> # load licenses
<ide> spdx = HOMEBREW_LIBRARY_PATH/"data/spdx.json"
<del> spdx_data = open(spdx, "r") do |file|
<add> spdx_data = File.open(spdx, "r") do |file|
<ide> JSON.parse(file.read)
<ide> end
<ide> new_formula_problem_lines = []
| 1
|
Python
|
Python
|
limit astroid version to < 2.12
|
ee564ef9e57707ef07db1c3353a1406e47d8e3db
|
<ide><path>setup.py
<ide> def write_version(filename: str = str(AIRFLOW_SOURCES_ROOT / "airflow" / "git_ve
<ide> 'requests>=2.26.0',
<ide> ]
<ide> doc = [
<add> # Astroid 2.12.* breaks documentation building
<add> # We can remove the limit here after https://github.com/PyCQA/astroid/issues/1708 is solved
<add> 'astroid<2.12.0',
<ide> 'click>=8.0',
<ide> # Docutils 0.17.0 converts generated <div class="section"> into <section> and breaks our doc formatting
<ide> # By adding a lot of whitespace separation. This limit can be lifted when we update our doc to handle
| 1
|
Ruby
|
Ruby
|
fix schema_cache_test.rb for sqlite3_mem
|
1defb6adb8be9051402d2496ded4bb8233d0d925
|
<ide><path>activerecord/test/cases/connection_adapters/schema_cache_test.rb
<ide> class SchemaCacheTest < ActiveRecord::TestCase
<ide> def setup
<ide> connection = ActiveRecord::Base.connection
<ide> @cache = SchemaCache.new connection
<del>
<del> if in_memory_db?
<del> connection.create_table :posts do |t|
<del> t.integer :cololumn
<del> end
<del> end
<ide> end
<ide>
<ide> def test_primary_key
| 1
|
Ruby
|
Ruby
|
prefer dir.glob when iterating over the result
|
bf365fc23b89e924e1bfbbb65befdf2a72774819
|
<ide><path>Library/Homebrew/cmd/tap.rb
<ide> def link_tap_formula paths
<ide> def repair_taps
<ide> count = 0
<ide> # prune dead symlinks in Formula
<del> Dir["#{HOMEBREW_LIBRARY}/Formula/*.rb"].each do |fn|
<add> Dir.glob("#{HOMEBREW_LIBRARY}/Formula/*.rb") do |fn|
<ide> if not File.exist? fn
<ide> File.delete fn
<ide> count += 1
<ide><path>Library/Homebrew/cmd/update.rb
<ide> def git_init_if_necessary
<ide>
<ide> def rename_taps_dir_if_necessary
<ide> need_repair_taps = false
<del> Dir["#{HOMEBREW_LIBRARY}/Taps/*/"].each do |tapd|
<add> Dir.glob("#{HOMEBREW_LIBRARY}/Taps/*/") do |tapd|
<ide> begin
<ide> tapd_basename = File.basename(tapd)
<ide>
| 2
|
PHP
|
PHP
|
fix unguarded bug
|
dfaeb785e478981a49dd1a0e4c95faadbd69ba50
|
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function fill(array $attributes)
<ide> */
<ide> protected function fillableFromArray(array $attributes)
<ide> {
<del> if (count($this->fillable) > 0)
<add> if (count($this->fillable) > 0 and ! static::$unguarded)
<ide> {
<ide> return array_intersect_key($attributes, array_flip($this->fillable));
<ide> }
| 1
|
Java
|
Java
|
add default destination for @sendto methods
|
72dec7d0fed80cf74139157690641096de23f41a
|
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandler.java
<ide> public class SendToMethodReturnValueHandler implements HandlerMethodReturnValueH
<ide>
<ide> private final boolean annotationRequired;
<ide>
<add> private String defaultDestinationPrefix = "/topic";
<add>
<add> private String defaultUserDestinationPrefix = "/queue";
<add>
<ide>
<ide> public SendToMethodReturnValueHandler(SimpMessageSendingOperations messagingTemplate, boolean annotationRequired) {
<ide> Assert.notNull(messagingTemplate, "messagingTemplate is required");
<ide> public SendToMethodReturnValueHandler(SimpMessageSendingOperations messagingTemp
<ide> }
<ide>
<ide>
<add> /**
<add> * Configure a default prefix to add to message destinations in cases where a method
<add> * is not annotated with {@link SendTo @SendTo} or does not specify any destinations
<add> * through the annotation's value attribute.
<add> * <p>
<add> * By default, the prefix is set to "/topic".
<add> */
<add> public void setDefaultDestinationPrefix(String defaultDestinationPrefix) {
<add> this.defaultDestinationPrefix = defaultDestinationPrefix;
<add> }
<add>
<add> /**
<add> * Return the configured default destination prefix.
<add> * @see #setDefaultDestinationPrefix(String)
<add> */
<add> public String getDefaultDestinationPrefix() {
<add> return this.defaultDestinationPrefix;
<add> }
<add>
<add> /**
<add> * Configure a default prefix to add to message destinations in cases where a
<add> * method is annotated with {@link SendToUser @SendToUser} but does not specify
<add> * any destinations through the annotation's value attribute.
<add> * <p>
<add> * By default, the prefix is set to "/queue".
<add> */
<add> public void setDefaultUserDestinationPrefix(String prefix) {
<add> this.defaultUserDestinationPrefix = prefix;
<add> }
<add>
<add> /**
<add> * Return the configured default user destination prefix.
<add> * @see #setDefaultUserDestinationPrefix(String)
<add> */
<add> public String getDefaultUserDestinationPrefix() {
<add> return this.defaultUserDestinationPrefix;
<add> }
<add>
<add>
<ide> @Override
<ide> public boolean supportsReturnType(MethodParameter returnType) {
<ide> if ((returnType.getMethodAnnotation(SendTo.class) != null) ||
<ide> public void handleReturnValue(Object returnValue, MethodParameter returnType, Me
<ide> throw new MissingSessionUserException(inputMessage);
<ide> }
<ide> String user = inputHeaders.getUser().getName();
<del> for (String destination : getDestinations(sendToUser, inputHeaders.getDestination())) {
<add> String[] destinations = getTargetDestinations(sendToUser, inputHeaders, this.defaultUserDestinationPrefix);
<add> for (String destination : destinations) {
<ide> this.messagingTemplate.convertAndSendToUser(user, destination, returnValue, postProcessor);
<ide> }
<ide> return;
<ide> }
<del>
<del> SendTo sendTo = returnType.getMethodAnnotation(SendTo.class);
<del> if (sendTo != null) {
<del> for (String destination : getDestinations(sendTo, inputHeaders.getDestination())) {
<add> else {
<add> SendTo sendTo = returnType.getMethodAnnotation(SendTo.class);
<add> String[] destinations = getTargetDestinations(sendTo, inputHeaders, this.defaultDestinationPrefix);
<add> for (String destination : getTargetDestinations(sendTo, inputHeaders, this.defaultDestinationPrefix)) {
<ide> this.messagingTemplate.convertAndSend(destination, returnValue, postProcessor);
<ide> }
<del> return;
<ide> }
<del>
<del> this.messagingTemplate.convertAndSend(inputHeaders.getDestination(), returnValue, postProcessor);
<ide> }
<ide>
<del> private String[] getDestinations(Annotation annot, String inputDestination) {
<del> String[] destinations = (String[]) AnnotationUtils.getValue(annot);
<del> return ObjectUtils.isEmpty(destinations) ? new String[] { inputDestination } : destinations;
<add> protected String[] getTargetDestinations(Annotation annot, SimpMessageHeaderAccessor inputHeaders,
<add> String defaultPrefix) {
<add>
<add> if (annot != null) {
<add> String[] value = (String[]) AnnotationUtils.getValue(annot);
<add> if (!ObjectUtils.isEmpty(value)) {
<add> return value;
<add> }
<add> }
<add> return new String[] { defaultPrefix + inputHeaders.getDestination() };
<ide> }
<ide>
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SendToMethodReturnValueHandlerTests.java
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.MessageChannel;
<del>import org.springframework.messaging.handler.annotation.MessageMapping;
<ide> import org.springframework.messaging.handler.annotation.SendTo;
<ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
<ide> import org.springframework.messaging.simp.SimpMessagingTemplate;
<ide> public class SendToMethodReturnValueHandlerTests {
<ide>
<ide> @Mock private MessageConverter messageConverter;
<ide>
<add> private MethodParameter noAnnotationsReturnType;
<ide> private MethodParameter sendToReturnType;
<del>
<add> private MethodParameter sendToDefaultDestReturnType;
<ide> private MethodParameter sendToUserReturnType;
<del>
<del> private MethodParameter missingSendToReturnType;
<add> private MethodParameter sendToUserDefaultDestReturnType;
<ide>
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> public void setup() throws Exception {
<ide> this.handler = new SendToMethodReturnValueHandler(messagingTemplate, true);
<ide> this.handlerAnnotationNotRequired = new SendToMethodReturnValueHandler(messagingTemplate, false);
<ide>
<del> Method method = this.getClass().getDeclaredMethod("handleAndSendTo");
<add> Method method = this.getClass().getDeclaredMethod("handleNoAnnotations");
<add> this.noAnnotationsReturnType = new MethodParameter(method, -1);
<add>
<add> method = this.getClass().getDeclaredMethod("handleAndSendToDefaultDestination");
<add> this.sendToDefaultDestReturnType = new MethodParameter(method, -1);
<add>
<add> method = this.getClass().getDeclaredMethod("handleAndSendTo");
<ide> this.sendToReturnType = new MethodParameter(method, -1);
<ide>
<ide> method = this.getClass().getDeclaredMethod("handleAndSendToUser");
<ide> this.sendToUserReturnType = new MethodParameter(method, -1);
<ide>
<del> method = this.getClass().getDeclaredMethod("handleWithMissingSendTo");
<del> this.missingSendToReturnType = new MethodParameter(method, -1);
<add> method = this.getClass().getDeclaredMethod("handleAndSendToUserDefaultDestination");
<add> this.sendToUserDefaultDestReturnType = new MethodParameter(method, -1);
<ide> }
<ide>
<ide>
<ide> @Test
<ide> public void supportsReturnType() throws Exception {
<ide> assertTrue(this.handler.supportsReturnType(this.sendToReturnType));
<ide> assertTrue(this.handler.supportsReturnType(this.sendToUserReturnType));
<del> assertFalse(this.handler.supportsReturnType(this.missingSendToReturnType));
<del> assertTrue(this.handlerAnnotationNotRequired.supportsReturnType(this.missingSendToReturnType));
<add> assertFalse(this.handler.supportsReturnType(this.noAnnotationsReturnType));
<add> assertTrue(this.handlerAnnotationNotRequired.supportsReturnType(this.noAnnotationsReturnType));
<add> }
<add>
<add> @Test
<add> public void sendToNoAnnotations() throws Exception {
<add>
<add> when(this.messageChannel.send(any(Message.class))).thenReturn(true);
<add>
<add> Message<?> inputMessage = createInputMessage("sess1", "sub1", "/dest", null);
<add> this.handler.handleReturnValue(payloadContent, this.noAnnotationsReturnType, inputMessage);
<add>
<add> verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
<add>
<add> Message<?> message = this.messageCaptor.getAllValues().get(0);
<add> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
<add> assertEquals("sess1", headers.getSessionId());
<add> assertNull(headers.getSubscriptionId());
<add> assertEquals("/topic/dest", headers.getDestination());
<ide> }
<ide>
<ide> @Test
<ide> public void sendToMethod() throws Exception {
<ide> when(this.messageChannel.send(any(Message.class))).thenReturn(true);
<ide>
<ide> String sessionId = "sess1";
<del> Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/dest", null);
<del>
<add> Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, null);
<ide> this.handler.handleReturnValue(payloadContent, this.sendToReturnType, inputMessage);
<ide>
<ide> verify(this.messageChannel, times(2)).send(this.messageCaptor.capture());
<ide>
<ide> Message<?> message = this.messageCaptor.getAllValues().get(0);
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
<del>
<ide> assertEquals(sessionId, headers.getSessionId());
<ide> assertNull(headers.getSubscriptionId());
<ide> assertEquals("/dest1", headers.getDestination());
<ide>
<ide> message = this.messageCaptor.getAllValues().get(1);
<ide> headers = SimpMessageHeaderAccessor.wrap(message);
<del>
<ide> assertEquals(sessionId, headers.getSessionId());
<ide> assertNull(headers.getSubscriptionId());
<ide> assertEquals("/dest2", headers.getDestination());
<ide> }
<ide>
<add> @Test
<add> public void sendToDefaultDestinationMethod() throws Exception {
<add>
<add> when(this.messageChannel.send(any(Message.class))).thenReturn(true);
<add>
<add> String sessionId = "sess1";
<add> Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/dest", null);
<add> this.handler.handleReturnValue(payloadContent, this.sendToDefaultDestReturnType, inputMessage);
<add>
<add> verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
<add>
<add> Message<?> message = this.messageCaptor.getAllValues().get(0);
<add> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
<add> assertEquals(sessionId, headers.getSessionId());
<add> assertNull(headers.getSubscriptionId());
<add> assertEquals("/topic/dest", headers.getDestination());
<add> }
<add>
<ide> @Test
<ide> public void sendToUserMethod() throws Exception {
<ide>
<ide> when(this.messageChannel.send(any(Message.class))).thenReturn(true);
<ide>
<ide> String sessionId = "sess1";
<ide> TestUser user = new TestUser();
<del> Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/dest", user);
<del>
<add> Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, user);
<ide> this.handler.handleReturnValue(payloadContent, this.sendToUserReturnType, inputMessage);
<ide>
<ide> verify(this.messageChannel, times(2)).send(this.messageCaptor.capture());
<ide>
<ide> Message<?> message = this.messageCaptor.getAllValues().get(0);
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
<del>
<ide> assertEquals(sessionId, headers.getSessionId());
<ide> assertNull(headers.getSubscriptionId());
<ide> assertEquals("/user/" + user.getName() + "/dest1", headers.getDestination());
<ide>
<ide> message = this.messageCaptor.getAllValues().get(1);
<ide> headers = SimpMessageHeaderAccessor.wrap(message);
<del>
<ide> assertEquals(sessionId, headers.getSessionId());
<ide> assertNull(headers.getSubscriptionId());
<ide> assertEquals("/user/" + user.getName() + "/dest2", headers.getDestination());
<ide> }
<ide>
<add> @Test
<add> public void sendToUserDefaultDestinationMethod() throws Exception {
<add>
<add> when(this.messageChannel.send(any(Message.class))).thenReturn(true);
<add>
<add> String sessionId = "sess1";
<add> TestUser user = new TestUser();
<add> Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/dest", user);
<add> this.handler.handleReturnValue(payloadContent, this.sendToUserDefaultDestReturnType, inputMessage);
<add>
<add> verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
<add>
<add> Message<?> message = this.messageCaptor.getAllValues().get(0);
<add> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
<add> assertEquals(sessionId, headers.getSessionId());
<add> assertNull(headers.getSubscriptionId());
<add> assertEquals("/user/" + user.getName() + "/queue/dest", headers.getDestination());
<add> }
<add>
<ide>
<del> private Message<?> createInputMessage(String sessId, String subsId, String dest, Principal principal) {
<add> private Message<?> createInputMessage(String sessId, String subsId, String destination, Principal principal) {
<ide> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create();
<ide> headers.setSessionId(sessId);
<ide> headers.setSubscriptionId(subsId);
<del> headers.setDestination(dest);
<del> headers.setUser(principal);
<add> if (destination != null) {
<add> headers.setDestination(destination);
<add> }
<add> if (principal != null) {
<add> headers.setUser(principal);
<add> }
<ide> return MessageBuilder.withPayload(new byte[0]).copyHeaders(headers.toMap()).build();
<ide> }
<ide>
<ide> public boolean implies(Subject subject) {
<ide> }
<ide> }
<ide>
<del> @MessageMapping("/handle") // not needed for the tests but here for completeness
<del> public String handleWithMissingSendTo() {
<add> public String handleNoAnnotations() {
<add> return payloadContent;
<add> }
<add>
<add> @SendTo
<add> public String handleAndSendToDefaultDestination() {
<ide> return payloadContent;
<ide> }
<ide>
<del> @MessageMapping("/handle") // not needed for the tests but here for completeness
<ide> @SendTo({"/dest1", "/dest2"})
<ide> public String handleAndSendTo() {
<ide> return payloadContent;
<ide> }
<ide>
<del> @MessageMapping("/handle") // not needed for the tests but here for completeness
<add> @SendToUser
<add> public String handleAndSendToUserDefaultDestination() {
<add> return payloadContent;
<add> }
<add>
<ide> @SendToUser({"/dest1", "/dest2"})
<ide> public String handleAndSendToUser() {
<ide> return payloadContent;
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/handler/SimpAnnotationMethodIntegrationTests.java
<ide> public void sendMessageToControllerAndReceiveReplyViaTopic() throws Exception {
<ide> "id:subs1", "destination:/topic/increment").build();
<ide>
<ide> TextMessage message2 = create(StompCommand.SEND).headers(
<del> "destination:/app/topic/increment").body("5").build();
<add> "destination:/app/increment").body("5").build();
<ide>
<ide> TestClientWebSocketHandler clientHandler = new TestClientWebSocketHandler(1, message1, message2);
<ide> WebSocketSession session = doHandshake(clientHandler, "/ws").get();
<ide> public void handleException(IllegalArgumentException ex) {
<ide> @IntegrationTestController
<ide> static class IncrementController {
<ide>
<del> @MessageMapping(value="/topic/increment")
<add> @MessageMapping(value="/increment")
<ide> public int handle(int i) {
<ide> return i + 1;
<ide> }
| 3
|
Python
|
Python
|
use keywords instead of args
|
ef5d4ed17c4d38148f357ecfa15f42b763a49b39
|
<ide><path>celery/app/base.py
<ide> from celery.local import PromiseProxy, maybe_evaluate
<ide> from celery.utils.functional import first
<ide> from celery.utils.imports import instantiate, symbol_by_name
<add>from celery.utils.objects import mro_lookup
<ide>
<ide> from .annotations import prepare as prepare_annotations
<ide> from .builtins import shared_task, load_shared_tasks
<ide> from .defaults import DEFAULTS, find_deprecated_settings
<ide> from .registry import TaskRegistry
<del>from .utils import AppPickler, Settings, bugreport, _unpickle_app
<add>from .utils import (
<add> AppPickler, Settings, bugreport, _unpickle_app, _unpickle_app_v2,
<add>)
<ide>
<ide> DEFAULT_FIXUPS = (
<ide> 'celery.fixups.django:DjangoFixup',
<ide> )
<ide>
<ide>
<add>def app_has_custom(app, attr):
<add> return mro_lookup(app.__class__, attr, stop=(Celery, object),
<add> monkey_patched=[__name__])
<add>
<add>
<ide> def _unpickle_appattr(reverse_name, args):
<ide> """Given an attribute name and a list of args, gets
<ide> the attribute from the current app and calls it."""
<ide> def __init__(self, main=None, loader=None, backend=None,
<ide> if not isinstance(self._tasks, TaskRegistry):
<ide> self._tasks = TaskRegistry(self._tasks or {})
<ide>
<add> # If the class defins a custom __reduce_args__ we need to use
<add> # the old way of pickling apps, which is pickling a list of
<add> # args instead of the new way that pickles a dict of keywords.
<add> self._using_v1_reduce = app_has_custom(self, '__reduce_args__')
<add>
<ide> # these options are moved to the config to
<ide> # simplify pickling of the app object.
<del> self._preconf = {}
<add> self._preconf = changes or {}
<ide> if broker:
<ide> self._preconf['BROKER_URL'] = broker
<ide> if include:
<ide> def __repr__(self):
<ide> type(self).__name__, self.main or '__main__', id(self))
<ide>
<ide> def __reduce__(self):
<add> if self._using_v1_reduce:
<add> return self.__reduce_v1__()
<add> return (_unpickle_app_v2, (self.__class__, self.__reduce_keys__()))
<add>
<add> def __reduce_v1__(self):
<ide> # Reduce only pickles the configuration changes,
<ide> # so the default configuration doesn't have to be passed
<ide> # between processes.
<ide> return (_unpickle_app, (self.__class__, self.Pickler)
<ide> + self.__reduce_args__())
<ide>
<add> def __reduce_keys__(self):
<add> """Returns keyword arguments used to reconstruct the object
<add> when unpickling."""
<add> return {
<add> 'main': self.main,
<add> 'changes': self.conf.changes,
<add> 'loader': self.loader_cls,
<add> 'backend': self.backend_cls,
<add> 'amqp': self.amqp_cls,
<add> 'events': self.events_cls,
<add> 'log': self.log_cls,
<add> 'control': self.control_cls,
<add> 'accept_magic_kwargs': self.accept_magic_kwargs,
<add> }
<add>
<ide> def __reduce_args__(self):
<add> """Deprecated method, please use :meth:`__reduce_keys__` instead."""
<ide> return (self.main, self.conf.changes, self.loader_cls,
<ide> self.backend_cls, self.amqp_cls, self.events_cls,
<ide> self.log_cls, self.control_cls, self.accept_magic_kwargs)
<ide><path>celery/app/utils.py
<ide> def humanize(self):
<ide>
<ide>
<ide> class AppPickler(object):
<del> """Default application pickler/unpickler."""
<add> """Old application pickler/unpickler (<= 3.0)."""
<ide>
<ide> def __call__(self, cls, *args):
<ide> kwargs = self.build_kwargs(*args)
<ide> def construct(self, cls, **kwargs):
<ide>
<ide>
<ide> def _unpickle_app(cls, pickler, *args):
<add> """Rebuild app for versions 2.5+"""
<ide> return pickler()(cls, *args)
<ide>
<ide>
<add>def _unpickle_app_v2(cls, kwargs):
<add> """Rebuild app for versions 3.1+"""
<add> kwargs['set_as_current'] = False
<add> return cls(**kwargs)
<add>
<add>
<ide> def bugreport(app):
<ide> """Returns a string containing information useful in bug reports."""
<ide> import billiard
| 2
|
Ruby
|
Ruby
|
use variations hash when installing from api
|
7392f9811e6c5a03038b336d9560c6fa1d76682d
|
<ide><path>Library/Homebrew/formulary.rb
<ide> def self.load_formula_from_api(name, flags:)
<ide> class_s = Formulary.class_s(name)
<ide> json_formula = Homebrew::API::Formula.all_formulae[name]
<ide>
<add> bottle_tag = Utils::Bottles.tag.to_s
<add> if json_formula.key?("variations") && json_formula["variations"].key?(bottle_tag)
<add> json_formula = json_formula.merge(json_formula["variations"][bottle_tag])
<add> end
<add>
<ide> klass = Class.new(::Formula) do
<ide> desc json_formula["desc"]
<ide> homepage json_formula["homepage"]
<ide><path>Library/Homebrew/test/formulary_spec.rb
<ide> def formula_json_contents(extra_items = {})
<ide> }
<ide> end
<ide>
<add> let(:variations_json) do
<add> {
<add> "variations" => {
<add> Utils::Bottles.tag.to_s => {
<add> "dependencies" => ["dep", "variations_dep"],
<add> },
<add> },
<add> }
<add> end
<add>
<ide> before do
<ide> allow(described_class).to receive(:loader_for).and_return(described_class::FormulaAPILoader.new(formula_name))
<ide> end
<ide> def formula_json_contents(extra_items = {})
<ide> formula.install
<ide> }.to raise_error("Cannot build from source from abstract formula.")
<ide> end
<add>
<add> it "returns a Formula with variations when given a name", :needs_macos do
<add> allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents(variations_json)
<add> allow(Utils::Bottles).to receive(:tag).and_return(:arm64_monterey)
<add>
<add> formula = described_class.factory(formula_name)
<add> expect(formula).to be_kind_of(Formula)
<add> expect(formula.deps.count).to eq 5
<add> expect(formula.deps.map(&:name).include?("variations_dep")).to be true
<add> end
<ide> end
<ide> end
<ide>
| 2
|
Javascript
|
Javascript
|
commit lint fixes for the api
|
07266b7e432489f757250b395ef52e3c93da4678
|
<ide><path>api-server/common/models/User-Identity.js
<ide> export default function(UserIdent) {
<ide> return identity
<ide> ? Observable.of(identity.user())
<ide> : User.findOne$({ where: { email } }).flatMap(user => {
<del> return user
<del> ? Observable.of(user)
<del> : User.create$({ email }).toPromise();
<del> });
<add> return user
<add> ? Observable.of(user)
<add> : User.create$({ email }).toPromise();
<add> });
<ide> })
<ide> .flatMap(user => {
<ide> const createToken = observeQuery(AccessToken, 'create', {
<ide><path>api-server/common/utils/index.js
<ide> export function dashify(str) {
<ide> return ('' + str)
<ide> .toLowerCase()
<ide> .replace(/\s/g, '-')
<del> .replace(/[^a-z0-9\-\.]/gi, '')
<del> .replace(/\:/g, '');
<add> .replace(/[^a-z0-9\-.]/gi, '')
<add> .replace(/:/g, '');
<ide> }
<ide> // todo: unify with server/utils/index.js:dasherize
<ide> const dasherize = dashify;
<ide> export { dasherize };
<ide>
<del>export const fixCompletedChallengeItem = obj => pick(
<del> obj,
<del> [ 'id', 'completedDate', 'solution', 'githubLink', 'challengeType', 'files' ]
<del>);
<add>export const fixCompletedChallengeItem = obj =>
<add> pick(obj, [
<add> 'id',
<add> 'completedDate',
<add> 'solution',
<add> 'githubLink',
<add> 'challengeType',
<add> 'files',
<add> ]);
<ide><path>api-server/server/boot/donate.js
<ide> export default function donateBoot(app, done) {
<ide> name:
<ide> 'Monthly Donation to freeCodeCamp.org - ' +
<ide> `Thank you ($${current / 100})`
<del> },
<del> currency: 'usd',
<del> id: `monthly-donation-${current}`
<add> },
<add> currency: 'usd',
<add> id: `monthly-donation-${current}`
<ide> }
<ide> }), {}
<ide> );
<ide> export default function donateBoot(app, done) {
<ide> throw err;
<ide> }
<ide> console.log(`${plan.id} created`);
<del> return;
<del> });
<add> return;
<add> });
<ide> }
<ide>
<ide> function createStripeDonation(req, res) {
<ide> export default function donateBoot(app, done) {
<ide> email,
<ide> card: id
<ide> });
<del> })
<del> .then(customer => {
<del> donation.customerId = customer.id;
<del> return stripe.subscriptions.create({
<del> customer: customer.id,
<del> items: [
<del> {
<del> plan: `monthly-donation-${amount}`
<del> }
<del> ]
<del> });
<del> })
<del> .then(subscription => {
<del> donation.subscriptionId = subscription.id;
<del> return res.send(subscription);
<del> })
<del> .then(() => {
<del> donatingUser.createDonation(donation).toPromise()
<del> .catch(err => {
<del> throw new Error(err);
<add> })
<add> .then(customer => {
<add> donation.customerId = customer.id;
<add> return stripe.subscriptions.create({
<add> customer: customer.id,
<add> items: [
<add> {
<add> plan: `monthly-donation-${amount}`
<add> }
<add> ]
<ide> });
<del> })
<del> .catch(err => {
<del> if (err.type === 'StripeCardError') {
<del> return res.status(402).send({ error: err.message });
<del> }
<del> return res.status(500).send({ error: 'Donation Failed' });
<del> });
<add> })
<add> .then(subscription => {
<add> donation.subscriptionId = subscription.id;
<add> return res.send(subscription);
<add> })
<add> .then(() => {
<add> donatingUser.createDonation(donation).toPromise()
<add> .catch(err => {
<add> throw new Error(err);
<add> });
<add> })
<add> .catch(err => {
<add> if (err.type === 'StripeCardError') {
<add> return res.status(402).send({ error: err.message });
<add> }
<add> return res.status(500).send({ error: 'Donation Failed' });
<add> });
<ide> }
<ide>
<ide> const pubKey = keys.stripe.public;
<ide><path>api-server/server/boot/randomAPIs.js
<ide> module.exports = function(app) {
<ide> .then(() => {
<ide> req.flash(
<ide> 'success',
<del> "We've successfully updated your email preferences."
<add> 'We\'ve successfully updated your email preferences.'
<ide> );
<ide> return res.redirectWithFlash(
<ide> `${homeLocation}/unsubscribed/${unsubscribeId}`
<ide> module.exports = function(app) {
<ide> .then(() => {
<ide> req.flash(
<ide> 'success',
<del> "We've successfully updated your email preferences. Thank you " +
<add> 'We\'ve successfully updated your email preferences. Thank you ' +
<ide> 'for resubscribing.'
<ide> );
<ide> return res.redirectWithFlash(homeLocation);
<ide> module.exports = function(app) {
<ide> }
<ide> pulls = pulls
<ide> ? Object.keys(JSON.parse(pulls)).length
<del> : "Can't connect to github";
<add> : 'Can\'t connect to github';
<ide>
<ide> return request(
<ide> [
<ide> module.exports = function(app) {
<ide> issues =
<ide> pulls === parseInt(pulls, 10) && issues
<ide> ? Object.keys(JSON.parse(issues)).length - pulls
<del> : "Can't connect to GitHub";
<add> : 'Can\'t connect to GitHub';
<ide> return res.send({
<ide> issues: issues,
<ide> pulls: pulls
<ide><path>api-server/server/boot/user.js
<ide> function createPostReportUserProfile(app) {
<ide> to: 'team@freecodecamp.org',
<ide> cc: user.email,
<ide> from: 'team@freecodecamp.org',
<del> subject: 'Abuse Report : Reporting ' + username + "'s profile.",
<add> subject: `Abuse Report : Reporting ${username}'s profile.`,
<ide> text: dedent(`
<ide> Hello Team,\n
<ide> This is to report the profile of ${username}.\n
<ide><path>api-server/server/middlewares/csp.js
<ide> import helmet from 'helmet';
<ide> import { homeLocation } from '../../../config/env';
<ide>
<ide> let trusted = [
<del> "'self'",
<add> '\'self\'',
<ide> 'https://search.freecodecamp.org',
<ide> homeLocation,
<ide> 'https://' + process.env.AUTH0_DOMAIN
<ide> export default function csp() {
<ide> 'https://*.algolia.net'
<ide> ]),
<ide> scriptSrc: [
<del> "'unsafe-eval'",
<del> "'unsafe-inline'",
<add> '\'unsafe-eval\'',
<add> '\'unsafe-inline\'',
<ide> '*.google-analytics.com',
<ide> '*.gstatic.com',
<ide> 'https://*.cloudflare.com',
<ide> export default function csp() {
<ide> '*.ytimg.com'
<ide> ].concat(trusted),
<ide> styleSrc: [
<del> "'unsafe-inline'",
<add> '\'unsafe-inline\'',
<ide> '*.gstatic.com',
<ide> '*.googleapis.com',
<ide> '*.bootstrapcdn.com',
<ide><path>api-server/server/middlewares/jwt-authorization.js
<ide> export default () => function authorizeByJWT(req, res, next) {
<ide> if (!req.user) {
<ide> const User = loopback.getModelByType('User');
<ide> return User.findById(userId)
<del> .then(user => {
<del> if (user) {
<del> user.points = user.progressTimestamps.length;
<del> req.user = user;
<del> }
<del> return;
<del> })
<del> .then(next)
<del> .catch(next);
<add> .then(user => {
<add> if (user) {
<add> user.points = user.progressTimestamps.length;
<add> req.user = user;
<add> }
<add> return;
<add> })
<add> .then(next)
<add> .catch(next);
<ide> } else {
<ide> return next();
<ide> }
<ide><path>api-server/server/rss/index.js
<ide> class NewsFeed {
<ide> const currentFeed = this.state.combinedFeed.slice(0);
<ide> log('grabbing feeds');
<ide> return Promise.all([
<del> getMediumFeed(),
<del> getLybsynFeed()
<del> ]).then(
<del> ([mediumFeed, lybsynFeed]) => this.setState(
<del> state => ({
<del> ...state,
<del> mediumFeed,
<del> lybsynFeed
<add> getMediumFeed(),
<add> getLybsynFeed()
<add> ]).then(
<add> ([mediumFeed, lybsynFeed]) => this.setState(
<add> state => ({
<add> ...state,
<add> mediumFeed,
<add> lybsynFeed
<add> })
<add> ))
<add> .then(() => {
<add> log('crossing the streams');
<add> const { mediumFeed, lybsynFeed} = this.state;
<add> const combinedFeed = [ ...mediumFeed, ...lybsynFeed ].sort((a, b) => {
<add> return compareDesc(a.isoDate, b.isoDate);
<add> });
<add> this.setState(state => ({
<add> ...state,
<add> combinedFeed,
<add> readyState: true
<add> }));
<ide> })
<del> ))
<del> .then(() => {
<del> log('crossing the streams');
<del> const { mediumFeed, lybsynFeed} = this.state;
<del> const combinedFeed = [ ...mediumFeed, ...lybsynFeed ].sort((a, b) => {
<del> return compareDesc(a.isoDate, b.isoDate);
<add> .catch(err => {
<add> console.log(err);
<add> this.setState(state => ({
<add> ...state,
<add> combinedFeed: currentFeed
<add> }));
<ide> });
<del> this.setState(state => ({
<del> ...state,
<del> combinedFeed,
<del> readyState: true
<del> }));
<del> })
<del> .catch(err => {
<del> console.log(err);
<del> this.setState(state => ({
<del> ...state,
<del> combinedFeed: currentFeed
<del> }));
<del> });
<ide> }
<ide>
<ide>
<ide><path>api-server/server/rss/lybsyn.js
<ide> export function getLybsynFeed() {
<ide> ])
<ide> )
<ide> /* eslint-disable camelcase */
<del> .map(({ full_item_url, item_title, release_date, item_body_short}) => ({
<del> title: item_title,
<del> extract: item_body_short,
<del> isoDate: new Date(release_date).toISOString(),
<del> link: full_item_url
<del> }));
<add> .map(({ full_item_url, item_title, release_date, item_body_short}) => ({
<add> title: item_title,
<add> extract: item_body_short,
<add> isoDate: new Date(release_date).toISOString(),
<add> link: full_item_url
<add> }));
<ide> /* eslint-enable camelcase */
<ide> return resolve(items);
<ide> });
<ide><path>api-server/server/rss/medium.js
<ide> function getExtract(str) {
<ide>
<ide>
<ide> function addResponsiveClass(str) {
<del> return str.replace(/\<img/g, '<img class="img-responsive"');
<add> return str.replace(/<img/g, '<img class="img-responsive"');
<ide> }
<ide>
<ide> export function getMediumFeed() {
<ide><path>api-server/server/services/challenge.js
<ide> export default function getChallengesForBlock(app) {
<ide> return {
<ide> name: 'challenge',
<ide> read: function readChallengesForBlock(
<del> req,
<del> resource,
<del> { dashedName, blockName} = {},
<del> config,
<del> cb
<del> ) {
<add> req,
<add> resource,
<add> { dashedName, blockName} = {},
<add> config,
<add> cb
<add> ) {
<ide> const getChallengeBlock$ = challengeMap
<ide> .flatMap(({
<ide> result: { superBlocks },
<ide><path>api-server/server/services/user.js
<ide> export default function userServices() {
<ide> config,
<ide> cb) {
<ide> const queryUser = req.user;
<del> console.log(queryUser.completedChallengeCount)
<ide> const source = queryUser && Observable.forkJoin(
<ide> queryUser.getCompletedChallenges$(),
<ide> queryUser.getPoints$(),
<ide> export default function userServices() {
<ide> result: user.username
<ide> })
<ide> )
<del> )
<add> )
<ide> .subscribe(
<ide> user => cb(null, user),
<ide> cb
<ide><path>api-server/server/utils/date-utils.js
<ide> export function dayCount([head, tail], timezone = 'UTC') {
<ide> moment(tail).tz(timezone).startOf('day'),
<ide> 'days',
<ide> true)
<del> );
<add> );
<ide> }
<ide><path>api-server/server/utils/getDynamicPropsForUser.js
<del>
<ide> function getCompletedCertCount(user) {
<ide> return [
<ide> 'isApisMicroservicesCert',
<ide> function getCompletedCertCount(user) {
<ide> 'isInfosecQaCert',
<ide> 'isJsAlgoDataStructCert',
<ide> 'isRespWebDesignCert'
<del> ].reduce((sum, key) => user[key] ? sum + 1 : sum, 0);
<add> ].reduce((sum, key) => (user[key] ? sum + 1 : sum), 0);
<ide> }
<ide>
<ide> function getLegacyCertCount(user) {
<del> return [
<del> 'isFrontEndCert',
<del> 'isBackEndCert',
<del> 'isDataVisCert'
<del> ].reduce((sum, key) => user[key] ? sum + 1 : sum, 0);
<add> return ['isFrontEndCert', 'isBackEndCert', 'isDataVisCert'].reduce(
<add> (sum, key) => (user[key] ? sum + 1 : sum),
<add> 0
<add> );
<ide> }
<ide>
<ide> export default function populateUser(db, user) {
<ide> return new Promise((resolve, reject) => {
<del> let populatedUser = {...user};
<add> let populatedUser = { ...user };
<ide> db.collection('user')
<del> .aggregate([
<del> { $match: { _id: user.id } },
<del> { $project: { points: { $size: '$progressTimestamps' } } }
<del> ]).get(function(err, [{ points = 1 } = {}]) {
<del> if (err) { return reject(err); }
<del> user.points = points;
<del> let completedChallengeCount = 0;
<del> let completedProjectCount = 0;
<del> if ('completedChallenges' in user) {
<del> completedChallengeCount = user.completedChallenges.length;
<del> user.completedChallenges.forEach(item => {
<del> if (
<del> 'challengeType' in item &&
<del> (item.challengeType === 3 || item.challengeType === 4)
<del> ) {
<del> completedProjectCount++;
<del> }
<del> });
<del> }
<del> populatedUser.completedChallengeCount = completedChallengeCount;
<del> populatedUser.completedProjectCount = completedProjectCount;
<del> populatedUser.completedCertCount = getCompletedCertCount(user);
<del> populatedUser.completedLegacyCertCount = getLegacyCertCount(user);
<del> populatedUser.completedChallenges = [];
<del> return resolve(populatedUser);
<del> });
<add> .aggregate([
<add> { $match: { _id: user.id } },
<add> { $project: { points: { $size: '$progressTimestamps' } } },
<add> ])
<add> .get(function(err, [{ points = 1 } = {}]) {
<add> if (err) {
<add> return reject(err);
<add> }
<add> user.points = points;
<add> let completedChallengeCount = 0;
<add> let completedProjectCount = 0;
<add> if ('completedChallenges' in user) {
<add> completedChallengeCount = user.completedChallenges.length;
<add> user.completedChallenges.forEach(item => {
<add> if (
<add> 'challengeType' in item &&
<add> (item.challengeType === 3 || item.challengeType === 4)
<add> ) {
<add> completedProjectCount++;
<add> }
<add> });
<add> }
<add> populatedUser.completedChallengeCount = completedChallengeCount;
<add> populatedUser.completedProjectCount = completedProjectCount;
<add> populatedUser.completedCertCount = getCompletedCertCount(user);
<add> populatedUser.completedLegacyCertCount = getLegacyCertCount(user);
<add> populatedUser.completedChallenges = [];
<add> return resolve(populatedUser);
<add> });
<ide> });
<ide> }
<ide><path>api-server/server/utils/index.js
<ide> exports.dasherize = function dasherize(name) {
<ide> return ('' + name)
<ide> .toLowerCase()
<ide> .replace(/\s/g, '-')
<del> .replace(/[^a-z0-9\-\.]/gi, '')
<del> .replace(/\:/g, '');
<del>}
<add> .replace(/[^a-z0-9\-.]/gi, '')
<add> .replace(/:/g, '');
<add>};
<ide>
<ide> exports.nameify = function nameify(str) {
<del> return ('' + str)
<del> .replace(/[^a-zA-Z0-9\s]/g, '')
<del> .replace(/\:/g, '');
<del>}
<add> return ('' + str).replace(/[^a-zA-Z0-9\s]/g, '').replace(/:/g, '');
<add>};
<ide>
<ide> exports.unDasherize = function unDasherize(name) {
<del> return ('' + name)
<del> // replace dash with space
<del> .replace(/\-/g, ' ')
<del> // strip nonalphanumarics chars except whitespace
<del> .replace(/[^a-zA-Z\d\s]/g, '')
<del> .trim();
<del>}
<add> return (
<add> ('' + name)
<add> // replace dash with space
<add> .replace(/-/g, ' ')
<add> // strip nonalphanumarics chars except whitespace
<add> .replace(/[^a-zA-Z\d\s]/g, '')
<add> .trim()
<add> );
<add>};
<ide>
<ide> exports.addPlaceholderImage = function addPlaceholderImage(name) {
<ide> return `https://identicon.org?t=${name}&s=256`;
<del>}
<add>};
<ide><path>api-server/server/utils/publicUserProps.js
<ide> export function getProgress(progressTimestamps, timezone = 'EST') {
<ide> .reduce((data, timestamp) => {
<ide> data[Math.floor(timestamp / 1000)] = 1;
<ide> return data;
<del> }, {});
<add> }, {});
<ide> const uniqueHours = prepUniqueDaysByHours(progressTimestamps, timezone);
<ide> const streak = {
<ide> longest: calcLongestStreak(uniqueHours, timezone),
<ide><path>api-server/server/utils/url-utils.js
<ide> export function getHost() {
<ide>
<ide> export function getServerFullURL() {
<ide> if (!isDev) {
<del> return getProtocol()
<add> return getProtocol()
<ide> + '://'
<ide> + getHost();
<ide> }
| 17
|
Ruby
|
Ruby
|
fix broken condition
|
dd9b317e245670ac06610e4f69bbba98e224b851
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_python
<ide> end
<ide>
<ide> # Checks that apply only to code in def caveats
<del> if text =~ /(\s*)def\s+caveats((.*\n)*?)(\1end)/ || /(\s*)def\s+caveats;(.*?)end/
<add> if text =~ /(\s*)def\s+caveats((.*\n)*?)(\1end)/ || text =~ /(\s*)def\s+caveats;(.*?)end/
<ide> caveats_body = $2
<ide> if caveats_body =~ /[ \{=](python[23]?)\.(.*\w)/
<ide> # So if in the body of caveats there is a `python.whatever` called,
| 1
|
Text
|
Text
|
give credit to browserstack in readme
|
f5b1875ce909a6122f6cd3cb2b6abd9760e02372
|
<ide><path>README.md
<ide> Ember.js also provides access to the most advanced features of JavaScript, HTML
<ide> # Contribution
<ide>
<ide> See [CONTRIBUTING.md](https://github.com/emberjs/ember.js/blob/master/CONTRIBUTING.md)
<add>
<add>---
<add>
<add>Cross-browser testing provided by:
<add>
<add><a href="http://browserstack.com"><img height="70" src="https://p3.zdusercontent.com/attachment/1015988/PWfFdN71Aung2evRkIVQuKJpE?token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..aUrNFb8clSXsFwgw5BUTcg.IJr5piuCen7PmSSBHSrOnqM9K5YZfxX3lvbp-5LCqoKOi4CjjgdA419iqjofs0nLtm26FMURvZ8JRTuKB4iHer6lGu5f8dXHtIkYAHjP5fXDWkl044Yg2mSdrhF6uPy62GdlBYoYxwvgkNrac8nN_In8GY-qOC7bYmlZyJT7tsTZUTYbNMQiXS86YA5LgdCEWzWreMvc3C6cvZtVXIrcVgpkroIhvsTQPm4vQA-Uq6iCbTPA4oX5cpEtMtrlg4jYBnnAE4BTw5UwU_dY83ep5g.7wpc1IKv0rSRGsvqCG_q3g" alt="BrowserStack"></a>
| 1
|
Javascript
|
Javascript
|
remove var in reactandroid/src/androidtest
|
0beb1cc55deff20061e5bccbb6a6f2561be79250
|
<ide><path>ReactAndroid/src/androidTest/js/ProgressBarTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var React = require('React');
<del>var ProgressBar = require('ProgressBarAndroid');
<del>var View = require('View');
<add>const BatchedBridge = require('BatchedBridge');
<add>const React = require('React');
<add>const ProgressBar = require('ProgressBarAndroid');
<add>const View = require('View');
<ide>
<del>var renderApplication = require('renderApplication');
<add>const renderApplication = require('renderApplication');
<ide>
<ide> class ProgressBarSampleApp extends React.Component {
<ide> state = {};
<ide> class ProgressBarSampleApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var ProgressBarTestModule = {
<add>const ProgressBarTestModule = {
<ide> renderProgressBarApplication: function(rootTag) {
<ide> renderApplication(ProgressBarSampleApp, {}, rootTag);
<ide> },
<ide><path>ReactAndroid/src/androidTest/js/ScrollViewTestModule.js
<ide> class Item extends React.Component<ItemProps, ItemState> {
<ide> }
<ide>
<ide> const getInitialState = function() {
<del> var data = [];
<del> for (var i = 0; i < NUM_ITEMS; i++) {
<add> const data = [];
<add> for (let i = 0; i < NUM_ITEMS; i++) {
<ide> data[i] = {text: 'Item ' + i + '!'};
<ide> }
<ide> return {
<ide> class ScrollViewTestApp extends React.Component<Props, State> {
<ide>
<ide> render() {
<ide> scrollViewApp = this;
<del> var children = this.state.data.map((item, index) => (
<add> const children = this.state.data.map((item, index) => (
<ide> <Item
<ide> key={index}
<ide> text={item.text}
<ide> class HorizontalScrollViewTestApp extends React.Component<Props, State> {
<ide>
<ide> render() {
<ide> scrollViewApp = this;
<del> var children = this.state.data.map((item, index) => (
<add> const children = this.state.data.map((item, index) => (
<ide> <Item
<ide> key={index}
<ide> text={item.text}
<ide> class HorizontalScrollViewTestApp extends React.Component<Props, State> {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> item_container: {
<ide> padding: 30,
<ide> backgroundColor: '#ffffff',
<ide> var styles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>var ScrollViewTestModule = {
<add>const ScrollViewTestModule = {
<ide> ScrollViewTestApp: ScrollViewTestApp,
<ide> HorizontalScrollViewTestApp: HorizontalScrollViewTestApp,
<ide> scrollTo(destX: number, destY: number) {
<ide><path>ReactAndroid/src/androidTest/js/ShareTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var React = require('React');
<del>var RecordingModule = require('NativeModules').ShareRecordingModule;
<del>var Share = require('Share');
<del>var View = require('View');
<add>const BatchedBridge = require('BatchedBridge');
<add>const React = require('React');
<add>const RecordingModule = require('NativeModules').ShareRecordingModule;
<add>const Share = require('Share');
<add>const View = require('View');
<ide>
<ide> class ShareTestApp extends React.Component {
<ide> render() {
<ide> return <View />;
<ide> }
<ide> }
<ide>
<del>var ShareTestModule = {
<add>const ShareTestModule = {
<ide> ShareTestApp: ShareTestApp,
<ide> showShareDialog: function(content, options) {
<ide> Share.share(content, options).then(
<ide><path>ReactAndroid/src/androidTest/js/SubviewsClippingTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var React = require('React');
<del>var ScrollView = require('ScrollView');
<del>var StyleSheet = require('StyleSheet');
<del>var View = require('View');
<add>const BatchedBridge = require('BatchedBridge');
<add>const React = require('React');
<add>const ScrollView = require('ScrollView');
<add>const StyleSheet = require('StyleSheet');
<add>const View = require('View');
<ide>
<del>var requireNativeComponent = require('requireNativeComponent');
<add>const requireNativeComponent = require('requireNativeComponent');
<ide>
<del>var ClippableView = requireNativeComponent('ClippableView');
<add>const ClippableView = requireNativeComponent('ClippableView');
<ide>
<ide> class ClippingSample1 extends React.Component {
<ide> render() {
<del> var styles = sample1Styles;
<add> const styles = sample1Styles;
<ide> return (
<ide> <View>
<ide> <ClippableView
<ide> class ClippingSample1 extends React.Component {
<ide> }
<ide> }
<ide>
<del>var sample1Styles = StyleSheet.create({
<add>const sample1Styles = StyleSheet.create({
<ide> outer: {
<ide> width: 200,
<ide> height: 200,
<ide> var sample1Styles = StyleSheet.create({
<ide>
<ide> class ClippingSample2 extends React.Component {
<ide> render() {
<del> var styles = sample2Styles;
<add> const styles = sample2Styles;
<ide> return (
<ide> <View>
<ide> <ClippableView
<ide> class ClippingSample2 extends React.Component {
<ide> }
<ide> }
<ide>
<del>var sample2Styles = StyleSheet.create({
<add>const sample2Styles = StyleSheet.create({
<ide> outer: {
<ide> width: 200,
<ide> height: 200,
<ide> var sample2Styles = StyleSheet.create({
<ide>
<ide> class UpdatingSample1 extends React.Component {
<ide> render() {
<del> var styles = updating1Styles;
<del> var inner1Styles = [
<add> const styles = updating1Styles;
<add> const inner1Styles = [
<ide> styles.inner1,
<ide> {height: this.props.update1 ? 200 : 100},
<ide> ];
<del> var inner2Styles = [styles.inner2, {top: this.props.update2 ? 200 : 50}];
<add> const inner2Styles = [styles.inner2, {top: this.props.update2 ? 200 : 50}];
<ide> return (
<ide> <View>
<ide> <ClippableView
<ide> class UpdatingSample1 extends React.Component {
<ide> }
<ide> }
<ide>
<del>var updating1Styles = StyleSheet.create({
<add>const updating1Styles = StyleSheet.create({
<ide> outer: {
<ide> width: 200,
<ide> height: 200,
<ide> var updating1Styles = StyleSheet.create({
<ide>
<ide> class UpdatingSample2 extends React.Component {
<ide> render() {
<del> var styles = updating2Styles;
<del> var outerStyles = [styles.outer, {height: this.props.update ? 200 : 100}];
<add> const styles = updating2Styles;
<add> const outerStyles = [styles.outer, {height: this.props.update ? 200 : 100}];
<ide> return (
<ide> <View>
<ide> <ClippableView
<ide> class UpdatingSample2 extends React.Component {
<ide> }
<ide> }
<ide>
<del>var updating2Styles = StyleSheet.create({
<add>const updating2Styles = StyleSheet.create({
<ide> outer: {
<ide> width: 100,
<ide> height: 100,
<ide> var updating2Styles = StyleSheet.create({
<ide>
<ide> class ScrollViewTest extends React.Component {
<ide> render() {
<del> var styles = scrollTestStyles;
<del> var children = [];
<del> for (var i = 0; i < 4; i++) {
<add> const styles = scrollTestStyles;
<add> const children = [];
<add> for (let i = 0; i < 4; i++) {
<ide> children[i] = (
<ide> <ClippableView key={i} style={styles.row} clippableViewID={'' + i} />
<ide> );
<ide> }
<del> for (var i = 4; i < 6; i++) {
<del> var viewID = 'C' + (i - 4);
<add> for (let i = 4; i < 6; i++) {
<add> const viewID = 'C' + (i - 4);
<ide> children[i] = (
<ide> <ClippableView
<ide> key={i}
<ide> class ScrollViewTest extends React.Component {
<ide> }
<ide> }
<ide>
<del>var scrollTestStyles = StyleSheet.create({
<add>const scrollTestStyles = StyleSheet.create({
<ide> scrollView: {
<ide> width: 200,
<ide> height: 300,
<ide> var scrollTestStyles = StyleSheet.create({
<ide> },
<ide> });
<ide>
<del>var appInstance = null;
<add>let appInstance = null;
<ide>
<ide> class SubviewsClippingTestApp extends React.Component {
<ide> state = {};
<ide> class SubviewsClippingTestApp extends React.Component {
<ide> };
<ide>
<ide> render() {
<del> var component = this.state.component;
<add> const component = this.state.component;
<ide> return <View>{component}</View>;
<ide> }
<ide> }
<ide>
<del>var SubviewsClippingTestModule = {
<add>const SubviewsClippingTestModule = {
<ide> App: SubviewsClippingTestApp,
<ide> renderClippingSample1: function() {
<ide> appInstance.setComponent(<ClippingSample1 />);
<ide><path>ReactAndroid/src/androidTest/js/SwipeRefreshLayoutTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var React = require('React');
<del>var RecordingModule = require('NativeModules')
<add>const BatchedBridge = require('BatchedBridge');
<add>const React = require('React');
<add>const RecordingModule = require('NativeModules')
<ide> .SwipeRefreshLayoutRecordingModule;
<del>var ScrollView = require('ScrollView');
<del>var RefreshControl = require('RefreshControl');
<del>var Text = require('Text');
<del>var TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<del>var View = require('View');
<add>const ScrollView = require('ScrollView');
<add>const RefreshControl = require('RefreshControl');
<add>const Text = require('Text');
<add>const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<add>const View = require('View');
<ide>
<ide> class Row extends React.Component {
<ide> state = {
<ide> class Row extends React.Component {
<ide> };
<ide> }
<ide>
<del>var app = null;
<add>let app = null;
<ide>
<ide> class SwipeRefreshLayoutTestApp extends React.Component {
<ide> state = {
<ide> class SwipeRefreshLayoutTestApp extends React.Component {
<ide> }
<ide>
<ide> render() {
<del> var rows = [];
<del> for (var i = 0; i < this.state.rows; i++) {
<add> const rows = [];
<add> for (let i = 0; i < this.state.rows; i++) {
<ide> rows.push(<Row key={i} />);
<ide> }
<ide> return (
<ide> class SwipeRefreshLayoutTestApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var SwipeRefreshLayoutTestModule = {
<add>const SwipeRefreshLayoutTestModule = {
<ide> SwipeRefreshLayoutTestApp,
<ide> setRows: function(rows) {
<ide> if (app != null) {
<ide><path>ReactAndroid/src/androidTest/js/TestBundle.js
<ide> require('TextInputTestModule');
<ide> require('TimePickerDialogTestModule');
<ide>
<ide> // Define catalyst test apps used in integration tests
<del>var AppRegistry = require('AppRegistry');
<add>const AppRegistry = require('AppRegistry');
<ide>
<del>var apps = [
<add>const apps = [
<ide> {
<ide> appKey: 'CatalystRootViewTestApp',
<ide> component: () =>
<ide><path>ReactAndroid/src/androidTest/js/TestIdTestModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var Image = require('Image');
<del>var React = require('React');
<del>var StyleSheet = require('StyleSheet');
<del>var Text = require('Text');
<del>var TextInput = require('TextInput');
<del>var TouchableBounce = require('TouchableBounce');
<del>var TouchableHighlight = require('TouchableHighlight');
<del>var TouchableOpacity = require('TouchableOpacity');
<del>var TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<del>var View = require('View');
<add>const Image = require('Image');
<add>const React = require('React');
<add>const StyleSheet = require('StyleSheet');
<add>const Text = require('Text');
<add>const TextInput = require('TextInput');
<add>const TouchableBounce = require('TouchableBounce');
<add>const TouchableHighlight = require('TouchableHighlight');
<add>const TouchableOpacity = require('TouchableOpacity');
<add>const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
<add>const View = require('View');
<ide>
<ide> /**
<ide> * All the views implemented on Android, each with the testID property set.
<ide> class TestIdTestApp extends React.Component {
<ide> }
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<add>const styles = StyleSheet.create({
<ide> base: {
<ide> width: 150,
<ide> height: 50,
<ide><path>ReactAndroid/src/androidTest/js/TestJSLocaleModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var Recording = require('NativeModules').Recording;
<add>const BatchedBridge = require('BatchedBridge');
<add>const Recording = require('NativeModules').Recording;
<ide>
<del>var TestJSLocaleModule = {
<add>const TestJSLocaleModule = {
<ide> toUpper: function(s) {
<ide> Recording.record(s.toUpperCase());
<ide> },
<ide><path>ReactAndroid/src/androidTest/js/TestJavaToJSArgumentsModule.js
<ide>
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<del>var {assertEquals, assertTrue} = require('Asserts');
<add>const BatchedBridge = require('BatchedBridge');
<add>const {assertEquals, assertTrue} = require('Asserts');
<ide>
<ide> function strictStringCompare(a, b) {
<ide> if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) {
<ide> return false;
<ide> }
<del> for (var i = 0; i < a.length; i++) {
<add> for (let i = 0; i < a.length; i++) {
<ide> if (a.charCodeAt(i) !== b.charCodeAt(i)) {
<ide> return false;
<ide> }
<ide> function assertStrictStringEquals(a, b) {
<ide> assertTrue(strictStringCompare(a, b), 'Expected: ' + a + ', received: ' + b);
<ide> }
<ide>
<del>var TestJavaToJSArgumentsModule = {
<add>const TestJavaToJSArgumentsModule = {
<ide> receiveBasicTypes: function(str, dbl, bool, null_arg) {
<ide> assertEquals('foo', str);
<ide> assertEquals(3.14, dbl);
<ide> var TestJavaToJSArgumentsModule = {
<ide> receiveNestedArray: function(arr) {
<ide> assertEquals(2, arr.length);
<ide> assertEquals('level1', arr[0]);
<del> var arr2 = arr[1];
<add> const arr2 = arr[1];
<ide> assertEquals('level2', arr2[0]);
<del> var arr3 = arr2[1];
<add> const arr3 = arr2[1];
<ide> assertEquals('level3', arr3[0]);
<ide> },
<ide> receiveArrayWithMaps: function(arr) {
<ide> assertEquals(2, arr.length);
<del> var m1 = arr[0];
<del> var m2 = arr[1];
<add> const m1 = arr[0];
<add> const m2 = arr[1];
<ide> assertEquals('m1v1', m1.m1k1);
<ide> assertEquals('m1v2', m1.m1k2);
<ide> assertEquals('m2v1', m2.m2k1);
<ide> var TestJavaToJSArgumentsModule = {
<ide> assertEquals(null, map.nullKey);
<ide> },
<ide> receiveNestedMap: function(map) {
<del> var nestedMap = map.nestedMap;
<add> const nestedMap = map.nestedMap;
<ide> assertEquals('foxes', nestedMap.animals);
<ide> },
<ide> receiveMapWithArrays: function(map) {
<del> var a1 = map.array1;
<del> var a2 = map.array2;
<add> const a1 = map.array1;
<add> const a2 = map.array2;
<ide> assertEquals(3, a1.length);
<ide> assertEquals(2, a2.length);
<ide> assertEquals(3, a1[0]);
<ide><path>ReactAndroid/src/androidTest/js/TestJavaToJSReturnValuesModule.js
<ide> const BatchedBridge = require('BatchedBridge');
<ide> const {assertEquals, assertTrue} = require('Asserts');
<ide> const {TestModule} = require('NativeModules');
<ide>
<del>var TestJavaToJSReturnValuesModule = {
<add>const TestJavaToJSReturnValuesModule = {
<ide> callMethod: function(methodName, expectedType, expectedJSON) {
<ide> const result = TestModule[methodName]();
<ide> assertEquals(expectedType, typeof result);
| 10
|
PHP
|
PHP
|
fix coding standards
|
480c1bbb54d9bdf5d2af024c50037169ec53192b
|
<ide><path>lib/Cake/Test/Case/AllTestsTest.php
<ide> public static function suite() {
<ide> $suite->addTestFile($path . 'Model' . DS . 'ModelTest.php');
<ide> $suite->addTestFile($path . 'AllRoutingTest.php');
<ide> $suite->addTestFile($path . 'AllNetworkTest.php');
<del> $suite->addTestFile($path . 'AllTestSuiteTest.php');;
<add> $suite->addTestFile($path . 'AllTestSuiteTest.php');
<ide> $suite->addTestFile($path . 'AllUtilityTest.php');
<ide> $suite->addTestFile($path . 'AllViewTest.php');
<ide> $suite->addTestFile($path . 'AllI18nTest.php');
<ide><path>lib/Cake/Test/Case/BasicsTest.php
<ide> public function testDebug() {
<ide> ob_start();
<ide> debug('this-is-a-test', false);
<ide> $result = ob_get_clean();
<del>$expectedText = <<<EXPECTED
<add> $expectedText = <<<EXPECTED
<ide> %s (line %d)
<ide> ########## DEBUG ##########
<ide> 'this-is-a-test'
<ide> public function testDebug() {
<ide> ob_start();
<ide> debug('<div>this-is-a-test</div>', true);
<ide> $result = ob_get_clean();
<del>$expectedHtml = <<<EXPECTED
<add> $expectedHtml = <<<EXPECTED
<ide> <div class="cake-debug-output">
<ide> <span><strong>%s</strong> (line <strong>%d</strong>)</span>
<ide> <pre class="cake-debug">
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', true, true);
<add> debug('<div>this-is-a-test</div>', true, true);
<ide> $result = ob_get_clean();
<del>$expected = <<<EXPECTED
<add> $expected = <<<EXPECTED
<ide> <div class="cake-debug-output">
<ide> <span><strong>%s</strong> (line <strong>%d</strong>)</span>
<ide> <pre class="cake-debug">
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', true, false);
<add> debug('<div>this-is-a-test</div>', true, false);
<ide> $result = ob_get_clean();
<del>$expected = <<<EXPECTED
<add> $expected = <<<EXPECTED
<ide> <div class="cake-debug-output">
<ide>
<ide> <pre class="cake-debug">
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', null);
<add> debug('<div>this-is-a-test</div>', null);
<ide> $result = ob_get_clean();
<del>$expectedHtml = <<<EXPECTED
<add> $expectedHtml = <<<EXPECTED
<ide> <div class="cake-debug-output">
<ide> <span><strong>%s</strong> (line <strong>%d</strong>)</span>
<ide> <pre class="cake-debug">
<ide> '<div>this-is-a-test</div>'
<ide> </pre>
<ide> </div>
<ide> EXPECTED;
<del>$expectedText = <<<EXPECTED
<add> $expectedText = <<<EXPECTED
<ide> %s (line %d)
<ide> ########## DEBUG ##########
<ide> '<div>this-is-a-test</div>'
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', null, false);
<add> debug('<div>this-is-a-test</div>', null, false);
<ide> $result = ob_get_clean();
<del>$expectedHtml = <<<EXPECTED
<add> $expectedHtml = <<<EXPECTED
<ide> <div class="cake-debug-output">
<ide>
<ide> <pre class="cake-debug">
<ide> '<div>this-is-a-test</div>'
<ide> </pre>
<ide> </div>
<ide> EXPECTED;
<del>$expectedText = <<<EXPECTED
<add> $expectedText = <<<EXPECTED
<ide>
<ide> ########## DEBUG ##########
<ide> '<div>this-is-a-test</div>'
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', false);
<add> debug('<div>this-is-a-test</div>', false);
<ide> $result = ob_get_clean();
<del>$expected = <<<EXPECTED
<add> $expected = <<<EXPECTED
<ide> %s (line %d)
<ide> ########## DEBUG ##########
<ide> '<div>this-is-a-test</div>'
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', false, true);
<add> debug('<div>this-is-a-test</div>', false, true);
<ide> $result = ob_get_clean();
<del>$expected = <<<EXPECTED
<add> $expected = <<<EXPECTED
<ide> %s (line %d)
<ide> ########## DEBUG ##########
<ide> '<div>this-is-a-test</div>'
<ide> public function testDebug() {
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> debug('<div>this-is-a-test</div>', false, false);
<add> debug('<div>this-is-a-test</div>', false, false);
<ide> $result = ob_get_clean();
<del>$expected = <<<EXPECTED
<add> $expected = <<<EXPECTED
<ide>
<ide> ########## DEBUG ##########
<ide> '<div>this-is-a-test</div>'
<ide> public function testDebug() {
<ide> */
<ide> public function testPr() {
<ide> ob_start();
<del> pr('this is a test');
<add> pr('this is a test');
<ide> $result = ob_get_clean();
<ide> $expected = "<pre>this is a test</pre>";
<ide> $this->assertEquals($expected, $result);
<ide>
<ide> ob_start();
<del> pr(array('this' => 'is', 'a' => 'test'));
<add> pr(array('this' => 'is', 'a' => 'test'));
<ide> $result = ob_get_clean();
<ide> $expected = "<pre>Array\n(\n [this] => is\n [a] => test\n)\n</pre>";
<ide> $this->assertEquals($expected, $result);
<ide><path>lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php
<ide> class MockPDO extends PDO {
<ide>
<ide> public function __construct() {
<ide> }
<add>
<ide> }
<ide>
<ide> class MockDataSource extends DataSource {
<ide> public function setConfig($config = array()) {
<ide> public function setConnection($conn) {
<ide> $this->_connection = $conn;
<ide> }
<add>
<ide> }
<ide>
<ide> /**
<ide> public function tearDown() {
<ide> unset($this->Model);
<ide> }
<ide>
<del>
<ide> /**
<ide> * test that booleans and null make logical condition strings.
<ide> *
<ide> public function testMergeAssociations() {
<ide> $this->assertEquals($data, $expected);
<ide> }
<ide>
<del>
<ide> /**
<ide> * testMagicMethodQuerying method
<ide> *
<ide> public function testDirectCallThrowsException() {
<ide> $result = $this->db->query('directCall', array(), $this->Model);
<ide> }
<ide>
<del>
<ide> /**
<ide> * testValue method
<ide> *
<ide> public function testGetLog() {
<ide> $expected = array('query' => 'Error 1', 'affected' => '', 'numRows' => '', 'took' => '');
<ide> }
<ide>
<del>
<ide> /**
<ide> * test getting the query log as an array, setting bind params.
<ide> *
<ide> public function testGetLogParams() {
<ide> $this->assertEquals($log['log'][1], $expected);
<ide> }
<ide>
<del>
<ide> /**
<ide> * test that query() returns boolean values from operations like CREATE TABLE
<ide> *
<ide> public function testFetchAllBooleanReturns() {
<ide> $this->assertTrue($result, 'Query did not return a boolean');
<ide> }
<ide>
<del>
<ide> /**
<ide> * test order to generate query order clause for virtual fields
<ide> *
<ide> public function testVirtualFieldsInOrder() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<del>
<del>
<ide> /**
<ide> * test the permutations of fullTableName()
<ide> *
<ide> public function testFieldsUsingMethodCache() {
<ide> $this->assertTrue(empty(DboTestSource::$methodCache['fields']), 'Cache not empty');
<ide> }
<ide>
<del>
<ide> /**
<ide> * Test that group works without a model
<ide> *
| 3
|
Ruby
|
Ruby
|
add a truncate option
|
2b847959f098414fb12600535b5f0ab584a11e40
|
<ide><path>Library/Homebrew/utils.rb
<ide> def ohai(title, *sput)
<ide> puts sput
<ide> end
<ide>
<del>def oh1(title)
<del> title = Tty.truncate(title) if $stdout.tty? && !ARGV.verbose?
<add>def oh1(title, options = {})
<add> if $stdout.tty? && !ARGV.verbose? && options.fetch(:truncate, :auto) == :auto
<add> title = Tty.truncate(title)
<add> end
<ide> puts "#{Tty.green}==>#{Tty.white} #{title}#{Tty.reset}"
<ide> end
<ide>
| 1
|
Text
|
Text
|
add onleave to legend config docs
|
b36d55d0936bf591d5ab58ae3d6a076f8f2d62e1
|
<ide><path>docs/configuration/legend.md
<ide> The legend configuration is passed into the `options.legend` namespace. The glob
<ide> | `fullWidth` | `boolean` | `true` | Marks that this box should take the full width of the canvas (pushing down other boxes). This is unlikely to need to be changed in day-to-day use.
<ide> | `onClick` | `function` | | A callback that is called when a click event is registered on a label item.
<ide> | `onHover` | `function` | | A callback that is called when a 'mousemove' event is registered on top of a label item.
<add>| `onLeave` | `function` | | A callback that is called when a 'mousemove' event is registered outside of a previously hovered label item.
<ide> | `reverse` | `boolean` | `false` | Legend will show datasets in reverse order.
<ide> | `labels` | `object` | | See the [Legend Label Configuration](#legend-label-configuration) section below.
<ide>
| 1
|
Text
|
Text
|
update incremental adoption documentation.
|
d47d83d88dc8db43e4b974f8a124794a8e5c9f72
|
<ide><path>docs/migrating/incremental-adoption.md
<ide> description: Learn different strategies for incrementally adopting Next.js into
<ide> </ul>
<ide> </details>
<ide>
<del>Next.js has been designed from the start for gradual adoption. You can use as much (or as little) React as you need. By starting small and incrementally adding more pages, you can prevent derailing feature work by avoiding a complete rewrite.
<add>Next.js has been designed for gradual adoption. With Next.js, you can continue using your existing code and add as much (or as little) React as you need. By starting small and incrementally adding more pages, you can prevent derailing feature work by avoiding a complete rewrite.
<ide>
<ide> ## Strategies
<ide>
<ide> ### Subpath
<ide>
<del>If you need multiple applications on a single domain, you can take over an entire subpath. For example, you might deploy your Next.js e-commerce store at `acme.com/store`.
<add>The first strategy is to configure your server or proxy such that, everything under a specific subpath points to a Next.js app. For example, your existing website might be at `example.com`, and you might configure your proxy such that `example.com/store` serves a Next.js e-commerce store.
<ide>
<del>Using [`basePath`](/docs/api-reference/next.config.js/basepath.md), you can configure your Next.js application's assets and links to automatically work with your new subpath `/store`. Since each page in Next.js is its own [standalone route](/docs/routing/introduction.md), new files like `pages/products.js` will route to `acme.com/store/products` in your new application.
<add>Using [`basePath`](/docs/api-reference/next.config.js/basepath.md), you can configure your Next.js application's assets and links to automatically work with your new subpath `/store`. Since each page in Next.js is its own [standalone route](/docs/routing/introduction.md), pages like `pages/products.js` will route to `example.com/store/products` in your application.
<ide>
<ide> ```jsx
<ide> // next.config.js
<ide> module.exports = {
<ide> }
<ide> ```
<ide>
<add>To learn more about `basePath`, take a look at our [documentation](/docs/api-reference/next.config.js/basepath.md).
<add>
<ide> > This feature was introduced in [Next.js 9.5](https://nextjs.org/blog/next-9-5) and up. If you’re using older versions of Next.js, please upgrade before trying it out.
<ide>
<ide> ### Rewrites
<ide>
<del>If you plan on fully migrating your domain to Next.js, you can use [`rewrites`](/docs/api-reference/next.config.js/rewrites.md) inside `next.config.js`. This allows you to check your new routes before falling back to proxying your existing website.
<add>The second strategy is to create a new Next.js app that points to the root URL of your domain. Then, you can use [`rewrites`](/docs/api-reference/next.config.js/rewrites.md) inside `next.config.js` to have some subpaths to be proxied to your existing app.
<ide>
<del>For example, let's say you took over `/about` with Next.js. When a request for `acme.com/about` hits your Next.js application, it will serve the new page. A request for any other route (e.g. `acme.com/dashboard`) will fall back and proxy the URL you specify.
<add>For example, let's say you created a Next.js app to be served from `example.com` with the following `next.config.js`. Now, requests for the pages you’ve added to this Next.js app (e.g. `/about` if you’ve added `pages/about.js`) will be handled by Next.js, and requests for any other route (e.g. `/dashboard`) will be proxied to `proxy.example.com`.
<ide>
<ide> ```jsx
<ide> // next.config.js
<ide> module.exports = {
<ide> },
<ide> {
<ide> source: '/:path*',
<del> destination: `https://acme-proxy.com/:path*`,
<add> destination: `https://proxy.example.com/:path*`,
<ide> },
<ide> ]
<ide> },
<ide> }
<ide> ```
<ide>
<add>To learn more about rewrites, take a look at our [documentation](/docs/api-reference/next.config.js/rewrites.md).
<add>
<ide> > This feature was introduced in [Next.js 9.5](https://nextjs.org/blog/next-9-5) and up. If you’re using older versions of Next.js, please upgrade before trying it out.
<ide>
<del>### Micro-Frontends
<add>### Micro-Frontends with Monorepos and Subdomains
<ide>
<ide> Next.js and [Vercel](https://vercel.com) make it easy to adopt [micro-frontends](https://martinfowler.com/articles/micro-frontends.html) and deploy as a [Monorepo](https://vercel.com/blog/monorepos). This allows you to use [subdomains](https://en.wikipedia.org/wiki/Subdomain) to adopt new applications incrementally. Some benefits of micro-frontends:
<ide>
| 1
|
Text
|
Text
|
fix typo in esm.md
|
75cc41e4c89778c0955037da8626b77e6e712073
|
<ide><path>doc/api/esm.md
<ide> Alterantively `module.createRequire()` can be used.
<ide>
<ide> Native modules are not currently supported with ES module imports.
<ide>
<del>The can instead be loaded with [`module.createRequire()`][] or
<add>They can instead be loaded with [`module.createRequire()`][] or
<ide> [`process.dlopen`][].
<ide>
<ide> #### No `require.resolve`
| 1
|
Python
|
Python
|
change dag audit log sort by date from asc to desc
|
8b928b4172c7d3abb42c141a8d874e85639decf8
|
<ide><path>airflow/www/views.py
<ide> def audit_log(self, dag_id: str, session=None):
<ide>
<ide> current_page = request.args.get('page', default=0, type=int)
<ide> arg_sorting_key = request.args.get('sorting_key', 'dttm')
<del> arg_sorting_direction = request.args.get('sorting_direction', default='asc')
<add> arg_sorting_direction = request.args.get('sorting_direction', default='desc')
<ide>
<ide> logs_per_page = PAGE_SIZE
<ide> audit_logs_count = query.count()
| 1
|
Python
|
Python
|
add regression test for
|
dcff10abe98c844f2f66ff22835c9eb8ea8e7138
|
<ide><path>spacy/tests/regression/test_issue1281.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>import pytest
<add>
<add>
<add>@pytest.mark.parametrize('text', [
<add> "She hasn't done the housework.",
<add> "I haven't done it before.",
<add> "you daren't do that"])
<add>def test_issue1281(en_tokenizer, text):
<add> tokens = en_tokenizer(text)
<add> assert tokens[2].text == "n't"
| 1
|
PHP
|
PHP
|
fix cs errors
|
699a9535dc09d324b8b83fd031492730c7ce630d
|
<ide><path>src/Http/MiddlewareQueue.php
<ide> public function count(): int
<ide> * @return void
<ide> * @see \SeekableIterator::seek()
<ide> */
<del> public function seek($position) {
<add> public function seek($position)
<add> {
<ide> if (!isset($this->queue[$position])) {
<ide> throw new OutOfBoundsException("Invalid seek position ($position)");
<ide> }
<ide> public function seek($position) {
<ide> * @return void
<ide> * @see \Iterator::rewind()
<ide> */
<del> public function rewind() {
<add> public function rewind()
<add> {
<ide> $this->position = 0;
<ide> }
<ide>
<ide> public function rewind() {
<ide> * @return \Psr\Http\Server\MiddlewareInterface
<ide> * @see \Iterator::current()
<ide> */
<del> public function current() {
<add> public function current()
<add> {
<ide> return $this->get($this->position);
<ide> }
<ide>
<ide> public function current() {
<ide> * @return int
<ide> * @see \Iterator::key()
<ide> */
<del> public function key() {
<add> public function key()
<add> {
<ide> return $this->position;
<ide> }
<ide>
<ide> public function key() {
<ide> * @return void
<ide> * @see \Iterator::next()
<ide> */
<del> public function next() {
<add> public function next()
<add> {
<ide> ++$this->position;
<ide> }
<ide>
<ide> public function next() {
<ide> * @return bool
<ide> * @see \Iterator::valid()
<ide> */
<del> public function valid() {
<add> public function valid()
<add> {
<ide> return isset($this->queue[$this->position]);
<ide> }
<ide> }
| 1
|
PHP
|
PHP
|
clarify deprecation warning
|
c09687df6b37902ad1c75d3238a33e14ca5236a2
|
<ide><path>src/Event/EventDispatcherTrait.php
<ide> trait EventDispatcherTrait
<ide> *
<ide> * @param \Cake\Event\EventManager|null $eventManager the eventManager to set
<ide> * @return \Cake\Event\EventManager
<del> * @deprecated 3.5.0 Use getter/setter instead.
<add> * @deprecated 3.5.0 Use getEventManager()/setEventManager() instead.
<ide> */
<ide> public function eventManager(EventManager $eventManager = null)
<ide> {
| 1
|
Python
|
Python
|
fix numpy by including negative shifts
|
60981410a6be95db211491e76190259ca41b03a0
|
<ide><path>numpy/core/numeric.py
<ide> def roll(a, shift, axis=None):
<ide> >>> x = np.arange(10)
<ide> >>> np.roll(x, 2)
<ide> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
<del>
<add> >>> np.roll(x, -2)
<add> array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
<ide> >>> x2 = np.reshape(x, (2,5))
<ide> >>> x2
<ide> array([[0, 1, 2, 3, 4],
<ide> [5, 6, 7, 8, 9]])
<ide> >>> np.roll(x2, 1)
<ide> array([[9, 0, 1, 2, 3],
<ide> [4, 5, 6, 7, 8]])
<add> >>> np.roll(x2, -1)
<add> array([[1, 2, 3, 4, 5],
<add> [6, 7, 8, 9, 0]])
<ide> >>> np.roll(x2, 1, axis=0)
<add> array([[5, 6, 7, 8, 9],
<add> [0, 1, 2, 3, 4]])
<add> >>> np.roll(x2, -1, axis=0)
<ide> array([[5, 6, 7, 8, 9],
<ide> [0, 1, 2, 3, 4]])
<ide> >>> np.roll(x2, 1, axis=1)
<ide> array([[4, 0, 1, 2, 3],
<ide> [9, 5, 6, 7, 8]])
<add> >>> np.roll(x2, -1, axis=1)
<add> array([[1, 2, 3, 4, 0],
<add> [6, 7, 8, 9, 5]])
<ide>
<ide> """
<ide> a = asanyarray(a)
| 1
|
Python
|
Python
|
remove leftover statement
|
d1f6530b8c7bf02bc8a79131253a384fbfd0dafe
|
<ide><path>celery/concurrency/processes/pool.py
<ide> def on_state_change(task):
<ide> on_state_change(task)
<ide> join_exited_workers()
<ide>
<del> job, i, obj = task
<del> try:
<del> cache[job]._set(i, obj)
<del> except KeyError:
<del> pass
<del>
<ide> if hasattr(outqueue, '_reader'):
<ide> debug('ensuring that outqueue is not full')
<ide> # If we don't make room available in outqueue then
| 1
|
Go
|
Go
|
fix the driver name empty case
|
6c78edaf7f22bfe3bd731855f767b9fa3c7d8549
|
<ide><path>volume/store/store.go
<ide> func (s *VolumeStore) create(name, driverName string, opts map[string]string) (v
<ide> }
<ide> }
<ide>
<del> logrus.Debugf("Registering new volume reference: driver %q, name %q", driverName, name)
<ide> vd, err := volumedrivers.GetDriver(driverName)
<add>
<ide> if err != nil {
<ide> return nil, &OpErr{Op: "create", Name: name, Err: err}
<ide> }
<ide>
<add> logrus.Debugf("Registering new volume reference: driver %q, name %q", vd.Name(), name)
<add>
<ide> if v, _ := vd.Get(name); v != nil {
<ide> return v, nil
<ide> }
| 1
|
Javascript
|
Javascript
|
fix typo in orderedmap
|
6c3c643c8e63f3cd2319e4e1e53a6b8627724062
|
<ide><path>src/utils/OrderedMap.js
<ide> var NO_EXIST = 'NO_EXIST';
<ide> if (__DEV__) {
<ide> ARRAY_MUST_CB =
<ide> 'If providing an array to an OrderedMap constructor, you must provide ' +
<del> 'a callback that may determine the uniqueue key for each entry. ' +
<add> 'a callback that may determine the unique key for each entry. ' +
<ide> 'The key that you return from the callback should uniquely define that ' +
<ide> 'entity. What is returned from that function must answer the question: ' +
<ide> '"If you were to shuffle the array of entities, how would you be able to ' +
| 1
|
Javascript
|
Javascript
|
handle errors thrown in nested error handlers
|
29cd0f2a77faa3b2a746e64e4871cded32e8aa98
|
<ide><path>src/node.js
<ide> var caught = false;
<ide> if (process.domain) {
<ide> var domain = process.domain;
<add> var domainModule = NativeModule.require('domain');
<add> var domainStack = domainModule._stack;
<ide>
<ide> // ignore errors on disposed domains.
<ide> //
<ide> caught = domain.emit('error', er);
<ide>
<ide> // Exit all domains on the stack. Uncaught exceptions end the
<del> // current tick and no domains should be left on the stack between
<del> // ticks. Since a domain exists, this require will not be loading
<del> // it for the first time and should be safe.
<add> // current tick and no domains should be left on the stack
<add> // between ticks.
<ide> var domainModule = NativeModule.require('domain');
<del> domainModule._stack.length = 0;
<add> domainStack.length = 0;
<ide> domainModule.active = process.domain = null;
<ide> } catch (er2) {
<del> caught = false;
<add> // The domain error handler threw! oh no!
<add> // See if another domain can catch THIS error,
<add> // or else crash on the original one.
<add> domainStack.pop();
<add> if (domainStack.length) {
<add> var parentDomain = domainStack[ domainStack.length - 1];
<add> process.domain = domainModule.active = parentDomain;
<add> caught = process._fatalException(er2);
<add> } else
<add> caught = false;
<ide> }
<ide> } else {
<ide> caught = process.emit('uncaughtException', er);
<ide><path>test/simple/test-domain-nested-throw.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>var domain = require('domain');
<add>
<add>var gotDomain1Error = false;
<add>var gotDomain2Error = false;
<add>
<add>var threw1 = false;
<add>var threw2 = false;
<add>
<add>function throw1() {
<add> threw1 = true;
<add> throw new Error('handled by domain1');
<add>}
<add>
<add>function throw2() {
<add> threw2 = true;
<add> throw new Error('handled by domain2');
<add>}
<add>
<add>function inner(throw1, throw2) {
<add> var domain1 = domain.createDomain();
<add>
<add> domain1.on('error', function (err) {
<add> console.error('domain 1 error');
<add> if (gotDomain1Error) process.exit(1);
<add> gotDomain1Error = true;
<add> throw2();
<add> });
<add>
<add> domain1.run(function () {
<add> throw1();
<add> });
<add>}
<add>
<add>function outer() {
<add> var domain2 = domain.createDomain();
<add>
<add> domain2.on('error', function (err) {
<add> console.error('domain 2 error');
<add> gotDomain2Error = true;
<add> });
<add>
<add> domain2.run(function () {
<add> inner(throw1, throw2);
<add> });
<add>}
<add>
<add>process.on('exit', function() {
<add> assert(gotDomain1Error);
<add> assert(gotDomain2Error);
<add> assert(threw1);
<add> assert(threw2);
<add> console.log('ok');
<add>});
<add>
<add>outer();
| 2
|
Python
|
Python
|
support sentinel with ssl"
|
0fa4db8889325fd774f7e89ebb219a87fc1d8cfb
|
<ide><path>celery/backends/redis.py
<ide> class RedisBackend(BaseKeyValueStoreBackend, AsyncBackendMixin):
<ide>
<ide> #: :pypi:`redis` client module.
<ide> redis = redis
<del> connection_class_ssl = redis.SSLConnection if redis else None
<ide>
<ide> #: Maximum number of connections in the pool.
<ide> max_connections = None
<ide> def __init__(self, host=None, port=None, db=None, password=None,
<ide> ssl = _get('redis_backend_use_ssl')
<ide> if ssl:
<ide> self.connparams.update(ssl)
<del> self.connparams['connection_class'] = self.connection_class_ssl
<add> self.connparams['connection_class'] = redis.SSLConnection
<ide>
<ide> if url:
<ide> self.connparams = self._params_from_url(url, self.connparams)
<ide> def __init__(self, host=None, port=None, db=None, password=None,
<ide> # redis_backend_use_ssl dict, check ssl_cert_reqs is valid. If set
<ide> # via query string ssl_cert_reqs will be a string so convert it here
<ide> if ('connection_class' in self.connparams and
<del> issubclass(self.connparams['connection_class'], redis.SSLConnection)):
<add> self.connparams['connection_class'] is redis.SSLConnection):
<ide> ssl_cert_reqs_missing = 'MISSING'
<ide> ssl_string_to_constant = {'CERT_REQUIRED': CERT_REQUIRED,
<ide> 'CERT_OPTIONAL': CERT_OPTIONAL,
<ide> def __reduce__(self, args=(), kwargs=None):
<ide> )
<ide>
<ide>
<del>if getattr(redis, "sentinel", None):
<del> class SentinelManagedSSLConnection(
<del> redis.sentinel.SentinelManagedConnection,
<del> redis.SSLConnection):
<del> """Connect to a Redis server using Sentinel + TLS.
<del>
<del> Use Sentinel to identify which Redis server is the current master
<del> to connect to and when connecting to the Master server, use an
<del> SSL Connection.
<del> """
<del>
<del> pass
<del>
<del>
<ide> class SentinelBackend(RedisBackend):
<ide> """Redis sentinel task result store."""
<ide>
<ide> sentinel = getattr(redis, "sentinel", None)
<del> connection_class_ssl = SentinelManagedSSLConnection if sentinel else None
<ide>
<ide> def __init__(self, *args, **kwargs):
<ide> if self.sentinel is None:
<ide><path>t/unit/backends/test_redis.py
<ide> def test_get_pool(self):
<ide> )
<ide> pool = x._get_pool(**x.connparams)
<ide> assert pool
<del>
<del> def test_backend_ssl(self):
<del> pytest.importorskip('redis')
<del>
<del> from celery.backends.redis import SentinelBackend
<del> self.app.conf.redis_backend_use_ssl = {
<del> 'ssl_cert_reqs': "CERT_REQUIRED",
<del> 'ssl_ca_certs': '/path/to/ca.crt',
<del> 'ssl_certfile': '/path/to/client.crt',
<del> 'ssl_keyfile': '/path/to/client.key',
<del> }
<del> self.app.conf.redis_socket_timeout = 30.0
<del> self.app.conf.redis_socket_connect_timeout = 100.0
<del> x = SentinelBackend(
<del> 'sentinel://:bosco@vandelay.com:123//1', app=self.app,
<del> )
<del> assert x.connparams
<del> assert len(x.connparams['hosts']) == 1
<del> assert x.connparams['hosts'][0]['host'] == 'vandelay.com'
<del> assert x.connparams['hosts'][0]['db'] == 1
<del> assert x.connparams['hosts'][0]['port'] == 123
<del> assert x.connparams['hosts'][0]['password'] == 'bosco'
<del> assert x.connparams['socket_timeout'] == 30.0
<del> assert x.connparams['socket_connect_timeout'] == 100.0
<del> assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED
<del> assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt'
<del> assert x.connparams['ssl_certfile'] == '/path/to/client.crt'
<del> assert x.connparams['ssl_keyfile'] == '/path/to/client.key'
<del>
<del> from celery.backends.redis import SentinelManagedSSLConnection
<del> assert x.connparams['connection_class'] is SentinelManagedSSLConnection
| 2
|
Python
|
Python
|
remove redundant coverage
|
6730ecdd3c92f068ddb598812c90baddd4ff22c7
|
<ide><path>tests/test_tokenization_common.py
<ide> def test_get_vocab(self):
<ide> self.assertIsInstance(vocab, dict)
<ide> self.assertEqual(len(vocab), len(tokenizer))
<ide>
<del> for word, ind in vocab.items():
<del> self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind)
<del> self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word)
<del>
<ide> tokenizer.add_tokens(["asdfasdfasdfasdf"])
<ide> vocab = tokenizer.get_vocab()
<ide> self.assertIsInstance(vocab, dict)
| 1
|
Go
|
Go
|
remove extra args in testexitcode
|
4b80ec9aae2f43e831de64f3746c7838252e9203
|
<ide><path>integration/container_test.go
<ide> func TestExitCode(t *testing.T) {
<ide>
<ide> trueContainer, _, err := runtime.Create(&docker.Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"/bin/true", ""},
<add> Cmd: []string{"/bin/true"},
<ide> }, "")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestExitCode(t *testing.T) {
<ide>
<ide> falseContainer, _, err := runtime.Create(&docker.Config{
<ide> Image: GetTestImage(runtime).ID,
<del> Cmd: []string{"/bin/false", ""},
<add> Cmd: []string{"/bin/false"},
<ide> }, "")
<ide> if err != nil {
<ide> t.Fatal(err)
| 1
|
Java
|
Java
|
fix modal when the activity is paused or resumed
|
a0562c7ccffea7d001499ce8e431ede5249cab5e
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostManager.java
<ide> public Class<? extends LayoutShadowNode> getShadowNodeClass() {
<ide> @Override
<ide> public void onDropViewInstance(ReactModalHostView view) {
<ide> super.onDropViewInstance(view);
<del> view.dismiss();
<add> view.onDropInstance();
<ide> }
<ide>
<ide> @ReactProp(name = "animationType")
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/modal/ReactModalHostView.java
<ide> public void addChildrenForAccessibility(ArrayList<View> outChildren) {
<ide> // Those will be handled by the mHostView which lives in the dialog
<ide> }
<ide>
<del> public void dismiss() {
<add> public void onDropInstance() {
<add> ((ReactContext) getContext()).removeLifecycleEventListener(this);
<add> dismiss();
<add> }
<add>
<add> private void dismiss() {
<ide> if (mDialog != null) {
<ide> mDialog.dismiss();
<ide> mDialog = null;
<ide> protected void setAnimationType(String animationType) {
<ide>
<ide> @Override
<ide> public void onHostResume() {
<del> // do nothing
<add> // We show the dialog again when the host resumes
<add> showOrUpdate();
<ide> }
<ide>
<ide> @Override
<ide> public void onHostPause() {
<del> // do nothing
<add> // We dismiss the dialog and reconstitute it onHostResume
<add> dismiss();
<ide> }
<ide>
<ide> @Override
<ide> public void onHostDestroy() {
<del> // Dismiss the dialog if it is present
<del> dismiss();
<add> // Drop the instance if the host is destroyed which will dismiss the dialog
<add> onDropInstance();
<ide> }
<ide>
<ide> @VisibleForTesting
| 2
|
Go
|
Go
|
fix some typos
|
70f1910a8bbeb3727829070a2454a636a91e2d48
|
<ide><path>pkg/term/winconsole/term_emulator_test.go
<ide> func TestAssertEqualBytesNegative(t *testing.T) {
<ide> AssertBytesEqual(t, []byte{1, 2, 3}, []byte{1, 1, 1}, "content mismatch")
<ide> }*/
<ide>
<del>// Checks that the calls recieved
<add>// Checks that the calls received
<ide> func assertHandlerOutput(t *testing.T, mock *mockTerminal, plainText string, commands ...string) {
<ide> text := make([]byte, 0, 3*len(plainText))
<ide> cmdIndex := 0
| 1
|
PHP
|
PHP
|
remove deprecated code for association classes
|
5d0ffb15be3a30d57b511617e3a6fff6cf9ab9e9
|
<ide><path>src/ORM/Association.php
<ide> public function getName()
<ide> return $this->_name;
<ide> }
<ide>
<del> /**
<del> * Sets the name for this association.
<del> *
<del> * @deprecated 3.4.0 Use setName()/getName() instead.
<del> * @param string|null $name Name to be assigned
<del> * @return string
<del> */
<del> public function name($name = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::name() is deprecated. ' .
<del> 'Use setName()/getName() instead.'
<del> );
<del> if ($name !== null) {
<del> $this->setName($name);
<del> }
<del>
<del> return $this->getName();
<del> }
<del>
<ide> /**
<ide> * Sets whether or not cascaded deletes should also fire callbacks.
<ide> *
<ide> public function getCascadeCallbacks()
<ide> return $this->_cascadeCallbacks;
<ide> }
<ide>
<del> /**
<del> * Sets whether or not cascaded deletes should also fire callbacks. If no
<del> * arguments are passed, the current configured value is returned
<del> *
<del> * @deprecated 3.4.0 Use setCascadeCallbacks()/getCascadeCallbacks() instead.
<del> * @param bool|null $cascadeCallbacks cascade callbacks switch value
<del> * @return bool
<del> */
<del> public function cascadeCallbacks($cascadeCallbacks = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::cascadeCallbacks() is deprecated. ' .
<del> 'Use setCascadeCallbacks()/getCascadeCallbacks() instead.'
<del> );
<del> if ($cascadeCallbacks !== null) {
<del> $this->setCascadeCallbacks($cascadeCallbacks);
<del> }
<del>
<del> return $this->getCascadeCallbacks();
<del> }
<del>
<ide> /**
<ide> * The class name of the target table object
<ide> *
<ide> public function getSource()
<ide> return $this->_sourceTable;
<ide> }
<ide>
<del> /**
<del> * Sets the table instance for the source side of the association. If no arguments
<del> * are passed, the current configured table instance is returned
<del> *
<del> * @deprecated 3.4.0 Use setSource()/getSource() instead.
<del> * @param \Cake\ORM\Table|null $table the instance to be assigned as source side
<del> * @return \Cake\ORM\Table
<del> */
<del> public function source(Table $table = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::source() is deprecated. ' .
<del> 'Use setSource()/getSource() instead.'
<del> );
<del> if ($table === null) {
<del> return $this->_sourceTable;
<del> }
<del>
<del> return $this->_sourceTable = $table;
<del> }
<del>
<ide> /**
<ide> * Sets the table instance for the target side of the association.
<ide> *
<ide> public function getTarget()
<ide> return $this->_targetTable;
<ide> }
<ide>
<del> /**
<del> * Sets the table instance for the target side of the association. If no arguments
<del> * are passed, the current configured table instance is returned
<del> *
<del> * @deprecated 3.4.0 Use setTarget()/getTarget() instead.
<del> * @param \Cake\ORM\Table|null $table the instance to be assigned as target side
<del> * @return \Cake\ORM\Table
<del> */
<del> public function target(Table $table = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::target() is deprecated. ' .
<del> 'Use setTarget()/getTarget() instead.'
<del> );
<del> if ($table !== null) {
<del> $this->setTarget($table);
<del> }
<del>
<del> return $this->getTarget();
<del> }
<del>
<ide> /**
<ide> * Sets a list of conditions to be always included when fetching records from
<ide> * the target association.
<ide> public function getConditions()
<ide> return $this->_conditions;
<ide> }
<ide>
<del> /**
<del> * Sets a list of conditions to be always included when fetching records from
<del> * the target association. If no parameters are passed the current list is returned
<del> *
<del> * @deprecated 3.4.0 Use setConditions()/getConditions() instead.
<del> * @param array|null $conditions list of conditions to be used
<del> * @see \Cake\Database\Query::where() for examples on the format of the array
<del> * @return array|callable
<del> */
<del> public function conditions($conditions = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::conditions() is deprecated. ' .
<del> 'Use setConditions()/getConditions() instead.'
<del> );
<del> if ($conditions !== null) {
<del> $this->setConditions($conditions);
<del> }
<del>
<del> return $this->getConditions();
<del> }
<del>
<ide> /**
<ide> * Sets the name of the field representing the binding field with the target table.
<ide> * When not manually specified the primary key of the owning side table is used.
<ide> public function getBindingKey()
<ide> return $this->_bindingKey;
<ide> }
<ide>
<del> /**
<del> * Sets the name of the field representing the binding field with the target table.
<del> * When not manually specified the primary key of the owning side table is used.
<del> *
<del> * If no parameters are passed the current field is returned
<del> *
<del> * @deprecated 3.4.0 Use setBindingKey()/getBindingKey() instead.
<del> * @param string|null $key the table field to be used to link both tables together
<del> * @return string|array
<del> */
<del> public function bindingKey($key = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::bindingKey() is deprecated. ' .
<del> 'Use setBindingKey()/getBindingKey() instead.'
<del> );
<del> if ($key !== null) {
<del> $this->setBindingKey($key);
<del> }
<del>
<del> return $this->getBindingKey();
<del> }
<del>
<ide> /**
<ide> * Gets the name of the field representing the foreign key to the target table.
<ide> *
<ide> public function setForeignKey($key)
<ide> return $this;
<ide> }
<ide>
<del> /**
<del> * Sets the name of the field representing the foreign key to the target table.
<del> * If no parameters are passed the current field is returned
<del> *
<del> * @deprecated 3.4.0 Use setForeignKey()/getForeignKey() instead.
<del> * @param string|null $key the key to be used to link both tables together
<del> * @return string|array
<del> */
<del> public function foreignKey($key = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::foreignKey() is deprecated. ' .
<del> 'Use setForeignKey()/getForeignKey() instead.'
<del> );
<del> if ($key !== null) {
<del> $this->setForeignKey($key);
<del> }
<del>
<del> return $this->getForeignKey();
<del> }
<del>
<ide> /**
<ide> * Sets whether the records on the target table are dependent on the source table.
<ide> *
<ide> public function getDependent()
<ide> return $this->_dependent;
<ide> }
<ide>
<del> /**
<del> * Sets whether the records on the target table are dependent on the source table.
<del> *
<del> * This is primarily used to indicate that records should be removed if the owning record in
<del> * the source table is deleted.
<del> *
<del> * If no parameters are passed the current setting is returned.
<del> *
<del> * @deprecated 3.4.0 Use setDependent()/getDependent() instead.
<del> * @param bool|null $dependent Set the dependent mode. Use null to read the current state.
<del> * @return bool
<del> */
<del> public function dependent($dependent = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::dependent() is deprecated. ' .
<del> 'Use setDependent()/getDependent() instead.'
<del> );
<del> if ($dependent !== null) {
<del> $this->setDependent($dependent);
<del> }
<del>
<del> return $this->getDependent();
<del> }
<del>
<ide> /**
<ide> * Whether this association can be expressed directly in a query join
<ide> *
<ide> public function getJoinType()
<ide> return $this->_joinType;
<ide> }
<ide>
<del> /**
<del> * Sets the type of join to be used when adding the association to a query.
<del> * If no arguments are passed, the currently configured type is returned.
<del> *
<del> * @deprecated 3.4.0 Use setJoinType()/getJoinType() instead.
<del> * @param string|null $type the join type to be used (e.g. INNER)
<del> * @return string
<del> */
<del> public function joinType($type = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::joinType() is deprecated. ' .
<del> 'Use setJoinType()/getJoinType() instead.'
<del> );
<del> if ($type !== null) {
<del> $this->setJoinType($type);
<del> }
<del>
<del> return $this->getJoinType();
<del> }
<del>
<ide> /**
<ide> * Sets the property name that should be filled with data from the target table
<ide> * in the source table record.
<ide> public function getProperty()
<ide> return $this->_propertyName;
<ide> }
<ide>
<del> /**
<del> * Sets the property name that should be filled with data from the target table
<del> * in the source table record.
<del> * If no arguments are passed, the currently configured type is returned.
<del> *
<del> * @deprecated 3.4.0 Use setProperty()/getProperty() instead.
<del> * @param string|null $name The name of the association property. Use null to read the current value.
<del> * @return string
<del> */
<del> public function property($name = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::property() is deprecated. ' .
<del> 'Use setProperty()/getProperty() instead.'
<del> );
<del> if ($name !== null) {
<del> $this->setProperty($name);
<del> }
<del>
<del> return $this->getProperty();
<del> }
<del>
<ide> /**
<ide> * Returns default property name based on association name.
<ide> *
<ide> public function getStrategy()
<ide> return $this->_strategy;
<ide> }
<ide>
<del> /**
<del> * Sets the strategy name to be used to fetch associated records. Keep in mind
<del> * that some association types might not implement but a default strategy,
<del> * rendering any changes to this setting void.
<del> * If no arguments are passed, the currently configured strategy is returned.
<del> *
<del> * @deprecated 3.4.0 Use setStrategy()/getStrategy() instead.
<del> * @param string|null $name The strategy type. Use null to read the current value.
<del> * @return string
<del> * @throws \InvalidArgumentException When an invalid strategy is provided.
<del> */
<del> public function strategy($name = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::strategy() is deprecated. ' .
<del> 'Use setStrategy()/getStrategy() instead.'
<del> );
<del> if ($name !== null) {
<del> $this->setStrategy($name);
<del> }
<del>
<del> return $this->getStrategy();
<del> }
<del>
<ide> /**
<ide> * Gets the default finder to use for fetching rows from the target table.
<ide> *
<ide> public function setFinder($finder)
<ide> return $this;
<ide> }
<ide>
<del> /**
<del> * Sets the default finder to use for fetching rows from the target table.
<del> * If no parameters are passed, it will return the currently configured
<del> * finder name.
<del> *
<del> * @deprecated 3.4.0 Use setFinder()/getFinder() instead.
<del> * @param string|null $finder the finder name to use
<del> * @return string
<del> */
<del> public function finder($finder = null)
<del> {
<del> deprecationWarning(
<del> get_called_class() . '::finder() is deprecated. ' .
<del> 'Use setFinder()/getFinder() instead.'
<del> );
<del> if ($finder !== null) {
<del> $this->setFinder($finder);
<del> }
<del>
<del> return $this->getFinder();
<del> }
<del>
<ide> /**
<ide> * Override this function to initialize any concrete association class, it will
<ide> * get passed the original list of options used in the constructor
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> public function getTargetForeignKey()
<ide> return $this->_targetForeignKey;
<ide> }
<ide>
<del> /**
<del> * Sets the name of the field representing the foreign key to the target table.
<del> * If no parameters are passed current field is returned
<del> *
<del> * @deprecated 3.4.0 Use setTargetForeignKey()/getTargetForeignKey() instead.
<del> * @param string|null $key the key to be used to link both tables together
<del> * @return string
<del> */
<del> public function targetForeignKey($key = null)
<del> {
<del> deprecationWarning(
<del> 'BelongToMany::targetForeignKey() is deprecated. ' .
<del> 'Use setTargetForeignKey()/getTargetForeignKey() instead.'
<del> );
<del> if ($key !== null) {
<del> $this->setTargetForeignKey($key);
<del> }
<del>
<del> return $this->getTargetForeignKey();
<del> }
<del>
<ide> /**
<ide> * Whether this association can be expressed directly in a query join
<ide> *
<ide> public function getSort()
<ide> return $this->_sort;
<ide> }
<ide>
<del> /**
<del> * Sets the sort order in which target records should be returned.
<del> * If no arguments are passed the currently configured value is returned
<del> *
<del> * @deprecated 3.5.0 Use setSort()/getSort() instead.
<del> * @param mixed $sort A find() compatible order clause
<del> * @return mixed
<del> */
<del> public function sort($sort = null)
<del> {
<del> deprecationWarning(
<del> 'BelongToMany::sort() is deprecated. ' .
<del> 'Use setSort()/getSort() instead.'
<del> );
<del> if ($sort !== null) {
<del> $this->setSort($sort);
<del> }
<del>
<del> return $this->getSort();
<del> }
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide> public function getSaveStrategy()
<ide> return $this->_saveStrategy;
<ide> }
<ide>
<del> /**
<del> * Sets the strategy that should be used for saving. If called with no
<del> * arguments, it will return the currently configured strategy
<del> *
<del> * @deprecated 3.4.0 Use setSaveStrategy()/getSaveStrategy() instead.
<del> * @param string|null $strategy the strategy name to be used
<del> * @throws \InvalidArgumentException if an invalid strategy name is passed
<del> * @return string the strategy to be used for saving
<del> */
<del> public function saveStrategy($strategy = null)
<del> {
<del> deprecationWarning(
<del> 'BelongsToMany::saveStrategy() is deprecated. ' .
<del> 'Use setSaveStrategy()/getSaveStrategy() instead.'
<del> );
<del> if ($strategy !== null) {
<del> $this->setSaveStrategy($strategy);
<del> }
<del>
<del> return $this->getSaveStrategy();
<del> }
<del>
<ide> /**
<ide> * Takes an entity from the source table and looks if there is a field
<ide> * matching the property name for this association. The found entity will be
<ide><path>src/ORM/Association/DependentDeleteTrait.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 3.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\ORM\Association;
<del>
<del>use Cake\Datasource\EntityInterface;
<del>use Cake\ORM\Association\DependentDeleteHelper;
<del>
<del>/**
<del> * Implements cascading deletes for dependent associations.
<del> *
<del> * Included by HasOne and HasMany association classes.
<del> *
<del> * @deprecated 3.5.0 Unused in CakePHP now. This class will be removed in 4.0.0
<del> */
<del>trait DependentDeleteTrait
<del>{
<del>
<del> /**
<del> * Cascade a delete to remove dependent records.
<del> *
<del> * This method does nothing if the association is not dependent.
<del> *
<del> * @param \Cake\Datasource\EntityInterface $entity The entity that started the cascaded delete.
<del> * @param array $options The options for the original delete.
<del> * @return bool Success.
<del> */
<del> public function cascadeDelete(EntityInterface $entity, array $options = [])
<del> {
<del> deprecationWarning(
<del> 'The DependentDeleteTrait is deprecated. ' .
<del> 'You should use Cake\ORM\Association\DependentDeleteHelper instead.'
<del> );
<del> $helper = new DependentDeleteHelper();
<del>
<del> return $helper->cascadeDelete($this, $entity, $options);
<del> }
<del>}
<ide><path>src/ORM/Association/HasMany.php
<ide> public function getSaveStrategy()
<ide> return $this->_saveStrategy;
<ide> }
<ide>
<del> /**
<del> * Sets the strategy that should be used for saving. If called with no
<del> * arguments, it will return the currently configured strategy
<del> *
<del> * @deprecated 3.4.0 Use setSaveStrategy()/getSaveStrategy() instead.
<del> * @param string|null $strategy the strategy name to be used
<del> * @throws \InvalidArgumentException if an invalid strategy name is passed
<del> * @return string the strategy to be used for saving
<del> */
<del> public function saveStrategy($strategy = null)
<del> {
<del> deprecationWarning(
<del> 'HasMany::saveStrategy() is deprecated. ' .
<del> 'Use setSaveStrategy()/getSaveStrategy() instead.'
<del> );
<del> if ($strategy !== null) {
<del> $this->setSaveStrategy($strategy);
<del> }
<del>
<del> return $this->getSaveStrategy();
<del> }
<del>
<ide> /**
<ide> * Takes an entity from the source table and looks if there is a field
<ide> * matching the property name for this association. The found entity will be
<ide> public function getSort()
<ide> return $this->_sort;
<ide> }
<ide>
<del> /**
<del> * Sets the sort order in which target records should be returned.
<del> * If no arguments are passed the currently configured value is returned
<del> *
<del> * @deprecated 3.4.0 Use setSort()/getSort() instead.
<del> * @param mixed $sort A find() compatible order clause
<del> * @return mixed
<del> */
<del> public function sort($sort = null)
<del> {
<del> deprecationWarning(
<del> 'HasMany::sort() is deprecated. ' .
<del> 'Use setSort()/getSort() instead.'
<del> );
<del> if ($sort !== null) {
<del> $this->setSort($sort);
<del> }
<del>
<del> return $this->getSort();
<del> }
<del>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<ide><path>src/ORM/AssociationCollection.php
<ide> public function keys()
<ide> return array_keys($this->_items);
<ide> }
<ide>
<del> /**
<del> * Get an array of associations matching a specific type.
<del> *
<del> * @param string|array $class The type of associations you want.
<del> * For example 'BelongsTo' or array like ['BelongsTo', 'HasOne']
<del> * @return array An array of Association objects.
<del> * @deprecated 3.5.3 Use getByType() instead.
<del> */
<del> public function type($class)
<del> {
<del> deprecationWarning(
<del> 'AssociationCollection::type() is deprecated. ' .
<del> 'Use getByType() instead.'
<del> );
<del>
<del> return $this->getByType($class);
<del> }
<del>
<ide> /**
<ide> * Get an array of associations matching a specific type.
<ide> *
<ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php
<ide> public function testSetForeignKey()
<ide> $this->assertEquals('another_key', $assoc->getForeignKey());
<ide> }
<ide>
<del> /**
<del> * Tests that foreignKey() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testForeignKey()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new BelongsToMany('Test', [
<del> 'sourceTable' => $this->article,
<del> 'targetTable' => $this->tag
<del> ]);
<del> $this->assertEquals('article_id', $assoc->foreignKey());
<del> $this->assertEquals('another_key', $assoc->foreignKey('another_key'));
<del> $this->assertEquals('another_key', $assoc->foreignKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that the association reports it can be joined
<ide> *
<ide> public function testCanBeJoined()
<ide> $this->assertFalse($assoc->canBeJoined());
<ide> }
<ide>
<del> /**
<del> * Tests sort() method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSort()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new BelongsToMany('Test');
<del> $this->assertNull($assoc->sort());
<del> $assoc->sort(['id' => 'ASC']);
<del> $this->assertEquals(['id' => 'ASC'], $assoc->sort());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests setSort() method
<ide> *
<ide> public function testJunctionWithDefaultTableName()
<ide> $this->assertEquals('tags_articles', $junction->getTable());
<ide> }
<ide>
<del> /**
<del> * Tests saveStrategy
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSaveStrategy()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new BelongsToMany('Test');
<del> $this->assertEquals(BelongsToMany::SAVE_REPLACE, $assoc->saveStrategy());
<del> $assoc->saveStrategy(BelongsToMany::SAVE_APPEND);
<del> $this->assertEquals(BelongsToMany::SAVE_APPEND, $assoc->saveStrategy());
<del> $assoc->saveStrategy(BelongsToMany::SAVE_REPLACE);
<del> $this->assertEquals(BelongsToMany::SAVE_REPLACE, $assoc->saveStrategy());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests saveStrategy
<ide> *
<ide> public function testSaveAssociatedOnlyEntitiesAppend()
<ide> $association->saveAssociated($entity);
<ide> }
<ide>
<del> /**
<del> * Tests that targetForeignKey() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testTargetForeignKey()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new BelongsToMany('Test', [
<del> 'sourceTable' => $this->article,
<del> 'targetTable' => $this->tag
<del> ]);
<del> $this->assertEquals('tag_id', $assoc->targetForeignKey());
<del> $this->assertEquals('another_key', $assoc->targetForeignKey('another_key'));
<del> $this->assertEquals('another_key', $assoc->targetForeignKey());
<del>
<del> $assoc = new BelongsToMany('Test', [
<del> 'sourceTable' => $this->article,
<del> 'targetTable' => $this->tag,
<del> 'targetForeignKey' => 'foo'
<del> ]);
<del> $this->assertEquals('foo', $assoc->targetForeignKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that setTargetForeignKey() returns the correct configured value
<ide> *
<ide><path>tests/TestCase/ORM/Association/BelongsToTest.php
<ide> public function testSetForeignKey()
<ide> $this->assertEquals('another_key', $assoc->getForeignKey());
<ide> }
<ide>
<del> /**
<del> * Test that foreignKey generation
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testForeignKey()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new BelongsTo('Companies', [
<del> 'sourceTable' => $this->client,
<del> 'targetTable' => $this->company,
<del> ]);
<del> $this->assertEquals('company_id', $assoc->foreignKey());
<del> $this->assertEquals('another_key', $assoc->foreignKey('another_key'));
<del> $this->assertEquals('another_key', $assoc->foreignKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Test that foreignKey generation ignores database names in target table.
<ide> *
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> public function testSetForeignKey()
<ide> $this->assertEquals('another_key', $assoc->getForeignKey());
<ide> }
<ide>
<del> /**
<del> * Tests that foreignKey() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testForeignKey()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new HasMany('Articles', [
<del> 'sourceTable' => $this->author
<del> ]);
<del> $this->assertEquals('author_id', $assoc->foreignKey());
<del> $this->assertEquals('another_key', $assoc->foreignKey('another_key'));
<del> $this->assertEquals('another_key', $assoc->foreignKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Test that foreignKey generation ignores database names in target table.
<ide> *
<ide> public function testCanBeJoined()
<ide> $this->assertFalse($assoc->canBeJoined());
<ide> }
<ide>
<del> /**
<del> * Tests sort() method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSort()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new HasMany('Test');
<del> $this->assertNull($assoc->sort());
<del> $assoc->sort(['id' => 'ASC']);
<del> $this->assertEquals(['id' => 'ASC'], $assoc->sort());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests setSort() method
<ide> *
<ide> public function testSetSaveStrategy()
<ide> $this->assertSame($association, $association->setSaveStrategy(HasMany::SAVE_REPLACE));
<ide> $this->assertSame(HasMany::SAVE_REPLACE, $association->getSaveStrategy());
<ide> }
<del>
<del> /**
<del> * Tests saveStrategy
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSaveStrategy()
<del> {
<del> $this->deprecated(function () {
<del> $articles = $this->getTableLocator()->get('Articles');
<del>
<del> $association = $articles->hasMany('Comments');
<del> $this->assertSame(HasMany::SAVE_REPLACE, $association->saveStrategy(HasMany::SAVE_REPLACE));
<del> $this->assertSame(HasMany::SAVE_REPLACE, $association->saveStrategy());
<del> });
<del> }
<ide> }
<ide><path>tests/TestCase/ORM/Association/HasOneTest.php
<ide> public function tearDown()
<ide> $this->getTableLocator()->clear();
<ide> }
<ide>
<del> /**
<del> * Tests that foreignKey() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testForeignKey()
<del> {
<del> $this->deprecated(function () {
<del> $assoc = new HasOne('Profiles', [
<del> 'sourceTable' => $this->user
<del> ]);
<del> $this->assertEquals('user_id', $assoc->foreignKey());
<del> $this->assertEquals('another_key', $assoc->foreignKey('another_key'));
<del> $this->assertEquals('another_key', $assoc->foreignKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that setForeignKey() returns the correct configured value
<ide> *
<ide><path>tests/TestCase/ORM/AssociationTest.php
<ide> public function testOptionsIsCalled()
<ide> $this->association->__construct('Name', $options);
<ide> }
<ide>
<del> /**
<del> * Tests that name() returns the correct configure association name
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testName()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals('Foo', $this->association->name());
<del> $this->association->name('Bar');
<del> $this->assertEquals('Bar', $this->association->name());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that setName()
<ide> *
<ide> public function testTargetTableDescendant()
<ide> $this->assertInstanceOf($className, $target);
<ide> }
<ide>
<del> /**
<del> * Tests that cascadeCallbacks() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testCascadeCallbacks()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertFalse($this->association->cascadeCallbacks());
<del> $this->association->cascadeCallbacks(true);
<del> $this->assertTrue($this->association->cascadeCallbacks());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that cascadeCallbacks() returns the correct configured value
<ide> *
<ide> public function testSetCascadeCallbacks()
<ide> $this->assertTrue($this->association->getCascadeCallbacks());
<ide> }
<ide>
<del> /**
<del> * Tests the bindingKey method as a setter/getter
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testBindingKey()
<del> {
<del> $this->deprecated(function () {
<del> $this->association->bindingKey('foo_id');
<del> $this->assertEquals('foo_id', $this->association->bindingKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests the bindingKey method as a setter/getter
<ide> *
<ide> public function testBindingDefaultNoOwningSide()
<ide> $this->assertEquals(['foo', 'site_id'], $result);
<ide> }
<ide>
<del> /**
<del> * Tests that name() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testForeignKey()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals('a_key', $this->association->foreignKey());
<del> $this->association->foreignKey('another_key');
<del> $this->assertEquals('another_key', $this->association->foreignKey());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests setForeignKey()
<ide> *
<ide> public function testSetForeignKey()
<ide> $this->assertEquals('another_key', $this->association->getForeignKey());
<ide> }
<ide>
<del> /**
<del> * Tests that conditions() returns the correct configured value
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testConditions()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals(['field' => 'value'], $this->association->conditions());
<del> $conds = ['another_key' => 'another value'];
<del> $this->association->conditions($conds);
<del> $this->assertEquals($conds, $this->association->conditions());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests setConditions()
<ide> *
<ide> public function testCanBeJoined()
<ide> $this->assertTrue($this->association->canBeJoined());
<ide> }
<ide>
<del> /**
<del> * Tests that target() returns the correct Table object
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testTarget()
<del> {
<del> $this->deprecated(function () {
<del> $table = $this->association->target();
<del> $this->assertInstanceOf(__NAMESPACE__ . '\TestTable', $table);
<del>
<del> $other = new Table;
<del> $this->association->target($other);
<del> $this->assertSame($other, $this->association->target());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that setTarget()
<ide> *
<ide> public function testTargetPlugin()
<ide> $this->assertSame('ThisAssociationName', $table->getAlias());
<ide> }
<ide>
<del> /**
<del> * Tests that source() returns the correct Table object
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testSource()
<del> {
<del> $this->deprecated(function () {
<del> $table = $this->association->source();
<del> $this->assertSame($this->source, $table);
<del>
<del> $other = new Table;
<del> $this->association->source($other);
<del> $this->assertSame($other, $this->association->source());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests that source() returns the correct Table object
<ide> *
<ide> public function testSetSource()
<ide> $this->assertSame($other, $this->association->getSource());
<ide> }
<ide>
<del> /**
<del> * Tests joinType method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testJoinType()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals('INNER', $this->association->joinType());
<del> $this->association->joinType('LEFT');
<del> $this->assertEquals('LEFT', $this->association->joinType());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests setJoinType method
<ide> *
<ide> public function testSetJoinType()
<ide> $this->assertEquals('LEFT', $this->association->getJoinType());
<ide> }
<ide>
<del> /**
<del> * Tests dependent method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testDependent()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertTrue($this->association->dependent());
<del> $this->association->dependent(false);
<del> $this->assertFalse($this->association->dependent());
<del> });
<del> }
<del>
<del> /**
<del> * Tests property method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testProperty()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals('foo', $this->association->property());
<del> $this->association->property('thing');
<del> $this->assertEquals('thing', $this->association->property());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests property method
<ide> *
<ide> public function testPropertyNameExplicitySet()
<ide> $this->assertEquals('foo', $association->getProperty());
<ide> }
<ide>
<del> /**
<del> * Tests strategy method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testStrategy()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals('join', $this->association->strategy());
<del>
<del> $this->association->strategy('select');
<del> $this->assertEquals('select', $this->association->strategy());
<del>
<del> $this->association->strategy('subquery');
<del> $this->assertEquals('subquery', $this->association->strategy());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests strategy method
<ide> *
<ide> public function testInvalidStrategy()
<ide> $this->association->setStrategy('anotherThing');
<ide> }
<ide>
<del> /**
<del> * Tests test finder() method as getter and setter
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testFinderMethod()
<del> {
<del> $this->deprecated(function () {
<del> $this->assertEquals('all', $this->association->finder());
<del> $this->assertEquals('published', $this->association->finder('published'));
<del> $this->assertEquals('published', $this->association->finder());
<del> });
<del> }
<del>
<ide> /**
<ide> * Tests test setFinder() method
<ide> *
| 10
|
Javascript
|
Javascript
|
fix reference urls in animated
|
f8fc90546cd75c271b4d10a5f5a16f26998af645
|
<ide><path>Libraries/Animated/AnimatedImplementation.js
<ide> const event = function (
<ide> * If additional transforms are added, be sure to include them in
<ide> * AnimatedMock.js as well.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html
<add> * See https://reactnative.dev/docs/animated
<ide> */
<ide> module.exports = {
<ide> /**
<ide> * Standard value class for driving animations. Typically initialized with
<ide> * `new Animated.Value(0);`
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#value
<add> * See https://reactnative.dev/docs/animated#value
<ide> */
<ide> Value: AnimatedValue,
<ide> /**
<ide> * 2D value class for driving 2D animations, such as pan gestures.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html
<add> * See https://reactnative.dev/docs/animatedvaluexy
<ide> */
<ide> ValueXY: AnimatedValueXY,
<ide> /**
<ide> * Exported to use the Interpolation type in flow.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#interpolation
<add> * See https://reactnative.dev/docs/animated#interpolation
<ide> */
<ide> Interpolation: AnimatedInterpolation,
<ide> /**
<ide> * Exported for ease of type checking. All animated values derive from this
<ide> * class.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#node
<add> * See https://reactnative.dev/docs/animated#node
<ide> */
<ide> Node: AnimatedNode,
<ide>
<ide> /**
<ide> * Animates a value from an initial velocity to zero based on a decay
<ide> * coefficient.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#decay
<add> * See https://reactnative.dev/docs/animated#decay
<ide> */
<ide> decay,
<ide> /**
<ide> * Animates a value along a timed easing curve. The Easing module has tons of
<ide> * predefined curves, or you can use your own function.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#timing
<add> * See https://reactnative.dev/docs/animated#timing
<ide> */
<ide> timing,
<ide> /**
<ide> * Animates a value according to an analytical spring model based on
<ide> * damped harmonic oscillation.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#spring
<add> * See https://reactnative.dev/docs/animated#spring
<ide> */
<ide> spring,
<ide>
<ide> /**
<ide> * Creates a new Animated value composed from two Animated values added
<ide> * together.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#add
<add> * See https://reactnative.dev/docs/animated#add
<ide> */
<ide> add,
<ide>
<ide> /**
<ide> * Creates a new Animated value composed by subtracting the second Animated
<ide> * value from the first Animated value.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#subtract
<add> * See https://reactnative.dev/docs/animated#subtract
<ide> */
<ide> subtract,
<ide>
<ide> /**
<ide> * Creates a new Animated value composed by dividing the first Animated value
<ide> * by the second Animated value.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#divide
<add> * See https://reactnative.dev/docs/animated#divide
<ide> */
<ide> divide,
<ide>
<ide> /**
<ide> * Creates a new Animated value composed from two Animated values multiplied
<ide> * together.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#multiply
<add> * See https://reactnative.dev/docs/animated#multiply
<ide> */
<ide> multiply,
<ide>
<ide> /**
<ide> * Creates a new Animated value that is the (non-negative) modulo of the
<ide> * provided Animated value.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#modulo
<add> * See https://reactnative.dev/docs/animated#modulo
<ide> */
<ide> modulo,
<ide>
<ide> module.exports = {
<ide> * difference between the last value so even if the value is far from the
<ide> * bounds it will start changing when the value starts getting closer again.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#diffclamp
<add> * See https://reactnative.dev/docs/animated#diffclamp
<ide> */
<ide> diffClamp,
<ide>
<ide> /**
<ide> * Starts an animation after the given delay.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#delay
<add> * See https://reactnative.dev/docs/animated#delay
<ide> */
<ide> delay,
<ide> /**
<ide> * Starts an array of animations in order, waiting for each to complete
<ide> * before starting the next. If the current running animation is stopped, no
<ide> * following animations will be started.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#sequence
<add> * See https://reactnative.dev/docs/animated#sequence
<ide> */
<ide> sequence,
<ide> /**
<ide> * Starts an array of animations all at the same time. By default, if one
<ide> * of the animations is stopped, they will all be stopped. You can override
<ide> * this with the `stopTogether` flag.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#parallel
<add> * See https://reactnative.dev/docs/animated#parallel
<ide> */
<ide> parallel,
<ide> /**
<ide> * Array of animations may run in parallel (overlap), but are started in
<ide> * sequence with successive delays. Nice for doing trailing effects.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#stagger
<add> * See https://reactnative.dev/docs/animated#stagger
<ide> */
<ide> stagger,
<ide> /**
<ide> * Loops a given animation continuously, so that each time it reaches the
<ide> * end, it resets and begins again from the start.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#loop
<add> * See https://reactnative.dev/docs/animated#loop
<ide> */
<ide> loop,
<ide>
<ide> /**
<ide> * Takes an array of mappings and extracts values from each arg accordingly,
<ide> * then calls `setValue` on the mapped outputs.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#event
<add> * See https://reactnative.dev/docs/animated#event
<ide> */
<ide> event,
<ide>
<ide> /**
<ide> * Make any React component Animatable. Used to create `Animated.View`, etc.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#createanimatedcomponent
<add> * See https://reactnative.dev/docs/animated#createanimatedcomponent
<ide> */
<ide> createAnimatedComponent,
<ide>
<ide> /**
<ide> * Imperative API to attach an animated value to an event on a view. Prefer
<ide> * using `Animated.event` with `useNativeDrive: true` if possible.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#attachnativeevent
<add> * See https://reactnative.dev/docs/animated#attachnativeevent
<ide> */
<ide> attachNativeEvent,
<ide>
<ide> /**
<ide> * Advanced imperative API for snooping on animated events that are passed in
<ide> * through props. Use values directly where possible.
<ide> *
<del> * See https://reactnative.dev/docs/animated.html#forkevent
<add> * See https://reactnative.dev/docs/animated#forkevent
<ide> */
<ide> forkEvent,
<ide> unforkEvent,
<ide><path>Libraries/Animated/nodes/AnimatedNode.js
<ide> class AnimatedNode {
<ide> * animations. This is useful because there is no way to
<ide> * synchronously read the value because it might be driven natively.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#addlistener
<add> * See https://reactnative.dev/docs/animatedvalue#addlistener
<ide> */
<ide> addListener(callback: (value: any) => mixed): string {
<ide> const id = String(_uniqueId++);
<ide> class AnimatedNode {
<ide> * Unregister a listener. The `id` param shall match the identifier
<ide> * previously returned by `addListener()`.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#removelistener
<add> * See https://reactnative.dev/docs/animatedvalue#removelistener
<ide> */
<ide> removeListener(id: string): void {
<ide> delete this._listeners[id];
<ide> class AnimatedNode {
<ide> /**
<ide> * Remove all registered listeners.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#removealllisteners
<add> * See https://reactnative.dev/docs/animatedvalue#removealllisteners
<ide> */
<ide> removeAllListeners(): void {
<ide> this._listeners = {};
<ide><path>Libraries/Animated/nodes/AnimatedValue.js
<ide> function _executeAsAnimatedBatch(id: string, operation: () => void) {
<ide> * mechanism at a time. Using a new mechanism (e.g. starting a new animation,
<ide> * or calling `setValue`) will stop any previous ones.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html
<add> * See https://reactnative.dev/docs/animatedvalue
<ide> */
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> _value: number;
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> * Directly set the value. This will stop any animations running on the value
<ide> * and update all the bound properties.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#setvalue
<add> * See https://reactnative.dev/docs/animatedvalue#setvalue
<ide> */
<ide> setValue(value: number): void {
<ide> if (this._animation) {
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> * `setValue`, an animation, or `Animated.event`. Useful for compensating
<ide> * things like the start of a pan gesture.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#setoffset
<add> * See https://reactnative.dev/docs/animatedvalue#setoffset
<ide> */
<ide> setOffset(offset: number): void {
<ide> this._offset = offset;
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> * Merges the offset value into the base value and resets the offset to zero.
<ide> * The final output of the value is unchanged.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#flattenoffset
<add> * See https://reactnative.dev/docs/animatedvalue#flattenoffset
<ide> */
<ide> flattenOffset(): void {
<ide> this._value += this._offset;
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> * Sets the offset value to the base value, and resets the base value to zero.
<ide> * The final output of the value is unchanged.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#extractoffset
<add> * See https://reactnative.dev/docs/animatedvalue#extractoffset
<ide> */
<ide> extractOffset(): void {
<ide> this._offset += this._value;
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> * final value after stopping the animation, which is useful for updating
<ide> * state to match the animation position with layout.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#stopanimation
<add> * See https://reactnative.dev/docs/animatedvalue#stopanimation
<ide> */
<ide> stopAnimation(callback?: ?(value: number) => void): void {
<ide> this.stopTracking();
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> /**
<ide> * Stops any animation and resets the value to its original.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#resetanimation
<add> * See https://reactnative.dev/docs/animatedvalue#resetanimation
<ide> */
<ide> resetAnimation(callback?: ?(value: number) => void): void {
<ide> this.stopAnimation(callback);
<ide> class AnimatedValue extends AnimatedWithChildren {
<ide> * Typically only used internally, but could be used by a custom Animation
<ide> * class.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvalue.html#animate
<add> * See https://reactnative.dev/docs/animatedvalue#animate
<ide> */
<ide> animate(animation: Animation, callback: ?EndCallback): void {
<ide> let handle = null;
<ide><path>Libraries/Animated/nodes/AnimatedValueXY.js
<ide> let _uniqueId = 1;
<ide> * 2D Value for driving 2D animations, such as pan gestures. Almost identical
<ide> * API to normal `Animated.Value`, but multiplexed.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html
<add> * See https://reactnative.dev/docs/animatedvaluexy
<ide> */
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> x: AnimatedValue;
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> * Directly set the value. This will stop any animations running on the value
<ide> * and update all the bound properties.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#setvalue
<add> * See https://reactnative.dev/docs/animatedvaluexy#setvalue
<ide> */
<ide> setValue(value: {x: number, y: number, ...}) {
<ide> this.x.setValue(value.x);
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> * via `setValue`, an animation, or `Animated.event`. Useful for compensating
<ide> * things like the start of a pan gesture.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#setoffset
<add> * See https://reactnative.dev/docs/animatedvaluexy#setoffset
<ide> */
<ide> setOffset(offset: {x: number, y: number, ...}) {
<ide> this.x.setOffset(offset.x);
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> * Merges the offset value into the base value and resets the offset to zero.
<ide> * The final output of the value is unchanged.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#flattenoffset
<add> * See https://reactnative.dev/docs/animatedvaluexy#flattenoffset
<ide> */
<ide> flattenOffset(): void {
<ide> this.x.flattenOffset();
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> * Sets the offset value to the base value, and resets the base value to
<ide> * zero. The final output of the value is unchanged.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#extractoffset
<add> * See https://reactnative.dev/docs/animatedvaluexy#extractoffset
<ide> */
<ide> extractOffset(): void {
<ide> this.x.extractOffset();
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> /**
<ide> * Stops any animation and resets the value to its original.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#resetanimation
<add> * See https://reactnative.dev/docs/animatedvaluexy#resetanimation
<ide> */
<ide> resetAnimation(
<ide> callback?: (value: {
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> * final value after stopping the animation, which is useful for updating
<ide> * state to match the animation position with layout.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#stopanimation
<add> * See https://reactnative.dev/docs/animatedvaluexy#stopanimation
<ide> */
<ide> stopAnimation(
<ide> callback?: (value: {
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> *
<ide> * Returns a string that serves as an identifier for the listener.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#addlistener
<add> * See https://reactnative.dev/docs/animatedvaluexy#addlistener
<ide> */
<ide> addListener(callback: ValueXYListenerCallback): string {
<ide> const id = String(_uniqueId++);
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> * Unregister a listener. The `id` param shall match the identifier
<ide> * previously returned by `addListener()`.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#removelistener
<add> * See https://reactnative.dev/docs/animatedvaluexy#removelistener
<ide> */
<ide> removeListener(id: string): void {
<ide> this.x.removeListener(this._listeners[id].x);
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> /**
<ide> * Remove all registered listeners.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#removealllisteners
<add> * See https://reactnative.dev/docs/animatedvaluexy#removealllisteners
<ide> */
<ide> removeAllListeners(): void {
<ide> this.x.removeAllListeners();
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> /**
<ide> * Converts `{x, y}` into `{left, top}` for use in style.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#getlayout
<add> * See https://reactnative.dev/docs/animatedvaluexy#getlayout
<ide> */
<ide> getLayout(): {[key: string]: AnimatedValue, ...} {
<ide> return {
<ide> class AnimatedValueXY extends AnimatedWithChildren {
<ide> /**
<ide> * Converts `{x, y}` into a useable translation transform.
<ide> *
<del> * See https://reactnative.dev/docs/animatedvaluexy.html#gettranslatetransform
<add> * See https://reactnative.dev/docs/animatedvaluexy#gettranslatetransform
<ide> */
<ide> getTranslateTransform(): Array<{[key: string]: AnimatedValue, ...}> {
<ide> return [{translateX: this.x}, {translateY: this.y}];
| 4
|
Python
|
Python
|
remove duplicated code in iotools.py
|
37214699e18b55b51a3cda5fcaf64ba31c32990c
|
<ide><path>numpy/lib/_iotools.py
<ide> def __call__(self, value):
<ide> return self._callingfunction(value)
<ide> #
<ide>
<add> def _do_upgrade(self):
<add> # Raise an exception if we locked the converter...
<add> if self._locked:
<add> errmsg = "Converter is locked and cannot be upgraded"
<add> raise ConverterLockError(errmsg)
<add> _statusmax = len(self._mapper)
<add> # Complains if we try to upgrade by the maximum
<add> _status = self._status
<add> if _status == _statusmax:
<add> errmsg = "Could not find a valid conversion function"
<add> raise ConverterError(errmsg)
<add> elif _status < _statusmax - 1:
<add> _status += 1
<add> self.type, self.func, default = self._mapper[_status]
<add> self._status = _status
<add> if self._initial_default is not None:
<add> self.default = self._initial_default
<add> else:
<add> self.default = default
<add>
<ide> def upgrade(self, value):
<ide> """
<ide> Find the best converter for a given string, and return the result.
<ide> def upgrade(self, value):
<ide> try:
<ide> return self._strict_call(value)
<ide> except ValueError:
<del> # Raise an exception if we locked the converter...
<del> if self._locked:
<del> errmsg = "Converter is locked and cannot be upgraded"
<del> raise ConverterLockError(errmsg)
<del> _statusmax = len(self._mapper)
<del> # Complains if we try to upgrade by the maximum
<del> _status = self._status
<del> if _status == _statusmax:
<del> errmsg = "Could not find a valid conversion function"
<del> raise ConverterError(errmsg)
<del> elif _status < _statusmax - 1:
<del> _status += 1
<del> (self.type, self.func, default) = self._mapper[_status]
<del> self._status = _status
<del> if self._initial_default is not None:
<del> self.default = self._initial_default
<del> else:
<del> self.default = default
<add> self._do_upgrade()
<ide> return self.upgrade(value)
<ide>
<ide> def iterupgrade(self, value):
<ide> def iterupgrade(self, value):
<ide> for _m in value:
<ide> _strict_call(_m)
<ide> except ValueError:
<del> # Raise an exception if we locked the converter...
<del> if self._locked:
<del> errmsg = "Converter is locked and cannot be upgraded"
<del> raise ConverterLockError(errmsg)
<del> _statusmax = len(self._mapper)
<del> # Complains if we try to upgrade by the maximum
<del> _status = self._status
<del> if _status == _statusmax:
<del> raise ConverterError(
<del> "Could not find a valid conversion function"
<del> )
<del> elif _status < _statusmax - 1:
<del> _status += 1
<del> (self.type, self.func, default) = self._mapper[_status]
<del> if self._initial_default is not None:
<del> self.default = self._initial_default
<del> else:
<del> self.default = default
<del> self._status = _status
<add> self._do_upgrade()
<ide> self.iterupgrade(value)
<ide>
<ide> def update(self, func, default=None, testing_value=None,
| 1
|
Ruby
|
Ruby
|
permit glibc 2.27, 2.31, or 2.35
|
7d1197e8eb938f30c3db9a8754c5557a8c08ed5c
|
<ide><path>Library/Homebrew/formula_auditor.rb
<ide> def audit_postgresql
<ide>
<ide> def audit_glibc
<ide> return unless @core_tap
<del> return if formula.name != "glibc" || [OS::CI_GLIBC_VERSION, "2.35"].include?(formula.version.to_s)
<add> return if formula.name != "glibc"
<add> return if [OS::CI_GLIBC_VERSION, "2.27", "2.31", "2.35"].include?(formula.version.to_s)
<ide>
<ide> problem "The glibc version must be #{OS::CI_GLIBC_VERSION}, as this is the version used by our CI on Linux. " \
<ide> "Glibc is for users who have a system Glibc with a lower version, " \
| 1
|
Ruby
|
Ruby
|
add version class
|
104fc0e09b8bfe825a0fecd71a971677cb11c271
|
<ide><path>Library/Homebrew/version.rb
<add>class Version
<add> include Comparable
<add>
<add> def initialize val
<add> return val if val.is_a? Version or val.nil?
<add> @version = val.to_s.strip
<add> end
<add>
<add> def nums
<add> @version.scan(/\d+/).map { |d| d.to_i }
<add> end
<add>
<add> def <=>(other)
<add> @version <=> other.version
<add> end
<add>
<add> def to_s
<add> @version
<add> end
<add> alias_method :to_str, :to_s
<add>
<add> def self.parse spec
<add> Pathname.new(spec.to_s).version
<add> end
<add>end
| 1
|
Text
|
Text
|
remove obsolete i18n links from guides [ci skip]
|
71a3e6634c654b245d2e0b4b1074340dd746d6ad
|
<ide><path>guides/source/i18n.md
<ide> Conclusion
<ide>
<ide> At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
<ide>
<del>If you find anything missing or wrong in this guide, please file a ticket on our [issue tracker](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview). If you want to discuss certain portions or have questions, please sign up to our [mailing list](http://groups.google.com/group/rails-i18n).
<add>If you want to discuss certain portions or have questions, please sign up to the [rails-i18n mailing list](http://groups.google.com/group/rails-i18n).
<ide>
<ide>
<ide> Contributing to Rails I18n
<ide> Resources
<ide> ---------
<ide>
<ide> * [Google group: rails-i18n](http://groups.google.com/group/rails-i18n) - The project's mailing list.
<del>* [GitHub: rails-i18n](https://github.com/svenfuchs/rails-i18n/tree/master) - Code repository for the rails-i18n project. Most importantly you can find lots of [example translations](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for Rails that should work for your application in most cases.
<del>* [GitHub: i18n](https://github.com/svenfuchs/i18n/tree/master) - Code repository for the i18n gem.
<del>* [Lighthouse: rails-i18n](http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview) - Issue tracker for the rails-i18n project.
<del>* [Lighthouse: i18n](http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview) - Issue tracker for the i18n gem.
<add>* [GitHub: rails-i18n](https://github.com/svenfuchs/rails-i18n) - Code repository and issue tracker for the rails-i18n project. Most importantly you can find lots of [example translations](https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale) for Rails that should work for your application in most cases.
<add>* [GitHub: i18n](https://github.com/svenfuchs/i18n) - Code repository and issue tracker for the i18n gem.
<ide>
<ide>
<ide> Authors
| 1
|
Ruby
|
Ruby
|
fix tests when preserving timezones
|
b782665cbb55260bfdfc19c366c5fbc4ddd6fb12
|
<ide><path>activesupport/test/core_ext/date_time_ext_test.rb
<ide> def test_to_datetime
<ide> def test_to_time
<ide> with_env_tz 'US/Eastern' do
<ide> assert_instance_of Time, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
<del> assert_equal Time.local(2005, 2, 21, 5, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
<del> assert_equal Time.local(2005, 2, 21, 5, 11, 12).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
<add>
<add> if ActiveSupport.to_time_preserves_timezone
<add> assert_equal Time.local(2005, 2, 21, 5, 11, 12).getlocal(0), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
<add> assert_equal Time.local(2005, 2, 21, 5, 11, 12).getlocal(0).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
<add> else
<add> assert_equal Time.local(2005, 2, 21, 5, 11, 12), DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time
<add> assert_equal Time.local(2005, 2, 21, 5, 11, 12).utc_offset, DateTime.new(2005, 2, 21, 10, 11, 12, 0).to_time.utc_offset
<add> end
<ide> end
<ide> end
<ide>
<ide><path>activesupport/test/core_ext/string_ext_test.rb
<ide> def test_string_to_time
<ide>
<ide> def test_string_to_time_utc_offset
<ide> with_env_tz "US/Eastern" do
<del> assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
<del> assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
<del> assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
<del> assert_equal(-18000, "2005-02-27 22:50 -0100".to_time.utc_offset)
<add> if ActiveSupport.to_time_preserves_timezone
<add> assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
<add> assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
<add> assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
<add> assert_equal(-3600, "2005-02-27 22:50 -0100".to_time.utc_offset)
<add> else
<add> assert_equal 0, "2005-02-27 23:50".to_time(:utc).utc_offset
<add> assert_equal(-18000, "2005-02-27 23:50".to_time.utc_offset)
<add> assert_equal 0, "2005-02-27 22:50 -0100".to_time(:utc).utc_offset
<add> assert_equal(-18000, "2005-02-27 22:50 -0100".to_time.utc_offset)
<add> end
<ide> end
<ide> end
<ide>
| 2
|
Go
|
Go
|
fix a panic in handling forwarded queries
|
6a96717344a782c136eb03d642766e02eaba4519
|
<ide><path>libnetwork/resolver.go
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> extConn net.Conn
<ide> resp *dns.Msg
<ide> err error
<add> writer dns.ResponseWriter
<ide> )
<ide>
<ide> if query == nil || len(query.Question) == 0 {
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide> if resp.Len() > maxSize {
<ide> truncateResp(resp, maxSize, proto == "tcp")
<ide> }
<add> writer = w
<ide> } else {
<add> queryID := query.Id
<ide> for i := 0; i < maxExtDNS; i++ {
<ide> extDNS := &r.extDNSList[i]
<ide> if extDNS.ipStr == "" {
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide>
<ide> // forwardQueryStart stores required context to mux multiple client queries over
<ide> // one connection; and limits the number of outstanding concurrent queries.
<del> if r.forwardQueryStart(w, query) == false {
<add> if r.forwardQueryStart(w, query, queryID) == false {
<ide> old := r.tStamp
<ide> r.tStamp = time.Now()
<ide> if r.tStamp.Sub(old) > logInterval {
<ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) {
<ide>
<ide> // Retrieves the context for the forwarded query and returns the client connection
<ide> // to send the reply to
<del> w = r.forwardQueryEnd(w, resp)
<del> if w == nil {
<add> writer = r.forwardQueryEnd(w, resp)
<add> if writer == nil {
<ide> continue
<ide> }
<ide>
<ide> resp.Compress = true
<ide> break
<ide> }
<del>
<del> if resp == nil || w == nil {
<add> if resp == nil || writer == nil {
<ide> return
<ide> }
<ide> }
<ide>
<del> err = w.WriteMsg(resp)
<del> if err != nil {
<add> if writer == nil {
<add> return
<add> }
<add> if err = writer.WriteMsg(resp); err != nil {
<ide> log.Errorf("error writing resolver resp, %s", err)
<ide> }
<ide> }
<ide>
<del>func (r *resolver) forwardQueryStart(w dns.ResponseWriter, msg *dns.Msg) bool {
<add>func (r *resolver) forwardQueryStart(w dns.ResponseWriter, msg *dns.Msg, queryID uint16) bool {
<ide> proto := w.LocalAddr().Network()
<ide> dnsID := uint16(rand.Intn(maxDNSID))
<ide>
<ide> cc := clientConn{
<del> dnsID: msg.Id,
<add> dnsID: queryID,
<ide> respWriter: w,
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
assign timeoutid to avoid multiple requests
|
6df050e726b324dff9d92af8712dccc0121b96dd
|
<ide><path>src/devtools/views/Components/SelectedElement.js
<ide> function useInspectedElement(id: number | null): InspectedElement | null {
<ide> // Ask for an update in a second.
<ide> // Make sure we only ask once though.
<ide> clearTimeout(((timeoutID: any): TimeoutID));
<del> setTimeout(sendBridgeRequest, 1000);
<add> timeoutID = setTimeout(sendBridgeRequest, 1000);
<ide> };
<ide>
<ide> bridge.addListener('inspectedElement', onInspectedElement);
| 1
|
Python
|
Python
|
simplify stat collecting for process tree
|
0c494fd3782ddd32e47f3ce600012d474d43ea6c
|
<ide><path>glances/core/glances_processes.py
<ide> def __init__(self, cache_timeout=60):
<ide> # Whether or not to hide kernel threads
<ide> self.no_kernel_threads = False
<ide>
<add> self.process_tree = None
<add>
<ide> def enable(self):
<ide> """Enable process stats."""
<ide> self.disable_tag = False
<ide> def update(self):
<ide> if PROCESS_TREE:
<ide> self.process_tree = ProcessTreeNode.buildTree(processdict, self.getsortkey())
<ide>
<del> # Process optimization
<del> # Only retreive stats for visible processes (get_max_processes)
<del> if self.get_max_processes() is not None:
<del> # Sort the internal dict and cut the top N (Return a list of tuple)
<del> # tuple=key (proc), dict (returned by __get_process_stats)
<del> if PROCESS_TREE:
<del> processiter = [[n.process, n.stats] for n in iter(self.process_tree)]
<del> processloop = processiter[0:self.get_max_processes()]
<del> first = True
<del> else:
<add> for i, node in enumerate(self.process_tree):
<add> # Only retreive stats for visible processes (get_max_processes)
<add> # if (self.get_max_processes() is not None) and (i >= self.get_max_processes()):
<add> # break
<add>
<add> # add standard stats
<add> new_stats = self.__get_process_stats(node.process,
<add> mandatory_stats=False,
<add> standard_stats=True,
<add> extended_stats=False)
<add> if new_stats is not None:
<add> node.stats.update(new_stats)
<add>
<add> # Add a specific time_since_update stats for bitrate
<add> node.stats['time_since_update'] = time_since_update
<add>
<add> else:
<add> # Process optimization
<add> # Only retreive stats for visible processes (get_max_processes)
<add> if self.get_max_processes() is not None:
<add> # Sort the internal dict and cut the top N (Return a list of tuple)
<add> # tuple=key (proc), dict (returned by __get_process_stats)
<ide> try:
<ide> processiter = sorted(
<ide> processdict.items(), key=lambda x: x[1][self.getsortkey()], reverse=True)
<ide> def update(self):
<ide> else:
<ide> processloop = processiter[0:self.get_max_processes()]
<ide> first = True
<del> else:
<del> # Get all processes stats
<del> processloop = processdict.items()
<del> first = False
<del> for i in processloop:
<del> # Already existing mandatory stats
<del> procstat = i[1]
<del> if self.get_max_processes() is not None:
<del> # Update with standard stats
<del> # and extended stats but only for TOP (first) process
<del> s = self.__get_process_stats(i[0],
<del> mandatory_stats=False,
<del> standard_stats=True,
<del> extended_stats=first)
<del> if s is None:
<del> continue
<del> procstat.update(s)
<del> # Add a specific time_since_update stats for bitrate
<del> procstat['time_since_update'] = time_since_update
<del> # Update process list
<del> self.processlist.append(procstat)
<del> # Next...
<del> first = False
<add> else:
<add> # Get all processes stats
<add> processloop = processdict.items()
<add> first = False
<add> for i in processloop:
<add> # Already existing mandatory stats
<add> procstat = i[1]
<add> if self.get_max_processes() is not None:
<add> # Update with standard stats
<add> # and extended stats but only for TOP (first) process
<add> s = self.__get_process_stats(i[0],
<add> mandatory_stats=False,
<add> standard_stats=True,
<add> extended_stats=first)
<add> if s is None:
<add> continue
<add> procstat.update(s)
<add> # Add a specific time_since_update stats for bitrate
<add> procstat['time_since_update'] = time_since_update
<add> # Update process list
<add> self.processlist.append(procstat)
<add> # Next...
<add> first = False
<ide>
<ide> # Clean internals caches if timeout is reached
<ide> if self.cache_timer.finished():
<ide> def getlist(self, sortedby=None):
<ide> """Get the processlist."""
<ide> return self.processlist
<ide>
<add> def gettree(self):
<add> """Get the process tree."""
<add> return self.process_tree
<add>
<ide> def getsortkey(self):
<ide> """Get the current sort key"""
<ide> if self.getmanualsortkey() is not None:
| 1
|
Javascript
|
Javascript
|
add support for custom files in bugreporting
|
610cfdc8198133bc89e6977193c2d7b217b03e61
|
<ide><path>Libraries/BugReporting/BugReporting.js
<ide>
<ide> const BugReportingNativeModule = require('NativeModules').BugReporting;
<ide> const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<add>const Map = require('Map');
<ide>
<ide> import type EmitterSubscription from 'EmitterSubscription';
<ide>
<ide> type ExtraData = { [key: string]: string };
<ide> type SourceCallback = () => string;
<add>type DebugData = { extras: ExtraData, files: ExtraData };
<ide>
<ide> /**
<ide> * A simple class for collecting bug report data. Components can add sources that will be queried when a bug report
<ide> type SourceCallback = () => string;
<ide> * returned by `addSource` when they are unmounted.
<ide> */
<ide> class BugReporting {
<del>
<del> static _sources: Map<string, SourceCallback> = new Map();
<add> static _extraSources: Map<string, SourceCallback> = new Map();
<add> static _fileSources: Map<string, SourceCallback> = new Map();
<ide> static _subscription: ?EmitterSubscription = null;
<ide>
<ide> /**
<ide> class BugReporting {
<ide> * Conflicts trample with a warning.
<ide> */
<ide> static addSource(key: string, callback: SourceCallback): {remove: () => void} {
<del> if (BugReporting._sources.has(key)) {
<del> console.warn(`BugReporting.addSource called multiple times for same key '${key}'`);
<add> return this._addSource(key, callback, BugReporting._extraSources);
<add> }
<add>
<add> /**
<add> * Maps a string key to a simple callback that should return a string payload to be attached
<add> * to a bug report. Source callbacks are called when `collectExtraData` is called.
<add> *
<add> * Returns an object to remove the source when the component unmounts.
<add> *
<add> * Conflicts trample with a warning.
<add> */
<add> static addFileSource(key: string, callback: SourceCallback): {remove: () => void} {
<add> return this._addSource(key, callback, BugReporting._fileSources);
<add> }
<add>
<add> static _addSource(key: string, callback: SourceCallback, source: Map<string, SourceCallback>): {remove: () => void} {
<add> if (source.has(key)) {
<add> console.warn(`BugReporting.add* called multiple times for same key '${key}'`);
<ide> }
<del> BugReporting._sources.set(key, callback);
<del> return {remove: () => { BugReporting._sources.delete(key); }};
<add> source.set(key, callback);
<add> return {remove: () => { source.delete(key); }};
<ide> }
<ide>
<ide> /**
<ide> class BugReporting {
<ide> * If available, this will call `NativeModules.BugReporting.setExtraData(extraData)`
<ide> * after collecting `extraData`.
<ide> */
<del> static collectExtraData(): ExtraData {
<add> static collectExtraData(): DebugData {
<ide> const extraData: ExtraData = {};
<del> for (const [key, callback] of BugReporting._sources) {
<add> for (const [key, callback] of BugReporting._extraSources) {
<ide> extraData[key] = callback();
<ide> }
<add> const fileData: ExtraData = {};
<add> for (const [key, callback] of BugReporting._fileSources) {
<add> fileData[key] = callback();
<add> }
<ide> console.log('BugReporting extraData:', extraData);
<ide> BugReportingNativeModule &&
<ide> BugReportingNativeModule.setExtraData &&
<del> BugReportingNativeModule.setExtraData(extraData);
<del> return extraData;
<add> BugReportingNativeModule.setExtraData(extraData, fileData);
<add>
<add> return { extras: extraData, files: fileData };
<ide> }
<ide> }
<ide>
| 1
|
Python
|
Python
|
fix ticket #252
|
44b8093162207cf82143b58d9cdf5a2af7ed0731
|
<ide><path>numpy/oldnumeric/alter_code1.py
<ide>
<ide> def fixtypechars(fstr):
<ide> for name in _func2 + _func4 + _meth1:
<del> fstr = func2_re[name].sub('\\1B\\2',fstr)
<add> fstr = func_re[name].sub('\\1B\\2',fstr)
<ide> for char in _chars.keys():
<ide> fstr = meth_re[char].sub('\\1%s\\2'%_chars[char], fstr)
<ide> return fstr
| 1
|
Javascript
|
Javascript
|
remove redundant function
|
4ae320f2b3c745402955019d6a57a22ee2b8d3bd
|
<ide><path>lib/path.js
<ide> function isWindowsDeviceRoot(code) {
<ide> }
<ide>
<ide> // Resolves . and .. elements in a path with directory names
<del>function normalizeStringWin32(path, allowAboveRoot) {
<add>function normalizeString(path, allowAboveRoot, separator) {
<ide> var res = '';
<ide> var lastSegmentLength = 0;
<ide> var lastSlash = -1;
<ide> function normalizeStringWin32(path, allowAboveRoot) {
<ide> res.charCodeAt(res.length - 1) !== CHAR_DOT ||
<ide> res.charCodeAt(res.length - 2) !== CHAR_DOT) {
<ide> if (res.length > 2) {
<del> const lastSlashIndex = res.lastIndexOf('\\');
<add> const lastSlashIndex = res.lastIndexOf(separator);
<ide> if (lastSlashIndex !== res.length - 1) {
<ide> if (lastSlashIndex === -1) {
<ide> res = '';
<ide> lastSegmentLength = 0;
<ide> } else {
<ide> res = res.slice(0, lastSlashIndex);
<del> lastSegmentLength = res.length - 1 - res.lastIndexOf('\\');
<add> lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
<ide> }
<ide> lastSlash = i;
<ide> dots = 0;
<ide> function normalizeStringWin32(path, allowAboveRoot) {
<ide> }
<ide> if (allowAboveRoot) {
<ide> if (res.length > 0)
<del> res += '\\..';
<add> res += `${separator}..`;
<ide> else
<ide> res = '..';
<ide> lastSegmentLength = 2;
<ide> }
<ide> } else {
<ide> if (res.length > 0)
<del> res += '\\' + path.slice(lastSlash + 1, i);
<del> else
<del> res = path.slice(lastSlash + 1, i);
<del> lastSegmentLength = i - lastSlash - 1;
<del> }
<del> lastSlash = i;
<del> dots = 0;
<del> } else if (code === CHAR_DOT && dots !== -1) {
<del> ++dots;
<del> } else {
<del> dots = -1;
<del> }
<del> }
<del> return res;
<del>}
<del>
<del>// Resolves . and .. elements in a path with directory names
<del>function normalizeStringPosix(path, allowAboveRoot) {
<del> var res = '';
<del> var lastSegmentLength = 0;
<del> var lastSlash = -1;
<del> var dots = 0;
<del> var code;
<del> for (var i = 0; i <= path.length; ++i) {
<del> if (i < path.length)
<del> code = path.charCodeAt(i);
<del> else if (code === CHAR_FORWARD_SLASH)
<del> break;
<del> else
<del> code = CHAR_FORWARD_SLASH;
<del> if (code === CHAR_FORWARD_SLASH) {
<del> if (lastSlash === i - 1 || dots === 1) {
<del> // NOOP
<del> } else if (lastSlash !== i - 1 && dots === 2) {
<del> if (res.length < 2 || lastSegmentLength !== 2 ||
<del> res.charCodeAt(res.length - 1) !== CHAR_DOT ||
<del> res.charCodeAt(res.length - 2) !== CHAR_DOT) {
<del> if (res.length > 2) {
<del> const lastSlashIndex = res.lastIndexOf('/');
<del> if (lastSlashIndex !== res.length - 1) {
<del> if (lastSlashIndex === -1) {
<del> res = '';
<del> lastSegmentLength = 0;
<del> } else {
<del> res = res.slice(0, lastSlashIndex);
<del> lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
<del> }
<del> lastSlash = i;
<del> dots = 0;
<del> continue;
<del> }
<del> } else if (res.length === 2 || res.length === 1) {
<del> res = '';
<del> lastSegmentLength = 0;
<del> lastSlash = i;
<del> dots = 0;
<del> continue;
<del> }
<del> }
<del> if (allowAboveRoot) {
<del> if (res.length > 0)
<del> res += '/..';
<del> else
<del> res = '..';
<del> lastSegmentLength = 2;
<del> }
<del> } else {
<del> if (res.length > 0)
<del> res += '/' + path.slice(lastSlash + 1, i);
<add> res += separator + path.slice(lastSlash + 1, i);
<ide> else
<ide> res = path.slice(lastSlash + 1, i);
<ide> lastSegmentLength = i - lastSlash - 1;
<ide> const win32 = {
<ide> // fails)
<ide>
<ide> // Normalize the tail path
<del> resolvedTail = normalizeStringWin32(resolvedTail, !resolvedAbsolute);
<add> resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\');
<ide>
<ide> return (resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail) ||
<ide> '.';
<ide> const win32 = {
<ide>
<ide> var tail;
<ide> if (rootEnd < len)
<del> tail = normalizeStringWin32(path.slice(rootEnd), !isAbsolute);
<add> tail = normalizeString(path.slice(rootEnd), !isAbsolute, '\\');
<ide> else
<ide> tail = '';
<ide> if (tail.length === 0 && !isAbsolute)
<ide> const posix = {
<ide> // handle relative paths to be safe (might happen when process.cwd() fails)
<ide>
<ide> // Normalize the path
<del> resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
<add> resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/');
<ide>
<ide> if (resolvedAbsolute) {
<ide> if (resolvedPath.length > 0)
<ide> const posix = {
<ide> path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
<ide>
<ide> // Normalize the path
<del> path = normalizeStringPosix(path, !isAbsolute);
<add> path = normalizeString(path, !isAbsolute, '/');
<ide>
<ide> if (path.length === 0 && !isAbsolute)
<ide> path = '.';
| 1
|
Javascript
|
Javascript
|
fix win32 parse()
|
4717ea9186eb3995b5b317f223f6b516c6182197
|
<ide><path>lib/path.js
<ide> const win32 = {
<ide> isAbsolute = true;
<ide>
<ide> code = path.charCodeAt(1);
<add> rootEnd = 1;
<ide> if (code === 47/*/*/ || code === 92/*\*/) {
<del> rootEnd = 1;
<ide> // Matched double path separator at beginning
<ide> var j = 2;
<ide> var last = j;
<ide><path>test/parallel/test-path-parse-format.js
<ide> const winPaths = [
<ide> '\\\\?\\UNC\\server\\share'
<ide> ];
<ide>
<add>const winSpecialCaseParseTests = [
<add> ['/foo/bar', {root: '/'}]
<add>];
<add>
<ide> const winSpecialCaseFormatTests = [
<ide> [{dir: 'some\\dir'}, 'some\\dir\\'],
<ide> [{base: 'index.html'}, 'index.html'],
<ide> const errors = [
<ide>
<ide> checkParseFormat(path.win32, winPaths);
<ide> checkParseFormat(path.posix, unixPaths);
<add>checkSpecialCaseParseFormat(path.win32, winSpecialCaseParseTests);
<ide> checkErrors(path.win32);
<ide> checkErrors(path.posix);
<ide> checkFormat(path.win32, winSpecialCaseFormatTests);
<ide> function checkParseFormat(path, paths) {
<ide> });
<ide> }
<ide>
<add>function checkSpecialCaseParseFormat(path, testCases) {
<add> testCases.forEach(function(testCase) {
<add> const element = testCase[0];
<add> const expect = testCase[1];
<add> const output = path.parse(element);
<add> Object.keys(expect).forEach(function(key) {
<add> assert.strictEqual(output[key], expect[key]);
<add> });
<add> });
<add>}
<add>
<ide> function checkFormat(path, testCases) {
<ide> testCases.forEach(function(testCase) {
<ide> assert.strictEqual(path.format(testCase[0]), testCase[1]);
| 2
|
Go
|
Go
|
ignore kernel-memory on api >= 1.42
|
2597a7162360ef56001a1764d0cb53b51b912d8f
|
<ide><path>client/container_create.go
<ide> func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config
<ide> if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil {
<ide> return response, err
<ide> }
<del>
<del> clientVersion := cli.ClientVersion()
<del>
<del> // When using API 1.24 and under, the client is responsible for removing the container
<del> if hostConfig != nil && versions.LessThan(clientVersion, "1.25") {
<del> hostConfig.AutoRemove = false
<del> }
<del>
<del> // When using API under 1.42, the Linux daemon doesn't respect the ConsoleSize
<del> if hostConfig != nil && platform != nil && platform.OS == "linux" && versions.LessThan(clientVersion, "1.42") {
<del> hostConfig.ConsoleSize = [2]uint{0, 0}
<del> }
<del>
<ide> if err := cli.NewVersionError("1.41", "specify container image platform"); platform != nil && err != nil {
<ide> return response, err
<ide> }
<ide>
<add> if hostConfig != nil {
<add> if versions.LessThan(cli.ClientVersion(), "1.25") {
<add> // When using API 1.24 and under, the client is responsible for removing the container
<add> hostConfig.AutoRemove = false
<add> }
<add> if versions.GreaterThanOrEqualTo(cli.ClientVersion(), "1.42") || versions.LessThan(cli.ClientVersion(), "1.40") {
<add> // KernelMemory was added in API 1.40, and deprecated in API 1.42
<add> hostConfig.KernelMemory = 0
<add> }
<add> if platform != nil && platform.OS == "linux" && versions.LessThan(cli.ClientVersion(), "1.42") {
<add> // When using API under 1.42, the Linux daemon doesn't respect the ConsoleSize
<add> hostConfig.ConsoleSize = [2]uint{0, 0}
<add> }
<add> }
<add>
<ide> query := url.Values{}
<ide> if p := formatPlatform(platform); p != "" {
<ide> query.Set("platform", p)
| 1
|
Javascript
|
Javascript
|
fix buggy getttyfd() implementation
|
1af82f3d0e13a175c424017565189fffb2f49e83
|
<ide><path>test/sequential/test-async-wrap-getasyncid.js
<ide> if (common.hasCrypto) { // eslint-disable-line crypto-check
<ide> // Do our best to grab a tty fd.
<ide> function getTTYfd() {
<ide> const tty = require('tty');
<del> let tty_fd = 0;
<del> if (!tty.isatty(tty_fd)) tty_fd++;
<del> else if (!tty.isatty(tty_fd)) tty_fd++;
<del> else if (!tty.isatty(tty_fd)) tty_fd++;
<del> else {
<add> let ttyFd = [0, 1, 2].find(tty.isatty);
<add> if (ttyFd === undefined) {
<ide> try {
<del> tty_fd = fs.openSync('/dev/tty');
<add> ttyFd = fs.openSync('/dev/tty');
<ide> } catch (e) {
<ide> // There aren't any tty fd's available to use.
<ide> return -1;
<ide> }
<ide> }
<del> return tty_fd;
<add> return ttyFd;
<ide> }
<ide>
<del> const tty_fd = getTTYfd();
<del> if (tty_fd >= 0) {
<add> const ttyFd = getTTYfd();
<add> if (ttyFd >= 0) {
<ide> const tty_wrap = process.binding('tty_wrap');
<ide> // fd may still be invalid, so guard against it.
<ide> const handle = (() => {
<ide> try {
<del> return new tty_wrap.TTY(tty_fd, false);
<add> return new tty_wrap.TTY(ttyFd, false);
<ide> } catch (e) {
<ide> return null;
<ide> }
| 1
|
PHP
|
PHP
|
add return type into phpdoc
|
da09db73f3c3b4ecf788870896d84c73cd574107
|
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function insertGetId(array $values, $sequence = null)
<ide> *
<ide> * @param array $columns
<ide> * @param \Closure|\Illuminate\Database\Query\Builder|string $query
<add> * @return bool
<ide> */
<ide> public function insertSub(array $columns, $query)
<ide> {
| 1
|
Javascript
|
Javascript
|
adjust code style
|
ace8e6b56d7e621619564ab23da423378f9944fb
|
<ide><path>examples/js/animation/MMDAnimationHelper.js
<ide> THREE.MMDAnimationHelper = ( function () {
<ide>
<ide> if ( this.currentTime < this.delayTime ) return false;
<ide>
<del> if ((this.currentTime - this.delayTime) > this.audioDuration) return false;
<add> if ( ( this.currentTime - this.delayTime ) > this.audioDuration ) return false;
<ide>
<ide> this.audio.startTime = this.currentTime - this.delayTime;
<ide>
| 1
|
Javascript
|
Javascript
|
prepare files for no-var lint rule
|
49547abe99678bf090f666663efdd7f9292758fe
|
<ide><path>lib/internal/crypto/util.js
<ide> function lazyRequire(name) {
<ide> return ret;
<ide> }
<ide>
<del>var defaultEncoding = 'buffer';
<add>let defaultEncoding = 'buffer';
<ide>
<ide> function setDefaultEncoding(val) {
<ide> defaultEncoding = val;
<ide><path>lib/internal/dns/promises.js
<ide> function onlookupall(err, addresses) {
<ide>
<ide> const family = this.family;
<ide>
<del> for (var i = 0; i < addresses.length; i++) {
<add> for (let i = 0; i < addresses.length; i++) {
<ide> const address = addresses[i];
<ide>
<ide> addresses[i] = {
<ide> function createLookupPromise(family, hostname, all, hints, verbatim) {
<ide> }
<ide>
<ide> function lookup(hostname, options) {
<del> var hints = 0;
<del> var family = -1;
<del> var all = false;
<del> var verbatim = getDefaultVerbatim();
<add> let hints = 0;
<add> let family = -1;
<add> let all = false;
<add> let verbatim = getDefaultVerbatim();
<ide>
<ide> // Parse arguments
<ide> if (hostname) {
<ide> Resolver.prototype.resolveNaptr = resolveMap.NAPTR = resolver('queryNaptr');
<ide> Resolver.prototype.resolveSoa = resolveMap.SOA = resolver('querySoa');
<ide> Resolver.prototype.reverse = resolver('getHostByAddr');
<ide> Resolver.prototype.resolve = function resolve(hostname, rrtype) {
<del> var resolver;
<add> let resolver;
<ide>
<ide> if (rrtype !== undefined) {
<ide> validateString(rrtype, 'rrtype');
<ide><path>lib/internal/http2/util.js
<ide> const assertWithinRange = hideStackFrames(
<ide>
<ide> function toHeaderObject(headers, sensitiveHeaders) {
<ide> const obj = ObjectCreate(null);
<del> for (var n = 0; n < headers.length; n += 2) {
<add> for (let n = 0; n < headers.length; n += 2) {
<ide> const name = headers[n];
<ide> let value = headers[n + 1];
<ide> if (name === HTTP2_HEADER_STATUS)
| 3
|
PHP
|
PHP
|
snake function
|
4ef2c071dcf7a6cdffdcc9e0a4e6a5d90ebf88d4
|
<ide><path>src/Illuminate/Support/Str.php
<ide> public static function slug($title, $separator = '-')
<ide> *
<ide> * @param string $value
<ide> * @param string $delimiter
<add> * @param bool $each
<ide> * @return string
<ide> */
<del> public static function snake($value, $delimiter = '_')
<add> public static function snake($value, $delimiter = '_', $each = true)
<ide> {
<ide> if (ctype_lower($value)) return $value;
<ide>
<del> $replace = '$1'.$delimiter.'$2';
<add> $replace = $each ? '$1'.$delimiter : '$1'.$delimiter.'$2';
<add> $pattern = $each ? '/(.)(?=[A-Z])/' : '/(.)([A-Z]+)/';
<ide>
<del> return strtolower(preg_replace('/(.)([A-Z])/', $replace, $value));
<add> return strtolower(preg_replace($pattern, $replace, $value));
<ide> }
<ide>
<ide> /**
<ide><path>tests/Support/SupportStrTest.php
<ide> public function testRandom()
<ide> $this->assertInternalType('string', Str::random());
<ide> }
<ide>
<add> public function testSnake()
<add> {
<add> $this->assertEquals('laravel_p_h_p_framework', Str::snake('LaravelPHPFramework'));
<add> $this->assertEquals('laravel-phpframework', Str::snake('LaravelPHPFramework', '-', false));
<add> }
<add>
<ide> }
| 2
|
PHP
|
PHP
|
remove deprecation code
|
4251cbe1d1ca00459906715e781c081e37c253b4
|
<ide><path>src/Core/Plugin.php
<ide> class Plugin
<ide> *
<ide> * - `bootstrap` - array - Whether or not you want the $plugin/config/bootstrap.php file loaded.
<ide> * - `routes` - boolean - Whether or not you want to load the $plugin/config/routes.php file.
<del> * - `ignoreMissing` - boolean - Set to true to ignore missing bootstrap/routes files.
<ide> * - `path` - string - The path the plugin can be found on. If empty the default plugin path (App.pluginPaths) will be used.
<ide> * - `classBase` - The path relative to `path` which contains the folders with class files.
<ide> * Defaults to "src".
<ide> public static function load($plugin, array $config = [])
<ide> 'routes' => false,
<ide> 'console' => true,
<ide> 'classBase' => 'src',
<del> 'ignoreMissing' => false,
<ide> 'name' => $plugin
<ide> ];
<ide>
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function sort($key, $title = null, array $options = [])
<ide> * @param array $options Pagination/URL options array
<ide> * @param string|null $model Which model to paginate on
<ide> * @param array $urlOptions Array of options
<del> * The bool version of this argument is *deprecated* and will be removed in 4.0.0
<ide> * @return string By default, returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript)
<ide> * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#generating-pagination-urls
<ide> */
<ide> public function generateUrl(array $options = [], $model = null, $urlOptions = [])
<ide> {
<del> if (is_bool($urlOptions)) {
<del> $urlOptions = ['fullBase' => $urlOptions];
<del> deprecationWarning(
<del> 'Passing a boolean value as third argument into PaginatorHelper::generateUrl() is deprecated ' .
<del> 'and will be removed in 4.0.0 . ' .
<del> 'Pass an array instead.'
<del> );
<del> }
<ide> $urlOptions += [
<ide> 'escape' => true,
<ide> 'fullBase' => false
<ide><path>tests/TestCase/Utility/Crypto/McryptTest.php
<del><?php
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> *
<del> * Licensed under The MIT License
<del> * For full copyright and license information, please see the LICENSE.txt
<del> * Redistributions of files must retain the above copyright notice.
<del> *
<del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 3.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\Test\TestCase\Utility\Crypto;
<del>
<del>use Cake\TestSuite\TestCase;
<del>use Cake\Utility\Crypto\Mcrypt;
<del>
<del>/**
<del> * Mcrypt engine tests.
<del> */
<del>class McryptTest extends TestCase
<del>{
<del>
<del> /**
<del> * Setup function.
<del> *
<del> * @return void
<del> */
<del> public function setUp()
<del> {
<del> parent::setUp();
<del> $this->skipIf(!function_exists('mcrypt_encrypt') || version_compare(PHP_VERSION, '7.1', '>='), 'No mcrypt skipping tests');
<del> $this->crypt = new Mcrypt();
<del> }
<del>
<del> /**
<del> * testRijndael method
<del> *
<del> * @return void
<del> */
<del> public function testRijndael()
<del> {
<del> $txt = 'The quick brown fox jumped over the lazy dog.';
<del> $key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
<del>
<del> $result = $this->crypt->rijndael($txt, $key, 'encrypt');
<del> $this->assertEquals($txt, $this->crypt->rijndael($result, $key, 'decrypt'));
<del>
<del> $result = $this->crypt->rijndael($key, $txt, 'encrypt');
<del> $this->assertEquals($key, $this->crypt->rijndael($result, $txt, 'decrypt'));
<del>
<del> $result = $this->crypt->rijndael('', $key, 'encrypt');
<del> $this->assertEquals('', $this->crypt->rijndael($result, $key, 'decrypt'));
<del>
<del> $key = 'this is my key of over 32 chars, yes it is';
<del> $result = $this->crypt->rijndael($txt, $key, 'encrypt');
<del> $this->assertEquals($txt, $this->crypt->rijndael($result, $key, 'decrypt'));
<del> }
<del>
<del> /**
<del> * Test encrypt/decrypt.
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testEncryptDecrypt()
<del> {
<del> $this->deprecated(function () {
<del> $txt = 'The quick brown fox';
<del> $key = 'This key is enough bytes';
<del> $result = $this->crypt->encrypt($txt, $key);
<del> $this->assertNotEquals($txt, $result, 'Should be encrypted.');
<del> $this->assertNotEquals($result, $this->crypt->encrypt($txt, $key), 'Each result is unique.');
<del> $this->assertEquals($txt, $this->crypt->decrypt($result, $key));
<del> });
<del> }
<del>
<del> /**
<del> * Test that changing the key causes decryption to fail.
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testDecryptKeyFailure()
<del> {
<del> $this->deprecated(function () {
<del> $txt = 'The quick brown fox';
<del>
<del> $key = substr(hash('sha256', 'This key is enough bytes'), 0, 32);
<del> $result = $this->crypt->encrypt($txt, $key);
<del>
<del> $key = substr(hash('sha256', 'Not the same key.'), 0, 32);
<del> $this->assertFalse($this->crypt->decrypt($txt, $key), 'Modified key will fail.');
<del> });
<del> }
<del>
<del> /**
<del> * Ensure that data encrypted with 2.x encrypt() function can be decrypted with mcrypt engine.
<del> *
<del> * The $cipher variable is base64 encoded data from 2.x encrypt()
<del> *
<del> * @group deprecated
<del> * @return
<del> */
<del> public function testDecryptOldData()
<del> {
<del> $this->deprecated(function () {
<del> $key = 'My password is nice and long really it is';
<del> $key = substr(hash('sha256', $key), 0, 32);
<del>
<del> $cipher = 'ZmFkMjdmY2U2NjgzOTkwMGZmMWJiMzY0ZDA5ZDUwZmNjYTdjNWVkZThkMzhmNzdiY' .
<del> 'Tg3ZDFjMzNjNmViMDljMnk9k0LmYpwSZH5eq7GmDozMwHxzh37YaXFQ2TK5gXb5OfTKXv83K+NjAS9lIo/Zvw==';
<del> $data = base64_decode($cipher);
<del> $cipher = substr($data, 64);
<del>
<del> $result = $this->crypt->decrypt($cipher, $key);
<del> $this->assertEquals('This is a secret message', $result);
<del> });
<del> }
<del>}
<ide><path>tests/TestCase/Utility/SecurityTest.php
<ide> public function testDecryptInvalidData()
<ide> }
<ide>
<ide> /**
<del> * Test that values encrypted with open ssl can be decrypted with mcrypt and the reverse.
<add> * Test engine
<ide> *
<del> * @group deprecated
<ide> * @return void
<ide> */
<ide> public function testEngineEquivalence()
<ide> {
<del> $this->skipIf(!function_exists('mcrypt_encrypt') || version_compare(PHP_VERSION, '7.1', '>='), 'This needs mcrypt extension to be loaded.');
<del> $this->deprecated(function () {
<del> $restore = Security::engine();
<del> $txt = "Obi-wan you're our only hope";
<del> $key = 'This is my secret key phrase it is quite long.';
<del> $salt = 'A tasty salt that is delicious';
<del>
<del> Security::engine(new OpenSsl());
<del> $cipher = Security::encrypt($txt, $key, $salt);
<del> $this->assertEquals($txt, Security::decrypt($cipher, $key, $salt));
<del>
<del> Security::engine(new OpenSsl());
<del> $this->assertEquals($txt, Security::decrypt($cipher, $key, $salt));
<del>
<del> Security::engine(new OpenSsl());
<del> $cipher = Security::encrypt($txt, $key, $salt);
<del> $this->assertEquals($txt, Security::decrypt($cipher, $key, $salt));
<del>
<del> Security::engine(new OpenSsl());
<del> $this->assertEquals($txt, Security::decrypt($cipher, $key, $salt));
<del> });
<add> $restore = Security::engine();
<add> $newEngine = new OpenSsl();
<add>
<add> Security::engine($newEngine);
<add>
<add> $this->assertSame($newEngine, Security::engine());
<add> $this->assertNotSame($restore, Security::engine());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testUrlGeneration()
<ide> $options = ['sort' => 'Article.name', 'direction' => 'desc'];
<ide> $result = $this->Paginator->generateUrl($options, null, ['fullBase' => true]);
<ide> $this->assertEquals('http://localhost/index?page=3&sort=Article.name&direction=desc', $result);
<del>
<del> // @deprecated 3.3.5 Use fullBase array option instead.
<del> $this->deprecated(function () {
<del> $this->Paginator->request = $this->Paginator->request->withParam('paging.Article.page', 3);
<del> $options = ['sort' => 'Article.name', 'direction' => 'desc'];
<del> $result = $this->Paginator->generateUrl($options, null, true);
<del> $this->assertEquals('http://localhost/index?page=3&sort=Article.name&direction=desc', $result);
<del> });
<ide> }
<ide>
<ide> /**
| 5
|
Ruby
|
Ruby
|
fix version mapping
|
05b496194af2340826bc9d33ee8118186b1e6487
|
<ide><path>Library/Homebrew/test/unversioned_cask_checker_spec.rb
<ide> ["1.0", "1"] => "1.0",
<ide> ["1.0", "0"] => "1.0",
<ide> ["1.2.3.4000", "4000"] => "1.2.3.4000",
<add> ["5", "5.0.45"] => "5.0.45",
<ide> }
<ide>
<ide> expected_mappings.each do |(short_version, version), expected_version|
<ide><path>Library/Homebrew/unversioned_cask_checker.rb
<ide> def self.version_from_package_info(package_info_path)
<ide> def self.decide_between_versions(short_version, version)
<ide> return short_version if short_version == version
<ide>
<del> short_version_match = short_version&.match?(/\A\d+(\.\d+)+\Z/)
<del> version_match = version&.match?(/\A\d+(\.\d+)+\Z/)
<add> if short_version && version
<add> return version if version.match?(/\A\d+(\.\d+)+\Z/) && version.start_with?("#{short_version}.")
<add> return short_version if short_version.match?(/\A\d+(\.\d+)+\Z/) && short_version.start_with?("#{version}.")
<ide>
<del> if short_version_match && version_match
<del> return version if version.length > short_version.length && version.start_with?("#{short_version}.")
<del> return short_version if short_version.length > version.length && short_version.start_with?("#{version}.")
<del> end
<del>
<del> if short_version&.match?(/\A\d+(\.\d+)*\Z/) && version&.match?(/\A\d+\Z/)
<del> return short_version if short_version.start_with?("#{version}.") || short_version.end_with?(".#{version}")
<add> if short_version.match?(/\A\d+(\.\d+)*\Z/) && version.match?(/\A\d+\Z/)
<add> return short_version if short_version.start_with?("#{version}.") || short_version.end_with?(".#{version}")
<ide>
<del> return "#{short_version},#{version}"
<add> return "#{short_version},#{version}"
<add> end
<ide> end
<ide>
<ide> short_version || version
| 2
|
Text
|
Text
|
add comments and update callback arguments' names
|
a30982e862e241a4f4615211ef0c14543a77b1e2
|
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data/index.md
<ide> var watchList = [
<ide> ];
<ide>
<ide> // Add your code below this line
<del>
<del>var averageRating = watchList.filter(x => x.Director === "Christopher Nolan").map(x => Number(x.imdbRating)).reduce((x1, x2) => x1 + x2) / watchList.filter(x => x.Director === "Christopher Nolan").length;
<add>var averageRating = watchList
<add> // Use filter to find films directed by Christopher Nolan
<add> .filter(film => film.Director === "Christopher Nolan")
<add> // Use map to convert their ratings from strings to numbers
<add> .map(film => Number(film.imdbRating))
<add> // Use reduce to add together their ratings
<add> .reduce((sumOfRatings, rating) => sumOfRatings + rating)
<add> // Divide by the number of Nolan films to get the average rating
<add> / watchList.filter(film => film.Director === "Christopher Nolan").length;
<ide>
<ide> // Add your code above this line
<ide>
<del>console.log(averageRating);
<add>console.log(averageRating);
<ide>
<ide> ```
| 1
|
PHP
|
PHP
|
add defualt value
|
7642f12d7199456e5bf634a3e449023e3ee0160d
|
<ide><path>src/Illuminate/Validation/Validator.php
<ide> public function extractValuesForWildcards($data, $attribute)
<ide> * @param string|array $rules
<ide> * @return $this
<ide> */
<del> public function mergeRules($attribute, $rules)
<add> public function mergeRules($attribute, $rules = [])
<ide> {
<ide> if (is_array($attribute)) {
<ide> foreach ($attribute as $innerAttribute => $innerRules) {
| 1
|
Go
|
Go
|
add support for external cas
|
11085b2260a78b3248f3e98e0a1e3203431fae22
|
<ide><path>api/client/swarm/opts.go
<ide> package swarm
<ide>
<ide> import (
<add> "encoding/csv"
<add> "errors"
<ide> "fmt"
<ide> "strings"
<ide> "time"
<ide> const (
<ide> flagListenAddr = "listen-addr"
<ide> flagSecret = "secret"
<ide> flagTaskHistoryLimit = "task-history-limit"
<add> flagExternalCA = "external-ca"
<ide> )
<ide>
<ide> var (
<ide> type swarmOptions struct {
<ide> taskHistoryLimit int64
<ide> dispatcherHeartbeat time.Duration
<ide> nodeCertExpiry time.Duration
<add> externalCA ExternalCAOption
<ide> }
<ide>
<ide> // NodeAddrOption is a pflag.Value for listen and remote addresses
<ide> func NewAutoAcceptOption() AutoAcceptOption {
<ide> return AutoAcceptOption{values: make(map[string]bool)}
<ide> }
<ide>
<add>// ExternalCAOption is a Value type for parsing external CA specifications.
<add>type ExternalCAOption struct {
<add> values []*swarm.ExternalCA
<add>}
<add>
<add>// Set parses an external CA option.
<add>func (m *ExternalCAOption) Set(value string) error {
<add> parsed, err := parseExternalCA(value)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> m.values = append(m.values, parsed)
<add> return nil
<add>}
<add>
<add>// Type returns the type of this option.
<add>func (m *ExternalCAOption) Type() string {
<add> return "external-ca"
<add>}
<add>
<add>// String returns a string repr of this option.
<add>func (m *ExternalCAOption) String() string {
<add> externalCAs := []string{}
<add> for _, externalCA := range m.values {
<add> repr := fmt.Sprintf("%s: %s", externalCA.Protocol, externalCA.URL)
<add> externalCAs = append(externalCAs, repr)
<add> }
<add> return strings.Join(externalCAs, ", ")
<add>}
<add>
<add>// Value returns the external CAs
<add>func (m *ExternalCAOption) Value() []*swarm.ExternalCA {
<add> return m.values
<add>}
<add>
<add>// parseExternalCA parses an external CA specification from the command line,
<add>// such as protocol=cfssl,url=https://example.com.
<add>func parseExternalCA(caSpec string) (*swarm.ExternalCA, error) {
<add> csvReader := csv.NewReader(strings.NewReader(caSpec))
<add> fields, err := csvReader.Read()
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> externalCA := swarm.ExternalCA{
<add> Options: make(map[string]string),
<add> }
<add>
<add> var (
<add> hasProtocol bool
<add> hasURL bool
<add> )
<add>
<add> for _, field := range fields {
<add> parts := strings.SplitN(field, "=", 2)
<add>
<add> if len(parts) != 2 {
<add> return nil, fmt.Errorf("invalid field '%s' must be a key=value pair", field)
<add> }
<add>
<add> key, value := parts[0], parts[1]
<add>
<add> switch strings.ToLower(key) {
<add> case "protocol":
<add> hasProtocol = true
<add> if strings.ToLower(value) == string(swarm.ExternalCAProtocolCFSSL) {
<add> externalCA.Protocol = swarm.ExternalCAProtocolCFSSL
<add> } else {
<add> return nil, fmt.Errorf("unrecognized external CA protocol %s", value)
<add> }
<add> case "url":
<add> hasURL = true
<add> externalCA.URL = value
<add> default:
<add> externalCA.Options[key] = value
<add> }
<add> }
<add>
<add> if !hasProtocol {
<add> return nil, errors.New("the external-ca option needs a protocol= parameter")
<add> }
<add> if !hasURL {
<add> return nil, errors.New("the external-ca option needs a url= parameter")
<add> }
<add>
<add> return &externalCA, nil
<add>}
<add>
<ide> func addSwarmFlags(flags *pflag.FlagSet, opts *swarmOptions) {
<ide> flags.Var(&opts.autoAccept, flagAutoAccept, "Auto acceptance policy (worker, manager or none)")
<ide> flags.StringVar(&opts.secret, flagSecret, "", "Set secret value needed to accept nodes into cluster")
<ide> flags.Int64Var(&opts.taskHistoryLimit, flagTaskHistoryLimit, 10, "Task history retention limit")
<ide> flags.DurationVar(&opts.dispatcherHeartbeat, flagDispatcherHeartbeat, time.Duration(5*time.Second), "Dispatcher heartbeat period")
<ide> flags.DurationVar(&opts.nodeCertExpiry, flagCertExpiry, time.Duration(90*24*time.Hour), "Validity period for node certificates")
<add> flags.Var(&opts.externalCA, flagExternalCA, "Specifications of one or more certificate signing endpoints")
<ide> }
<ide>
<ide> func (opts *swarmOptions) ToSpec() swarm.Spec {
<ide> func (opts *swarmOptions) ToSpec() swarm.Spec {
<ide> spec.Orchestration.TaskHistoryRetentionLimit = opts.taskHistoryLimit
<ide> spec.Dispatcher.HeartbeatPeriod = uint64(opts.dispatcherHeartbeat.Nanoseconds())
<ide> spec.CAConfig.NodeCertExpiry = opts.nodeCertExpiry
<add> spec.CAConfig.ExternalCAs = opts.externalCA.Value()
<ide> return spec
<ide> }
<ide><path>api/client/swarm/update.go
<ide> func mergeSwarm(swarm *swarm.Swarm, flags *pflag.FlagSet) error {
<ide> }
<ide> }
<ide>
<add> if flags.Changed(flagExternalCA) {
<add> value := flags.Lookup(flagExternalCA).Value.(*ExternalCAOption)
<add> spec.CAConfig.ExternalCAs = value.Value()
<add> }
<add>
<ide> return nil
<ide> }
<ide><path>daemon/cluster/convert/swarm.go
<ide> func SwarmFromGRPC(c swarmapi.Cluster) types.Swarm {
<ide>
<ide> swarm.Spec.CAConfig.NodeCertExpiry, _ = ptypes.Duration(c.Spec.CAConfig.NodeCertExpiry)
<ide>
<add> for _, ca := range c.Spec.CAConfig.ExternalCAs {
<add> swarm.Spec.CAConfig.ExternalCAs = append(swarm.Spec.CAConfig.ExternalCAs, &types.ExternalCA{
<add> Protocol: types.ExternalCAProtocol(strings.ToLower(ca.Protocol.String())),
<add> URL: ca.URL,
<add> Options: ca.Options,
<add> })
<add> }
<add>
<ide> // Meta
<ide> swarm.Version.Index = c.Meta.Version.Index
<ide> swarm.CreatedAt, _ = ptypes.Timestamp(c.Meta.CreatedAt)
<ide> func SwarmSpecToGRPCandMerge(s types.Spec, existingSpec *swarmapi.ClusterSpec) (
<ide> },
<ide> }
<ide>
<add> for _, ca := range s.CAConfig.ExternalCAs {
<add> protocol, ok := swarmapi.ExternalCA_CAProtocol_value[strings.ToUpper(string(ca.Protocol))]
<add> if !ok {
<add> return swarmapi.ClusterSpec{}, fmt.Errorf("invalid protocol: %q", ca.Protocol)
<add> }
<add> spec.CAConfig.ExternalCAs = append(spec.CAConfig.ExternalCAs, &swarmapi.ExternalCA{
<add> Protocol: swarmapi.ExternalCA_CAProtocol(protocol),
<add> URL: ca.URL,
<add> Options: ca.Options,
<add> })
<add> }
<add>
<ide> if err := SwarmSpecUpdateAcceptancePolicy(&spec, s.AcceptancePolicy, existingSpec); err != nil {
<ide> return swarmapi.ClusterSpec{}, err
<ide> }
| 3
|
Go
|
Go
|
remove osversion from oci
|
72de562943a9bfbc44d24c80dfc9d0dc112ab0f4
|
<ide><path>daemon/oci_windows.go
<ide> func (daemon *Daemon) createSpec(c *container.Container) (*libcontainerd.Spec, e
<ide> return nil, fmt.Errorf("Failed to graph.Get on ImageID %s - %s", c.ImageID, err)
<ide> }
<ide>
<del> s.Platform.OSVersion = img.OSVersion
<del>
<ide> // In base spec
<ide> s.Hostname = c.FullHostname()
<ide>
<ide><path>libcontainerd/client_windows.go
<ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir
<ide> configuration.HvRuntime = &hcsshim.HvRuntime{
<ide> ImagePath: spec.Windows.HvRuntime.ImagePath,
<ide> }
<del>
<del> // Images with build version < 14350 don't support running with clone, but
<del> // Windows cannot automatically detect this. Explicitly block cloning in this
<del> // case.
<del> if build := buildFromVersion(spec.Platform.OSVersion); build > 0 && build < 14350 {
<del> configuration.HvRuntime.SkipTemplate = true
<del> }
<ide> }
<ide>
<ide> if configuration.HvPartition {
<ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly
<ide> iopipe := &IOPipe{Terminal: procToAdd.Terminal}
<ide> iopipe.Stdin = createStdInCloser(stdin, newProcess)
<ide>
<del> // TEMP: Work around Windows BS/DEL behavior.
<del> iopipe.Stdin = fixStdinBackspaceBehavior(iopipe.Stdin, container.ociSpec.Platform.OSVersion, procToAdd.Terminal)
<del>
<ide> // Convert io.ReadClosers to io.Readers
<ide> if stdout != nil {
<ide> iopipe.Stdout = openReaderFromPipe(stdout)
<ide><path>libcontainerd/container_windows.go
<ide> func (ctr *container) start() error {
<ide>
<ide> iopipe.Stdin = createStdInCloser(stdin, hcsProcess)
<ide>
<del> // TEMP: Work around Windows BS/DEL behavior.
<del> iopipe.Stdin = fixStdinBackspaceBehavior(iopipe.Stdin, ctr.ociSpec.Platform.OSVersion, ctr.ociSpec.Process.Terminal)
<del>
<ide> // Convert io.ReadClosers to io.Readers
<ide> if stdout != nil {
<ide> iopipe.Stdout = openReaderFromPipe(stdout)
<ide><path>libcontainerd/process_windows.go
<ide> func openReaderFromPipe(p io.ReadCloser) io.Reader {
<ide> return r
<ide> }
<ide>
<del>// fixStdinBackspaceBehavior works around a bug in Windows before build 14350
<del>// where it interpreted DEL as VK_DELETE instead of as VK_BACK. This replaces
<del>// DEL with BS to work around this.
<del>func fixStdinBackspaceBehavior(w io.WriteCloser, osversion string, tty bool) io.WriteCloser {
<del> if !tty {
<del> return w
<del> }
<del> if build := buildFromVersion(osversion); build == 0 || build >= 14350 {
<del> return w
<del> }
<del>
<del> return &delToBsWriter{w}
<del>}
<del>
<del>type delToBsWriter struct {
<del> io.WriteCloser
<del>}
<del>
<del>func (w *delToBsWriter) Write(b []byte) (int, error) {
<del> const (
<del> backspace = 0x8
<del> del = 0x7f
<del> )
<del> bc := make([]byte, len(b))
<del> for i, c := range b {
<del> if c == del {
<del> bc[i] = backspace
<del> } else {
<del> bc[i] = c
<del> }
<del> }
<del> return w.WriteCloser.Write(bc)
<del>}
<del>
<ide> type stdInCloser struct {
<ide> io.WriteCloser
<ide> hcsshim.Process
<ide><path>libcontainerd/utils_windows.go
<ide> package libcontainerd
<ide>
<del>import (
<del> "strconv"
<del> "strings"
<del>)
<add>import "strings"
<ide>
<ide> // setupEnvironmentVariables converts a string array of environment variables
<ide> // into a map as required by the HCS. Source array is in format [v1=k1] [v2=k2] etc.
<ide> func (s *ServicingOption) Apply(interface{}) error {
<ide> func (s *FlushOption) Apply(interface{}) error {
<ide> return nil
<ide> }
<del>
<del>// buildFromVersion takes an image version string and returns the Windows build
<del>// number. It returns 0 if the build number is not present.
<del>func buildFromVersion(osver string) int {
<del> v := strings.Split(osver, ".")
<del> if len(v) < 3 {
<del> return 0
<del> }
<del> if build, err := strconv.Atoi(v[2]); err == nil {
<del> return build
<del> }
<del> return 0
<del>}
<ide><path>libcontainerd/windowsoci/oci_windows.go
<ide> type Platform struct {
<ide> OS string `json:"os"`
<ide> // Arch is the architecture
<ide> Arch string `json:"arch"`
<del> // OSVersion is the version of the operating system.
<del> OSVersion string `json:"os.version,omitempty"`
<ide> }
<ide>
<ide> // Mount specifies a mount for a container.
| 6
|
Javascript
|
Javascript
|
make repl test pass in coverage mode
|
61567299e79525e82f4942fb1941e61c633f551f
|
<ide><path>test/parallel/test-repl-tab-complete.js
<ide> const editor = repl.start({
<ide> editorStream.run(['.clear']);
<ide> editorStream.run(['.editor']);
<ide>
<del>editor.completer('co', common.mustCall((error, data) => {
<del> assert.deepStrictEqual(data, [['con'], 'co']);
<add>editor.completer('Uin', common.mustCall((error, data) => {
<add> assert.deepStrictEqual(data, [['Uint'], 'Uin']);
<ide> }));
<ide>
<ide> editorStream.run(['.clear']);
| 1
|
Javascript
|
Javascript
|
add comments to pmrem generator and packer
|
f053a9268ce175aeccdbb67d9fe0dbc4a864597a
|
<ide><path>examples/js/pmrem/PMREMCubeUVPacker.js
<ide> /**
<ide> * @author Prashant Sharma / spidersharma03
<ide> * @author Ben Houston / bhouston, https://clara.io
<add> *
<add> * This class takes the cube lods(corresponding to different roughness values), and creates a single cubeUV
<add> * Texture. The format for a given roughness set of faces is simply::
<add> * +X+Y+Z
<add> * -X-Y-Z
<add> * For every roughness a mip map chain is also saved, which is essential to remove the texture artifacts due to
<add> * minification.
<add> * Right now for every face a PlaneMesh is drawn, which leads to a lot of geometry draw calls, but can be replaced
<add> * later by drawing a single buffer and by sending the appropriate faceIndex via vertex attributes.
<add> * The arrangement of the faces is fixed, as assuming this arrangement, the sampling function has been written.
<ide> */
<ide>
<ide>
<ide><path>examples/js/pmrem/PMREMGenerator.js
<ide> /**
<ide> * @author Prashant Sharma / spidersharma03
<ide> * @author Ben Houston / bhouston, https://clara.io
<add> *
<add> * To avoid cube map seams, I create an extra pixel around each face. This way when the cube map is
<add> * sampled by an application later(with a little care by sampling the centre of the texel), the extra 1 border
<add> * of pixels makes sure that there is no seams artifacts present. This works perfectly for cubeUV format as
<add> * well where the 6 faces can be arranged in any manner whatsoever.
<add> * Code in the beginning of fragment shader's main function does this job for a given resolution.
<add> * Run Scene_PMREM_Test.html in the examples directory to see the sampling from the cube lods generated
<add> * by this class.
<ide> */
<ide>
<ide> THREE.PMREMGenerator = function( sourceTexture ) {
<ide> var size = this.resolution;
<ide> var params = { format: this.sourceTexture.format, magFilter: this.sourceTexture.magFilter, minFilter: this.sourceTexture.minFilter, type: this.sourceTexture.type };
<ide>
<add> // how many LODs fit in the given CubeUV Texture.
<ide> this.numLods = Math.log2( size ) - 2;
<ide> for ( var i = 0; i < this.numLods; i ++ ) {
<ide> var renderTarget = new THREE.WebGLRenderTargetCube( size, size, params );
<ide> THREE.PMREMGenerator.prototype = {
<ide>
<ide> constructor : THREE.PMREMGenerator,
<ide>
<add> /*
<add> * Prashant Sharma / spidersharma03: More thought and work is needed here.
<add> * Right now it's a kind of a hack to use the previously convolved map to convolve the current one.
<add> * I tried to use the original map to convolve all the lods, but for many textures(specially the high frequency)
<add> * even a high number of samples(1024) dosen't lead to satisfactory results.
<add> * By using the previous convolved maps, a lower number of samples are generally sufficient(right now 32, which
<add> * gives okay results unless we see the reflection very carefully, or zoom in too much), however the math
<add> * goes wrong as the distribution function tries to sample a larger area than what it should be. So I simply scaled
<add> * the roughness by 0.9(totally empirical) to try to visually match the original result.
<add> * The condition "if(i <5)" is also an attemt to make the result match the original result.
<add> * This method requires the most amount of thinking I guess. Here is a paper which we could try to implement in future::
<add> * http://http.developer.nvidia.com/GPUGems3/gpugems3_ch20.html
<add> */
<ide> update: function( renderer ) {
<ide>
<ide> this.shader.uniforms[ "envMap" ].value = this.sourceTexture;
<ide> THREE.PMREMGenerator.prototype = {
<ide> for ( var i = 0; i < this.numLods; i ++ ) {
<ide>
<ide> var r = i / ( this.numLods - 1 );
<del> this.shader.uniforms[ "roughness" ].value = r * 0.9;
<add> this.shader.uniforms[ "roughness" ].value = r * 0.9; // see comment above, pragmatic choice
<ide> var size = this.cubeLods[ i ].width;
<ide> this.shader.uniforms[ "mapSize" ].value = size;
<ide> this.renderToCubeMapTarget( renderer, this.cubeLods[ i ] );
| 2
|
Ruby
|
Ruby
|
use same weekday correspondance as date#wday
|
dd7f8ca3cd18086b012715ba88fc2fb9f153c9ac
|
<ide><path>activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
<ide> module DateAndTime
<ide> module Calculations
<ide> DAYS_INTO_WEEK = {
<del> monday: 0,
<del> tuesday: 1,
<del> wednesday: 2,
<del> thursday: 3,
<del> friday: 4,
<del> saturday: 5,
<del> sunday: 6
<add> sunday: 0,
<add> monday: 1,
<add> tuesday: 2,
<add> wednesday: 3,
<add> thursday: 4,
<add> friday: 5,
<add> saturday: 6,
<ide> }
<ide> WEEKEND_DAYS = [ 6, 0 ]
<ide>
<ide> def last_year
<ide> # +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
<ide> def days_to_week_start(start_day = Date.beginning_of_week)
<ide> start_day_number = DAYS_INTO_WEEK[start_day]
<del> current_day_number = wday != 0 ? wday - 1 : 6
<del> (current_day_number - start_day_number) % 7
<add> (wday - start_day_number) % 7
<ide> end
<ide>
<ide> # Returns a new date/time representing the start of this week on the given day.
<ide> def all_year
<ide> # today.next_occurring(:monday) # => Mon, 18 Dec 2017
<ide> # today.next_occurring(:thursday) # => Thu, 21 Dec 2017
<ide> def next_occurring(day_of_week)
<del> current_day_number = wday != 0 ? wday - 1 : 6
<del> from_now = DAYS_INTO_WEEK.fetch(day_of_week) - current_day_number
<add> from_now = DAYS_INTO_WEEK.fetch(day_of_week) - wday
<ide> from_now += 7 unless from_now > 0
<ide> advance(days: from_now)
<ide> end
<ide> def next_occurring(day_of_week)
<ide> # today.prev_occurring(:monday) # => Mon, 11 Dec 2017
<ide> # today.prev_occurring(:thursday) # => Thu, 07 Dec 2017
<ide> def prev_occurring(day_of_week)
<del> current_day_number = wday != 0 ? wday - 1 : 6
<del> ago = current_day_number - DAYS_INTO_WEEK.fetch(day_of_week)
<add> ago = wday - DAYS_INTO_WEEK.fetch(day_of_week)
<ide> ago += 7 unless ago > 0
<ide> advance(days: -ago)
<ide> end
| 1
|
Text
|
Text
|
add angle brackets around implicit links
|
7183d70273d8fad1d33233d5737a076e40bacd8c
|
<ide><path>BUILDING.md
<ide> For use of AVX2,
<ide> * nasm version 2.10 or higher in Windows
<ide>
<ide> Please refer to
<del> https://www.openssl.org/docs/man1.1.1/man3/OPENSSL_ia32cap.html for details.
<add> <https://www.openssl.org/docs/man1.1.1/man3/OPENSSL_ia32cap.html> for details.
<ide>
<ide> If compiling without one of the above, use `configure` with the
<ide> `--openssl-no-asm` flag. Otherwise, `configure` will fail.
<ide> $ make -j4
<ide> If you run into a `No module named 'distutils.spawn'` error when executing
<ide> `./configure`, please try `python3 -m pip install --upgrade setuptools` or
<ide> `sudo apt install python3-distutils -y`.
<del>For more information, see https://github.com/nodejs/node/issues/30189.
<add>For more information, see <https://github.com/nodejs/node/issues/30189>.
<ide>
<ide> The `-j4` option will cause `make` to run 4 simultaneous compilation jobs which
<ide> may reduce build time. For more information, see the
<ide><path>doc/api/deprecations.md
<ide> The undocumented `net._setSimultaneousAccepts()` function was originally
<ide> intended for debugging and performance tuning when using the `child_process`
<ide> and `cluster` modules on Windows. The function is not generally useful and
<ide> is being removed. See discussion here:
<del>https://github.com/nodejs/node/issues/18391
<add><https://github.com/nodejs/node/issues/18391>
<ide>
<ide> <a id="DEP0122"></a>
<ide> ### DEP0122: `tls` `Server.prototype.setOptions()`
<ide><path>doc/api/errors.md
<ide> is set for the `Http2Stream`.
<ide> ### `ERR_INTERNAL_ASSERTION`
<ide>
<ide> There was a bug in Node.js or incorrect usage of Node.js internals.
<del>To fix the error, open an issue at https://github.com/nodejs/node/issues.
<add>To fix the error, open an issue at <https://github.com/nodejs/node/issues>.
<ide>
<ide> <a id="ERR_INCOMPATIBLE_OPTION_PAIR"></a>
<ide> ### `ERR_INCOMPATIBLE_OPTION_PAIR`
<ide><path>doc/api/os.md
<ide> Returns the operating system as a string.
<ide>
<ide> On POSIX systems, the operating system release is determined by calling
<ide> [uname(3)][]. On Windows, `GetVersionExW()` is used. See
<del>https://en.wikipedia.org/wiki/Uname#Examples for more information.
<add><https://en.wikipedia.org/wiki/Uname#Examples> for more information.
<ide>
<ide> ## `os.setPriority([pid, ]priority)`
<ide> <!-- YAML
<ide> added: v0.3.3
<ide> Returns the operating system name as returned by [uname(3)][]. For example, it
<ide> returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
<ide>
<del>See https://en.wikipedia.org/wiki/Uname#Examples for additional information
<add>See <https://en.wikipedia.org/wiki/Uname#Examples> for additional information
<ide> about the output of running [uname(3)][] on various operating systems.
<ide>
<ide> ## `os.uptime()`
<ide> Returns a string identifying the kernel version.
<ide> On POSIX systems, the operating system release is determined by calling
<ide> [uname(3)][]. On Windows, `RtlGetVersion()` is used, and if it is not available,
<ide> `GetVersionExW()` will be used. See
<del>https://en.wikipedia.org/wiki/Uname#Examples for more information.
<add><https://en.wikipedia.org/wiki/Uname#Examples> for more information.
<ide>
<ide> ## OS Constants
<ide>
<ide><path>doc/guides/cve-management-process.md
<ide> The Node.js project acts as a [Common Vulnerabilities and Exposures (CVE)
<ide> Numbering Authority (CNA)](https://cve.mitre.org/cve/cna.html).
<ide> The current scope is for all actively developed versions of software
<del>developed under the Node.js project (ie. https://github.com/nodejs).
<add>developed under the Node.js project (ie. <https://github.com/nodejs>).
<ide> This means that the Node.js team reviews CVE requests and if appropriate
<ide> assigns CVE numbers to vulnerabilities. The scope currently **does not**
<ide> include third party modules.
<ide> as outlined in the section titled `CVE Management process`.
<ide> In addition, when moving a CVE from Available such that there are less
<ide> than two remaining CVEs a new block must be requested as follows:
<ide>
<del>* Use the Mitre request form https://cveform.mitre.org/ with the
<add>* Use the Mitre request form <https://cveform.mitre.org/> with the
<ide> option `Request a Block of IDs` to request a new block.
<ide> * The new block will be sent to the requester through email.
<ide> * Once the new block has been received, the requester will add them
<ide><path>doc/guides/maintaining-openssl.md
<ide> This document describes how to update `deps/openssl/`.
<ide> ## Requirements
<ide> * Linux environment
<ide> * `perl` Only Perl version 5 is tested.
<del>* `nasm` (http://www.nasm.us/) The version of 2.11 or higher is needed.
<add>* `nasm` (<http://www.nasm.us/>) The version of 2.11 or higher is needed.
<ide> * GNU `as` in binutils. The version of 2.26 or higher is needed.
<ide>
<ide> ## 0. Check Requirements
<ide> NASM version 2.11.08
<ide>
<ide> ## 1. Obtain and extract new OpenSSL sources
<ide>
<del>Get a new source from https://www.openssl.org/source/ and extract
<add>Get a new source from <https://www.openssl.org/source/> and extract
<ide> all files into `deps/openssl/openssl`. Then add all files and commit
<ide> them.
<ide> ```sh
<ide><path>doc/guides/offboarding.md
<ide> Emeritus or leaves the project.
<ide> * Some teams may also require a pull request to remove the Collaborator from
<ide> a team listing. For example, if someone is removed from @nodejs/build,
<ide> they should also be removed from the Build WG README.md file in the
<del> https://github.com/nodejs/build repository.
<add> <https://github.com/nodejs/build> repository.
<ide><path>doc/guides/releases.md
<ide> The nodejs.org website will automatically rebuild and include the new version.
<ide> To announce the build on Twitter through the official @nodejs account, email
<ide> [pr@nodejs.org](mailto:pr@nodejs.org) with a message such as:
<ide>
<del>> v5.8.0 of @nodejs is out: https://nodejs.org/en/blog/release/v5.8.0/
<add>> v5.8.0 of @nodejs is out: <https://nodejs.org/en/blog/release/v5.8.0/>
<ide> > …
<ide> > something here about notable changes
<ide>
<ide><path>doc/guides/security-release-process.md
<ide> information described.
<ide> * [ ] Make sure the PRs for the vulnerabilities are closed.
<ide>
<ide> [H1 CVE requests]: https://hackerone.com/nodejs/cve_requests
<del>[docker-node]: https://github.com/nodejs/docker-node/issues)
<del>[nodejs/build]: https://github.com/nodejs/build/issues)
<add>[docker-node]: https://github.com/nodejs/docker-node/issues
<add>[nodejs/build]: https://github.com/nodejs/build/issues
<ide> [email]: https://groups.google.com/forum/#!forum/nodejs-sec
<ide><path>doc/guides/using-symbols.md
<ide> Symbol-keyed properties of an object are not included in the output of
<ide> default.
<ide>
<ide> Learn more about symbols at
<del>https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol.
<add><https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol>.
<ide>
<ide> ## `Symbol(string)`
<ide>
<ide><path>doc/guides/writing-and-running-benchmarks.md
<ide> from [nghttp2.org][] or built from source.
<ide> ### Benchmark Analysis Requirements
<ide>
<ide> To analyze the results, `R` should be installed. Use one of the available
<del>package managers or download it from https://www.r-project.org/.
<add>package managers or download it from <https://www.r-project.org/>.
<ide>
<ide> The R packages `ggplot2` and `plyr` are also used and can be installed using
<ide> the R REPL.
<ide> install.packages("plyr")
<ide> In the event that a message is reported stating that a CRAN mirror must be
<ide> selected first, specify a mirror by adding in the repo parameter.
<ide>
<del>If we used the "http://cran.us.r-project.org" mirror, it could look something
<add>If we used the "<http://cran.us.r-project.org>" mirror, it could look something
<ide> like this:
<ide>
<ide> ```R
<ide><path>doc/guides/writing-tests.md
<ide> To generate a test coverage report, see the
<ide> [Test Coverage section of the Building guide][].
<ide>
<ide> Nightly coverage reports for the Node.js master branch are available at
<del>https://coverage.nodejs.org/.
<add><https://coverage.nodejs.org/>.
<ide>
<ide> [ASCII]: http://man7.org/linux/man-pages/man7/ascii.7.html
<ide> [Google Test]: https://github.com/google/googletest
<ide><path>glossary.md
<del>You may also need to check https://chromium.googlesource.com/chromiumos/docs/+/master/glossary.md.
<add>You may also need to check <https://chromium.googlesource.com/chromiumos/docs/+/master/glossary.md>.
<ide>
<ide> * LGTM: "Looks good to me", commonly used to approve a code review.
<ide> * PTAL: Please take a look.
<ide><path>onboarding.md
<ide> onboarding session.
<ide> * It is not automatically run. You need to start it manually.
<ide> * Log in on CI is integrated with GitHub. Try to log in now!
<ide> * You will be using `node-test-pull-request` most of the time. Go there now!
<del> * Consider bookmarking it: https://ci.nodejs.org/job/node-test-pull-request/
<add> * Consider bookmarking it: <https://ci.nodejs.org/job/node-test-pull-request/>
<ide> * To get to the form to start a job, click on `Build with Parameters`. (If you
<ide> don't see it, that probably means you are not logged in!) Click it now!
<ide> * To start CI testing from this screen, you need to fill in two elements on
<ide> needs to be pointed out separately during the onboarding.
<ide> ## Exercise: Make a PR adding yourself to the README
<ide>
<ide> * Example:
<del> https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0
<add> <https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0>
<ide> * For raw commit message: `git log ce986de829457c39257cd205067602e765768fb0
<ide> -1`
<ide> * Collaborators are in alphabetical order by GitHub username.
<ide><path>tools/icu/README.md
<ide> Note:
<ide> > The files in this directory were written for the Node.js v0.12 effort.
<ide> > The original intent was to merge the tools such as `icutrim.py` and `iculslocs.cc`
<ide> > back into ICU. ICU has gained its own “data slicer” tool.
<del>> There is an issue open, https://github.com/nodejs/node/issues/25136
<add>> There is an issue open, <https://github.com/nodejs/node/issues/25136>
<ide> > for replacing `icutrim.py` with the [ICU data slicer][].
<ide>
<ide> ## See Also
| 15
|
Ruby
|
Ruby
|
fix problem with accessing constant proxy subclass
|
48c0abb4748c30adeecc17058f0220e87bcbe84a
|
<ide><path>activesupport/lib/active_support/deprecation/proxy_wrappers.rb
<ide> def warn(callstack, called, args)
<ide> # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead.
<ide> # (Backtrace information…)
<ide> # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
<del> class DeprecatedConstantProxy < DeprecationProxy
<add> class DeprecatedConstantProxy < Module
<add> def self.new(*args, &block)
<add> object = args.first
<add>
<add> return object unless object
<add> super
<add> end
<add>
<ide> def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance, message: "#{old_const} is deprecated! Use #{new_const} instead.")
<ide> require "active_support/inflector/methods"
<ide>
<ide> def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.ins
<ide> @message = message
<ide> end
<ide>
<add> instance_methods.each { |m| undef_method m unless /^__|^object_id$/.match?(m) }
<add>
<add> # Don't give a deprecation warning on inspect since test/unit and error
<add> # logs rely on it for diagnostics.
<add> def inspect
<add> target.inspect
<add> end
<add>
<ide> # Returns the class of the new constant.
<ide> #
<ide> # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
<ide> def target
<ide> ActiveSupport::Inflector.constantize(@new_const.to_s)
<ide> end
<ide>
<del> def warn(callstack, called, args)
<del> @deprecator.warn(@message, callstack)
<add> def const_missing(name)
<add> @deprecator.warn(@message, caller_locations)
<add> target.const_get(name)
<add> end
<add>
<add> def method_missing(called, *args, &block)
<add> @deprecator.warn(@message, caller_locations)
<add> target.__send__(called, *args, &block)
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/deprecation_test.rb
<ide> module B
<ide> C = 1
<ide> end
<ide> A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::A", "Deprecatee::B::C")
<add>
<add> module New
<add> class Descendant; end
<add> end
<add> Old = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::Old", "Deprecatee::New")
<ide> end
<ide>
<ide> class DeprecateeWithAccessor
<ide> def test_deprecated_constant_proxy
<ide> assert_not_deprecated { assert_equal Deprecatee::B::C.class, Deprecatee::A.class }
<ide> end
<ide>
<add> def test_deprecated_constant_descendant
<add> assert_not_deprecated { Deprecatee::New::Descendant }
<add>
<add> assert_deprecated("Deprecatee::Old") do
<add> assert_equal Deprecatee::Old::Descendant, Deprecatee::New::Descendant
<add> end
<add>
<add> assert_raises(NameError) do
<add> assert_deprecated("Deprecatee::Old") { Deprecatee::Old::NON_EXISTENCE }
<add> end
<add> end
<add>
<ide> def test_deprecated_constant_accessor
<ide> assert_not_deprecated { DeprecateeWithAccessor::B::C }
<ide> assert_deprecated("DeprecateeWithAccessor::A") { assert_equal DeprecateeWithAccessor::B::C, DeprecateeWithAccessor::A }
| 2
|
Text
|
Text
|
fix zh_cn links
|
8808b1cd0f11d9b33c977e9c6bad74c0baf158ba
|
<ide><path>threejs/lessons/zh_cn/threejs-fundamentals.md
<ide> import * as THREE from './resources/threejs/r122/build/three.module.js';
<ide> </script>
<ide> ```
<ide>
<del>拿到canvas后我们需要创建一个[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer)。渲染器负责将你提供的所有数据渲染绘制到canvas上。之前还有其他渲染器,比如[CSS渲染器(`CSSRenderer`)](CSSRenderer)、[Canvas渲染器(`CanvasRenderer`)](CanvasRenderer)。将来也可能会有[WebGL2渲染器(`WebGL2Renderer`)](WebGL2Renderer)或[WebGPU渲染器(`WebGPURenderer`)](WebGPURenderer)。目前的话是[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer),它通过WebGL将三维空间渲染到canvas上。
<add>拿到canvas后我们需要创建一个[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer)。渲染器负责将你提供的所有数据渲染绘制到canvas上。之前还有其他渲染器,比如CSS渲染器(`CSSRenderer`)、Canvas渲染器(`CanvasRenderer`)。将来也可能会有WebGL2渲染器(`WebGL2Renderer`)或WebGPU渲染器(`WebGPURenderer`)。目前的话是[WebGL渲染器(`WebGLRenderer`)](WebGLRenderer),它通过WebGL将三维空间渲染到canvas上。
<ide>
<ide> 注意这里有一些细节。如果你没有给three.js传canvas,three.js会自己创建一个 ,但是你必须手动把它添加到文档中。在哪里添加可能会不一样这取决你怎么使用, 我发现给three.js传一个canvas会更灵活一些。我可以将canvas放到任何地方, 代码都会找到它,假如我有一段代码是将canvas插入到文档中,那么当需求变化时, 我很可能必须去修改这段代码。
<ide>
| 1
|
Text
|
Text
|
add arch build instructions
|
27423fcc157884c95ddd643515b3915c3a46027f
|
<ide><path>docs/build-instructions/linux.md
<ide> Ubuntu LTS 12.04 64-bit is the recommended platform.
<ide> * C++ toolchain
<ide> * on Ubuntu/Debian: `sudo apt-get install build-essential`
<ide> * on Fedora: `sudo yum --assumeyes install make gcc gcc-c++ glibc-devel`
<add> * on Arch: `sudo pacman -S base-devel`
<ide> * [node.js](http://nodejs.org/download/) v0.10.x
<ide> * [Ubuntu/Debian/Mint instructions](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager#ubuntu-mint-elementary-os)
<ide> * [Fedora instructions](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager#fedora)
<add> * on Arch: `sudo pacman -S nodejs`
<ide> * [npm](http://www.npmjs.org/) v1.4.x
<ide> * `npm` comes with node.js so no explicit installation is needed here.
<ide> * You can check `npm` 1.4 or above is installed by running `npm -v`.
<ide> * libgnome-keyring-dev
<ide> * on Ubuntu/Debian: `sudo apt-get install libgnome-keyring-dev`
<ide> * on Fedora: `sudo yum --assumeyes install libgnome-keyring-devel`
<add> * on Arch: `sudo pacman -S libgnome-keyring`
<ide> * on other distributions refer to the manual on how to install packages
<ide> * `npm config set python /usr/bin/python2 -g` to ensure that gyp uses Python 2
<ide> * This command may require `sudo` depending on how you have
<ide> [configured npm](https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager#ubuntu-mint-elementary-os).
<ide> * Git
<ide> * on Ubuntu/Debian: `sudo apt-get install git`
<ide> * on Fedora: `sudo yum install git-core`
<add> * on Arch: `sudo pacman -S git`
<ide>
<ide> ## Instructions
<ide>
| 1
|
Ruby
|
Ruby
|
remove obsolete documentation [ci skip]
|
065be937f27c25bc7d23e0dd35ad4aa84818b167
|
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb
<ide> module Util
<ide> # A utility method for escaping HTML tag characters.
<ide> # This method is also aliased as <tt>h</tt>.
<ide> #
<del> # In your ERB templates, use this method to escape any unsafe content. For example:
<del> # <%= h @person.name %>
<del> #
<ide> # puts html_escape('is a > 0 & a < 10?')
<ide> # # => is a > 0 & a < 10?
<ide> def html_escape(s)
| 1
|
Text
|
Text
|
use lesson-builder v1.7.0
|
b98e8ff2d9dbfe261f7320749a825410a306545e
|
<ide><path>threejs/lessons/fr/threejs-primitives.md
<ide> ou votre [BufferGeometry](threejs-custom-buffergeometry.html).
<ide>
<ide> Voyons maintenant l'article traitant sur [comment fonctionne un graphe de scène three.js et comment l'utiliser](threejs-scenegraph.html).
<ide>
<del><link rel="stylesheet" href="../resources/threejs-primitives.css">
<del><script type="module" src="../resources/threejs-primitives.js"></script>
<add><link rel="stylesheet" href="resources/threejs-primitives.css">
<add><script type="module" src="resources/threejs-primitives.js"></script>
<ide><path>threejs/lessons/ja/threejs-primitives.md
<ide> const material = new THREE.PointsMaterial({
<ide>
<ide> 次は、[threeのシーングラフの動き方と使い方](threejs-scenegraph.html)を説明します。
<ide>
<del><link rel="stylesheet" href="../resources/threejs-primitives.css">
<del><script type="module" src="../resources/threejs-primitives.js"></script>
<add><link rel="stylesheet" href="resources/threejs-primitives.css">
<add><script type="module" src="resources/threejs-primitives.js"></script>
<ide>
<ide><path>threejs/lessons/kr/threejs-align-html-elements-to-3d.md
<ide> function updateLabels() {
<ide>
<ide> 다음 글에서는 더 나아가 [지구본 위의 나라를 선택하고 강조](threejs-indexed-textures.html)해보겠습니다.
<ide>
<del><link rel="stylesheet" href="../resources/threejs-align-html-elements-to-3d.css">
<del><script type="module" src="../resources/threejs-align-html-elements-to-3d.js"></script>
<add><link rel="stylesheet" href="resources/threejs-align-html-elements-to-3d.css">
<add><script type="module" src="resources/threejs-align-html-elements-to-3d.js"></script>
<ide><path>threejs/lessons/kr/threejs-cameras.md
<ide> function render(time) {
<ide> 대해 먼저 살펴보겠습니다.
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-cameras.js"></script>
<ide>\ No newline at end of file
<add><script type="module" src="resources/threejs-cameras.js"></script>
<ide>\ No newline at end of file
<ide><path>threejs/lessons/kr/threejs-custom-buffergeometry.md
<ide> positionAttribute.needsUpdate = true;
<ide> 데 도움이 되었으면 좋겠네요.
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-custom-buffergeometry.js"></script>
<add><script type="module" src="resources/threejs-custom-buffergeometry.js"></script>
<ide><path>threejs/lessons/kr/threejs-fog.md
<ide> class FogGUIHelper {
<ide> </div>
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-fog.js"></script>
<add><script type="module" src="resources/threejs-fog.js"></script>
<ide><path>threejs/lessons/kr/threejs-lights.md
<ide> gui.add(light, 'power', 0, 2000);
<ide> 다음 장에서는 [카메라 조작법](threejs-cameras.html)에 대해 알아보겠습니다.
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-lights.js"></script>
<add><script type="module" src="resources/threejs-lights.js"></script>
<ide><path>threejs/lessons/kr/threejs-materials.md
<ide> Three.js는 기본적으로 처음 한 번만 재질의 설정을 적용합니
<ide> </div>
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-materials.js"></script>
<ide>\ No newline at end of file
<add><script type="module" src="resources/threejs-materials.js"></script>
<ide>\ No newline at end of file
<ide><path>threejs/lessons/kr/threejs-optimize-lots-of-objects.md
<ide> geometry를 합치는 건 꽤 자주 사용하는 최적화 기법입니다. 예
<ide> 하지만 요소를 하나의 mesh로 합쳐버리면 별도의 요소였던 특정 부분을 조작하기가 어렵습니다. 상황에 따라 좋은 방법도 다 다를 테죠. [다음 글](threejs-optimize-lots-of-objects-animated.html)에서는 그 방법 중 하나를 살펴보겠습니다.
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-lots-of-objects.js"></script>
<ide>\ No newline at end of file
<add><script type="module" src="resources/threejs-lots-of-objects.js"></script>
<ide>\ No newline at end of file
<ide><path>threejs/lessons/kr/threejs-post-processing-3dlut.md
<ide> updateGUI();
<ide>
<ide> 이 글에서는 쉐이더가 어떻게 작동하는지에 대해서는 아예 설명하지 않았습니다. 나중에 GLSL에 대해 더 다룰 기회가 있었으면 좋겠네요. 쉐이더의 작동 방식을 알고 싶다면 [후처리에 관한 글](threejs-post-processing.html)에 있는 링크 또는 [이 유튜브 영상](https://www.youtube.com/watch?v=rfQ8rKGTVlg#t=24m30s)을 참고하기 바랍니다.
<ide>
<del><script type="module" src="../resources/threejs-post-processing-3dlut.js"></script>
<add><script type="module" src="resources/threejs-post-processing-3dlut.js"></script>
<ide><path>threejs/lessons/kr/threejs-primitives.md
<ide> const material = new THREE.PointsMaterial({
<ide> 다음 장에서는 [씬 그래프와 그 사용법](threejs-scenegraph.html)에 대해
<ide> 알아보겠습니다.
<ide>
<del><link rel="stylesheet" href="../resources/threejs-primitives.css">
<del><script type="module" src="../resources/threejs-primitives.js"></script>
<add><link rel="stylesheet" href="resources/threejs-primitives.css">
<add><script type="module" src="resources/threejs-primitives.js"></script>
<ide>
<ide><path>threejs/lessons/kr/threejs-textures.md
<ide> metalness
<ide> roughness
<ide> -->
<ide>
<del><link rel="stylesheet" href="../resources/threejs-textures.css">
<del><script type="module" src="../resources/threejs-textures.js"></script>
<ide>\ No newline at end of file
<add><link rel="stylesheet" href="resources/threejs-textures.css">
<add><script type="module" src="resources/threejs-textures.js"></script>
<ide>\ No newline at end of file
<ide><path>threejs/lessons/kr/threejs-voxel-geometry.md
<ide> function updateCellGeometry(x, y, z) {
<ide> 이 글이 Three.js로 마인크래프트 같은 그래픽을 구현할 때 좋은 시작점을 마련하고, geometry를 최적화하는 데 도움이 되었으면 합니다.
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-voxel-geometry.js"></script>
<add><script type="module" src="resources/threejs-voxel-geometry.js"></script>
<ide><path>threejs/lessons/ru/threejs-cameras.md
<ide> function render(time) {
<ide> А пока давайте перейдем к [теням](threejs-shadows.html).
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-cameras.js"></script>
<add><script type="module" src="resources/threejs-cameras.js"></script>
<ide><path>threejs/lessons/ru/threejs-custom-buffergeometry.md
<ide> positionAttribute.needsUpdate = true;
<ide> действительно зависит от ваших потребностей.
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-custom-buffergeometry.js"></script>
<add><script type="module" src="resources/threejs-custom-buffergeometry.js"></script>
<ide>
<ide><path>threejs/lessons/ru/threejs-fog.md
<ide> class FogGUIHelper {
<ide> </div>
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-fog.js"></script>
<add><script type="module" src="resources/threejs-fog.js"></script>
<ide><path>threejs/lessons/ru/threejs-lights.md
<ide> gui.add(light, 'power', 0, 2000);
<ide> Далее давайте перейдем к [работе с камерами](threejs-cameras.html).
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-lights.js"></script>
<add><script type="module" src="resources/threejs-lights.js"></script>
<ide><path>threejs/lessons/ru/threejs-material-table.md
<ide> Mesh. Вот таблица, показывающая, какие функции
<ide>
<ide> <div>
<ide> <div id="material-table" class="threejs_center"></div>
<del><script type="module" src="../resources/threejs-material-table.js"></script>
<del><link rel="stylesheet" href="../resources/threejs-material-table.css">
<add><script type="module" src="resources/threejs-material-table.js"></script>
<add><link rel="stylesheet" href="resources/threejs-material-table.css">
<ide> </div>
<ide><path>threejs/lessons/ru/threejs-materials.md
<ide> flat shaded
<ide> </div>
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-materials.js"></script>
<add><script type="module" src="resources/threejs-materials.js"></script>
<ide>
<ide><path>threejs/lessons/ru/threejs-optimize-lots-of-objects.md
<ide> scene.add(mesh);
<ide> [другой статье](threejs-optimize-lots-of-objects-animated.html).
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="../resources/threejs-lots-of-objects.js"></script>
<add><script type="module" src="resources/threejs-lots-of-objects.js"></script>
<ide><path>threejs/lessons/ru/threejs-primitives.md
<ide> function addLineGeometry(x, y, geometry) {
<ide>
<ide> Далее давайте рассмотрим [как работает граф сцены и как его использовать](threejs-scenegraph.html).
<ide>
<del><script type="module" src="../resources/threejs-primitives.js"></script>
<del><link rel="stylesheet" href="../resources/threejs-primitives.css">
<add><script type="module" src="resources/threejs-primitives.js"></script>
<add><link rel="stylesheet" href="resources/threejs-primitives.css">
<ide><path>threejs/lessons/ru/threejs-textures.md
<ide> metalness
<ide> roughness
<ide> -->
<ide>
<del><script type="module" src="../resources/threejs-textures.js"></script>
<del><link rel="stylesheet" href="../resources/threejs-textures.css">
<add><script type="module" src="resources/threejs-textures.js"></script>
<add><link rel="stylesheet" href="resources/threejs-textures.css">
| 22
|
Javascript
|
Javascript
|
fix man pages linking regex
|
66e6affb428efdfc8de1db4bd9d6dfd7984ebb44
|
<ide><path>tools/doc/html.js
<ide> const BSD_ONLY_SYSCALLS = new Set(['lchmod']);
<ide> // '<a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>'
<ide> function linkManPages(text) {
<ide> return text.replace(
<del> /\b([a-z.]+)\((\d)([a-z]?)\)/gm,
<del> (match, name, number, optionalCharacter) => {
<add> /(^|\s)([a-z.]+)\((\d)([a-z]?)\)/gm,
<add> (match, beginning, name, number, optionalCharacter) => {
<ide> // name consists of lowercase letters, number is a single digit
<ide> const displayAs = `${name}(${number}${optionalCharacter})`;
<ide> if (BSD_ONLY_SYSCALLS.has(name)) {
<del> return ` <a href="https://www.freebsd.org/cgi/man.cgi?query=${name}` +
<add> return `${beginning}<a href="https://www.freebsd.org/cgi/man.cgi?query=${name}` +
<ide> `&sektion=${number}">${displayAs}</a>`;
<ide> } else {
<del> return ` <a href="http://man7.org/linux/man-pages/man${number}` +
<add> return `${beginning}<a href="http://man7.org/linux/man-pages/man${number}` +
<ide> `/${name}.${number}${optionalCharacter}.html">${displayAs}</a>`;
<ide> }
<ide> });
| 1
|
Java
|
Java
|
update oss specs
|
e040a198e23c20d583041b520e2b01b7ce30ff07
|
<ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeImageEditorSpec.java
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
<add> * directory of this source tree.
<add> *
<add> * <p>Generated by an internal genrule from Flow types.
<add> *
<add> * @generated
<add> * @nolint
<add> */
<add>
<add>package com.facebook.fbreact.specs;
<add>
<add>import com.facebook.react.bridge.Callback;
<add>import com.facebook.react.bridge.ReactApplicationContext;
<add>import com.facebook.react.bridge.ReactContextBaseJavaModule;
<add>import com.facebook.react.bridge.ReactMethod;
<add>import com.facebook.react.bridge.ReactModuleWithSpec;
<add>import com.facebook.react.bridge.ReadableMap;
<add>import com.facebook.react.turbomodule.core.interfaces.TurboModule;
<add>
<add>public abstract class NativeImageEditorSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule {
<add> public NativeImageEditorSpec(ReactApplicationContext reactContext) {
<add> super(reactContext);
<add> }
<add>
<add> @ReactMethod
<add> public abstract void cropImage(String uri, ReadableMap cropData, Callback successCallback,
<add> Callback errorCallback);
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/fbreact/specs/NativeImageStoreSpec.java
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
<add> * directory of this source tree.
<add> *
<add> * <p>Generated by an internal genrule from Flow types.
<add> *
<add> * @generated
<add> * @nolint
<add> */
<add>
<add>package com.facebook.fbreact.specs;
<add>
<add>import com.facebook.react.bridge.Callback;
<add>import com.facebook.react.bridge.ReactApplicationContext;
<add>import com.facebook.react.bridge.ReactContextBaseJavaModule;
<add>import com.facebook.react.bridge.ReactMethod;
<add>import com.facebook.react.bridge.ReactModuleWithSpec;
<add>import com.facebook.react.turbomodule.core.interfaces.TurboModule;
<add>
<add>public abstract class NativeImageStoreSpec extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule {
<add> public NativeImageStoreSpec(ReactApplicationContext reactContext) {
<add> super(reactContext);
<add> }
<add>
<add> @ReactMethod
<add> public abstract void getBase64ForTag(String uri, Callback successCallback,
<add> Callback errorCallback);
<add>
<add> @ReactMethod
<add> public abstract void removeImageForTag(String uri);
<add>
<add> @ReactMethod
<add> public abstract void addImageFromBase64(String base64ImageData, Callback successCallback,
<add> Callback errorCallback);
<add>
<add> @ReactMethod
<add> public abstract void hasImageForTag(String uri, Callback callback);
<add>}
| 2
|
Go
|
Go
|
remove nil check for slices
|
ace53bbe65d1384893027d046a5d4eae83bd60af
|
<ide><path>api/types/filters/parse.go
<ide> func (filters Args) MatchKVList(field string, sources map[string]string) bool {
<ide> return true
<ide> }
<ide>
<del> if sources == nil || len(sources) == 0 {
<add> if len(sources) == 0 {
<ide> return false
<ide> }
<ide>
<ide><path>pkg/archive/archive_linux.go
<ide> func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os
<ide> if err != nil {
<ide> return err
<ide> }
<del> if opaque != nil && len(opaque) == 1 && opaque[0] == 'y' {
<add> if len(opaque) == 1 && opaque[0] == 'y' {
<ide> // create a header for the whiteout file
<ide> // it should inherit some properties from the parent, but be a regular file
<ide> *hdr = tar.Header{
<ide><path>pkg/archive/changes_linux.go
<ide> func overlayDeletedFile(root, path string, fi os.FileInfo) (string, error) {
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> if opaque != nil && len(opaque) == 1 && opaque[0] == 'y' {
<add> if len(opaque) == 1 && opaque[0] == 'y' {
<ide> return path, nil
<ide> }
<ide> }
<ide><path>pkg/discovery/backends.go
<ide> func ParseAdvertise(advertise string) (string, error) {
<ide> return "", fmt.Errorf("unable to get advertise IP address from interface (%s) : %v", advertise, err)
<ide> }
<ide>
<del> if addrs == nil || len(addrs) == 0 {
<add> if len(addrs) == 0 {
<ide> return "", fmt.Errorf("no available advertise IP address in interface (%s)", advertise)
<ide> }
<ide>
| 4
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.