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
Java
Java
improve the performance of iteration
564c6f7f86467e1f831d107d571ec34501104b18
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.java <ide> else if (args[0] instanceof Map) { <ide> resolveConstructorArguments(args, 2, hasClosureArgument ? args.length - 1 : args.length); <ide> this.currentBeanDefinition = new GroovyBeanDefinitionWrapper(beanName, (Class<?>) args[1], constructorArgs); <ide> Map<?, ?> namedArgs = (Map<?, ?>) args[0]; <del> for (Object key : namedArgs.keySet()) { <del> String propName = (String) key; <del> setProperty(propName, namedArgs.get(propName)); <add> for (Map.Entry<?, ?> entity : namedArgs.entrySet()) { <add> String propName = (String) entity.getKey(); <add> setProperty(propName, entity.getValue()); <ide> } <ide> } <ide> // factory method syntax
1
Go
Go
extend test coverage of secrets
0da7bd0314a61919428fe036660b822b0bf22d35
<ide><path>integration-cli/docker_cli_service_create_test.go <ide> package main <ide> import ( <ide> "encoding/json" <ide> "fmt" <add> "path/filepath" <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <ide> func (s *DockerSwarmSuite) TestServiceCreateWithSecretSourceTargetPaths(c *check <ide> d := s.AddDaemon(c, true, true) <ide> <ide> testPaths := map[string]string{ <del> "app": "/etc/secret", <del> "test_secret": "test_secret", <add> "app": "/etc/secret", <add> "test_secret": "test_secret", <add> "relative_secret": "relative/secret", <add> "escapes_in_container": "../secret", <ide> } <add> <add> var secretFlags []string <add> <ide> for testName, testTarget := range testPaths { <del> serviceName := "svc-" + testName <ide> id := d.CreateSecret(c, swarm.SecretSpec{ <ide> Annotations: swarm.Annotations{ <ide> Name: testName, <ide> }, <del> Data: []byte("TESTINGDATA"), <add> Data: []byte("TESTINGDATA " + testName + " " + testTarget), <ide> }) <ide> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id)) <ide> <del> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", fmt.Sprintf("source=%s,target=%s", testName, testTarget), "busybox", "top") <del> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> secretFlags = append(secretFlags, "--secret", fmt.Sprintf("source=%s,target=%s", testName, testTarget)) <add> } <add> <add> serviceName := "svc" <add> serviceCmd := []string{"service", "create", "--name", serviceName} <add> serviceCmd = append(serviceCmd, secretFlags...) <add> serviceCmd = append(serviceCmd, "busybox", "top") <add> out, err := d.Cmd(serviceCmd...) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> <add> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) <add> c.Assert(err, checker.IsNil) <add> <add> var refs []swarm.SecretReference <add> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) <add> c.Assert(refs, checker.HasLen, len(testPaths)) <add> <add> var tasks []swarm.Task <add> waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { <add> tasks = d.GetServiceTasks(c, serviceName) <add> return len(tasks) > 0, nil <add> }, checker.Equals, true) <ide> <del> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) <add> task := tasks[0] <add> waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { <add> if task.NodeID == "" || task.Status.ContainerStatus.ContainerID == "" { <add> task = d.GetTask(c, task.ID) <add> } <add> return task.NodeID != "" && task.Status.ContainerStatus.ContainerID != "", nil <add> }, checker.Equals, true) <add> <add> for testName, testTarget := range testPaths { <add> path := testTarget <add> if !filepath.IsAbs(path) { <add> path = filepath.Join("/run/secrets", path) <add> } <add> out, err := d.Cmd("exec", task.Status.ContainerStatus.ContainerID, "cat", path) <ide> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Equals, "TESTINGDATA "+testName+" "+testTarget) <add> } <ide> <del> var refs []swarm.SecretReference <del> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) <del> c.Assert(refs, checker.HasLen, 1) <add> out, err = d.Cmd("service", "rm", serviceName) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add>} <ide> <del> c.Assert(refs[0].SecretName, checker.Equals, testName) <del> c.Assert(refs[0].File, checker.Not(checker.IsNil)) <del> c.Assert(refs[0].File.Name, checker.Equals, testTarget) <add>func (s *DockerSwarmSuite) TestServiceCreateWithSecretReferencedTwice(c *check.C) { <add> d := s.AddDaemon(c, true, true) <ide> <del> out, err = d.Cmd("service", "rm", serviceName) <del> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> id := d.CreateSecret(c, swarm.SecretSpec{ <add> Annotations: swarm.Annotations{ <add> Name: "mysecret", <add> }, <add> Data: []byte("TESTINGDATA"), <add> }) <add> c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id)) <add> <add> serviceName := "svc" <add> out, err := d.Cmd("service", "create", "--name", serviceName, "--secret", "source=mysecret,target=target1", "--secret", "source=mysecret,target=target2", "busybox", "top") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> <add> out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) <add> c.Assert(err, checker.IsNil) <add> <add> var refs []swarm.SecretReference <add> c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) <add> c.Assert(refs, checker.HasLen, 2) <add> <add> var tasks []swarm.Task <add> waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { <add> tasks = d.GetServiceTasks(c, serviceName) <add> return len(tasks) > 0, nil <add> }, checker.Equals, true) <add> <add> task := tasks[0] <add> waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { <add> if task.NodeID == "" || task.Status.ContainerStatus.ContainerID == "" { <add> task = d.GetTask(c, task.ID) <add> } <add> return task.NodeID != "" && task.Status.ContainerStatus.ContainerID != "", nil <add> }, checker.Equals, true) <ide> <del> d.DeleteSecret(c, testName) <add> for _, target := range []string{"target1", "target2"} { <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> path := filepath.Join("/run/secrets", target) <add> out, err := d.Cmd("exec", task.Status.ContainerStatus.ContainerID, "cat", path) <add> c.Assert(err, checker.IsNil) <add> c.Assert(out, checker.Equals, "TESTINGDATA") <ide> } <add> <add> out, err = d.Cmd("service", "rm", serviceName) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestServiceCreateMountTmpfs(c *check.C) {
1
Go
Go
normalize comment formatting
e2addf46bfe863edd9d0fee8c05fc4000a052106
<ide><path>pkg/mount/mountinfo_freebsd.go <ide> import ( <ide> "unsafe" <ide> ) <ide> <del>//parseMountTable returns information about mounted filesystems <add>// parseMountTable returns information about mounted filesystems <ide> func parseMountTable(filter FilterFunc) ([]*Info, error) { <ide> var rawEntries *C.struct_statfs <ide>
1
Javascript
Javascript
add email settings
2de21434576719997bc0f712b7ee03791bbc01d8
<ide><path>api-server/common/models/User-Identity.js <ide> import { wrapHandledError } from '../../server/utils/create-handled-error.js'; <ide> // const log = debug('fcc:models:userIdent'); <ide> <ide> export default function(UserIdent) { <del> <ide> UserIdent.on('dataSourceAttached', () => { <ide> UserIdent.findOne$ = observeMethod(UserIdent, 'findOne'); <ide> }); <ide> export default function(UserIdent) { <ide> // get the social provider data and the external id from auth0 <ide> profile.id = profile.id || profile.openid; <ide> const auth0IdString = '' + profile.id; <del> const [ provider, socialExtId ] = auth0IdString.split('|'); <add> const [provider, socialExtId] = auth0IdString.split('|'); <ide> const query = { <ide> where: { <ide> provider: provider, <ide> export default function(UserIdent) { <ide> include: 'user' <ide> }; <ide> // get the email from the auth0 (its expected from social providers) <del> const email = (profile && profile.emails && profile.emails[0]) ? <del> profile.emails[0].value : ''; <add> const email = <add> profile && profile.emails && profile.emails[0] <add> ? profile.emails[0].value <add> : ''; <ide> if (!isEmail('' + email)) { <ide> throw wrapHandledError( <ide> new Error('invalid or empty email recieved from auth0'), <ide> export default function(UserIdent) { <ide> } <ide> <ide> if (provider === 'email') { <del> <ide> return User.findOne$({ where: { email } }) <ide> .flatMap(user => { <del> return user ? <del> Observable.of(user) : <del> User.create$({ email }).toPromise(); <add> return user <add> ? Observable.of(user) <add> : User.create$({ email }).toPromise(); <ide> }) <ide> .flatMap(user => { <ide> if (!user) { <ide> export default function(UserIdent) { <ide> } <ide> ); <ide> } <del> const createToken = observeQuery( <del> AccessToken, <del> 'create', <del> { <del> userId: user.id, <del> created: new Date(), <del> ttl: user.constructor.settings.ttl <del> } <del> ); <del> const updateUser = user.update$({ <del> emailVerified: true, <del> emailAuthLinkTTL: null, <del> emailVerifyTTL: null <add> const createToken = observeQuery(AccessToken, 'create', { <add> userId: user.id, <add> created: new Date(), <add> ttl: user.constructor.settings.ttl <ide> }); <add> const updateUserPromise = new Promise((resolve, reject) => <add> user.updateAttributes( <add> { <add> emailVerified: true, <add> emailAuthLinkTTL: null, <add> emailVerifyTTL: null <add> }, <add> err => { <add> if (err) { <add> return reject(err); <add> } <add> return resolve(); <add> } <add> ) <add> ); <ide> return Observable.combineLatest( <ide> Observable.of(user), <ide> createToken, <del> updateUser, <del> (user, token) => ({user, token}) <add> Observable.fromPromise(updateUserPromise), <add> (user, token) => ({ user, token }) <ide> ); <ide> }) <del> .subscribe( <del> ({ user, token }) => cb(null, user, null, token), <del> cb <del> ); <del> <add> .subscribe(({ user, token }) => cb(null, user, null, token), cb); <ide> } else { <del> <ide> return UserIdent.findOne$(query) <ide> .flatMap(identity => { <del> return identity ? <del> Observable.of(identity.user()) : <del> User.findOne$({ where: { email } }) <del> .flatMap(user => { <del> return user ? <del> Observable.of(user) : <del> User.create$({ email }).toPromise(); <add> return identity <add> ? Observable.of(identity.user()) <add> : User.findOne$({ where: { email } }).flatMap(user => { <add> return user <add> ? Observable.of(user) <add> : User.create$({ email }).toPromise(); <ide> }); <ide> }) <ide> .flatMap(user => { <del> <del> const createToken = observeQuery( <del> AccessToken, <del> 'create', <del> { <del> userId: user.id, <del> created: new Date(), <del> ttl: user.constructor.settings.ttl <del> } <del> ); <add> const createToken = observeQuery(AccessToken, 'create', { <add> userId: user.id, <add> created: new Date(), <add> ttl: user.constructor.settings.ttl <add> }); <ide> const updateUser = user.update$({ <ide> email: email, <ide> emailVerified: true, <ide> export default function(UserIdent) { <ide> (user, token) => ({ user, token }) <ide> ); <ide> }) <del> .subscribe( <del> ({ user, token }) => cb(null, user, null, token), <del> cb <del> ); <del> <add> .subscribe(({ user, token }) => cb(null, user, null, token), cb); <ide> } <ide> }; <ide> } <ide><path>api-server/common/models/user.js <ide> module.exports = function(User) { <ide> this.update$({ emailAuthLinkTTL }) <ide> ); <ide> }) <del> .map(() => <del> dedent` <del> Check your email and click the link we sent you to confirm you email. <del> ` <add> .map(() => 'Check your email and click the link we sent you to confirm' + <add> ' your new email address.' <ide> ); <ide> } <ide> <ide> module.exports = function(User) { <ide> } <ide> }) <ide> .flatMap(()=>{ <add> const updatePromise = new Promise((resolve, reject) => <add> this.updateAttributes(updateConfig, err => { <add> if (err) { <add> return reject(err); <add> } <add> return resolve(); <add> })); <ide> return Observable.forkJoin( <del> this.update$(updateConfig), <add> Observable.fromPromise(updatePromise), <ide> this.requestAuthEmail(false, newEmail), <ide> (_, message) => message <del> ) <del> .doOnNext(() => this.manualReload()); <add> ); <ide> }); <ide> <ide> } else { <ide><path>api-server/server/middlewares/email-not-verified-notice.js <ide> import dedent from 'dedent'; <ide> <ide> const ALLOWED_METHODS = ['GET']; <ide> const EXCLUDED_PATHS = [ <del> '/api/flyers/findOne', <ide> '/signout', <ide> '/accept-privacy-terms', <ide> '/update-email', <ide> '/confirm-email', <del> '/passwordless-change', <del> '/external/services/user' <del>]; <add> '/passwordless-change' <add>].reduce((list, item) => [...list, item, `/internal${item}`], []); <ide> <ide> export default function emailNotVerifiedNotice() { <ide> return function(req, res, next) { <ide><path>client/src/client-only-routes/ShowSettings.js <ide> import { submitNewAbout, updateUserFlag } from '../redux/settings'; <ide> import Layout from '../components/Layout'; <ide> import Spacer from '../components/helpers/Spacer'; <ide> import Loader from '../components/helpers/Loader'; <del>import { FullWidthRow } from '../components/helpers'; <add>import FullWidthRow from '../components/helpers/FullWidthRow'; <ide> import About from '../components/settings/About'; <ide> import Privacy from '../components/settings/Privacy'; <add>import Email from '../components/settings/Email'; <ide> <ide> const propTypes = { <ide> about: PropTypes.string, <add> email: PropTypes.string, <add> isEmailVerified: PropTypes.bool, <ide> location: PropTypes.string, <ide> name: PropTypes.string, <ide> picture: PropTypes.string, <ide> points: PropTypes.number, <add> sendQuincyEmail: PropTypes.bool, <ide> showLoading: PropTypes.bool, <ide> submitNewAbout: PropTypes.func.isRequired, <ide> theme: PropTypes.string, <ide> toggleNightMode: PropTypes.func.isRequired, <add> updateQuincyEmail: PropTypes.func.isRequired, <ide> username: PropTypes.string <ide> }; <ide> <ide> const mapStateToProps = createSelector( <ide> userSelector, <ide> ( <ide> showLoading, <del> { username = '', about, picture, points, name, location, theme } <add> { <add> username = '', <add> about, <add> email, <add> sendQuincyEmail, <add> isEmailVerified, <add> picture, <add> points, <add> name, <add> location, <add> theme <add> } <ide> ) => ({ <add> email, <add> sendQuincyEmail, <add> isEmailVerified, <ide> showLoading, <ide> username, <ide> about, <ide> const mapStateToProps = createSelector( <ide> <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators( <del> { submitNewAbout, toggleNightMode: theme => updateUserFlag({theme}) }, <add> { <add> submitNewAbout, <add> toggleNightMode: theme => updateUserFlag({ theme }), <add> updateQuincyEmail: sendQuincyEmail => updateUserFlag({ sendQuincyEmail }) <add> }, <ide> dispatch <ide> ); <ide> <ide> function ShowSettings(props) { <ide> const { <add> email, <add> isEmailVerified, <add> sendQuincyEmail, <ide> showLoading, <ide> username, <ide> about, <ide> function ShowSettings(props) { <ide> location, <ide> name, <ide> submitNewAbout, <del> toggleNightMode <add> toggleNightMode, <add> updateQuincyEmail <ide> } = props; <ide> <ide> if (showLoading) { <ide> function ShowSettings(props) { <ide> <Spacer /> <ide> <Privacy /> <ide> <Spacer /> <del> {/* <EmailSettings /> <add> <Email <add> email={email} <add> isEmailVerified={isEmailVerified} <add> sendQuincyEmail={sendQuincyEmail} <add> updateQuincyEmail={updateQuincyEmail} <add> /> <ide> <Spacer /> <del> <InternetSettings /> <add> {/* <InternetSettings /> <ide> <Spacer /> <ide> <PortfolioSettings /> <ide> <Spacer /> <ide><path>client/src/components/settings/Email.js <add>import React, { Component } from 'react'; <add>import PropTypes from 'prop-types'; <add>import { bindActionCreators } from 'redux'; <add>import { connect } from 'react-redux'; <add>import { Link } from 'gatsby'; <add>import { <add> HelpBlock, <add> Alert, <add> FormGroup, <add> ControlLabel, <add> FormControl, <add> Button <add>} from '@freecodecamp/react-bootstrap'; <add>import isEmail from 'validator/lib/isEmail'; <add> <add>import { updateMyEmail } from '../../redux/settings'; <add>import { maybeEmailRE } from '../../utils'; <add> <add>import FullWidthRow from '../helpers/FullWidthRow'; <add>import Spacer from '../helpers/Spacer'; <add>import SectionHeader from './SectionHeader'; <add>import BlockSaveButton from '../helpers/form/BlockSaveButton'; <add>import ToggleSetting from './ToggleSetting'; <add> <add>const mapStateToProps = () => ({}); <add>const mapDispatchToProps = dispatch => <add> bindActionCreators({ updateMyEmail }, dispatch); <add> <add>const propTypes = { <add> email: PropTypes.string, <add> isEmailVerified: PropTypes.bool, <add> sendQuincyEmail: PropTypes.bool, <add> updateMyEmail: PropTypes.func.isRequired, <add> updateQuincyEmail: PropTypes.func.isRequired <add>}; <add> <add>export function UpdateEmailButton() { <add> return ( <add> <Link style={{ textDecoration: 'none' }} to='/update-email'> <add> <Button block={true} bsSize='lg' bsStyle='primary'> <add> Edit <add> </Button> <add> </Link> <add> ); <add>} <add> <add>class EmailSettings extends Component { <add> constructor(props) { <add> super(props); <add> <add> this.state = { <add> emailForm: { <add> currentEmail: props.email, <add> newEmail: '', <add> confirmNewEmail: '', <add> isPristine: true <add> } <add> }; <add> } <add> <add> handleSubmit = e => { <add> e.preventDefault(); <add> const { <add> emailForm: { newEmail } <add> } = this.state; <add> const { updateMyEmail } = this.props; <add> return updateMyEmail(newEmail); <add> }; <add> <add> createHandleEmailFormChange = key => e => { <add> e.preventDefault(); <add> const userInput = e.target.value.slice(); <add> return this.setState(state => ({ <add> emailForm: { <add> ...state.emailForm, <add> [key]: userInput, <add> isPristine: userInput === state.emailForm.currentEmail <add> } <add> })); <add> }; <add> <add> getValidationForNewEmail = () => { <add> const { <add> emailForm: { newEmail, currentEmail } <add> } = this.state; <add> <add> if (!maybeEmailRE.test(newEmail)) { <add> return { <add> state: null, <add> message: '' <add> }; <add> } <add> if (newEmail === currentEmail) { <add> return { <add> state: 'error', <add> message: 'This email is the same as your current email' <add> }; <add> } <add> if (isEmail(newEmail)) { <add> return { state: 'success', message: '' }; <add> } else { <add> return { <add> state: 'warning', <add> message: <add> 'We could not validate your email correctly, ' + <add> 'please ensure it is correct' <add> }; <add> } <add> }; <add> <add> getValidationForConfirmEmail = () => { <add> const { <add> emailForm: { confirmNewEmail, newEmail } <add> } = this.state; <add> <add> if (!maybeEmailRE.test(newEmail)) { <add> return { <add> state: null, <add> message: '' <add> }; <add> } <add> const isMatch = newEmail === confirmNewEmail; <add> if (maybeEmailRE.test(confirmNewEmail)) { <add> return { <add> state: isMatch ? 'success' : 'error', <add> message: isMatch ? '' : 'Both new email addresses must be the same' <add> }; <add> } else { <add> return { <add> state: null, <add> message: '' <add> }; <add> } <add> }; <add> <add> render() { <add> const { <add> emailForm: { newEmail, confirmNewEmail, currentEmail, isPristine } <add> } = this.state; <add> const { isEmailVerified, updateQuincyEmail, sendQuincyEmail } = this.props; <add> <add> const { <add> state: newEmailValidation, <add> message: newEmailValidationMessage <add> } = this.getValidationForNewEmail(); <add> <add> const { <add> state: confirmEmailValidation, <add> message: confirmEmailValidationMessage <add> } = this.getValidationForConfirmEmail(); <add> if (!currentEmail) { <add> return ( <add> <div> <add> <FullWidthRow> <add> <p className='large-p text-center'> <add> You do not have an email associated with this account. <add> </p> <add> </FullWidthRow> <add> <FullWidthRow> <add> <UpdateEmailButton /> <add> </FullWidthRow> <add> </div> <add> ); <add> } <add> return ( <add> <div className='email-settings'> <add> <SectionHeader>Email Settings</SectionHeader> <add> {isEmailVerified ? null : ( <add> <FullWidthRow> <add> <HelpBlock> <add> <Alert bsStyle='info' className='text-center'> <add> Your email has not been verified. <add> <br /> <add> Please check your email, or{' '} <add> <Link to='/update-email'> <add> request a new verification email here <add> </Link> <add> . <add> </Alert> <add> </HelpBlock> <add> </FullWidthRow> <add> )} <add> <FullWidthRow> <add> <form id='form-update-email' onSubmit={this.handleSubmit}> <add> <FormGroup controlId='current-email'> <add> <ControlLabel>Current Email</ControlLabel> <add> <FormControl.Static>{currentEmail}</FormControl.Static> <add> </FormGroup> <add> <FormGroup <add> controlId='new-email' <add> validationState={newEmailValidation} <add> > <add> <ControlLabel>New Email</ControlLabel> <add> <FormControl <add> onChange={this.createHandleEmailFormChange('newEmail')} <add> type='email' <add> value={newEmail} <add> /> <add> {newEmailValidationMessage ? ( <add> <HelpBlock>{newEmailValidationMessage}</HelpBlock> <add> ) : null} <add> </FormGroup> <add> <FormGroup <add> controlId='confirm-email' <add> validationState={confirmEmailValidation} <add> > <add> <ControlLabel>Confirm New Email</ControlLabel> <add> <FormControl <add> onChange={this.createHandleEmailFormChange('confirmNewEmail')} <add> type='email' <add> value={confirmNewEmail} <add> /> <add> {confirmEmailValidationMessage ? ( <add> <HelpBlock>{confirmEmailValidationMessage}</HelpBlock> <add> ) : null} <add> </FormGroup> <add> <BlockSaveButton <add> disabled={ <add> newEmailValidation !== 'success' || <add> confirmEmailValidation !== 'success' || <add> isPristine <add> } <add> /> <add> </form> <add> </FullWidthRow> <add> <Spacer /> <add> <FullWidthRow> <add> <form id='form-quincy-email' onSubmit={this.handleSubmit}> <add> <ToggleSetting <add> action="Send me Quincy's weekly email" <add> flag={sendQuincyEmail} <add> flagName='sendQuincyEmail' <add> offLabel='No thanks' <add> onLabel='Yes please' <add> toggleFlag={() => updateQuincyEmail(!sendQuincyEmail)} <add> /> <add> </form> <add> </FullWidthRow> <add> </div> <add> ); <add> } <add>} <add> <add>EmailSettings.displayName = 'EmailSettings'; <add>EmailSettings.propTypes = propTypes; <add> <add>export default connect( <add> mapStateToProps, <add> mapDispatchToProps <add>)(EmailSettings); <ide><path>client/src/pages/update-email.js <ide> import { <ide> Button <ide> } from '@freecodecamp/react-bootstrap'; <ide> import Helmet from 'react-helmet'; <add>import isEmail from 'validator/lib/isEmail'; <add>import { isString } from 'lodash'; <ide> <ide> import Layout from '../components/Layout'; <ide> import { Spacer } from '../components/helpers'; <ide> import './update-email.css'; <del>import { userSelector, updateMyEmail } from '../redux'; <del>import { isString } from 'lodash'; <del>import isEmail from 'validator/lib/isEmail'; <add>import { userSelector } from '../redux'; <add>import { updateMyEmail } from '../redux/settings'; <add>import { maybeEmailRE } from '../utils'; <ide> <ide> const propTypes = { <ide> isNewEmail: PropTypes.bool, <ide> const mapStateToProps = createSelector( <ide> const mapDispatchToProps = dispatch => <ide> bindActionCreators({ updateMyEmail }, dispatch); <ide> <del>const maybeEmailRE = /[\w.+]*?@\w*?\.\w+?/; <del> <ide> class UpdateEmail extends Component { <ide> constructor(props) { <ide> super(props); <ide> class UpdateEmail extends Component { <ide> emailValue: '' <ide> }; <ide> <del> // this.createSubmitHandler = this.createSubmitHandler.bind(this); <ide> this.onChange = this.onChange.bind(this); <ide> } <ide> <del> createSubmitHandler(fn) { <del> return e => { <del> e.preventDefault(); <del> return fn(this.state.emailValue); <del> }; <del> } <add> handleSubmit = e => { <add> e.preventDefault(); <add> const { emailValue } = this.state; <add> const { updateMyEmail } = this.props; <add> return updateMyEmail(emailValue); <add> }; <ide> <ide> onChange(e) { <ide> const change = e.target.value; <ide> class UpdateEmail extends Component { <ide> } <ide> <ide> render() { <del> const { isNewEmail, updateMyEmail } = this.props; <add> const { isNewEmail } = this.props; <ide> return ( <ide> <Layout> <ide> <Helmet> <ide> class UpdateEmail extends Component { <ide> <Row> <ide> <Col sm={6} smOffset={3}> <ide> <Row> <del> <Form <del> horizontal={true} <del> onSubmit={this.createSubmitHandler(updateMyEmail)} <del> > <add> <Form horizontal={true} onSubmit={this.handleSubmit}> <ide> <FormGroup <ide> controlId='emailInput' <ide> validationState={this.getEmailValidationState()} <ide><path>client/src/redux/index.js <ide> import { createAcceptTermsSaga } from './accept-terms-saga'; <ide> import { createAppMountSaga } from './app-mount-saga'; <ide> import { createReportUserSaga } from './report-user-saga'; <ide> import { createShowCertSaga } from './show-cert-saga'; <del>import { createUpdateMyEmailSaga } from './update-email-saga'; <ide> import { createNightModeSaga } from './night-mode-saga'; <ide> <ide> import { types as settingsTypes } from './settings'; <ide> const types = createTypes( <ide> ...createAsyncTypes('fetchUser'), <ide> ...createAsyncTypes('acceptTerms'), <ide> ...createAsyncTypes('showCert'), <del> ...createAsyncTypes('updateMyEmail'), <ide> ...createAsyncTypes('reportUser') <ide> ], <ide> ns <ide> export const sagas = [ <ide> ...createAcceptTermsSaga(types), <ide> ...createAppMountSaga(types), <ide> ...createFetchUserSaga(types), <del> ...createUpdateMyEmailSaga(types), <ide> ...createShowCertSaga(types), <ide> ...createReportUserSaga(types), <ide> ...createNightModeSaga({ ...types, ...settingsTypes }) <ide> export const showCert = createAction(types.showCert); <ide> export const showCertComplete = createAction(types.showCertComplete); <ide> export const showCertError = createAction(types.showCertError); <ide> <del>export const updateMyEmail = createAction(types.updateMyEmail); <del>export const updateMyEmailComplete = createAction(types.updateMyEmailComplete); <del>export const updateMyEmailError = createAction(types.updateMyEmailError); <del> <ide> export const isSignedInSelector = state => !!Object.keys(state[ns].user).length; <ide> <ide> export const signInLoadingSelector = state => <ide> export const userSelector = state => { <ide> return state[ns].user[username] || {}; <ide> }; <ide> <add>function spreadThePayloadOnUser(state, payload) { <add> return { <add> ...state, <add> user: { <add> ...state.user, <add> [state.appUsername]: { <add> ...state.user[state.appUsername], <add> ...payload <add> } <add> } <add> }; <add>} <add> <ide> export const reducer = handleActions( <ide> { <ide> [types.fetchUser]: state => ({ <ide> export const reducer = handleActions( <ide> } <ide> : state, <ide> [settingsTypes.submitNewAboutComplete]: (state, { payload }) => <del> payload <del> ? { <del> ...state, <del> user: { <del> ...state.user, <del> [state.appUsername]: { <del> ...state.user[state.appUsername], <del> ...payload <del> } <del> } <del> } <del> : state, <add> payload ? spreadThePayloadOnUser(state, payload) : state, <add> [settingsTypes.updateMyEmailComplete]: (state, { payload }) => <add> payload ? spreadThePayloadOnUser(state, payload) : state, <ide> [settingsTypes.updateUserFlagComplete]: (state, { payload }) => <del> payload <del> ? { <del> ...state, <del> user: { <del> ...state.user, <del> [state.appUsername]: { <del> ...state.user[state.appUsername], <del> ...payload <del> } <del> } <del> } <del> : state <add> payload ? spreadThePayloadOnUser(state, payload) : state <ide> }, <ide> initialState <ide> ); <ide><path>client/src/redux/settings/index.js <ide> import { createAction, handleActions } from 'redux-actions'; <ide> <ide> import { createTypes, createAsyncTypes } from '../../utils/createTypes'; <ide> import { createSettingsSagas } from './settings-sagas'; <add>import { createUpdateMyEmailSaga } from './update-email-saga'; <ide> <ide> const ns = 'settings'; <ide> <ide> export const types = createTypes( <ide> ...createAsyncTypes('validateUsername'), <ide> ...createAsyncTypes('submitNewAbout'), <ide> ...createAsyncTypes('submitNewUsername'), <add> ...createAsyncTypes('updateMyEmail'), <ide> ...createAsyncTypes('updateUserFlag'), <ide> ...createAsyncTypes('submitProfileUI') <ide> ], <ide> ns <ide> ); <add> <add>export const sagas = [ <add> ...createSettingsSagas(types), <add> ...createUpdateMyEmailSaga(types) <add>]; <add> <ide> const checkForSuccessPayload = ({ type, payload }) => <ide> type === 'success' ? payload : null; <ide> <del>export const sagas = [...createSettingsSagas(types)]; <del> <ide> export const submitNewAbout = createAction(types.submitNewAbout); <ide> export const submitNewAboutComplete = createAction( <ide> types.submitNewAboutComplete, <ide> export const submitProfileUIComplete = createAction( <ide> ); <ide> export const submitProfileUIError = createAction(types.submitProfileUIError); <ide> <add>export const updateMyEmail = createAction(types.updateMyEmail); <add>export const updateMyEmailComplete = createAction(types.updateMyEmailComplete); <add>export const updateMyEmailError = createAction(types.updateMyEmailError); <add> <ide> export const updateUserFlag = createAction(types.updateUserFlag); <ide> export const updateUserFlagComplete = createAction( <ide> types.updateUserFlagComplete, <ide><path>client/src/redux/settings/update-email-saga.js <add>import { call, put, takeEvery } from 'redux-saga/effects'; <add>import isEmail from 'validator/lib/isEmail'; <add> <add>import { updateMyEmailComplete, updateMyEmailError } from './'; <add>import { createFlashMessage } from '../../components/Flash/redux'; <add> <add>import { putUserUpdateEmail } from '../../utils/ajax'; <add>import reallyWeirdErrorMessage from '../../utils/reallyWeirdErrorMessage'; <add> <add>function* updateMyEmailSaga({ payload: email = '' }) { <add> console.log('saga', email); <add> if (!email || !isEmail(email)) { <add> yield put(createFlashMessage(reallyWeirdErrorMessage)); <add> return; <add> } <add> try { <add> const { data: response } = yield call(putUserUpdateEmail, email); <add> yield put( <add> updateMyEmailComplete({ <add> ...response, <add> payload: { email, isEmailVerified: false } <add> }) <add> ); <add> yield put(createFlashMessage(response)); <add> } catch (e) { <add> yield put(updateMyEmailError(e)); <add> } <add>} <add> <add>export function createUpdateMyEmailSaga(types) { <add> return [takeEvery(types.updateMyEmail, updateMyEmailSaga)]; <add>} <ide><path>client/src/redux/update-email-saga.js <del>import { call, put, takeEvery } from 'redux-saga/effects'; <del> <del>import { updateMyEmailComplete, updateMyEmailError } from './'; <del>import { createFlashMessage } from '../components/Flash/redux'; <del> <del>import { putUserUpdateEmail } from '../utils/ajax'; <del> <del>function* updateMyEmailSaga({ payload: newEmail }) { <del> try { <del> const { data: response } = yield call(putUserUpdateEmail, newEmail); <del> <del> yield put(updateMyEmailComplete()); <del> yield put(createFlashMessage(response)); <del> } catch (e) { <del> yield put(updateMyEmailError(e)); <del> } <del>} <del> <del>export function createUpdateMyEmailSaga(types) { <del> return [takeEvery(types.updateMyEmail, updateMyEmailSaga)]; <del>} <ide><path>client/src/utils/index.js <add>// This regex is not for validation, it is purely to see <add>// if we are looking at something like an email before we try to validate <add>export const maybeEmailRE = /.*@.*\.\w\w/;
11
Go
Go
add refcount for mountpoint
df0d317a64e4a74433359e826bc1d606e050a5ed
<ide><path>container/container.go <ide> func (container *Container) AddMountPointWithVolume(destination string, vol volu <ide> func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error { <ide> var errors []string <ide> for _, volumeMount := range container.MountPoints { <del> // Check if the mountpoint has an ID, this is currently the best way to tell if it's actually mounted <del> // TODO(cpuguyh83): there should be a better way to handle this <del> if volumeMount.Volume != nil && volumeMount.ID != "" { <del> if err := volumeMount.Volume.Unmount(volumeMount.ID); err != nil { <del> errors = append(errors, err.Error()) <del> continue <del> } <del> volumeMount.ID = "" <add> if volumeMount.Volume == nil { <add> continue <add> } <ide> <del> attributes := map[string]string{ <del> "driver": volumeMount.Volume.DriverName(), <del> "container": container.ID, <del> } <del> volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes) <add> if err := volumeMount.Cleanup(); err != nil { <add> errors = append(errors, err.Error()) <add> continue <add> } <add> <add> attributes := map[string]string{ <add> "driver": volumeMount.Volume.DriverName(), <add> "container": container.ID, <ide> } <add> volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes) <ide> } <ide> if len(errors) > 0 { <ide> return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; ")) <ide><path>integration-cli/docker_cli_external_volume_driver_unix_test.go <ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnmountOnMountFail(c <ide> out, _ = s.d.Cmd("run", "-w", "/foo", "-v", "testumount:/foo", "busybox", "true") <ide> c.Assert(s.ec.unmounts, checker.Equals, 0, check.Commentf(out)) <ide> } <add> <add>func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnmountOnCp(c *check.C) { <add> s.d.StartWithBusybox(c) <add> s.d.Cmd("volume", "create", "-d", "test-external-volume-driver", "--name=test") <add> <add> out, _ := s.d.Cmd("run", "-d", "--name=test", "-v", "test:/foo", "busybox", "/bin/sh", "-c", "touch /test && top") <add> c.Assert(s.ec.mounts, checker.Equals, 1, check.Commentf(out)) <add> <add> out, _ = s.d.Cmd("cp", "test:/test", "/tmp/test") <add> c.Assert(s.ec.mounts, checker.Equals, 2, check.Commentf(out)) <add> c.Assert(s.ec.unmounts, checker.Equals, 1, check.Commentf(out)) <add> <add> out, _ = s.d.Cmd("kill", "test") <add> c.Assert(s.ec.unmounts, checker.Equals, 2, check.Commentf(out)) <add>} <ide><path>volume/volume.go <ide> type MountPoint struct { <ide> <ide> // Sepc is a copy of the API request that created this mount. <ide> Spec mounttypes.Mount <add> <add> // Track usage of this mountpoint <add> // Specicially needed for containers which are running and calls to `docker cp` <add> // because both these actions require mounting the volumes. <add> active int <add>} <add> <add>// Cleanup frees resources used by the mountpoint <add>func (m *MountPoint) Cleanup() error { <add> if m.Volume == nil || m.ID == "" { <add> return nil <add> } <add> <add> if err := m.Volume.Unmount(m.ID); err != nil { <add> return errors.Wrapf(err, "error unmounting volume %s", m.Volume.Name()) <add> } <add> <add> m.active-- <add> if m.active == 0 { <add> m.ID = "" <add> } <add> return nil <ide> } <ide> <ide> // Setup sets up a mount point by either mounting the volume if it is <ide> func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (path string <ide> if err != nil { <ide> return "", errors.Wrapf(err, "error while mounting volume '%s'", m.Source) <ide> } <add> <ide> m.ID = id <add> m.active++ <ide> return path, nil <ide> } <add> <ide> if len(m.Source) == 0 { <ide> return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined") <ide> } <add> <ide> // system.MkdirAll() produces an error if m.Source exists and is a file (not a directory), <ide> if m.Type == mounttypes.TypeBind { <ide> // idtools.MkdirAllNewAs() produces an error if m.Source exists and is a file (not a directory)
3
Javascript
Javascript
remove obsolete workaround for firefox bug
7df29521d8c1c494f615c49d6c2e1e267e3a6be5
<ide><path>src/ng/location.js <ide> function $LocationProvider() { <ide> // update location manually <ide> if ($location.absUrl() !== $browser.url()) { <ide> $rootScope.$apply(); <del> // hack to work around FF6 bug 684208 when scenario runner clicks on links <del> $window.angular['ff-684208-preventDefault'] = true; <ide> } <ide> } <ide> } <ide><path>src/ngMock/browserTrigger.js <ide> <ide> if (!evnt) return; <ide> <del> var originalPreventDefault = evnt.preventDefault, <del> appWindow = element.ownerDocument.defaultView, <del> fakeProcessDefault = true, <del> finalProcessDefault, <del> angular = appWindow.angular || {}; <del> <del> // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 <del> angular['ff-684208-preventDefault'] = false; <del> evnt.preventDefault = function() { <del> fakeProcessDefault = false; <del> return originalPreventDefault.apply(evnt, arguments); <del> }; <del> <ide> if (!eventData.bubbles || supportsEventBubblingInDetachedTree() || isAttachedToDocument(element)) { <del> element.dispatchEvent(evnt); <add> return element.dispatchEvent(evnt); <ide> } else { <ide> triggerForPath(element, evnt); <ide> } <del> <del> finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault); <del> <del> delete angular['ff-684208-preventDefault']; <del> <del> return finalProcessDefault; <ide> }; <ide> <ide> function supportsTouchEvents() {
2
Python
Python
ignore localhost for linkcheck
06cc3ca91d40f63d3d77a8517e84d1de5479460d
<ide><path>docs/conf.py <ide> 'celery.utils.encoding', <ide> r'celery.utils.static.*', <ide> ], <add> linkcheck_ignore=[ <add> r'^http://localhost' <add> ] <ide> )) <ide> <ide> settings = {}
1
Java
Java
expose convenience method in mvc java config
826057bcdea8bfe5984c7c4df2b3faff35dcae52
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; <ide> import org.springframework.web.HttpRequestHandler; <ide> import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.bind.WebDataBinder; <ide> import org.springframework.web.bind.annotation.ExceptionHandler; <ide> import org.springframework.web.bind.annotation.ResponseStatus; <ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <ide> protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer c <ide> */ <ide> @Bean <ide> public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <del> ConfigurableWebBindingInitializer webBindingInitializer = new ConfigurableWebBindingInitializer(); <del> webBindingInitializer.setConversionService(mvcConversionService()); <del> webBindingInitializer.setValidator(mvcValidator()); <del> webBindingInitializer.setMessageCodesResolver(getMessageCodesResolver()); <del> <ide> List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<HandlerMethodArgumentResolver>(); <ide> addArgumentResolvers(argumentResolvers); <ide> <ide> public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <ide> RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); <ide> adapter.setContentNegotiationManager(mvcContentNegotiationManager()); <ide> adapter.setMessageConverters(getMessageConverters()); <del> adapter.setWebBindingInitializer(webBindingInitializer); <add> adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer()); <ide> adapter.setCustomArgumentResolvers(argumentResolvers); <ide> adapter.setCustomReturnValueHandlers(returnValueHandlers); <ide> <ide> public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { <ide> } <ide> <ide> /** <del> * Returns a {@link FormattingConversionService} for use with annotated <add> * Return the {@link ConfigurableWebBindingInitializer} to use for <add> * initializing all {@link WebDataBinder} instances. <add> */ <add> protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() { <add> ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer(); <add> initializer.setConversionService(mvcConversionService()); <add> initializer.setValidator(mvcValidator()); <add> initializer.setMessageCodesResolver(getMessageCodesResolver()); <add> return initializer; <add> } <add> <add> /** <add> * Return a {@link FormattingConversionService} for use with annotated <ide> * controller methods and the {@code spring:eval} JSP tag. <ide> * Also see {@link #addFormatters} as an alternative to overriding this method. <ide> */ <ide> public FormattingConversionService mvcConversionService() { <ide> } <ide> <ide> /** <del> * Returns a global {@link Validator} instance for example for validating <add> * Return a global {@link Validator} instance for example for validating <ide> * {@code @ModelAttribute} and {@code @RequestBody} method arguments. <ide> * Delegates to {@link #getValidator()} first and if that returns {@code null} <ide> * checks the classpath for the presence of a JSR-303 implementations
1
PHP
PHP
use cache instead of tmp
0d4549003aa94c09147d2904fd58f7118a9a0c9a
<ide><path>tests/TestCase/Cache/Engine/FileEngineTest.php <ide> public function testRemoveWindowsSlashesFromCache() <ide> 'engine' => 'File', <ide> 'isWindows' => true, <ide> 'prefix' => null, <del> 'path' => TMP <add> 'path' => CACHE <ide> ]); <ide> <ide> $expected = [
1
Javascript
Javascript
add serialization to dllmodule and entrydependency
2124b3f6844140a2f8a2c9a89650fceaa0bb6265
<ide><path>lib/DllModule.js <ide> const { RawSource } = require("webpack-sources"); <ide> const Module = require("./Module"); <ide> const RuntimeGlobals = require("./RuntimeGlobals"); <add>const makeSerializable = require("./util/makeSerializable"); <ide> <ide> /** @typedef {import("webpack-sources").Source} Source */ <ide> /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ <ide> class DllModule extends Module { <ide> hash.update(this.name || ""); <ide> super.updateHash(hash, chunkGraph); <ide> } <add> <add> serialize(context) { <add> super.serialize(context); <add> } <add> <add> deserialize(context) { <add> super.deserialize(context); <add> } <ide> } <ide> <add>makeSerializable(DllModule, "webpack/lib/DllModule"); <add> <ide> module.exports = DllModule; <ide><path>lib/dependencies/EntryDependency.js <ide> <ide> "use strict"; <ide> <add>const makeSerializable = require("../util/makeSerializable"); <ide> const ModuleDependency = require("./ModuleDependency"); <ide> <ide> class EntryDependency extends ModuleDependency { <ide> class EntryDependency extends ModuleDependency { <ide> get type() { <ide> return "entry"; <ide> } <add> <add> serialize(context) { <add> super.serialize(context); <add> } <add> <add> deserialize(context) { <add> super.deserialize(context); <add> } <ide> } <ide> <add>makeSerializable(EntryDependency, "webpack/lib/dependencies/EntryDependency"); <add> <ide> module.exports = EntryDependency; <ide><path>lib/util/internalSerializables.js <ide> module.exports = { <ide> require("../dependencies/DelegatedSourceDependency"), <ide> "dependencies/DllEntryDependency": () => <ide> require("../dependencies/DllEntryDependency"), <add> "dependencies/EntryDependency": () => <add> require("../dependencies/EntryDependency"), <ide> "dependencies/ExportsInfoDependency": () => <ide> require("../dependencies/ExportsInfoDependency"), <ide> "dependencies/HarmonyAcceptDependency": () => <ide> module.exports = { <ide> require("../optimize/ConcatenatedModule"), <ide> DelegatedModule: () => require("../DelegatedModule"), <ide> DependenciesBlock: () => require("../DependenciesBlock"), <add> DllModule: () => require("../DllModule"), <ide> ExternalModule: () => require("../ExternalModule"), <ide> Module: () => require("../Module"), <ide> ModuleBuildError: () => require("../ModuleBuildError"),
3
Ruby
Ruby
use utils.popen_read instead of backticks
11defcf847666adac44f0ff53a7f8ead9a7ac5f1
<ide><path>Library/Homebrew/formula_versions.rb <ide> def rev_list(branch="HEAD") <ide> end <ide> <ide> def file_contents_at_revision(rev) <del> repository.cd { `git cat-file blob #{rev}:#{entry_name}` } <add> repository.cd { Utils.popen_read("git", "cat-file", "blob", "#{rev}:#{entry_name}") } <ide> end <ide> <ide> def version_at_revision(rev)
1
Go
Go
handle plugin list not implemented
e7e11bdd44878d28c642d72761aa41eb9ffce3d1
<ide><path>client/errors.go <ide> func wrapResponseError(err error, resp serverResponse, object, id string) error <ide> return nil <ide> case resp.statusCode == http.StatusNotFound: <ide> return objectNotFoundError{object: object, id: id} <add> case resp.statusCode == http.StatusNotImplemented: <add> return notImplementedError{message: err.Error()} <ide> default: <ide> return err <ide> } <ide> func IsErrPluginPermissionDenied(err error) bool { <ide> return ok <ide> } <ide> <add>type notImplementedError struct { <add> message string <add>} <add> <add>func (e notImplementedError) Error() string { <add> return e.message <add>} <add> <add>func (e notImplementedError) NotImplemented() bool { <add> return true <add>} <add> <add>// IsNotImplementedError returns true if the error is a NotImplemented error. <add>// This is returned by the API when a requested feature has not been <add>// implemented. <add>func IsNotImplementedError(err error) bool { <add> te, ok := err.(notImplementedError) <add> return ok && te.NotImplemented() <add>} <add> <ide> // NewVersionError returns an error if the APIVersion required <ide> // if less than the current supported version <ide> func (cli *Client) NewVersionError(APIrequired, feature string) error { <ide><path>client/plugin_list.go <ide> func (cli *Client) PluginList(ctx context.Context, filter filters.Args) (types.P <ide> } <ide> resp, err := cli.get(ctx, "/plugins", query, nil) <ide> if err != nil { <del> return plugins, err <add> return plugins, wrapResponseError(err, resp, "plugin", "") <ide> } <ide> <ide> err = json.NewDecoder(resp.body).Decode(&plugins)
2
Java
Java
fix failing test
fe77c3d5fe3b498ecba7f3e1dce31f0aec43d8d6
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/DefaultMvcResult.java <ide> public void setAsyncResultLatch(CountDownLatch asyncResultLatch) { <ide> } <ide> <ide> public Object getAsyncResult() { <del> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); <del> if (asyncManager.isConcurrentHandlingStarted()) { <del> if (!awaitAsyncResult()) { <add> HttpServletRequest request = this.mockRequest; <add> if (request.isAsyncStarted()) { <add> <add> long timeout = request.getAsyncContext().getTimeout(); <add> if (!awaitAsyncResult(timeout)) { <ide> throw new IllegalStateException( <ide> "Gave up waiting on async result from [" + this.handler + "] to complete"); <ide> } <add> <add> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); <ide> if (asyncManager.hasConcurrentResult()) { <ide> return asyncManager.getConcurrentResult(); <ide> } <ide> } <del> <ide> return null; <ide> } <ide> <del> private boolean awaitAsyncResult() { <del> if (this.asyncResultLatch == null) { <del> return true; <del> } <del> long timeout = ((HttpServletRequest) this.mockRequest).getAsyncContext().getTimeout(); <del> try { <del> return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); <del> } <del> catch (InterruptedException e) { <del> return false; <add> private boolean awaitAsyncResult(long timeout) { <add> if (this.asyncResultLatch != null) { <add> try { <add> return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); <add> } <add> catch (InterruptedException e) { <add> return false; <add> } <ide> } <add> return true; <ide> } <ide> <ide> } <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java <ide> public DeferredResult<Person> getDeferredResult() { <ide> public Callable<Person> getCallable() { <ide> return new Callable<Person>() { <ide> public Person call() throws Exception { <del> Thread.sleep(100); <ide> return new Person("Joe"); <ide> } <ide> };
2
Javascript
Javascript
change string concatenation to template
5bd8206b40c93882cd76e40049c8749984ad7c2f
<ide><path>test/fixtures/print-10-lines.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> for (var i = 0; i < 10; i++) { <del> console.log('count ' + i); <add> console.log(`count ${i}`); <ide> }
1
Python
Python
avoid increasing levels for identical arcs
4e1716223c99402efc97698116905c04d39ef6be
<ide><path>spacy/displacy/render.py <ide> def get_levels(self, arcs: List[Dict[str, Any]]) -> Dict[Tuple[int, int, str], i <ide> args (list): Individual arcs and their start, end, direction and label. <ide> RETURNS (dict): Arc levels keyed by (start, end, label). <ide> """ <add> arcs = [dict(t) for t in {tuple(sorted(arc.items())) for arc in arcs}] <ide> length = max([arc["end"] for arc in arcs], default=0) <ide> max_level = [0] * length <ide> levels = {} <ide><path>spacy/tests/test_displacy.py <ide> from spacy.tokens import Span, Doc <ide> <ide> <del>@pytest.mark.issue(5447) <del>def test_issue5447(): <del> """Test that overlapping arcs get separate levels.""" <del> renderer = DependencyRenderer() <del> words = [ <del> {"text": "This", "tag": "DT"}, <del> {"text": "is", "tag": "VBZ"}, <del> {"text": "a", "tag": "DT"}, <del> {"text": "sentence.", "tag": "NN"}, <del> ] <del> arcs = [ <del> {"start": 0, "end": 1, "label": "nsubj", "dir": "left"}, <del> {"start": 2, "end": 3, "label": "det", "dir": "left"}, <del> {"start": 2, "end": 3, "label": "overlap", "dir": "left"}, <del> {"start": 1, "end": 3, "label": "attr", "dir": "left"}, <del> ] <del> html = renderer.render([{"words": words, "arcs": arcs}]) <del> assert renderer.highest_level == 3 <del> <del> <ide> @pytest.mark.issue(2361) <ide> def test_issue2361(de_vocab): <ide> """Test if < is escaped when rendering""" <ide> def test_issue3882(en_vocab): <ide> displacy.parse_deps(doc) <ide> <ide> <add>@pytest.mark.issue(5447) <add>def test_issue5447(): <add> """Test that overlapping arcs get separate levels, unless they're identical.""" <add> renderer = DependencyRenderer() <add> words = [ <add> {"text": "This", "tag": "DT"}, <add> {"text": "is", "tag": "VBZ"}, <add> {"text": "a", "tag": "DT"}, <add> {"text": "sentence.", "tag": "NN"}, <add> ] <add> arcs = [ <add> {"start": 0, "end": 1, "label": "nsubj", "dir": "left"}, <add> {"start": 2, "end": 3, "label": "det", "dir": "left"}, <add> {"start": 2, "end": 3, "label": "overlap", "dir": "left"}, <add> {"end": 3, "label": "overlap", "start": 2, "dir": "left"}, <add> {"start": 1, "end": 3, "label": "attr", "dir": "left"}, <add> ] <add> renderer.render([{"words": words, "arcs": arcs}]) <add> assert renderer.highest_level == 3 <add> <add> <ide> @pytest.mark.issue(5838) <ide> def test_issue5838(): <ide> # Displacy's EntityRenderer break line
2
PHP
PHP
remove comment bloat from eloquent
98a691fa58640df321f12b8bf67a705f2d474312
<ide><path>system/db/eloquent.php <ide> public static function make($class) <ide> { <ide> $model = new $class; <ide> <del> // ----------------------------------------------------- <del> // Since this method is only used for instantiating <del> // models for querying purposes, we will go ahead and <del> // set the Query instance on the model. <del> // ----------------------------------------------------- <add> // Since this method is only used for instantiating/ models for querying <add> // purposes, we will go ahead and set the Query instance on the model. <ide> $model->query = Query::table(static::table($class)); <ide> <ide> return $model; <ide> public function has_many($model, $foreign_key = null) <ide> */ <ide> private function has_one_or_many($model, $foreign_key) <ide> { <del> // ----------------------------------------------------- <del> // The default foreign key for has one and has many <del> // relationships is the name of the model with an <del> // appended _id. <del> // <del> // For example, the foreign key for a User model would <del> // be user_id. Photo would be photo_id, etc. <del> // ----------------------------------------------------- <add> // The default foreign key for has one and has many relationships is the name <add> // of the model with an appended _id. For example, the foreign key for a <add> // User model would be user_id. Photo would be photo_id, etc. <ide> $this->relating_key = (is_null($foreign_key)) ? strtolower(get_class($this)).'_id' : $foreign_key; <ide> <ide> return static::make($model)->where($this->relating_key, '=', $this->id); <ide> public function belongs_to($model, $foreign_key = null) <ide> } <ide> else <ide> { <del> // ----------------------------------------------------- <del> // The default foreign key for belonging relationships <del> // is the name of the relationship method name with _id. <del> // <del> // So, if a model has a "manager" method returning a <del> // belongs_to relationship, the key would be manager_id. <del> // ----------------------------------------------------- <add> // The default foreign key for belonging relationships is the name of the <add> // relationship method name with _id. So, if a model has a "manager" method <add> // returning a belongs_to relationship, the key would be manager_id. <ide> list(, $caller) = debug_backtrace(false); <ide> <ide> $this->relating_key = $caller['function'].'_id'; <ide> public function has_and_belongs_to_many($model, $table = null) <ide> } <ide> else <ide> { <del> // ----------------------------------------------------- <del> // By default, the intermediate table name is the plural <del> // names of the models arranged alphabetically and <del> // concatenated with an underscore. <del> // ----------------------------------------------------- <add> // By default, the intermediate table name is the plural names of the models <add> // arranged alphabetically and concatenated with an underscore. <ide> $models = array(Inflector::plural($model), Inflector::plural(get_class($this))); <ide> <ide> sort($models); <ide> <ide> $this->relating_table = strtolower($models[0].'_'.$models[1]); <ide> } <ide> <del> // ----------------------------------------------------- <del> // The default foreign key for many-to-many relations <del> // is the name of the model with an appended _id. <del> // appended _id. <del> // <add> // The default foreign key for many-to-many relations is the name of the model with an appended _id. <ide> // This is the same convention as has_one and has_many. <del> // ----------------------------------------------------- <ide> $this->relating_key = strtolower(get_class($this)).'_id'; <ide> <ide> return static::make($model) <ide> public function has_and_belongs_to_many($model, $table = null) <ide> */ <ide> public function save() <ide> { <del> // ----------------------------------------------------- <del> // If the model doesn't have any dirty attributes, there <del> // is no need to save it to the database. <del> // ----------------------------------------------------- <ide> if ($this->exists and count($this->dirty) == 0) <ide> { <ide> return true; <ide> } <ide> <ide> $model = get_class($this); <ide> <del> // ----------------------------------------------------- <del> // Since the model was instantiated using "new", a query <del> // instance has not been set. We'll do it now. <del> // ----------------------------------------------------- <add> // Since the model was instantiated using "new", a query instance has not been set. <ide> $this->query = Query::table(static::table($model)); <ide> <del> // ----------------------------------------------------- <ide> // Set the creation and update timestamps. <del> // ----------------------------------------------------- <ide> if (property_exists($model, 'timestamps') and $model::$timestamps) <ide> { <ide> $this->updated_at = date('Y-m-d H:i:s'); <ide> public function save() <ide> } <ide> } <ide> <del> // ----------------------------------------------------- <del> // If the model already exists in the database, we only <del> // need to update it. Otherwise, we'll insert it. <del> // ----------------------------------------------------- <add> // If the model already exists in the database, we only need to update it. <add> // Otherwise, we'll insert the model into the database. <ide> if ($this->exists) <ide> { <ide> $result = $this->query->where('id', '=', $this->attributes['id'])->update($this->dirty) == 1; <ide> public function save() <ide> */ <ide> public function delete($id = null) <ide> { <del> // ----------------------------------------------------- <del> // If the method is being called from an existing model, <del> // only delete that model from the database. <del> // ----------------------------------------------------- <ide> if ($this->exists) <ide> { <ide> return Query::table(static::table(get_class($this)))->delete($this->id); <ide> } <ide> <del> return $this->query->delete($id); <add> return 0; <ide> } <ide> <ide> /** <ide> * Magic method for retrieving model attributes. <ide> */ <ide> public function __get($key) <ide> { <del> // ----------------------------------------------------- <del> // Check the ignored attributes first. These attributes <del> // hold all of the loaded relationships. <del> // ----------------------------------------------------- <add> // Check the ignored attributes first. These attributes hold all of the <add> // loaded relationships for the model. <ide> if (array_key_exists($key, $this->ignore)) <ide> { <ide> return $this->ignore[$key]; <ide> } <ide> <del> // ----------------------------------------------------- <del> // Is the attribute actually a relationship method? <del> // ----------------------------------------------------- <add> // Is the attribute actually a relationship method? If it is, return the <add> // models for the relationship. <ide> if (method_exists($this, $key)) <ide> { <ide> $model = $this->$key(); <ide> public function __get($key) <ide> */ <ide> public function __set($key, $value) <ide> { <del> // ----------------------------------------------------- <del> // If the key is a relationship, add it to the ignored. <del> // Otherwise, we can simply add it as an attribute. <del> // ----------------------------------------------------- <add> // If the key is a relationship, add it to the ignored attributes. <ide> if (method_exists($this, $key)) <ide> { <ide> $this->ignore[$key] = $value; <ide> public function __call($method, $parameters) <ide> return $this->_first(); <ide> } <ide> <del> // ----------------------------------------------------- <del> // Pass aggregate methods to the query instance. <del> // ----------------------------------------------------- <ide> if (in_array($method, array('count', 'sum', 'min', 'max', 'avg'))) <ide> { <ide> return call_user_func_array(array($this->query, $method), $parameters); <ide> } <ide> <del> // ----------------------------------------------------- <del> // Pass the method to the query instance. This allows <del> // the chaining of methods from the query builder. <del> // ----------------------------------------------------- <add> // Pass the method to the query instance. This allows the chaining of methods <add> // from the query builder, providing a nice, convenient API. <ide> call_user_func_array(array($this->query, $method), $parameters); <ide> <ide> return $this; <ide> public static function __callStatic($method, $parameters) <ide> return $model->_first(); <ide> } <ide> <del> // ----------------------------------------------------- <del> // Pass aggregate methods to the query instance. <del> // ----------------------------------------------------- <ide> if (in_array($method, array('count', 'sum', 'min', 'max', 'avg'))) <ide> { <ide> return call_user_func_array(array($model->query, $method), $parameters); <ide> } <ide> <del> // ----------------------------------------------------- <del> // Pass the method to the query instance. This allows <del> // the chaining of methods from the query builder. <del> // ----------------------------------------------------- <add> // Pass the method to the query instance. This allows the chaining of methods <add> // from the query builder, providing a nice, convenient API. <ide> call_user_func_array(array($model->query, $method), $parameters); <ide> <ide> return $model;
1
Javascript
Javascript
add jsdoc typings for assert
82d59882b13139672f5da4bffdf5883df3892dc0
<ide><path>lib/assert.js <ide> function innerFail(obj) { <ide> throw new AssertionError(obj); <ide> } <ide> <add>/** <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @param {string} [operator] <add> * @param {Function} [stackStartFn] <add> * @returns {never} <add> */ <ide> function fail(actual, expected, message, operator, stackStartFn) { <ide> const argsLen = arguments.length; <ide> <ide> function innerOk(fn, argLen, value, message) { <ide> } <ide> } <ide> <del>// Pure assertion tests whether a value is truthy, as determined <del>// by !!value. <add>/** <add> * Pure assertion tests whether a value is truthy, as determined <add> * by !!value. <add> * @param {...any} args <add> * @returns {void} <add> */ <ide> function ok(...args) { <ide> innerOk(ok, args.length, ...args); <ide> } <ide> assert.ok = ok; <ide> <del>// The equality assertion tests shallow, coercive equality with ==. <add>/** <add> * The equality assertion tests shallow, coercive equality with ==. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> /* eslint-disable no-restricted-properties */ <ide> assert.equal = function equal(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> assert.equal = function equal(actual, expected, message) { <ide> } <ide> }; <ide> <del>// The non-equality assertion tests for whether two objects are not <del>// equal with !=. <add>/** <add> * The non-equality assertion tests for whether two objects are not <add> * equal with !=. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.notEqual = function notEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> throw new ERR_MISSING_ARGS('actual', 'expected'); <ide> assert.notEqual = function notEqual(actual, expected, message) { <ide> } <ide> }; <ide> <del>// The equivalence assertion tests a deep equality relation. <add>/** <add> * The deep equivalence assertion tests a deep equality relation. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.deepEqual = function deepEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> throw new ERR_MISSING_ARGS('actual', 'expected'); <ide> assert.deepEqual = function deepEqual(actual, expected, message) { <ide> } <ide> }; <ide> <del>// The non-equivalence assertion tests for any deep inequality. <add>/** <add> * The deep non-equivalence assertion tests for any deep inequality. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.notDeepEqual = function notDeepEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> throw new ERR_MISSING_ARGS('actual', 'expected'); <ide> assert.notDeepEqual = function notDeepEqual(actual, expected, message) { <ide> }; <ide> /* eslint-enable */ <ide> <add>/** <add> * The deep strict equivalence assertion tests a deep strict equality <add> * relation. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> throw new ERR_MISSING_ARGS('actual', 'expected'); <ide> assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { <ide> } <ide> }; <ide> <add>/** <add> * The deep strict non-equivalence assertion tests for any deep strict <add> * inequality. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.notDeepStrictEqual = notDeepStrictEqual; <ide> function notDeepStrictEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> function notDeepStrictEqual(actual, expected, message) { <ide> } <ide> } <ide> <add>/** <add> * The strict equivalence assertion tests a strict equality relation. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.strictEqual = function strictEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> throw new ERR_MISSING_ARGS('actual', 'expected'); <ide> assert.strictEqual = function strictEqual(actual, expected, message) { <ide> } <ide> }; <ide> <add>/** <add> * The strict non-equivalence assertion tests for any strict inequality. <add> * @param {any} actual <add> * @param {any} expected <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.notStrictEqual = function notStrictEqual(actual, expected, message) { <ide> if (arguments.length < 2) { <ide> throw new ERR_MISSING_ARGS('actual', 'expected'); <ide> function expectsNoError(stackStartFn, actual, error, message) { <ide> throw actual; <ide> } <ide> <add>/** <add> * Expects the function `promiseFn` to throw an error. <add> * @param {() => any} promiseFn <add> * @param {...any} [args] <add> * @returns {void} <add> */ <ide> assert.throws = function throws(promiseFn, ...args) { <ide> expectsError(throws, getActual(promiseFn), ...args); <ide> }; <ide> <add>/** <add> * Expects `promiseFn` function or its value to reject. <add> * @param {() => Promise<any>} promiseFn <add> * @param {...any} [args] <add> * @returns {Promise<void>} <add> */ <ide> assert.rejects = async function rejects(promiseFn, ...args) { <ide> expectsError(rejects, await waitForActual(promiseFn), ...args); <ide> }; <ide> <add>/** <add> * Asserts that the function `fn` does not throw an error. <add> * @param {() => any} fn <add> * @param {...any} [args] <add> * @returns {void} <add> */ <ide> assert.doesNotThrow = function doesNotThrow(fn, ...args) { <ide> expectsNoError(doesNotThrow, getActual(fn), ...args); <ide> }; <ide> <add>/** <add> * Expects `fn` or its value to not reject. <add> * @param {() => Promise<any>} fn <add> * @param {...any} [args] <add> * @returns {Promise<void>} <add> */ <ide> assert.doesNotReject = async function doesNotReject(fn, ...args) { <ide> expectsNoError(doesNotReject, await waitForActual(fn), ...args); <ide> }; <ide> <add>/** <add> * Throws `value` if the value is not `null` or `undefined`. <add> * @param {any} err <add> * @returns {void} <add> */ <ide> assert.ifError = function ifError(err) { <ide> if (err !== null && err !== undefined) { <ide> let message = 'ifError got unwanted exception: '; <ide> function internalMatch(string, regexp, message, fn) { <ide> } <ide> } <ide> <add>/** <add> * Expects the `string` input to match the regular expression. <add> * @param {string} string <add> * @param {RegExp} regexp <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.match = function match(string, regexp, message) { <ide> internalMatch(string, regexp, message, match); <ide> }; <ide> <add>/** <add> * Expects the `string` input not to match the regular expression. <add> * @param {string} string <add> * @param {RegExp} regexp <add> * @param {string | Error} [message] <add> * @returns {void} <add> */ <ide> assert.doesNotMatch = function doesNotMatch(string, regexp, message) { <ide> internalMatch(string, regexp, message, doesNotMatch); <ide> }; <ide> <ide> assert.CallTracker = CallTracker; <ide> <del>// Expose a strict only variant of assert <add>/** <add> * Expose a strict only variant of assert. <add> * @param {...any} args <add> * @returns {void} <add> */ <ide> function strict(...args) { <ide> innerOk(strict, args.length, ...args); <ide> } <add> <ide> assert.strict = ObjectAssign(strict, assert, { <ide> equal: assert.strictEqual, <ide> deepEqual: assert.deepStrictEqual, <ide> notEqual: assert.notStrictEqual, <ide> notDeepEqual: assert.notDeepStrictEqual <ide> }); <add> <ide> assert.strict.strict = assert.strict;
1
Python
Python
add ipv6 to node, from primary nic
08937befa7d7877b2b5bb50df6c8c89b0ae65d87
<ide><path>libcloud/compute/drivers/dimensiondata.py <ide> def _to_node(self, element): <ide> if has_network_info else \ <ide> element.find(fixxpath('nic', TYPES_URN)).get('privateIpv4') <ide> <add> node.extra['ipv6'] = element.find( <add> fixxpath('networkInfo/primaryNic', TYPES_URN)) \ <add> .get('ipv6') \ <add> if has_network_info else \ <add> element.find(fixxpath('nic', TYPES_URN)).get('ipv6') <add> <ide> n = Node(id=element.get('id'), <ide> name=findtext(element, 'name', TYPES_URN), <ide> state=state,
1
Ruby
Ruby
add numeric type in the doc [ci skip]
40fd56052b03919b7ba5f07415e215a2b47df95f
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def drop_table(table_name, options = {}) <ide> # The +type+ parameter is normally one of the migrations native types, <ide> # which is one of the following: <ide> # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>, <del> # <tt>:integer</tt>, <tt>:bigint</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <add> # <tt>:integer</tt>, <tt>:bigint</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <tt>:numeric</tt>, <ide> # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>, <ide> # <tt>:binary</tt>, <tt>:boolean</tt>. <ide> # <ide> def drop_table(table_name, options = {}) <ide> # Allows or disallows +NULL+ values in the column. This option could <ide> # have been named <tt>:null_allowed</tt>. <ide> # * <tt>:precision</tt> - <del> # Specifies the precision for a <tt>:decimal</tt> column. <add> # Specifies the precision for the <tt>:decimal</tt> and <tt>:numeric</tt> columns. <ide> # * <tt>:scale</tt> - <del> # Specifies the scale for a <tt>:decimal</tt> column. <add> # Specifies the scale for the <tt>:decimal</tt> and <tt>:numeric</tt> columns. <ide> # <ide> # Note: The precision is the total number of significant digits <ide> # and the scale is the number of digits that can be stored following
1
PHP
PHP
remove forgotten line
078ce63639cf86f06009f486116c123534c403d3
<ide><path>src/Validation/Validation.php <ide> public static function comparison($check1, $operator, $check2) <ide> return false; <ide> } <ide> <del> $message = 'Operator `%s` is deprecated, use constant `Validation::%s` instead.'; <del> <ide> $operator = str_replace([' ', "\t", "\n", "\r", "\0", "\x0B"], '', strtolower($operator)); <ide> switch ($operator) { <ide> case static::COMPARE_GREATER:
1
Ruby
Ruby
fix broken macos sdk paths"
9b4a7856ac92e025e9df73ed5d18e4412fa55b5c
<ide><path>Library/Homebrew/extend/rbconfig_extension.rb <del># typed: false <del># frozen_string_literal: true <del> <del>macos_version = ENV["HOMEBREW_MACOS_VERSION"][0..4] <del>macos_sdk = "MacOSX#{macos_version}.sdk" <del> <del># Ruby hardcodes what might end up being an incorrect SDK path in some of the <del># variables that get used in mkmf.rb. <del># This patches them up to use the correct SDK. <del>RbConfig::CONFIG.each do |k, v| <del> next unless v.include?("MacOSX.sdk") <del> <del> new_value = v.gsub("MacOSX.sdk", macos_sdk) <del> next unless File.exist?(new_value) <del> <del> RbConfig::CONFIG[k] = new_value <del>end <ide><path>Library/Homebrew/utils/gems.rb <ide> def install_bundler_gems! <ide> install_bundler! <ide> <ide> ENV["BUNDLE_GEMFILE"] = File.join(ENV.fetch("HOMEBREW_LIBRARY"), "Homebrew", "Gemfile") <del> <del> # We can't use OS.mac? because not enough has <del> # been required yet this early in the boot process <del> if ENV["HOMEBREW_SYSTEM"] == "Macintosh" <del> # This patches up some paths used by mkmf.rb <del> extend_path = File.join(ENV.fetch("HOMEBREW_LIBRARY"), "Homebrew", "extend") <del> ENV["RUBYOPT"] = "-r#{extend_path}/rbconfig_extension" <del> end <del> <ide> @bundle_installed ||= begin <ide> bundle = File.join(find_in_path("bundle"), "bundle") <ide> bundle_check_output = `#{bundle} check 2>&1` <ide> def install_bundler_gems! <ide> end <ide> end <ide> <del> ENV["RUBYOPT"] = "" <del> <ide> setup_gem_environment! <ide> end <ide> end
2
Text
Text
update css classes
5e6b17bd4b4c48d56e1376cebc506ea6fe848c43
<ide><path>guide/english/html/css-classes/index.md <ide> Then in your css file: <ide> <ide> ```css <ide> <del>.iron-man{ <del> color:red; <add>.iron-man { <add> color: red; <ide> } <ide> <del>.alfred{ <add>.alfred { <ide> background-color: black; <ide> } <ide>
1
Javascript
Javascript
add handlebars helper for {{yield}}
672e25b8d901a9973fce139fcf687b94382e16ab
<ide><path>packages/ember-handlebars/lib/helpers.js <ide> require("ember-handlebars/helpers/unbound"); <ide> require("ember-handlebars/helpers/debug"); <ide> require("ember-handlebars/helpers/each"); <ide> require("ember-handlebars/helpers/template"); <del>require("ember-handlebars/helpers/action"); <ide>\ No newline at end of file <add>require("ember-handlebars/helpers/action"); <add>require("ember-handlebars/helpers/yield"); <ide><path>packages/ember-handlebars/lib/helpers/yield.js <add>var get = Ember.get, set = Ember.set; <add> <add>Ember.Handlebars.registerHelper('yield', function(options) { <add> var view = options.data.view, template; <add> <add> while (view && !get(view, 'layout')) { <add> view = get(view, 'parentView'); <add> } <add> <add> ember_assert("You called yield in a template that was not a layout", !!view); <add> <add> template = get(view, 'template'); <add> <add> ember_assert("You called yield on " + view.toString() + " without supplying a template", !!template); <add> template(this, options); <add>}); <ide><path>packages/ember-handlebars/tests/helpers/yield_test.js <add>// ========================================================================== <add>// Project: Ember Handlebar Views <add>// Copyright: ©2011 Strobe Inc. and contributors. <add>// License: Licensed under MIT license (see license.js) <add>// ========================================================================== <add>/*global TemplateTests*/ <add> <add>var set = Ember.set, get = Ember.get, setPath = Ember.setPath, getPath = Ember.getPath; <add> <add>var view; <add> <add>module("Support for {{yield}} helper (#307)", { <add> setup: function() { <add> window.TemplateTests = Ember.Namespace.create(); <add> }, <add> teardown: function() { <add> if (view) { <add> view.destroy(); <add> } <add> <add> window.TemplateTests = undefined; <add> } <add>}); <add> <add>test("a view with a layout set renders its template where the {{yield}} helper appears", function() { <add> TemplateTests.ViewWithLayout = Ember.View.extend({ <add> layout: Ember.Handlebars.compile('<div class="wrapper"><h1>{{title}}</h1>{{yield}}</div>') <add> }); <add> <add> view = Ember.View.create({ <add> template: Ember.Handlebars.compile('{{#view TemplateTests.ViewWithLayout title="My Fancy Page"}}<div class="page-body">Show something interesting here</div>{{/view}}') <add> }); <add> <add> Ember.run(function() { <add> view.appendTo('#qunit-fixture'); <add> }); <add> <add> equal(view.$('div.wrapper div.page-body').length, 1, 'page-body is embedded within wrapping my-page'); <add>}); <add> <add>test("block should work properly even when templates are not hard-coded", function() { <add> var templates = Ember.Object.create({ <add> nester: Ember.Handlebars.compile('<div class="wrapper"><h1>{{title}}</h1>{{yield}}</div>'), <add> nested: Ember.Handlebars.compile('{{#view TemplateTests.ViewWithLayout title="My Fancy Page"}}<div class="page-body">Show something interesting here</div>{{/view}}') <add> }); <add> <add> TemplateTests.ViewWithLayout = Ember.View.extend({ <add> layoutName: 'nester', <add> templates: templates <add> }); <add> <add> view = Ember.View.create({ <add> templateName: 'nested', <add> templates: templates <add> }); <add> <add> Ember.run(function() { <add> view.appendTo('#qunit-fixture'); <add> }); <add> <add> equal(view.$('div.wrapper div.page-body').length, 1, 'page-body is embedded within wrapping my-page'); <add> <add>}); <add> <add>test("templates should yield to block, when the yield is embedded in a hierarchy of virtual views", function() { <add> TemplateTests.TimesView = Ember.View.extend({ <add> layout: Ember.Handlebars.compile('<div class="times">{{#each index}}{{debugger}}{{yield}}{{/each}}</div>'), <add> n: null, <add> index: Ember.computed(function() { <add> var n = Ember.get(this, 'n'), indexArray = Ember.A([]); <add> for (var i=0; i < n; i++) { <add> indexArray[i] = i; <add> } <add> return indexArray; <add> }).property().cacheable() <add> }); <add> <add> view = Ember.View.create({ <add> template: Ember.Handlebars.compile('<div id="container"><div class="title">Counting to 5</div>{{#view TemplateTests.TimesView n=5}}<div class="times-item">Hello</div>{{/view}}</div>') <add> }); <add> <add> Ember.run(function() { <add> view.appendTo('#qunit-fixture'); <add> }); <add> <add> equal(view.$('div#container div.times-item').length, 5, 'times-item is embedded within wrapping container 5 times, as expected'); <add>}); <add> <add>test("templates should yield to block, when the yield is embedded in a hierarchy of non-virtual views", function() { <add> TemplateTests.NestingView = Ember.View.extend({ <add> layout: Ember.Handlebars.compile('{{#view Ember.View tagName="div" classNames="nesting"}}{{yield}}{{/view}}') <add> }); <add> <add> view = Ember.View.create({ <add> template: Ember.Handlebars.compile('<div id="container">{{#view TemplateTests.NestingView}}<div id="block">Hello</div>{{/view}}</div>') <add> }); <add> <add> Ember.run(function() { <add> view.appendTo('#qunit-fixture'); <add> }); <add> <add> equal(view.$('div#container div.nesting div#block').length, 1, 'nesting view yields correctly even within a view hierarchy in the nesting view'); <add>}); <add>
3
Javascript
Javascript
loosen timeout in https-no-reader
38176d3a1aa84cd2e7566673a965b966dc69a269
<ide><path>test/simple/test-https-no-reader.js <ide> server.listen(common.PORT, function() { <ide> // (i.e. should not leak) <ide> assert(res._readableState.length < 100 * 1024); <ide> process.exit(0); <del> }, 5000); <add> }, 2000); <ide> }); <ide> req.end(); <ide> });
1
Python
Python
fix deprecation warnings
4d3914841932065f19a61ad46e178f94dedeff5a
<ide><path>src/transformers/modeling_funnel.py <ide> def load_tf_weights_in_funnel(model, config, tf_checkpoint_path): <ide> skipped = False <ide> for m_name in name[1:]: <ide> if not isinstance(pointer, FunnelPositionwiseFFN) and re.fullmatch(r"layer_\d+", m_name): <del> layer_index = int(re.search("layer_(\d+)", m_name).groups()[0]) <add> layer_index = int(re.search(r"layer_(\d+)", m_name).groups()[0]) <ide> if layer_index < config.num_hidden_layers: <ide> block_idx = 0 <ide> while layer_index >= config.block_sizes[block_idx]: <ide><path>src/transformers/modeling_tf_utils.py <ide> def call(self, x): <ide> <ide> <ide> class TFSharedEmbeddings(tf.keras.layers.Layer): <del> """ <add> r""" <ide> Construct shared token embeddings. <ide> <ide> The weights of the embedding layer is usually shared with the weights of the linear decoder when doing <ide><path>tests/test_tokenization_common.py <ide> def test_save_and_load_tokenizer(self): <ide> tokenizers = self.get_tokenizers() <ide> for tokenizer in tokenizers: <ide> with self.subTest(f"{tokenizer.__class__.__name__}"): <del> self.assertNotEqual(tokenizer.max_len, 42) <add> self.assertNotEqual(tokenizer.model_max_length, 42) <ide> <ide> # Now let's start the test <ide> tokenizers = self.get_tokenizers()
3
PHP
PHP
remove brittle test for now
5e91cc382c12654dca7174264860d51aad0fed38
<ide><path>tests/Integration/Http/ThrottleRequestsWithRedisTest.php <ide> public function test_lock_opens_immediately_after_decay() <ide> $this->assertEquals(2, $response->headers->get('X-RateLimit-Limit')); <ide> $this->assertEquals(0, $response->headers->get('X-RateLimit-Remaining')); <ide> <del> Carbon::setTestNow( <del> $now->addSeconds(58) <del> ); <add> Carbon::setTestNow($finish = $now->addSeconds(58)); <ide> <ide> try { <ide> $this->withoutExceptionHandling()->get('/'); <ide> } catch (Throwable $e) { <ide> $this->assertEquals(429, $e->getStatusCode()); <ide> $this->assertEquals(2, $e->getHeaders()['X-RateLimit-Limit']); <ide> $this->assertEquals(0, $e->getHeaders()['X-RateLimit-Remaining']); <del> $this->assertTrue(in_array($e->getHeaders()['Retry-After'], [2, 3])); <del> $this->assertTrue(in_array($e->getHeaders()['X-RateLimit-Reset'], [Carbon::now()->getTimestamp() + 2, Carbon::now()->getTimestamp() + 3])); <add> // $this->assertTrue(in_array($e->getHeaders()['Retry-After'], [2, 3])); <add> // $this->assertTrue(in_array($e->getHeaders()['X-RateLimit-Reset'], [$finish->getTimestamp() + 2, $finish->getTimestamp() + 3])); <ide> } <ide> }); <ide> }
1
Ruby
Ruby
remove sprockets-rails from the gemfile generator
ed6d8f0ac6703f112da9cdf7f1c46365e60e8f11
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def assets_gemfile_entry <ide> # Gems used only for assets and not required <ide> # in production environments by default. <ide> group :assets do <del> gem 'sprockets-rails', '~> 2.0.0.rc3' <ide> gem 'sass-rails', '~> 4.0.0.beta' <ide> gem 'coffee-rails', '~> 4.0.0.beta' <ide>
1
Go
Go
add george washington carver to name generator
c90254c7464cac5c56e7ab9e6b1857c119d5d263
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> // Dame Mary Lucy Cartwright - British mathematician who was one of the first to study what is now known as chaos theory. Also known for Cartwright's theorem which finds applications in signal processing. https://en.wikipedia.org/wiki/Mary_Cartwright <ide> "cartwright", <ide> <add> // George Washington Carver - American agricultural scientist and inventor. He was the most prominent black scientist of the early 20th century. https://en.wikipedia.org/wiki/George_Washington_Carver <add> "carver", <add> <ide> // Vinton Gray Cerf - American Internet pioneer, recognised as one of "the fathers of the Internet". With Robert Elliot Kahn, he designed TCP and IP, the primary data communication protocols of the Internet and other computer networks. https://en.wikipedia.org/wiki/Vint_Cerf <ide> "cerf", <ide>
1
Ruby
Ruby
output what files `edit` is opening. (#444)
883b201c0906ad2942ec900290568836b5ddc240
<ide><path>Library/Homebrew/utils.rb <ide> def which_editor <ide> end <ide> <ide> def exec_editor(*args) <add> puts "Editing #{args.join "\n"}" <ide> safe_exec(which_editor, *args) <ide> end <ide>
1
Javascript
Javascript
use common.port to avoid conflicts
ec51bfc99574c7b42072bcb8d62dfe3165a6a034
<ide><path>test/simple/test-net-server-listen-remove-callback.js <ide> server.on('close', function() { <ide> assert.equal(0, listeners.length); <ide> }); <ide> <del>server.listen(3000, function() { <add>server.listen(common.PORT, function() { <ide> server.close(); <del> server.listen(3001, function() { <add> server.listen(common.PORT + 1, function() { <ide> server.close(); <ide> }); <ide> });
1
PHP
PHP
use instances of network\request everywhere
45ca5d0337cae62c87ae2172c961a84c629b0dd6
<ide><path>src/Http/BaseApplication.php <ide> public function bootstrap() <ide> /** <ide> * Invoke the application. <ide> * <del> * - Convert the PSR request/response into CakePHP equivalents. <add> * - Convert the PSR response into CakePHP equivalents. <ide> * - Create the controller that will handle this request. <ide> * - Invoke the controller. <ide> * <ide> public function bootstrap() <ide> */ <ide> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) <ide> { <del> // Convert the request/response to CakePHP equivalents. <del> $cakeRequest = RequestTransformer::toCake($request); <ide> $cakeResponse = ResponseTransformer::toCake($response); <ide> <ide> // Dispatch the request/response to CakePHP <del> $cakeResponse = $this->getDispatcher()->dispatch($cakeRequest, $cakeResponse); <add> $cakeResponse = $this->getDispatcher()->dispatch($request, $cakeResponse); <ide> <ide> // Convert the response back into a PSR7 object. <ide> return ResponseTransformer::toPsr($cakeResponse); <ide><path>src/Http/Server.php <ide> public function run(ServerRequestInterface $request = null, ResponseInterface $r <ide> { <ide> $this->app->bootstrap(); <ide> $response = $response ?: new Response(); <del> try { <del> $request = $request ?: ServerRequestFactory::fromGlobals(); <del> } catch (UnexpectedValueException $e) { <del> $response->getBody()->write('Bad Request'); <del> <del> return $response <del> ->withHeader('Content-Type', 'text/plain') <del> ->withStatus(400); <del> } <add> $request = $request ?: ServerRequestFactory::fromGlobals(); <ide> <ide> $middleware = $this->app->middleware(new MiddlewareQueue()); <ide> if (!($middleware instanceof MiddlewareQueue)) { <ide><path>src/Http/ServerRequestFactory.php <ide> namespace Cake\Http; <ide> <ide> use Cake\Core\Configure; <add>use Cake\Network\Request; <ide> use Cake\Network\Session; <ide> use Cake\Utility\Hash; <ide> use Zend\Diactoros\ServerRequestFactory as BaseFactory; <ide> public static function fromGlobals( <ide> array $cookies = null, <ide> array $files = null <ide> ) { <del> $request = parent::fromGlobals($server, $query, $body, $cookies, $files); <del> $uri = $request->getUri(); <del> <add> $server = static::normalizeServer($server ?: $_SERVER); <add> $uri = static::createUri($server); <ide> $sessionConfig = (array)Configure::read('Session') + [ <ide> 'defaults' => 'php', <ide> 'cookiePath' => $uri->webroot <ide> ]; <ide> $session = Session::create($sessionConfig); <del> $request = $request->withAttribute('base', $uri->base) <del> ->withAttribute('webroot', $uri->webroot) <del> ->withAttribute('session', $session); <del> <add> $request = new Request([ <add> 'environment' => $server, <add> 'uri' => $uri, <add> 'files' => $files, <add> 'input' => 'php://input', <add> 'cookies' => $cookies ?: $_COOKIE, <add> 'query' => $query ?: $_GET, <add> 'post' => $body ?: $_POST, <add> 'webroot' => $uri->webroot, <add> 'base' => $uri->base, <add> 'session' => $session, <add> ]); <ide> return $request; <ide> } <ide> <ide><path>src/Network/Request.php <ide> class Request implements ArrayAccess, ServerRequestInterface <ide> * the request. <ide> * <ide> * @return \Cake\Network\Request <add> * @deprecated 3.4.0 Use `Cake\Http\ServerRequestFactory` instead. <ide> */ <ide> public static function createFromGlobals() <ide> { <del> $uri = ServerRequestFactory::createUri($_SERVER); <del> $base = $uri->base; <del> $webroot = $uri->webroot; <del> <del> $sessionConfig = (array)Configure::read('Session') + [ <del> 'defaults' => 'php', <del> 'cookiePath' => $webroot <del> ]; <del> <del> $config = [ <del> 'query' => $_GET, <del> 'post' => $_POST, <del> 'files' => $_FILES, <del> 'cookies' => $_COOKIE, <del> 'environment' => $_SERVER + $_ENV, <del> 'uri' => $uri, <del> 'base' => $base, <del> 'webroot' => $webroot, <del> 'session' => Session::create($sessionConfig) <del> ]; <del> <del> return new static($config); <add> return ServerRequestFactory::fromGlobals(); <ide> } <ide> <ide> /** <ide> public static function createFromGlobals() <ide> * - `files` Uploaded file data formatted like $_FILES. <ide> * - `cookies` Cookies for this request. <ide> * - `environment` $_SERVER and $_ENV data. <del> * - `url` The URL without the base path for the request. <add> * - ~~`url`~~ The URL without the base path for the request. This option is deprecated and will be removed in 4.0.0 <ide> * - `uri` The PSR7 UriInterface object. If null, one will be created. <ide> * - `base` The base URL for the request. <ide> * - `webroot` The webroot directory for the request. <ide> * - `input` The data that would come from php://input this is useful for simulating <del> * - `session` An instance of a Session object <ide> * requests with put, patch or delete data. <add> * - `session` An instance of a Session object <ide> * <ide> * @param string|array $config An array of request data to create a request with. <add> * The string version of this argument is *deprecated* and will be removed in 4.0.0 <ide> */ <ide> public function __construct($config = []) <ide> { <ide><path>tests/TestCase/Http/ServerTest.php <ide> public function testRunWithGlobals() <ide> ); <ide> } <ide> <del> /** <del> * test run where the protocol is invalid <del> * <del> * @return void <del> */ <del> public function testRunInvalidProtocol() <del> { <del> $_SERVER['SERVER_PROTOCOL'] = 'HTTP/onclick 1=1'; <del> <del> $app = new MiddlewareApplication($this->config); <del> $server = new Server($app); <del> <del> $res = $server->run(); <del> $this->assertEquals(400, $res->getStatusCode()); <del> $this->assertEquals('text/plain', $res->getHeaderLine('content-type')); <del> $this->assertEquals('Bad Request', '' . $res->getBody()); <del> } <del> <ide> /** <ide> * Test an application failing to build middleware properly <ide> *
5
Python
Python
add prompt for file overwriting in save_weights
6892a20a9290c6a19e05ece4a428ed2c11461451
<ide><path>keras/models.py <ide> def save_weights(self, filepath, overwrite=False): <ide> import os.path <ide> # if file exists and should not be overwritten <ide> if not overwrite and os.path.isfile(filepath): <del> raise IOError('%s already exists' % (filepath)) <add> overwrite = input('[WARNING] %s already exists - overwrite? [y/n]' % (filepath)) <add> while overwrite not in ['y', 'n']: <add> overwrite = input('Enter "y" (overwrite) or "n" (cancel).') <add> if overwrite == 'n': <add> return <add> print('[TIP] Next time specify overwrite=True in save_weights!') <add> <ide> f = h5py.File(filepath, 'w') <ide> f.attrs['nb_layers'] = len(self.layers) <ide> for k, l in enumerate(self.layers):
1
PHP
PHP
add hook to configure broadcastable model event
5ca5768db439887217c86031ff7dd3bdf56cc466
<ide><path>src/Illuminate/Database/Eloquent/BroadcastsEvents.php <ide> protected function broadcastIfBroadcastChannelsExistForEvent($instance, $event, <ide> */ <ide> public function newBroadcastableModelEvent($event) <ide> { <del> return tap(new BroadcastableModelEventOccurred($this, $event), function ($event) { <add> return tap($this->withBroadcastableEvent(new BroadcastableModelEventOccurred($this, $event)), function ($event) { <ide> $event->connection = property_exists($this, 'broadcastConnection') <ide> ? $this->broadcastConnection <ide> : $this->broadcastConnection(); <ide> public function newBroadcastableModelEvent($event) <ide> }); <ide> } <ide> <add> /** <add> * Configure the broadcastable model event for the model. <add> * <add> * @param \Illuminate\Database\Eloquent\BroadcastableModelEventOccurred $event <add> * @return \Illuminate\Database\Eloquent\BroadcastableModelEventOccurred <add> */ <add> protected function withBroadcastableEvent(BroadcastableModelEventOccurred $event) <add> { <add> return $event; <add> } <add> <ide> /** <ide> * Get the channels that model events should broadcast on. <ide> *
1
PHP
PHP
apply fixes from styleci
cb70c44c5b01e6d449e9e32b8234f9854fabb932
<ide><path>src/Illuminate/Console/Scheduling/ManagesFrequencies.php <ide> public function yearly() <ide> ->spliceIntoPosition(4, 1); <ide> } <ide> <del> <ide> /** <ide> * Set the days of the week the command should run on. <ide> *
1
Javascript
Javascript
use image.src if htmlcanvaselement is undefined
1e2dcbd8a38475aebabae38785372131cf24159f
<ide><path>src/extras/ImageUtils.js <ide> var ImageUtils = { <ide> <ide> var canvas; <ide> <del> if ( image instanceof HTMLCanvasElement ) { <add> if ( typeof HTMLCanvasElement == 'undefined' ) { <add> <add> return image.src; <add> <add> } if ( image instanceof HTMLCanvasElement ) { <ide> <ide> canvas = image; <ide>
1
Javascript
Javascript
check travis env before checking if it's a pr
dfa791581f71ee236e87d3a73dc88ca6438c0534
<ide><path>build/tasks/test.js <ide> module.exports = function(grunt) { <ide> tasksMinified, <ide> tasksMinifiedApi; <ide> <del> grunt.task.run(['pretask']); <del> <del> if (process.env.TRAVIS_PULL_REQUEST !== 'false') { <add> // I believe this was done originally because of security implications around running <add> // Saucelabs automatically on PRs. <add> if (process.env.TRAVIS && process.env.TRAVIS_PULL_REQUEST !== 'false') { <ide> grunt.task.run(['karma:firefox', 'coveralls']); <ide> } else if (process.env.TRAVIS) { <ide> grunt.task.run(['karma:firefox', 'coveralls']);
1
PHP
PHP
fix lint errors
e3692225ffb73fc70aab37f88e024dfe6b0e285d
<ide><path>lib/Cake/Test/Case/Utility/HashTest.php <ide> public function testFlattenInfiniteLoop() { <ide> 'Order.Item.0.Product.sizes.4.Size.qty' => '', <ide> 'Order.Item.0.Product.sizes.4.Size.size' => '12-18mo', <ide> 'Order.Item.0.Product.sizes.4.Size.id' => '42', <del> 'Order.Item.0.Art.imprint_locations.0.id' => (int) 2, <add> 'Order.Item.0.Art.imprint_locations.0.id' => 2, <ide> 'Order.Item.0.Art.imprint_locations.0.name' => 'Left Chest', <del> 'Order.Item.0.Art.imprint_locations.0.imprint_type.id' => (int) 7, <add> 'Order.Item.0.Art.imprint_locations.0.imprint_type.id' => 7, <ide> 'Order.Item.0.Art.imprint_locations.0.imprint_type.type' => 'Embroidery', <ide> 'Order.Item.0.Art.imprint_locations.0.art' => '', <del> 'Order.Item.0.Art.imprint_locations.0.num_colors' => (int) 3, <add> 'Order.Item.0.Art.imprint_locations.0.num_colors' => 3, <ide> 'Order.Item.0.Art.imprint_locations.0.description' => 'Wooo! This is Embroidery!!', <ide> 'Order.Item.0.Art.imprint_locations.0.lines.0' => 'Platen', <ide> 'Order.Item.0.Art.imprint_locations.0.lines.1' => 'Logo', <del> 'Order.Item.0.Art.imprint_locations.0.height' => (int) 4, <del> 'Order.Item.0.Art.imprint_locations.0.width' => (int) 5, <add> 'Order.Item.0.Art.imprint_locations.0.height' => 4, <add> 'Order.Item.0.Art.imprint_locations.0.width' => 5, <ide> 'Order.Item.0.Art.imprint_locations.0.stitch_density' => 'Light', <ide> 'Order.Item.0.Art.imprint_locations.0.metallic_thread' => true, <del> 'Order.Item.0.Art.imprint_locations.1.id' => (int) 4, <add> 'Order.Item.0.Art.imprint_locations.1.id' => 4, <ide> 'Order.Item.0.Art.imprint_locations.1.name' => 'Full Back', <del> 'Order.Item.0.Art.imprint_locations.1.imprint_type.id' => (int) 6, <add> 'Order.Item.0.Art.imprint_locations.1.imprint_type.id' => 6, <ide> 'Order.Item.0.Art.imprint_locations.1.imprint_type.type' => 'Screenprinting', <ide> 'Order.Item.0.Art.imprint_locations.1.art' => '', <del> 'Order.Item.0.Art.imprint_locations.1.num_colors' => (int) 3, <add> 'Order.Item.0.Art.imprint_locations.1.num_colors' => 3, <ide> 'Order.Item.0.Art.imprint_locations.1.description' => 'Wooo! This is Screenprinting!!', <ide> 'Order.Item.0.Art.imprint_locations.1.lines.0' => 'Platen', <ide> 'Order.Item.0.Art.imprint_locations.1.lines.1' => 'Logo', <del> 'Order.Item.0.Art.imprint_locations.2.id' => (int) 26, <add> 'Order.Item.0.Art.imprint_locations.2.id' => 26, <ide> 'Order.Item.0.Art.imprint_locations.2.name' => 'HS - JSY Name Below', <del> 'Order.Item.0.Art.imprint_locations.2.imprint_type.id' => (int) 9, <add> 'Order.Item.0.Art.imprint_locations.2.imprint_type.id' => 9, <ide> 'Order.Item.0.Art.imprint_locations.2.imprint_type.type' => 'Names', <ide> 'Order.Item.0.Art.imprint_locations.2.description' => 'Wooo! This is Names!!', <del> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.active' => (int) 1, <add> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.active' => 1, <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.name' => 'Benjamin Talavera', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.color' => 'Red', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.height' => '3', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.layout' => 'Arched', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.0.style' => 'Classic', <del> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.active' => (int) 0, <add> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.active' => 0, <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.name' => 'Rishi Narayan', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.color' => 'Cardinal', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.height' => '4', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.layout' => 'Straight', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.S.1.style' => 'Team US', <del> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.active' => (int) 1, <add> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.active' => 1, <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.name' => 'Brandon Plasters', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.color' => 'Red', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.height' => '3', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.layout' => 'Arched', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.0.style' => 'Classic', <del> 'Order.Item.0.Art.imprint_locations.2.sizes.M.1.active' => (int) 0, <add> 'Order.Item.0.Art.imprint_locations.2.sizes.M.1.active' => 0, <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.1.name' => 'Andrew Reed', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.1.color' => 'Cardinal', <ide> 'Order.Item.0.Art.imprint_locations.2.sizes.M.1.height' => '4', <ide> public function testFlattenInfiniteLoop() { <ide> 'Order.QualityControl' => '0', <ide> 'Order.Receiving' => '0', <ide> 'Order.ScreenPrinting' => '0', <del> 'Order.Stage.art_approval' => (int) 0, <del> 'Order.Stage.draft' => (int) 1, <del> 'Order.Stage.quote' => (int) 1, <del> 'Order.Stage.order' => (int) 1, <add> 'Order.Stage.art_approval' => 0, <add> 'Order.Stage.draft' => 1, <add> 'Order.Stage.quote' => 1, <add> 'Order.Stage.order' => 1, <ide> 'Order.StoreLiason' => '0', <ide> 'Order.Tag_UI_Email' => '', <ide> 'Order.Tags' => '',
1
Javascript
Javascript
fix production test failing in ie11
56501aeb820aeee7f5077200462903ad0d12b2e9
<ide><path>test/integration/production/test/index.test.js <ide> describe('Production Usage', () => { <ide> try { <ide> browser = await webdriver(appPort, '/mark-in-head') <ide> <del> const currentPerfMarks = await browser.eval( <del> `window.performance.getEntriesByType('mark')` <del> ) <del> <del> expect(currentPerfMarks).toContainEqual( <del> expect.objectContaining({ name: 'custom-mark' }) <add> const customMarkFound = await browser.eval( <add> `window.performance.getEntriesByType('mark').filter(function(e) { <add> return e.name === 'custom-mark' <add> }).length === 1` <ide> ) <add> expect(customMarkFound).toBe(true) <ide> } finally { <ide> if (browser) { <ide> await browser.close()
1
Python
Python
flaubert pytorch tests
950c6a4f09787c8c5ef98dabd199082b25601fe8
<ide><path>tests/test_modeling_flaubert.py <add># coding=utf-8 <add># Copyright 2018 The Google AI Language Team Authors. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add> <add> <add>import unittest <add> <add>from transformers import is_torch_available <add> <add>from .test_configuration_common import ConfigTester <add>from .test_modeling_common import ModelTesterMixin, ids_tensor <add>from .utils import CACHE_DIR, require_torch, slow, torch_device <add> <add> <add>if is_torch_available(): <add> from transformers import ( <add> FlaubertConfig, <add> FlaubertModel, <add> FlaubertWithLMHeadModel, <add> FlaubertForQuestionAnswering, <add> FlaubertForQuestionAnsweringSimple, <add> FlaubertForSequenceClassification, <add> ) <add> from transformers.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_MAP <add> <add> <add>@require_torch <add>class FlaubertModelTest(ModelTesterMixin, unittest.TestCase): <add> <add> all_model_classes = ( <add> ( <add> FlaubertModel, <add> FlaubertWithLMHeadModel, <add> FlaubertForQuestionAnswering, <add> FlaubertForQuestionAnsweringSimple, <add> FlaubertForSequenceClassification, <add> ) <add> if is_torch_available() <add> else () <add> ) <add> <add> class FlaubertModelTester(object): <add> def __init__( <add> self, <add> parent, <add> batch_size=13, <add> seq_length=7, <add> is_training=True, <add> use_input_lengths=True, <add> use_token_type_ids=True, <add> use_labels=True, <add> gelu_activation=True, <add> sinusoidal_embeddings=False, <add> causal=False, <add> asm=False, <add> n_langs=2, <add> vocab_size=99, <add> n_special=0, <add> hidden_size=32, <add> num_hidden_layers=5, <add> num_attention_heads=4, <add> hidden_dropout_prob=0.1, <add> attention_probs_dropout_prob=0.1, <add> max_position_embeddings=512, <add> type_vocab_size=16, <add> type_sequence_label_size=2, <add> initializer_range=0.02, <add> num_labels=3, <add> num_choices=4, <add> summary_type="last", <add> use_proj=True, <add> scope=None, <add> ): <add> self.parent = parent <add> self.batch_size = batch_size <add> self.seq_length = seq_length <add> self.is_training = is_training <add> self.use_input_lengths = use_input_lengths <add> self.use_token_type_ids = use_token_type_ids <add> self.use_labels = use_labels <add> self.gelu_activation = gelu_activation <add> self.sinusoidal_embeddings = sinusoidal_embeddings <add> self.asm = asm <add> self.n_langs = n_langs <add> self.vocab_size = vocab_size <add> self.n_special = n_special <add> self.summary_type = summary_type <add> self.causal = causal <add> self.use_proj = use_proj <add> self.hidden_size = hidden_size <add> self.num_hidden_layers = num_hidden_layers <add> self.num_attention_heads = num_attention_heads <add> self.hidden_dropout_prob = hidden_dropout_prob <add> self.attention_probs_dropout_prob = attention_probs_dropout_prob <add> self.max_position_embeddings = max_position_embeddings <add> self.n_langs = n_langs <add> self.type_sequence_label_size = type_sequence_label_size <add> self.initializer_range = initializer_range <add> self.summary_type = summary_type <add> self.num_labels = num_labels <add> self.num_choices = num_choices <add> self.scope = scope <add> <add> def prepare_config_and_inputs(self): <add> input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) <add> input_mask = ids_tensor([self.batch_size, self.seq_length], 2).float() <add> <add> input_lengths = None <add> if self.use_input_lengths: <add> input_lengths = ( <add> ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2 <add> ) # small variation of seq_length <add> <add> token_type_ids = None <add> if self.use_token_type_ids: <add> token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.n_langs) <add> <add> sequence_labels = None <add> token_labels = None <add> is_impossible_labels = None <add> if self.use_labels: <add> sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) <add> token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) <add> is_impossible_labels = ids_tensor([self.batch_size], 2).float() <add> <add> config = FlaubertConfig( <add> vocab_size=self.vocab_size, <add> n_special=self.n_special, <add> emb_dim=self.hidden_size, <add> n_layers=self.num_hidden_layers, <add> n_heads=self.num_attention_heads, <add> dropout=self.hidden_dropout_prob, <add> attention_dropout=self.attention_probs_dropout_prob, <add> gelu_activation=self.gelu_activation, <add> sinusoidal_embeddings=self.sinusoidal_embeddings, <add> asm=self.asm, <add> causal=self.causal, <add> n_langs=self.n_langs, <add> max_position_embeddings=self.max_position_embeddings, <add> initializer_range=self.initializer_range, <add> summary_type=self.summary_type, <add> use_proj=self.use_proj, <add> ) <add> <add> return ( <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ) <add> <add> def check_loss_output(self, result): <add> self.parent.assertListEqual(list(result["loss"].size()), []) <add> <add> def create_and_check_flaubert_model( <add> self, <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ): <add> model = FlaubertModel(config=config) <add> model.to(torch_device) <add> model.eval() <add> outputs = model(input_ids, lengths=input_lengths, langs=token_type_ids) <add> outputs = model(input_ids, langs=token_type_ids) <add> outputs = model(input_ids) <add> sequence_output = outputs[0] <add> result = { <add> "sequence_output": sequence_output, <add> } <add> self.parent.assertListEqual( <add> list(result["sequence_output"].size()), [self.batch_size, self.seq_length, self.hidden_size] <add> ) <add> <add> def create_and_check_flaubert_lm_head( <add> self, <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ): <add> model = FlaubertWithLMHeadModel(config) <add> model.to(torch_device) <add> model.eval() <add> <add> loss, logits = model(input_ids, token_type_ids=token_type_ids, labels=token_labels) <add> <add> result = { <add> "loss": loss, <add> "logits": logits, <add> } <add> <add> self.parent.assertListEqual(list(result["loss"].size()), []) <add> self.parent.assertListEqual( <add> list(result["logits"].size()), [self.batch_size, self.seq_length, self.vocab_size] <add> ) <add> <add> def create_and_check_flaubert_simple_qa( <add> self, <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ): <add> model = FlaubertForQuestionAnsweringSimple(config) <add> model.to(torch_device) <add> model.eval() <add> <add> outputs = model(input_ids) <add> <add> outputs = model(input_ids, start_positions=sequence_labels, end_positions=sequence_labels) <add> loss, start_logits, end_logits = outputs <add> <add> result = { <add> "loss": loss, <add> "start_logits": start_logits, <add> "end_logits": end_logits, <add> } <add> self.parent.assertListEqual(list(result["start_logits"].size()), [self.batch_size, self.seq_length]) <add> self.parent.assertListEqual(list(result["end_logits"].size()), [self.batch_size, self.seq_length]) <add> self.check_loss_output(result) <add> <add> def create_and_check_flaubert_qa( <add> self, <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ): <add> model = FlaubertForQuestionAnswering(config) <add> model.to(torch_device) <add> model.eval() <add> <add> outputs = model(input_ids) <add> start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits = outputs <add> <add> outputs = model( <add> input_ids, <add> start_positions=sequence_labels, <add> end_positions=sequence_labels, <add> cls_index=sequence_labels, <add> is_impossible=is_impossible_labels, <add> p_mask=input_mask, <add> ) <add> <add> outputs = model( <add> input_ids, <add> start_positions=sequence_labels, <add> end_positions=sequence_labels, <add> cls_index=sequence_labels, <add> is_impossible=is_impossible_labels, <add> ) <add> <add> (total_loss,) = outputs <add> <add> outputs = model(input_ids, start_positions=sequence_labels, end_positions=sequence_labels) <add> <add> (total_loss,) = outputs <add> <add> result = { <add> "loss": total_loss, <add> "start_top_log_probs": start_top_log_probs, <add> "start_top_index": start_top_index, <add> "end_top_log_probs": end_top_log_probs, <add> "end_top_index": end_top_index, <add> "cls_logits": cls_logits, <add> } <add> <add> self.parent.assertListEqual(list(result["loss"].size()), []) <add> self.parent.assertListEqual( <add> list(result["start_top_log_probs"].size()), [self.batch_size, model.config.start_n_top] <add> ) <add> self.parent.assertListEqual( <add> list(result["start_top_index"].size()), [self.batch_size, model.config.start_n_top] <add> ) <add> self.parent.assertListEqual( <add> list(result["end_top_log_probs"].size()), <add> [self.batch_size, model.config.start_n_top * model.config.end_n_top], <add> ) <add> self.parent.assertListEqual( <add> list(result["end_top_index"].size()), <add> [self.batch_size, model.config.start_n_top * model.config.end_n_top], <add> ) <add> self.parent.assertListEqual(list(result["cls_logits"].size()), [self.batch_size]) <add> <add> def create_and_check_flaubert_sequence_classif( <add> self, <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ): <add> model = FlaubertForSequenceClassification(config) <add> model.to(torch_device) <add> model.eval() <add> <add> (logits,) = model(input_ids) <add> loss, logits = model(input_ids, labels=sequence_labels) <add> <add> result = { <add> "loss": loss, <add> "logits": logits, <add> } <add> <add> self.parent.assertListEqual(list(result["loss"].size()), []) <add> self.parent.assertListEqual( <add> list(result["logits"].size()), [self.batch_size, self.type_sequence_label_size] <add> ) <add> <add> def prepare_config_and_inputs_for_common(self): <add> config_and_inputs = self.prepare_config_and_inputs() <add> ( <add> config, <add> input_ids, <add> token_type_ids, <add> input_lengths, <add> sequence_labels, <add> token_labels, <add> is_impossible_labels, <add> input_mask, <add> ) = config_and_inputs <add> inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} <add> return config, inputs_dict <add> <add> def setUp(self): <add> self.model_tester = FlaubertModelTest.FlaubertModelTester(self) <add> self.config_tester = ConfigTester(self, config_class=FlaubertConfig, emb_dim=37) <add> <add> def test_config(self): <add> self.config_tester.run_common_tests() <add> <add> def test_flaubert_model(self): <add> config_and_inputs = self.model_tester.prepare_config_and_inputs() <add> self.model_tester.create_and_check_flaubert_model(*config_and_inputs) <add> <add> def test_flaubert_lm_head(self): <add> config_and_inputs = self.model_tester.prepare_config_and_inputs() <add> self.model_tester.create_and_check_flaubert_lm_head(*config_and_inputs) <add> <add> def test_flaubert_simple_qa(self): <add> config_and_inputs = self.model_tester.prepare_config_and_inputs() <add> self.model_tester.create_and_check_flaubert_simple_qa(*config_and_inputs) <add> <add> def test_flaubert_qa(self): <add> config_and_inputs = self.model_tester.prepare_config_and_inputs() <add> self.model_tester.create_and_check_flaubert_qa(*config_and_inputs) <add> <add> def test_flaubert_sequence_classif(self): <add> config_and_inputs = self.model_tester.prepare_config_and_inputs() <add> self.model_tester.create_and_check_flaubert_sequence_classif(*config_and_inputs) <add> <add> @slow <add> def test_model_from_pretrained(self): <add> for model_name in list(Flaubert_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <add> model = FlaubertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <add> self.assertIsNotNone(model)
1
Python
Python
add on_kill method to bigqueryinsertjoboperator
41a62735edcebbd9c39e505280646ef5d25aa1d5
<ide><path>airflow/providers/google/cloud/operators/bigquery.py <ide> def execute(self, context): <ide> ) <ide> <ide> <add># pylint: disable=too-many-arguments <ide> class BigQueryInsertJobOperator(BaseOperator): <ide> """ <ide> Executes a BigQuery job. Waits for the job to complete and returns job id. <ide> class BigQueryInsertJobOperator(BaseOperator): <ide> Service Account Token Creator IAM role to the directly preceding identity, with first <ide> account from the list granting this role to the originating account (templated). <ide> :type impersonation_chain: Union[str, Sequence[str]] <add> :param cancel_on_kill: Flag which indicates whether cancel the hook's job or not, when on_kill is called <add> :type cancel_on_kill: bool <ide> """ <ide> <ide> template_fields = ( <ide> def __init__( <ide> gcp_conn_id: str = 'google_cloud_default', <ide> delegate_to: Optional[str] = None, <ide> impersonation_chain: Optional[Union[str, Sequence[str]]] = None, <add> cancel_on_kill: bool = True, <ide> **kwargs, <ide> ) -> None: <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.force_rerun = force_rerun <ide> self.reattach_states: Set[str] = reattach_states or set() <ide> self.impersonation_chain = impersonation_chain <add> self.cancel_on_kill = cancel_on_kill <add> self.hook: Optional[BigQueryHook] = None <ide> <ide> def prepare_template(self) -> None: <ide> # If .json is passed then we have to read the file <ide> def execute(self, context: Any): <ide> delegate_to=self.delegate_to, <ide> impersonation_chain=self.impersonation_chain, <ide> ) <add> self.hook = hook <ide> <ide> job_id = self._job_id(context) <ide> <ide> def execute(self, context: Any): <ide> f"Or, if you want to reattach in this scenario add {job.state} to `reattach_states`" <ide> ) <ide> <add> self.job_id = job.job_id <ide> return job.job_id <add> <add> def on_kill(self): <add> if self.job_id and self.cancel_on_kill: <add> self.hook.cancel_job(job_id=self.job_id, project_id=self.project_id, location=self.location) <ide><path>tests/providers/google/cloud/operators/test_bigquery.py <ide> def test_execute_success(self, mock_hook, mock_md5): <ide> <ide> assert result == real_job_id <ide> <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <add> def test_on_kill(self, mock_hook, mock_md5): <add> job_id = "123456" <add> hash_ = "hash" <add> real_job_id = f"{job_id}_{hash_}" <add> mock_md5.return_value.hexdigest.return_value = hash_ <add> <add> configuration = { <add> "query": { <add> "query": "SELECT * FROM any", <add> "useLegacySql": False, <add> } <add> } <add> mock_hook.return_value.insert_job.return_value = MagicMock(job_id=real_job_id, error_result=False) <add> <add> op = BigQueryInsertJobOperator( <add> task_id="insert_query_job", <add> configuration=configuration, <add> location=TEST_DATASET_LOCATION, <add> job_id=job_id, <add> project_id=TEST_GCP_PROJECT_ID, <add> cancel_on_kill=False, <add> ) <add> op.execute({}) <add> <add> op.on_kill() <add> mock_hook.return_value.cancel_job.assert_not_called() <add> <add> op.cancel_on_kill = True <add> op.on_kill() <add> mock_hook.return_value.cancel_job.assert_called_once_with( <add> job_id=real_job_id, <add> location=TEST_DATASET_LOCATION, <add> project_id=TEST_GCP_PROJECT_ID, <add> ) <add> <ide> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <ide> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <ide> def test_execute_failure(self, mock_hook, mock_md5):
2
Python
Python
remove unused gptmodeltester
daf8bebcddb9cbef356e92c628cd9ca1a9e89923
<ide><path>tests/test_modeling_common.py <ide> <ide> from transformers import is_torch_available <ide> <del>from .utils import CACHE_DIR, require_torch, slow, torch_device <add>from .utils import require_torch, slow, torch_device <ide> <ide> <ide> if is_torch_available(): <ide> def test_inputs_embeds(self): <ide> outputs = model(**inputs_dict) <ide> <ide> <del>class GPTModelTester(ModelTesterMixin): <del> def __init__( <del> self, <del> parent, <del> batch_size=13, <del> seq_length=7, <del> is_training=True, <del> use_position_ids=True, <del> use_token_type_ids=True, <del> use_labels=True, <del> vocab_size=99, <del> n_positions=33, <del> hidden_size=32, <del> num_hidden_layers=5, <del> num_attention_heads=4, <del> n_choices=3, <del> type_sequence_label_size=2, <del> initializer_range=0.02, <del> num_labels=3, <del> scope=None, <del> config_class=None, <del> base_model_class=None, <del> lm_head_model_class=None, <del> double_head_model_class=None, <del> ): <del> self.parent = parent <del> self.batch_size = batch_size <del> self.seq_length = seq_length <del> self.is_training = is_training <del> self.use_position_ids = use_position_ids <del> self.use_token_type_ids = use_token_type_ids <del> self.use_labels = use_labels <del> self.vocab_size = vocab_size <del> self.n_positions = n_positions <del> self.hidden_size = hidden_size <del> self.num_hidden_layers = num_hidden_layers <del> self.num_attention_heads = num_attention_heads <del> self.n_choices = n_choices <del> self.type_sequence_label_size = type_sequence_label_size <del> self.initializer_range = initializer_range <del> self.num_labels = num_labels <del> self.scope = scope <del> self.config_class = config_class <del> self.base_model_class = base_model_class <del> self.lm_head_model_class = lm_head_model_class <del> self.double_head_model_class = double_head_model_class <del> self.all_model_classes = (base_model_class, lm_head_model_class, double_head_model_class) <del> <del> def prepare_config_and_inputs(self): <del> total_num_tokens = self.vocab_size <del> input_ids = ids_tensor([self.batch_size, self.n_choices, self.seq_length], total_num_tokens) <del> <del> position_ids = None <del> if self.use_position_ids: <del> position_ids = ids_tensor([self.batch_size, self.n_choices, self.seq_length], self.n_positions) <del> <del> token_type_ids = None <del> if self.use_token_type_ids: <del> total_voc = self.vocab_size <del> token_type_ids = ids_tensor([self.batch_size, self.n_choices, self.seq_length], total_voc) <del> <del> mc_labels = None <del> lm_labels = None <del> mc_token_ids = None <del> if self.use_labels: <del> mc_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) <del> lm_labels = ids_tensor([self.batch_size, self.n_choices, self.seq_length], self.num_labels) <del> mc_token_ids = ids_tensor([self.batch_size, self.n_choices], self.seq_length) <del> <del> config = self.config_class( <del> vocab_size=self.vocab_size, <del> n_positions=self.n_positions, <del> n_embd=self.hidden_size, <del> n_layer=self.num_hidden_layers, <del> n_head=self.num_attention_heads, <del> initializer_range=self.initializer_range, <del> ) <del> <del> return (config, input_ids, token_type_ids, position_ids, mc_labels, lm_labels, mc_token_ids) <del> <del> def create_and_check_base_model( <del> self, config, input_ids, token_type_ids, position_ids, mc_labels, lm_labels, mc_token_ids <del> ): <del> model = self.base_model_class(config) <del> model.to(torch_device) <del> model.eval() <del> <del> with torch.no_grad(): <del> outputs = model(input_ids, position_ids, token_type_ids) <del> outputs = model(input_ids, position_ids) <del> outputs = model(input_ids) <del> <del> hidden_state = outputs[0] <del> self.parent.assertListEqual( <del> list(hidden_state.size()), [self.batch_size, self.n_choices, self.seq_length, self.hidden_size] <del> ) <del> <del> def create_and_check_lm_head( <del> self, config, input_ids, token_type_ids, position_ids, mc_labels, lm_labels, mc_token_ids <del> ): <del> model = self.lm_head_model_class(config) <del> model.to(torch_device) <del> model.eval() <del> with torch.no_grad(): <del> outputs = model(input_ids, position_ids, token_type_ids, lm_labels) <del> loss, lm_logits = outputs[:2] <del> <del> total_voc = self.vocab_size <del> self.parent.assertListEqual( <del> list(lm_logits.size()), [self.batch_size, self.n_choices, self.seq_length, total_voc] <del> ) <del> self.parent.assertListEqual(list(loss.size()), []) <del> <del> def create_and_check_presents( <del> self, config, input_ids, token_type_ids, position_ids, mc_labels, lm_labels, mc_token_ids <del> ): <del> for model_class in self.all_model_classes: <del> model = model_class(config) <del> model.to(torch_device) <del> model.eval() <del> with torch.no_grad(): <del> outputs = model(input_ids) <del> presents = outputs[-1] <del> self.parent.assertEqual(self.num_hidden_layers, len(presents)) <del> self.parent.assertListEqual( <del> list(presents[0].size()), <del> [ <del> 2, <del> self.batch_size * self.n_choices, <del> self.num_attention_heads, <del> self.seq_length, <del> self.hidden_size // self.num_attention_heads, <del> ], <del> ) <del> <del> def create_and_check_double_heads( <del> self, config, input_ids, token_type_ids, position_ids, mc_labels, lm_labels, mc_token_ids <del> ): <del> model = self.double_head_model_class(config) <del> model.to(torch_device) <del> model.eval() <del> with torch.no_grad(): <del> outputs = model( <del> input_ids, <del> mc_token_ids, <del> lm_labels=lm_labels, <del> mc_labels=mc_labels, <del> token_type_ids=token_type_ids, <del> position_ids=position_ids, <del> ) <del> lm_loss, mc_loss, lm_logits, mc_logits = outputs[:4] <del> loss = [lm_loss, mc_loss] <del> <del> total_voc = self.vocab_size <del> self.parent.assertListEqual( <del> list(lm_logits.size()), [self.batch_size, self.n_choices, self.seq_length, total_voc] <del> ) <del> self.parent.assertListEqual(list(mc_logits.size()), [self.batch_size, self.n_choices]) <del> self.parent.assertListEqual([list(l.size()) for l in loss], [[], []]) <del> <del> def create_and_check_model_from_pretrained(self): <del> for model_name in list(self.base_model_class.pretrained_model_archive_map.keys())[:1]: <del> model = self.base_model_class.from_pretrained(model_name, cache_dir=CACHE_DIR) <del> self.parent.assertIsNotNone(model) <del> <del> def prepare_config_and_inputs_for_common(self): <del> config_and_inputs = self.prepare_config_and_inputs() <del> (config, input_ids, token_type_ids, position_ids, mc_labels, lm_labels, mc_token_ids) = config_and_inputs <del> inputs_dict = {"input_ids": input_ids} <del> return config, inputs_dict <del> <del> def run_common_tests(self, test_presents=False): <del> config_and_inputs = self.prepare_config_and_inputs() <del> self.create_and_check_base_model(*config_and_inputs) <del> <del> config_and_inputs = self.prepare_config_and_inputs() <del> self.create_and_check_lm_head(*config_and_inputs) <del> <del> config_and_inputs = self.prepare_config_and_inputs() <del> self.create_and_check_double_heads(*config_and_inputs) <del> <del> if test_presents: <del> config_and_inputs = self.prepare_config_and_inputs() <del> self.create_and_check_presents(*config_and_inputs) <del> <del> @slow <del> def run_slow_tests(self): <del> self.create_and_check_model_from_pretrained() <del> <del> <ide> class ConfigTester(object): <ide> def __init__(self, parent, config_class=None, **kwargs): <ide> self.parent = parent
1
Text
Text
use consistent term [skip ci]
258c95a9a206ffd2778691e1c02875d04d255c8e
<ide><path>guides/source/active_support_core_extensions.md <ide> Contributor.limit(2).order(:rank).to_xml <ide> <ide> To do so it sends `to_xml` to every item in turn, and collects the results under a root node. All items must respond to `to_xml`, an exception is raised otherwise. <ide> <del>By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors". <add>By default, the name of the root element is the underscored and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors". <ide> <ide> If there's any element that does not belong to the type of the first one the root node becomes "objects": <ide>
1
Python
Python
catch message for processuser information
26819112429706fcfa9c6d3e030a6c24cbd5dc50
<ide><path>glances/glances.py <ide> def __get_process_stats(self, proc): <ide> try: <ide> procstat['username'] = proc.username <ide> except KeyError: <del> procstat['username'] = proc.uids.real <add> try: <add> procstat['username'] = proc.uids.real <add> except KeyError: <add> procstat['username'] = "?" <ide> procstat['cmdline'] = " ".join(proc.cmdline) <ide> procstat['memory_info'] = proc.get_memory_info() <ide> procstat['memory_percent'] = proc.get_memory_percent()
1
PHP
PHP
fix foreach order
69a1f9616f55de439dca3800ed544861dbaf40e4
<ide><path>src/Illuminate/Routing/Router.php <ide> public function any($pattern, $action) <ide> */ <ide> public function controllers(array $controllers) <ide> { <del> foreach ($controllers as $name => $uri) <add> foreach ($controllers as $uri => $name) <ide> { <ide> $this->controller($uri, $name); <ide> }
1
Python
Python
fix issue #459
1f50270eeaeb9b19b9c3ca69e74e8517c3cb71db
<ide><path>slim/nets/resnet_v1.py <ide> def resnet_v1_101(inputs, <ide> return resnet_v1(inputs, blocks, num_classes, is_training, <ide> global_pool=global_pool, output_stride=output_stride, <ide> include_root_block=True, reuse=reuse, scope=scope) <del> <add>resnet_v1_101.default_image_size = resnet_v1.default_image_size <ide> <ide> def resnet_v1_152(inputs, <ide> num_classes=None, <ide> def resnet_v1_152(inputs, <ide> return resnet_v1(inputs, blocks, num_classes, is_training, <ide> global_pool=global_pool, output_stride=output_stride, <ide> include_root_block=True, reuse=reuse, scope=scope) <del> <add>resnet_v1_152.default_image_size = resnet_v1.default_image_size <ide> <ide> def resnet_v1_200(inputs, <ide> num_classes=None, <ide> def resnet_v1_200(inputs, <ide> return resnet_v1(inputs, blocks, num_classes, is_training, <ide> global_pool=global_pool, output_stride=output_stride, <ide> include_root_block=True, reuse=reuse, scope=scope) <add>resnet_v1_200.default_image_size = resnet_v1.default_image_size
1
Python
Python
add child to listfield when using arrayfield
48fa77c09e2198c7877a724a46230caedcc7b529
<ide><path>rest_framework/serializers.py <ide> def build_standard_field(self, field_name, model_field): <ide> # Fields with choices get coerced into `ChoiceField` <ide> # instead of using their regular typed field. <ide> field_class = ChoiceField <add> <ide> if not issubclass(field_class, ModelField): <ide> # `model_field` is only valid for the fallback case of <ide> # `ModelField`, which is used when no other typed field <ide> # matched to the model field. <ide> field_kwargs.pop('model_field', None) <add> <ide> if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField): <ide> # `allow_blank` is only valid for textual fields. <ide> field_kwargs.pop('allow_blank', None) <ide> <add> if postgres_fields and isinstance(model_field, postgres_fields.ArrayField): <add> child_model_field = model_field.base_field.base_field <add> child_field_class, child_field_kwargs = self.build_standard_field( <add> 'child', child_model_field <add> ) <add> <add> field_kwargs['child'] = child_field_class(**child_field_kwargs) <add> <ide> return field_class, field_kwargs <ide> <ide> def build_relational_field(self, field_name, relation_info):
1
Javascript
Javascript
replace assert.throws w/ common.expectserror
acd427713422138a92f74a4c3c2a1f6d8ecf9778
<ide><path>test/parallel/test-dns.js <ide> const goog = [ <ide> ]; <ide> assert.doesNotThrow(() => dns.setServers(goog)); <ide> assert.deepStrictEqual(dns.getServers(), goog); <del>assert.throws(() => dns.setServers(['foobar']), common.expectsError({ <add>common.expectsError(() => dns.setServers(['foobar']), { <ide> code: 'ERR_INVALID_IP_ADDRESS', <ide> type: Error, <ide> message: 'Invalid IP address: foobar' <del>})); <del>assert.throws(() => dns.setServers(['127.0.0.1:va']), common.expectsError({ <add>}); <add>common.expectsError(() => dns.setServers(['127.0.0.1:va']), { <ide> code: 'ERR_INVALID_IP_ADDRESS', <ide> type: Error, <ide> message: 'Invalid IP address: 127.0.0.1:va' <del>})); <add>}); <ide> assert.deepStrictEqual(dns.getServers(), goog); <ide> <ide> const goog6 = [ <ide> assert.deepStrictEqual(dns.getServers(), portsExpected); <ide> assert.doesNotThrow(() => dns.setServers([])); <ide> assert.deepStrictEqual(dns.getServers(), []); <ide> <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.resolve('example.com', [], common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "rrtype" argument must be of type string. ' + <ide> 'Received type object' <del>})); <add>}); <ide> <ide> // dns.lookup should accept only falsey and string values <ide> { <ide> assert.throws(() => { <ide> * - it's an odd number different than 1, and thus is invalid, because <ide> * flags are either === 1 or even. <ide> */ <del>assert.throws(() => { <add>common.expectsError(() => { <ide> dns.lookup('nodejs.org', { hints: (dns.V4MAPPED | dns.ADDRCONFIG) + 1 }, <ide> common.mustNotCall()); <del>}, common.expectsError({ <add>}, { <ide> code: 'ERR_INVALID_OPT_VALUE', <ide> type: TypeError, <ide> message: /The value "\d+" is invalid for option "hints"/ <del>})); <add>}); <ide> <del>assert.throws(() => dns.lookup('nodejs.org'), common.expectsError({ <add>common.expectsError(() => dns.lookup('nodejs.org'), { <ide> code: 'ERR_INVALID_CALLBACK', <ide> type: TypeError <del>})); <add>}); <ide> <del>assert.throws(() => dns.lookup('nodejs.org', 4), common.expectsError({ <add>common.expectsError(() => dns.lookup('nodejs.org', 4), { <ide> code: 'ERR_INVALID_CALLBACK', <ide> type: TypeError <del>})); <add>}); <ide> <ide> assert.doesNotThrow(() => dns.lookup('', { family: 4, hints: 0 }, <ide> common.mustCall())); <ide><path>test/parallel/test-fs-realpath.js <ide> function test_cyclic_link_protection(realpath, realpathSync, callback) { <ide> fs.symlinkSync(t[1], t[0], 'dir'); <ide> unlink.push(t[0]); <ide> }); <del> assert.throws(() => { <add> common.expectsError(() => { <ide> realpathSync(entry); <del> }, common.expectsError({ code: 'ELOOP', type: Error })); <add> }, { code: 'ELOOP', type: Error }); <ide> asynctest( <ide> realpath, [entry], callback, common.mustCall(function(err, result) { <ide> assert.strictEqual(err.path, entry); <ide><path>test/parallel/test-fs-watchfile.js <ide> common.expectsError( <ide> type: TypeError <ide> }); <ide> <del>assert.throws(function() { <add>common.expectsError(function() { <ide> fs.watchFile(new Object(), common.mustNotCall()); <del>}, common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError })); <add>}, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError }); <ide> <ide> const enoentFile = path.join(common.tmpDir, 'non-existent-file'); <ide> const expectedStatObject = new fs.Stats( <ide><path>test/parallel/test-http-client-check-http-token.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const http = require('http'); <ide> const Countdown = require('../common/countdown'); <ide> <ide> const server = http.createServer(common.mustCall((req, res) => { <ide> <ide> server.listen(0, common.mustCall(() => { <ide> expectedFails.forEach((method) => { <del> assert.throws(() => { <add> common.expectsError(() => { <ide> http.request({ method, path: '/' }, common.mustNotCall()); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "method" argument must be of type string. ' + <ide> `Received type ${typeof method}` <del> })); <add> }); <ide> }); <ide> <ide> expectedSuccesses.forEach((method) => { <ide><path>test/parallel/test-http-client-reject-unexpected-agent.js <ide> server.listen(0, baseOptions.host, common.mustCall(function() { <ide> baseOptions.port = this.address().port; <ide> <ide> failingAgentOptions.forEach((agent) => { <del> assert.throws( <add> common.expectsError( <ide> () => createRequest(agent), <del> common.expectsError({ <add> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "Agent option" argument must be one of type ' + <ide> 'Agent-like Object, undefined, or false' <del> }) <add> } <ide> ); <ide> }); <ide> <ide><path>test/parallel/test-http-client-unescaped-path.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const http = require('http'); <ide> <ide> for (let i = 0; i <= 32; i += 1) { <ide> const path = `bad${String.fromCharCode(i)}path`; <del> assert.throws( <add> common.expectsError( <ide> () => http.get({ path }, common.mustNotCall()), <del> common.expectsError({ <add> { <ide> code: 'ERR_UNESCAPED_CHARACTERS', <ide> type: TypeError, <ide> message: 'Request path contains unescaped characters' <del> }) <add> } <ide> ); <ide> } <ide><path>test/parallel/test-http-hostname-typechecking.js <ide> const http = require('http'); <ide> const vals = [{}, [], NaN, Infinity, -Infinity, true, false, 1, 0, new Date()]; <ide> <ide> vals.forEach((v) => { <del> assert.throws( <add> common.expectsError( <ide> () => http.request({ hostname: v }), <del> common.expectsError({ <add> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "options.hostname" property must be one of ' + <ide> 'type string, undefined, or null. ' + <ide> `Received type ${typeof v}` <del> }) <add> } <ide> ); <ide> <del> assert.throws( <add> common.expectsError( <ide> () => http.request({ host: v }), <del> common.expectsError({ <add> { <ide> code: 'ERR_INVALID_ARG_TYPE', <ide> type: TypeError, <ide> message: 'The "options.host" property must be one of ' + <ide> 'type string, undefined, or null. ' + <ide> `Received type ${typeof v}` <del> }) <add> } <ide> ); <ide> }); <ide> <ide><path>test/parallel/test-http-request-invalid-method-error.js <ide> 'use strict'; <ide> const common = require('../common'); <del>const assert = require('assert'); <ide> const http = require('http'); <ide> <del>assert.throws( <add>common.expectsError( <ide> () => http.request({ method: '\0' }), <del> common.expectsError({ <add> { <ide> code: 'ERR_INVALID_HTTP_TOKEN', <ide> type: TypeError, <ide> message: 'Method must be a valid HTTP token ["\u0000"]' <del> }) <add> } <ide> ); <ide><path>test/parallel/test-http-response-statuscode.js <ide> const server = http.Server(common.mustCall(function(req, res) { <ide> test(res, '404 this is not valid either', '404 this is not valid either'); <ide> break; <ide> case 12: <del> assert.throws(() => { res.writeHead(); }, <del> common.expectsError({ <del> code: 'ERR_HTTP_INVALID_STATUS_CODE', <del> type: RangeError, <del> message: 'Invalid status code: undefined' <del> })); <add> common.expectsError(() => { res.writeHead(); }, <add> { <add> code: 'ERR_HTTP_INVALID_STATUS_CODE', <add> type: RangeError, <add> message: 'Invalid status code: undefined' <add> }); <ide> this.close(); <ide> break; <ide> default: <ide><path>test/parallel/test-http-server-de-chunked-trailer.js <ide> const server = http.createServer(common.mustCall(function(req, res) { <ide> message: 'Trailers are invalid with this transfer encoding', <ide> type: Error <ide> }; <del> assert.throws(() => res.writeHead(200, { 'Content-Length': '2' }), <del> common.expectsError(trailerInvalidErr)); <add> common.expectsError(() => res.writeHead(200, { 'Content-Length': '2' }), <add> trailerInvalidErr); <ide> res.removeHeader('Trailer'); <ide> res.end('ok'); <ide> })); <ide><path>test/parallel/test-http-write-head.js <ide> const s = http.createServer(common.mustCall((req, res) => { <ide> <ide> res.writeHead(200, { Test: '2' }); <ide> <del> assert.throws(() => { <add> common.expectsError(() => { <ide> res.writeHead(100, {}); <del> }, common.expectsError({ <add> }, { <ide> code: 'ERR_HTTP_HEADERS_SENT', <ide> type: Error, <ide> message: 'Cannot render headers after they are sent to the client' <del> }) <del> ); <add> }); <ide> <ide> res.end(); <ide> }));
11
Javascript
Javascript
update electron builtins
10c1c97b607dfe31bcc34cfd342ef349cb94e93a
<ide><path>src/module-cache.js <ide> function registerBuiltins (devMode) { <ide> const electronAsarRoot = path.join(process.resourcesPath, 'electron.asar') <ide> <ide> const commonRoot = path.join(electronAsarRoot, 'common', 'api') <del> const commonBuiltins = ['callbacks-registry', 'clipboard', 'crash-reporter', 'shell'] <add> const commonBuiltins = ['clipboard', 'shell'] <ide> for (const builtin of commonBuiltins) { <ide> cache.builtins[builtin] = path.join(commonRoot, `${builtin}.js`) <ide> } <ide> <ide> const rendererRoot = path.join(electronAsarRoot, 'renderer', 'api') <del> const rendererBuiltins = ['ipc-renderer', 'remote', 'screen'] <add> const rendererBuiltins = ['crash-reporter', 'ipc-renderer', 'remote', 'screen'] <ide> for (const builtin of rendererBuiltins) { <ide> cache.builtins[builtin] = path.join(rendererRoot, `${builtin}.js`) <ide> }
1
Javascript
Javascript
pass meta labels through correctly [ci skip]
129670283e3eab5671fab0e4cc5dfcee4294c3b2
<ide><path>website/src/templates/models.js <ide> function formatModelMeta(data) { <ide> author: data.author, <ide> url: data.url, <ide> license: data.license, <add> labels: data.labels, <ide> vectors: formatVectors(data.vectors), <ide> accuracy: formatAccuracy(data.accuracy), <ide> }
1
Mixed
Javascript
add thisarg to asyncresource.bind
324a6c235a5bfcbcd7cc7491d55461915c10af34
<ide><path>doc/api/async_hooks.md <ide> class DBQuery extends AsyncResource { <ide> } <ide> ``` <ide> <del>#### Static method: `AsyncResource.bind(fn[, type])` <add>#### Static method: `AsyncResource.bind(fn[, type, [thisArg]])` <ide> <!-- YAML <ide> added: <ide> - v14.8.0 <ide> - v12.19.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36782 <add> description: Added optional thisArg. <ide> --> <ide> <ide> * `fn` {Function} The function to bind to the current execution context. <ide> * `type` {string} An optional name to associate with the underlying <ide> `AsyncResource`. <add>* `thisArg` {any} <ide> <ide> Binds the given function to the current execution context. <ide> <ide> The returned function will have an `asyncResource` property referencing <ide> the `AsyncResource` to which the function is bound. <ide> <del>#### `asyncResource.bind(fn)` <add>#### `asyncResource.bind(fn[, thisArg])` <ide> <!-- YAML <ide> added: <ide> - v14.8.0 <ide> - v12.19.0 <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/36782 <add> description: Added optional thisArg. <ide> --> <ide> <ide> * `fn` {Function} The function to bind to the current `AsyncResource`. <add>* `thisArg` {any} <ide> <ide> Binds the given function to execute to this `AsyncResource`'s scope. <ide> <ide><path>lib/async_hooks.js <ide> class AsyncResource { <ide> return this[trigger_async_id_symbol]; <ide> } <ide> <del> bind(fn) { <add> bind(fn, thisArg = this) { <ide> if (typeof fn !== 'function') <ide> throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); <del> const ret = FunctionPrototypeBind(this.runInAsyncScope, this, fn); <add> const ret = <add> FunctionPrototypeBind( <add> this.runInAsyncScope, <add> this, <add> fn, <add> thisArg); <ide> ObjectDefineProperties(ret, { <ide> 'length': { <ide> configurable: true, <ide> class AsyncResource { <ide> return ret; <ide> } <ide> <del> static bind(fn, type) { <add> static bind(fn, type, thisArg) { <ide> type = type || fn.name; <del> return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn); <add> return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn, thisArg); <ide> } <ide> } <ide> <ide><path>test/parallel/test-asyncresource-bind.js <ide> setImmediate(() => { <ide> assert.strictEqual(asyncResource.asyncId(), fn2()); <ide> assert.notStrictEqual(asyncId, fn2()); <ide> }); <add> <add>const foo = {}; <add>const fn3 = asyncResource.bind(common.mustCall(function() { <add> assert.strictEqual(this, foo); <add>}), foo); <add>fn3(); <add> <add>const fn4 = asyncResource.bind(common.mustCall(function() { <add> assert.strictEqual(this, asyncResource); <add>})); <add>fn4(); <add> <add>const fn5 = asyncResource.bind(common.mustCall(function() { <add> assert.strictEqual(this, false); <add>}), false); <add>fn5();
3
Javascript
Javascript
use default message for assert.strictequal
ef96b05c741cd2ab3434e89bcb9bf5b54b568c3a
<ide><path>test/parallel/test-zlib-from-concatenated-gzip.js <ide> const zlib = require('zlib'); <ide> const fs = require('fs'); <ide> const fixtures = require('../common/fixtures'); <ide> <del>const abcEncoded = zlib.gzipSync('abc'); <del>const defEncoded = zlib.gzipSync('def'); <add>const abc = 'abc'; <add>const def = 'def'; <add> <add>const abcEncoded = zlib.gzipSync(abc); <add>const defEncoded = zlib.gzipSync(def); <ide> <ide> const data = Buffer.concat([ <ide> abcEncoded, <ide> defEncoded <ide> ]); <ide> <del>assert.strictEqual(zlib.gunzipSync(data).toString(), 'abcdef'); <add>assert.strictEqual(zlib.gunzipSync(data).toString(), (abc + def)); <ide> <ide> zlib.gunzip(data, common.mustCall((err, result) => { <ide> assert.ifError(err); <del> assert.strictEqual(result.toString(), 'abcdef', <del> 'result should match original string'); <add> assert.strictEqual(result.toString(), (abc + def)); <ide> })); <ide> <ide> zlib.unzip(data, common.mustCall((err, result) => { <ide> assert.ifError(err); <del> assert.strictEqual(result.toString(), 'abcdef', <del> 'result should match original string'); <add> assert.strictEqual(result.toString(), (abc + def)); <ide> })); <ide> <ide> // Multi-member support does not apply to zlib inflate/deflate. <ide> zlib.unzip(Buffer.concat([ <ide> zlib.deflateSync('def') <ide> ]), common.mustCall((err, result) => { <ide> assert.ifError(err); <del> assert.strictEqual(result.toString(), 'abc', <del> 'result should match contents of first "member"'); <add> assert.strictEqual(result.toString(), abc); <ide> })); <ide> <ide> // files that have the "right" magic bytes for starting a new gzip member
1
PHP
PHP
add new assertion methods added in php 9
e01649deb97ec7749cae0d900be18ff6d6859b09
<ide><path>src/TestSuite/TestCase.php <ide> use Cake\TestSuite\Constraint\EventFiredWith; <ide> use Cake\Utility\Inflector; <ide> use LogicException; <add>use PHPUnit\Framework\Constraint\DirectoryExists; <add>use PHPUnit\Framework\Constraint\FileExists; <add>use PHPUnit\Framework\Constraint\LogicalNot; <add>use PHPUnit\Framework\Constraint\RegularExpression; <ide> use PHPUnit\Framework\TestCase as BaseTestCase; <ide> use ReflectionClass; <ide> use ReflectionException; <ide> abstract class TestCase extends BaseTestCase <ide> */ <ide> protected $_configure = []; <ide> <add> /** <add> * Asserts that a string matches a given regular expression. <add> * <add> * @param string $pattern Regex pattern <add> * @param string $string String to test <add> * @param string $message Message <add> * @return void <add> * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException <add> * @codeCoverageIgnore <add> */ <add> public static function assertMatchesRegularExpression(string $pattern, string $string, string $message = ''): void <add> { <add> static::assertThat($string, new RegularExpression($pattern), $message); <add> } <add> <add> /** <add> * Asserts that a string does not match a given regular expression. <add> * <add> * @param string $pattern Regex pattern <add> * @param string $string String to test <add> * @param string $message Message <add> * @return void <add> * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException <add> */ <add> public static function assertDoesNotMatchRegularExpression( <add> string $pattern, <add> string $string, <add> string $message = '' <add> ): void { <add> static::assertThat( <add> $string, <add> new LogicalNot( <add> new RegularExpression($pattern) <add> ), <add> $message <add> ); <add> } <add> <add> /** <add> * Asserts that a file does not exist. <add> * <add> * @param string $filename Filename <add> * @param string $message Message <add> * @return void <add> * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException <add> * @codeCoverageIgnore <add> */ <add> public static function assertFileDoesNotExist(string $filename, string $message = ''): void <add> { <add> static::assertThat($filename, new LogicalNot(new FileExists()), $message); <add> } <add> <add> /** <add> * Asserts that a directory does not exist. <add> * <add> * @param string $directory Directory <add> * @param string $message Message <add> * @return void <add> * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException <add> * @codeCoverageIgnore <add> */ <add> public static function assertDirectoryDoesNotExist(string $directory, string $message = ''): void <add> { <add> static::assertThat($directory, new LogicalNot(new DirectoryExists()), $message); <add> } <add> <ide> /** <ide> * Overrides SimpleTestCase::skipIf to provide a boolean return value <ide> * <ide> public function assertRegExpSql(string $pattern, string $actual, bool $optional <ide> $optional = $optional ? '?' : ''; <ide> $pattern = str_replace('<', '[`"\[]' . $optional, $pattern); <ide> $pattern = str_replace('>', '[`"\]]' . $optional, $pattern); <del> $this->assertRegExp('#' . $pattern . '#', $actual); <add> $this->assertMatchesRegularExpression('#' . $pattern . '#', $actual); <ide> } <ide> <ide> /** <ide> public function assertHtml(array $expected, string $string, bool $fullDebug = fa <ide> debug($string); <ide> debug($regex); <ide> } <del> $this->assertRegExp( <add> $this->assertMatchesRegularExpression( <ide> $expression, <ide> $string, <ide> sprintf('Item #%d / regex #%d failed: %s', $itemNum, $i, $description) <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php <ide> public function testAuthenticateChallenge(): void <ide> $this->assertNotEmpty($e); <ide> <ide> $header = $e->responseHeader(); <del> $this->assertRegexp( <add> $this->assertMatchesRegularExpression( <ide> '/^Digest realm="localhost",qop="auth",nonce="[a-zA-Z0-9=]+",opaque="123abc"$/', <ide> $header['WWW-Authenticate'] <ide> ); <ide> public function testLoginHeaders(): void <ide> ]); <ide> $result = $this->auth->loginHeaders($request); <ide> <del> $this->assertRegexp( <add> $this->assertMatchesRegularExpression( <ide> '/^Digest realm="localhost",qop="auth",nonce="[a-zA-Z0-9=]+",opaque="[a-f0-9]+"$/', <ide> $result['WWW-Authenticate'] <ide> ); <ide><path>tests/TestCase/Cache/Engine/FileEngineTest.php <ide> public function testDeleteCache() <ide> <ide> $result = Cache::delete('delete_test', 'file_test'); <ide> $this->assertTrue($result); <del> $this->assertFileNotExists(TMP . 'tests/delete_test'); <add> $this->assertFileDoesNotExist(TMP . 'tests/delete_test'); <ide> <ide> $result = Cache::delete('delete_test', 'file_test'); <ide> $this->assertFalse($result); <ide> public function testClear() <ide> <ide> $result = Cache::clear('file_test'); <ide> $this->assertTrue($result); <del> $this->assertFileNotExists(TMP . 'tests/cake_serialize_test1'); <del> $this->assertFileNotExists(TMP . 'tests/cake_serialize_test2'); <del> $this->assertFileNotExists(TMP . 'tests/cake_serialize_test3'); <add> $this->assertFileDoesNotExist(TMP . 'tests/cake_serialize_test1'); <add> $this->assertFileDoesNotExist(TMP . 'tests/cake_serialize_test2'); <add> $this->assertFileDoesNotExist(TMP . 'tests/cake_serialize_test3'); <ide> } <ide> <ide> /** <ide> public function testClearIsRestrictedToConfiguredPath() <ide> <ide> $result = Cache::clear('file_test'); <ide> $this->assertTrue($result); <del> $this->assertFileNotExists(TMP . 'tests/key'); <add> $this->assertFileDoesNotExist(TMP . 'tests/key'); <ide> <ide> $this->assertFileExists($unrelatedFile); <ide> $this->assertTrue(unlink($unrelatedFile)); <ide><path>tests/TestCase/Command/I18nExtractCommandTest.php <ide> public function testExecute() <ide> $this->assertFileExists($this->path . DS . 'default.pot'); <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> <del> $this->assertFileNotExists($this->path . DS . 'cake.pot'); <add> $this->assertFileDoesNotExist($this->path . DS . 'cake.pot'); <ide> <ide> // extract.ctp <ide> $pattern = '/\#: [\/\\\\]extract\.php:\d+\n'; <ide> $pattern .= '\#: [\/\\\\]extract\.php:\d+\n'; <ide> $pattern .= 'msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> <ide> $pattern = '/msgid "You have %d new message."\nmsgstr ""/'; <del> $this->assertNotRegExp($pattern, $result, 'No duplicate msgid'); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result, 'No duplicate msgid'); <ide> <ide> $pattern = '/\#: [\/\\\\]extract\.php:\d+\n'; <ide> $pattern .= 'msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> <ide> $pattern = '/\#: [\/\\\\]extract\.php:\d+\nmsgid "'; <ide> $pattern .= 'Hot features!'; <ide> $pattern .= '\\\n - No Configuration: Set-up the database and let the magic begin'; <ide> $pattern .= '\\\n - Extremely Simple: Just look at the name...It\'s Cake'; <ide> $pattern .= '\\\n - Active, Friendly Community: Join us #cakephp on IRC. We\'d love to help you get started'; <ide> $pattern .= '"\nmsgstr ""/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> <ide> $this->assertStringContainsString('msgid "double \\"quoted\\""', $result, 'Strings with quotes not handled correctly'); <ide> $this->assertStringContainsString("msgid \"single 'quoted'\"", $result, 'Strings with quotes not handled correctly'); <ide> <ide> $pattern = '/\#: [\/\\\\]extract\.php:\d+\n'; <ide> $pattern .= 'msgctxt "mail"\n'; <ide> $pattern .= 'msgid "letter"/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> <ide> $pattern = '/\#: [\/\\\\]extract\.php:\d+\n'; <ide> $pattern .= 'msgctxt "alphabet"\n'; <ide> $pattern .= 'msgid "letter"/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> <ide> // extract.php - reading the domain.pot <ide> $result = file_get_contents($this->path . DS . 'domain.pot'); <ide> <ide> $pattern = '/msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> $pattern = '/msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> <ide> $pattern = '/msgid "You have %d new message \(domain\)."\nmsgid_plural "You have %d new messages \(domain\)."/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> $pattern = '/msgid "You deleted %d message \(domain\)."\nmsgid_plural "You deleted %d messages \(domain\)."/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> } <ide> <ide> /** <ide> public function testExecuteMerge() <ide> ); <ide> $this->assertExitSuccess(); <ide> $this->assertFileExists($this->path . DS . 'default.pot'); <del> $this->assertFileNotExists($this->path . DS . 'cake.pot'); <del> $this->assertFileNotExists($this->path . DS . 'domain.pot'); <add> $this->assertFileDoesNotExist($this->path . DS . 'cake.pot'); <add> $this->assertFileDoesNotExist($this->path . DS . 'domain.pot'); <ide> } <ide> <ide> /** <ide> public function testExtractWithExclude() <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> <ide> $pattern = '/\#: .*extract\.php:\d+\n/'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> <ide> $pattern = '/\#: .*default\.php:\d+\n/'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> } <ide> <ide> /** <ide> public function testExtractWithoutLocations() <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> <ide> $pattern = '/\n\#: .*\n/'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> } <ide> <ide> /** <ide> public function testExtractMultiplePaths() <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <ide> <ide> $pattern = '/msgid "Add User"/'; <del> $this->assertRegExp($pattern, $result); <add> $this->assertMatchesRegularExpression($pattern, $result); <ide> } <ide> <ide> /** <ide> public function testExtractExcludePlugins() <ide> $this->assertExitSuccess(); <ide> <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <del> $this->assertNotRegExp('#TestPlugin#', $result); <add> $this->assertDoesNotMatchRegularExpression('#TestPlugin#', $result); <ide> } <ide> <ide> /** <ide> public function testExtractPlugin() <ide> $this->assertExitSuccess(); <ide> <ide> $result = file_get_contents($this->path . DS . 'default.pot'); <del> $this->assertNotRegExp('#Pages#', $result); <del> $this->assertRegExp('/translate\.php:\d+/', $result); <add> $this->assertDoesNotMatchRegularExpression('#Pages#', $result); <add> $this->assertMatchesRegularExpression('/translate\.php:\d+/', $result); <ide> $this->assertStringContainsString('This is a translatable string', $result); <ide> } <ide> <ide> public function testExtractVendoredPlugin() <ide> $this->assertExitSuccess(); <ide> <ide> $result = file_get_contents($this->path . DS . 'test_plugin_three.pot'); <del> $this->assertNotRegExp('#Pages#', $result); <del> $this->assertRegExp('/default\.php:\d+/', $result); <add> $this->assertDoesNotMatchRegularExpression('#Pages#', $result); <add> $this->assertMatchesRegularExpression('/default\.php:\d+/', $result); <ide> $this->assertStringContainsString('A vendor message', $result); <ide> } <ide> <ide> public function testExtractCore() <ide> $result = file_get_contents($this->path . DS . 'cake.pot'); <ide> <ide> $pattern = '/#: Console\/Templates\//'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> <ide> $pattern = '/#: Test\//'; <del> $this->assertNotRegExp($pattern, $result); <add> $this->assertDoesNotMatchRegularExpression($pattern, $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Command/PluginAssetsCommandsTest.php <ide> public function testForPluginWithoutWebroot() <ide> $this->loadPlugins(['TestPluginTwo']); <ide> <ide> $this->exec('plugin assets symlink'); <del> $this->assertFileNotExists($this->wwwRoot . 'test_plugin_two'); <add> $this->assertFileDoesNotExist($this->wwwRoot . 'test_plugin_two'); <ide> } <ide> <ide> /** <ide> public function testSymlinkingSpecifiedPlugin() <ide> unlink($path); <ide> <ide> $path = $this->wwwRoot . 'company' . DS . 'test_plugin_three'; <del> $this->assertDirectoryNotExists($path); <add> $this->assertDirectoryDoesNotExist($path); <ide> $this->assertFalse(is_link($path)); <ide> } <ide> <ide> public function testRemoveFolder() <ide> <ide> $this->exec('plugin assets remove'); <ide> <del> $this->assertDirectoryNotExists($this->wwwRoot . 'test_plugin'); <del> $this->assertDirectoryNotExists($this->wwwRoot . 'company' . DS . 'test_plugin_three'); <add> $this->assertDirectoryDoesNotExist($this->wwwRoot . 'test_plugin'); <add> $this->assertDirectoryDoesNotExist($this->wwwRoot . 'company' . DS . 'test_plugin_three'); <ide> $this->assertDirectoryExists($this->wwwRoot . 'company', 'Ensure namespace folder isn\'t removed'); <ide> <ide> rmdir($this->wwwRoot . 'company'); <ide><path>tests/TestCase/Command/PluginUnloadCommandTest.php <ide> public function testRegularExpressionsApplication($content) <ide> $result = file_get_contents($this->app); <ide> <ide> $this->assertStringNotContainsString("addPlugin('TestPlugin'", $result); <del> $this->assertNotRegexp("/this\-\>addPlugin\([\'\"]TestPlugin'[\'\"][^\)]*\)\;/mi", $result); <add> $this->assertDoesNotMatchRegularExpression("/this\-\>addPlugin\([\'\"]TestPlugin'[\'\"][^\)]*\)\;/mi", $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Console/ConsoleIoTest.php <ide> public function testCreateFileDirectoryCreation() <ide> ->method('write'); <ide> <ide> $directory = TMP . 'shell_test'; <del> $this->assertFileNotExists($directory, 'Directory should not exist before createFile'); <add> $this->assertFileDoesNotExist($directory, 'Directory should not exist before createFile'); <ide> <ide> $path = $directory . DS . 'create.txt'; <ide> $contents = 'some content'; <ide> public function testCreateFilePermissionsError() <ide> chmod($path, 0444); <ide> <ide> $this->io->createFile($file, 'testing'); <del> $this->assertFileNotExists($file); <add> $this->assertFileDoesNotExist($file); <ide> <ide> chmod($path, 0744); <ide> rmdir($path); <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testCreateFileNoPermissions() <ide> chmod($path, 0444); <ide> <ide> $this->Shell->createFile($file, 'testing'); <del> $this->assertFileNotExists($file); <add> $this->assertFileDoesNotExist($file); <ide> <ide> chmod($path, 0744); <ide> rmdir($path); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testRender(): void <ide> $Controller->viewBuilder()->setTemplatePath('Posts'); <ide> <ide> $result = $Controller->render('index'); <del> $this->assertRegExp('/posts index/', (string)$result); <add> $this->assertMatchesRegularExpression('/posts index/', (string)$result); <ide> <ide> $Controller->viewBuilder()->setTemplate('index'); <ide> $result = $Controller->render(); <del> $this->assertRegExp('/posts index/', (string)$result); <add> $this->assertMatchesRegularExpression('/posts index/', (string)$result); <ide> <ide> $result = $Controller->render('/element/test_element'); <del> $this->assertRegExp('/this is the test element/', (string)$result); <add> $this->assertMatchesRegularExpression('/this is the test element/', (string)$result); <ide> } <ide> <ide> /** <ide> public function testBeforeRenderTemplateAndLayout() <ide> }); <ide> <ide> $result = $Controller->render('/Element/test_element', 'default'); <del> $this->assertRegExp('/posts index/', (string)$result); <add> $this->assertMatchesRegularExpression('/posts index/', (string)$result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/ConnectionTest.php <ide> public function testPrepare() <ide> $result = $this->connection->prepare($query); <ide> $this->assertInstanceOf('Cake\Database\StatementInterface', $result); <ide> $sql = '#SELECT [`"\[]?1 \+ 1[`"\]]?#'; <del> $this->assertRegExp($sql, $result->queryString); <add> $this->assertMatchesRegularExpression($sql, $result->queryString); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Log/LoggingStatementTest.php <ide> public function testExecuteNoParams() <ide> <ide> $messages = Log::engine('queries')->read(); <ide> $this->assertCount(1, $messages); <del> $this->assertRegExp('/^debug connection=test duration=\d+ rows=3 SELECT bar FROM foo$/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^debug connection=test duration=\d+ rows=3 SELECT bar FROM foo$/', $messages[0]); <ide> } <ide> <ide> /** <ide> public function testExecuteWithParams() <ide> <ide> $messages = Log::engine('queries')->read(); <ide> $this->assertCount(1, $messages); <del> $this->assertRegExp('/^debug connection=test duration=\d+ rows=4 SELECT bar FROM foo WHERE x=1 AND y=2$/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^debug connection=test duration=\d+ rows=4 SELECT bar FROM foo WHERE x=1 AND y=2$/', $messages[0]); <ide> } <ide> <ide> /** <ide> public function testExecuteWithBinding() <ide> <ide> $messages = Log::engine('queries')->read(); <ide> $this->assertCount(2, $messages); <del> $this->assertRegExp("/^debug connection=test duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2013-01-01'$/", $messages[0]); <del> $this->assertRegExp("/^debug connection=test duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2014-01-01'$/", $messages[1]); <add> $this->assertMatchesRegularExpression("/^debug connection=test duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2013-01-01'$/", $messages[0]); <add> $this->assertMatchesRegularExpression("/^debug connection=test duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2014-01-01'$/", $messages[1]); <ide> } <ide> <ide> /** <ide> public function testExecuteWithError() <ide> <ide> $messages = Log::engine('queries')->read(); <ide> $this->assertCount(1, $messages); <del> $this->assertRegExp("/^debug connection=test duration=\d+ rows=0 SELECT bar FROM foo$/", $messages[0]); <add> $this->assertMatchesRegularExpression("/^debug connection=test duration=\d+ rows=0 SELECT bar FROM foo$/", $messages[0]); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/QueryTest.php <ide> public function assertQuotedQuery($pattern, $query, $optional = false) <ide> } <ide> $pattern = str_replace('<', '[`"\[]' . $optional, $pattern); <ide> $pattern = str_replace('>', '[`"\]]' . $optional, $pattern); <del> $this->assertRegExp('#' . $pattern . '#', $query); <add> $this->assertMatchesRegularExpression('#' . $pattern . '#', $query); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/TableSchemaTest.php <ide> public function assertQuotedQuery($pattern, $query, $optional = false) <ide> } <ide> $pattern = str_replace('<', '[`"\[]' . $optional, $pattern); <ide> $pattern = str_replace('>', '[`"\]]' . $optional, $pattern); <del> $this->assertRegExp('#' . $pattern . '#', $query); <add> $this->assertMatchesRegularExpression('#' . $pattern . '#', $query); <ide> } <ide> } <ide><path>tests/TestCase/Database/Type/UuidTypeTest.php <ide> public function testNewId() <ide> $two = $this->type->newId(); <ide> <ide> $this->assertNotEquals($one, $two, 'Should be different values'); <del> $this->assertRegExp('/^[a-f0-9-]+$/', $one, 'Should quack like a uuid'); <del> $this->assertRegExp('/^[a-f0-9-]+$/', $two, 'Should quack like a uuid'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9-]+$/', $one, 'Should quack like a uuid'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9-]+$/', $two, 'Should quack like a uuid'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Error/DebuggerTest.php <ide> public function testExcerpt() <ide> $result = Debugger::excerpt(__FILE__, __LINE__ - 1, 2); <ide> $this->assertIsArray($result); <ide> $this->assertCount(5, $result); <del> $this->assertRegExp('/function(.+)testExcerpt/', $result[1]); <add> $this->assertMatchesRegularExpression('/function(.+)testExcerpt/', $result[1]); <ide> <ide> $result = Debugger::excerpt(__FILE__, 2, 2); <ide> $this->assertIsArray($result); <ide> $this->assertCount(4, $result); <ide> <ide> $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not highlight php code'); <ide> $pattern = '/<code>.*?<span style\="color\: \#\d+">.*?&lt;\?php/'; <del> $this->assertRegExp($pattern, $result[0]); <add> $this->assertMatchesRegularExpression($pattern, $result[0]); <ide> <ide> $result = Debugger::excerpt(__FILE__, 11, 2); <ide> $this->assertCount(5, $result); <ide> <ide> $pattern = '/<span style\="color\: \#\d{6}">.*?<\/span>/'; <del> $this->assertRegExp($pattern, $result[0]); <add> $this->assertMatchesRegularExpression($pattern, $result[0]); <ide> <ide> $return = Debugger::excerpt('[internal]', 2, 2); <ide> $this->assertEmpty($return); <ide> public function testOutputErrorLineHighlight() <ide> $debugger->outputError($data); <ide> $result = ob_get_clean(); <ide> <del> $this->assertRegExp('#^\<span class\="code\-highlight"\>.*outputError.*\</span\>$#m', $result); <add> $this->assertMatchesRegularExpression('#^\<span class\="code\-highlight"\>.*outputError.*\</span\>$#m', $result); <ide> } <ide> <ide> /** <ide> public function testAddFormat() <ide> Debugger::setOutputFormat('js'); <ide> <ide> $result = Debugger::trace(); <del> $this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result); <ide> <ide> Debugger::addFormat('xml', [ <ide> 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' . <ide> public function testGetInstance() <ide> public function testExportVarRecursion() <ide> { <ide> $output = Debugger::exportVar($GLOBALS); <del> $this->assertRegExp("/'GLOBALS' => \[\s+'' \=\> \[maximum depth reached\]/", $output); <add> $this->assertMatchesRegularExpression("/'GLOBALS' => \[\s+'' \=\> \[maximum depth reached\]/", $output); <ide> } <ide> <ide> /** <ide> public function testExportVarRecursion() <ide> public function testTraceExclude() <ide> { <ide> $result = Debugger::trace(); <del> $this->assertRegExp('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result); <add> $this->assertMatchesRegularExpression('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result); <ide> <ide> $result = Debugger::trace([ <ide> 'exclude' => ['Cake\Test\TestCase\Error\DebuggerTest::testTraceExclude'], <ide> ]); <del> $this->assertNotRegExp('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result); <add> $this->assertDoesNotMatchRegularExpression('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> public function testHandleErrorDebugOn() <ide> $wrong = $wrong + 1; <ide> $result = ob_get_clean(); <ide> <del> $this->assertRegExp('/<pre class="cake-error">/', $result); <add> $this->assertMatchesRegularExpression('/<pre class="cake-error">/', $result); <ide> if (version_compare(PHP_VERSION, '8.0.0-dev', '<')) { <del> $this->assertRegExp('/<b>Notice<\/b>/', $result); <del> $this->assertRegExp('/variable:\s+wrong/', $result); <add> $this->assertMatchesRegularExpression('/<b>Notice<\/b>/', $result); <add> $this->assertMatchesRegularExpression('/variable:\s+wrong/', $result); <ide> } else { <del> $this->assertRegExp('/<b>Warning<\/b>/', $result); <del> $this->assertRegExp('/variable \$wrong/', $result); <add> $this->assertMatchesRegularExpression('/<b>Warning<\/b>/', $result); <add> $this->assertMatchesRegularExpression('/variable \$wrong/', $result); <ide> } <ide> $this->assertStringContainsString( <ide> 'ErrorHandlerTest.php, line ' . (__LINE__ - 12), <ide> public function testHandleErrorDebugOff() <ide> $out = $out + 1; <ide> <ide> $messages = $this->logger->read(); <del> $this->assertRegExp('/^(notice|debug|warning)/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^(notice|debug|warning)/', $messages[0]); <ide> <ide> if (version_compare(PHP_VERSION, '8.0.0-dev', '<')) { <ide> $this->assertStringContainsString( <ide> public function testHandleErrorLoggingTrace() <ide> $out = $out + 1; <ide> <ide> $messages = $this->logger->read(); <del> $this->assertRegExp('/^(notice|debug|warning)/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^(notice|debug|warning)/', $messages[0]); <ide> if (version_compare(PHP_VERSION, '8.0.0-dev', '<')) { <ide> $this->assertStringContainsString( <ide> 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ - 6) . ']', <ide> public function testHandleExceptionLog() <ide> $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.'); <ide> <ide> $messages = $this->logger->read(); <del> $this->assertRegExp('/^error/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^error/', $messages[0]); <ide> $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[0]); <ide> $this->assertStringContainsString( <ide> str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'), <ide> public function testHandleExceptionLog() <ide> $errorHandler->handleException($error); <ide> <ide> $messages = $this->logger->read(); <del> $this->assertRegExp('/^error/', $messages[1]); <add> $this->assertMatchesRegularExpression('/^error/', $messages[1]); <ide> $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[1]); <ide> $this->assertStringNotContainsString( <ide> str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'), <ide> public function testHandleExceptionLogAttributes() <ide> $errorHandler->handleException($error); <ide> <ide> $messages = $this->logger->read(); <del> $this->assertRegExp('/^error/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^error/', $messages[0]); <ide> $this->assertStringContainsString( <ide> '[Cake\Http\Exception\MissingControllerException] Controller class Derp could not be found.', <ide> $messages[0] <ide> public function testHandleExceptionLogSkipping() <ide> <ide> $messages = $this->logger->read(); <ide> $this->assertCount(1, $messages); <del> $this->assertRegExp('/^error/', $messages[0]); <add> $this->assertMatchesRegularExpression('/^error/', $messages[0]); <ide> $this->assertStringContainsString( <ide> '[Cake\Http\Exception\ForbiddenException] Fooled you!', <ide> $messages[0] <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> public function testSubclassConvertingFrameworkErrors() <ide> <ide> $result = $ExceptionRenderer->render(); <ide> <del> $this->assertRegExp( <add> $this->assertMatchesRegularExpression( <ide> '/Not Found/', <ide> (string)$result->getBody(), <ide> 'Method declared in error handler not converted to error400. %s' <ide> public function testError400() <ide> <ide> $this->assertEquals(404, $response->getStatusCode()); <ide> $this->assertStringContainsString('<h2>Custom message</h2>', $result); <del> $this->assertRegExp("/<strong>'.*?\/posts\/view\/1000'<\/strong>/", $result); <add> $this->assertMatchesRegularExpression("/<strong>'.*?\/posts\/view\/1000'<\/strong>/", $result); <ide> } <ide> <ide> /** <ide> public function testCakeExceptionHandling($exception, $patterns, $code) <ide> $this->assertEquals($code, $response->getStatusCode()); <ide> $body = (string)$response->getBody(); <ide> foreach ($patterns as $pattern) { <del> $this->assertRegExp($pattern, $body); <add> $this->assertMatchesRegularExpression($pattern, $body); <ide> } <ide> } <ide> <ide><path>tests/TestCase/Filesystem/FileTest.php <ide> public function testWrite() <ide> } <ide> <ide> $TmpFile = new File($tmpFile); <del> $this->assertFileNotExists($tmpFile); <add> $this->assertFileDoesNotExist($tmpFile); <ide> $this->assertNull($TmpFile->handle); <ide> <ide> $testData = ['CakePHP\'s', ' test suite', ' was here ...', '']; <ide> public function testAppend() <ide> } <ide> <ide> $TmpFile = new File($tmpFile); <del> $this->assertFileNotExists($tmpFile); <add> $this->assertFileDoesNotExist($tmpFile); <ide> <ide> $fragments = ['CakePHP\'s', ' test suite', ' was here ...']; <ide> $data = null; <ide> public function testDelete() <ide> $file->read(); <ide> $this->assertTrue($file->delete()); <ide> $this->assertFalse($file->exists()); <del> $this->assertFileNotExists($tmpFile); <add> $this->assertFileDoesNotExist($tmpFile); <ide> <ide> $TmpFile = new File('/this/does/not/exist'); <ide> $result = $TmpFile->delete(); <ide><path>tests/TestCase/Filesystem/FolderTest.php <ide> public function testCopyWithOverwrite() <ide> <ide> $this->assertFileExists($folderThree . DS . 'file1.php'); <ide> $this->assertFileExists($folderThree . DS . 'file2.php'); <del> $this->assertFileNotExists($folderThree . DS . 'folderA' . DS . 'fileA.php'); <add> $this->assertFileDoesNotExist($folderThree . DS . 'folderA' . DS . 'fileA.php'); <ide> $this->assertFileExists($folderThree . DS . 'folderB' . DS . 'fileB.php'); <ide> } <ide> <ide> public function testCopyWithoutRecursive() <ide> $Folder->copy($folderThree, ['recursive' => false]); <ide> <ide> $this->assertFileExists($folderThree . DS . 'file1.php'); <del> $this->assertDirectoryNotExists($folderThree . DS . 'folderA'); <del> $this->assertFileNotExists($folderThree . DS . 'folderA' . DS . 'fileA.php'); <add> $this->assertDirectoryDoesNotExist($folderThree . DS . 'folderA'); <add> $this->assertFileDoesNotExist($folderThree . DS . 'folderA' . DS . 'fileA.php'); <ide> } <ide> <ide> /** <ide> public function testMove() <ide> $this->assertFileExists($folderTwo . '/file1.php'); <ide> $this->assertDirectoryExists($folderTwo . '/folderB'); <ide> $this->assertFileExists($folderTwo . '/folderB/fileB.php'); <del> $this->assertFileNotExists($fileOne); <add> $this->assertFileDoesNotExist($fileOne); <ide> $this->assertFileExists($folderTwo . '/folderA'); <del> $this->assertFileNotExists($folderOneA); <del> $this->assertFileNotExists($fileOneA); <add> $this->assertFileDoesNotExist($folderOneA); <add> $this->assertFileDoesNotExist($fileOneA); <ide> <ide> $Folder = new Folder($folderTwo); <ide> $Folder->delete(); <ide> public function testMove() <ide> $this->assertFileExists($folderTwo . '/file1.php'); <ide> $this->assertDirectoryExists($folderTwo . '/folderA'); <ide> $this->assertFileExists($folderTwo . '/folderA/fileA.php'); <del> $this->assertFileNotExists($fileOne); <del> $this->assertFileNotExists($folderOneA); <del> $this->assertFileNotExists($fileOneA); <add> $this->assertFileDoesNotExist($fileOne); <add> $this->assertFileDoesNotExist($folderOneA); <add> $this->assertFileDoesNotExist($fileOneA); <ide> <ide> $Folder = new Folder($folderTwo); <ide> $Folder->delete(); <ide> public function testMove() <ide> $this->assertTrue($result); <ide> $this->assertFileExists($folderTwo . '/file1.php'); <ide> $this->assertStringEqualsFile($folderTwoB . '/fileB.php', ''); <del> $this->assertFileNotExists($fileOne); <del> $this->assertFileNotExists($folderOneA); <del> $this->assertFileNotExists($fileOneA); <add> $this->assertFileDoesNotExist($fileOne); <add> $this->assertFileDoesNotExist($folderOneA); <add> $this->assertFileDoesNotExist($fileOneA); <ide> <ide> $Folder = new Folder($path); <ide> $Folder->delete(); <ide> public function testMoveWithSkip() <ide> $this->assertFileExists($folderTwo . '/file1.php'); <ide> $this->assertDirectoryExists($folderTwo . '/folderB'); <ide> $this->assertFileExists($folderTwoB . '/fileB.php'); <del> $this->assertFileNotExists($fileOne); <del> $this->assertFileNotExists($folderOneA); <del> $this->assertFileNotExists($fileOneA); <add> $this->assertFileDoesNotExist($fileOne); <add> $this->assertFileDoesNotExist($folderOneA); <add> $this->assertFileDoesNotExist($fileOneA); <ide> <ide> $Folder = new Folder($folderTwo); <ide> $Folder->delete(); <ide> public function testMoveWithSkip() <ide> $this->assertFileExists($folderTwo . '/file1.php'); <ide> $this->assertDirectoryExists($folderTwo . '/folderA'); <ide> $this->assertFileExists($folderTwo . '/folderA/fileA.php'); <del> $this->assertFileNotExists($fileOne); <del> $this->assertFileNotExists($folderOneA); <del> $this->assertFileNotExists($fileOneA); <add> $this->assertFileDoesNotExist($fileOne); <add> $this->assertFileDoesNotExist($folderOneA); <add> $this->assertFileDoesNotExist($fileOneA); <ide> <ide> $Folder = new Folder($folderTwo); <ide> $Folder->delete(); <ide> public function testMoveWithSkip() <ide> $this->assertTrue($result); <ide> $this->assertFileExists($folderTwo . '/file1.php'); <ide> $this->assertStringEqualsFile($folderTwoB . '/fileB.php', 'untouched'); <del> $this->assertFileNotExists($fileOne); <del> $this->assertFileNotExists($folderOneA); <del> $this->assertFileNotExists($fileOneA); <add> $this->assertFileDoesNotExist($fileOne); <add> $this->assertFileDoesNotExist($folderOneA); <add> $this->assertFileDoesNotExist($fileOneA); <ide> <ide> $Folder = new Folder($path); <ide> $Folder->delete(); <ide> public function testMoveWithoutRecursive() <ide> $result = $Folder->move($folderTwo, ['recursive' => false]); <ide> $this->assertTrue($result); <ide> $this->assertFileExists($folderTwo . '/file1.php'); <del> $this->assertDirectoryNotExists($folderTwo . '/folderA'); <del> $this->assertFileNotExists($folderTwo . '/folderA/fileA.php'); <add> $this->assertDirectoryDoesNotExist($folderTwo . '/folderA'); <add> $this->assertFileDoesNotExist($folderTwo . '/folderA/fileA.php'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/Client/Auth/DigestTest.php <ide> public function testQop() <ide> <ide> $this->assertStringContainsString('qop="auth"', $result); <ide> $this->assertStringContainsString('nc=00000001', $result); <del> $this->assertRegexp('/cnonce="[a-z0-9]+"/', $result); <add> $this->assertMatchesRegularExpression('/cnonce="[a-z0-9]+"/', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/Client/FormDataTest.php <ide> public function testBoundary() <ide> { <ide> $data = new FormData(); <ide> $result = $data->boundary(); <del> $this->assertRegExp('/^[a-f0-9]{32}$/', $result); <add> $this->assertMatchesRegularExpression('/^[a-f0-9]{32}$/', $result); <ide> <ide> $result2 = $data->boundary(); <ide> $this->assertEquals($result, $result2); <ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php <ide> public function testSettingCookie() <ide> <ide> $cookie = $response->getCookie('csrfToken'); <ide> $this->assertNotEmpty($cookie, 'Should set a token.'); <del> $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.'); <ide> $this->assertSame(0, $cookie['expires'], 'session duration.'); <ide> $this->assertSame('/dir/', $cookie['path'], 'session path.'); <ide> $this->assertEquals($cookie['value'], $updatedRequest->getAttribute('csrfToken')); <ide> public function testConfigurationCookieCreate() <ide> $this->assertEmpty($response->getCookie('csrfToken')); <ide> $cookie = $response->getCookie('token'); <ide> $this->assertNotEmpty($cookie, 'Should set a token.'); <del> $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.'); <ide> $this->assertWithinRange(strtotime('+1 hour'), $cookie['expires'], 1, 'session duration.'); <ide> $this->assertSame('/dir/', $cookie['path'], 'session path.'); <ide> $this->assertTrue($cookie['secure'], 'cookie security flag missing'); <ide><path>tests/TestCase/Http/Middleware/SessionCsrfProtectionMiddlewareTest.php <ide> public function testSettingTokenInSession() <ide> $this->assertInstanceOf(Response::class, $response); <ide> $token = $request->getSession()->read('csrfToken'); <ide> $this->assertNotEmpty($token, 'Should set a token.'); <del> $this->assertRegExp('/^[a-f0-9]+$/', $token, 'Should look like a hash.'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9]+$/', $token, 'Should look like a hash.'); <ide> } <ide> <ide> /** <ide> public function testConfigurationCookieCreate() <ide> $this->assertEmpty($session->read('csrfToken')); <ide> $token = $session->read('csrf'); <ide> $this->assertNotEmpty($token, 'Should set a token.'); <del> $this->assertRegExp('/^[a-f0-9]+$/', $token, 'Should look like a hash.'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9]+$/', $token, 'Should look like a hash.'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/I18n/DateTest.php <ide> public function testDateAgoInWordsWithFormat($class) <ide> <ide> $date = new $class('+2 weeks +2 days'); <ide> $result = $date->timeAgoInWords(['format' => 'yyyy-MM-dd']); <del> $this->assertRegExp('/^2 weeks, [1|2] day(s)?$/', $result); <add> $this->assertMatchesRegularExpression('/^2 weeks, [1|2] day(s)?$/', $result); <ide> <ide> $date = new $class('+2 months +2 days'); <ide> $result = $date->timeAgoInWords(['end' => '1 month', 'format' => 'yyyy-MM-dd']); <ide><path>tests/TestCase/I18n/NumberTest.php <ide> public function testCurrency() <ide> // The following tests use regexp because whitespace used <ide> // is inconsistent between *nix & windows. <ide> $expected = '/^EUR\W+100\W+100\W+100,00$/'; <del> $this->assertRegExp($expected, $result); <add> $this->assertMatchesRegularExpression($expected, $result); <ide> <ide> $options = ['locale' => 'fr_FR', 'pattern' => '#,###.00 ¤¤']; <ide> $result = $this->Number->currency($value, 'EUR', $options); <ide> $expected = '/^100\W+100\W+100,00\W+EUR$/'; <del> $this->assertRegExp($expected, $result); <add> $this->assertMatchesRegularExpression($expected, $result); <ide> <ide> $options = ['locale' => 'fr_FR', 'pattern' => '#,###.00;(¤#,###.00)']; <ide> $result = $this->Number->currency(-1235.03, 'EUR', $options); <ide> $expected = '/^\(€1\W+235,03\)$/'; <del> $this->assertRegExp($expected, $result); <add> $this->assertMatchesRegularExpression($expected, $result); <ide> <ide> $result = $this->Number->currency(0.5, 'USD', ['locale' => 'en_US', 'fractionSymbol' => 'c']); <ide> $expected = '50c'; <ide><path>tests/TestCase/I18n/TimeTest.php <ide> public function testTimeAgoInWordsWithFormat($class) <ide> <ide> $time = new $class('+2 weeks +2 days'); <ide> $result = $time->timeAgoInWords(['format' => 'yyyy-MM-dd']); <del> $this->assertRegExp('/^2 weeks, [1|2] day(s)?$/', $result); <add> $this->assertMatchesRegularExpression('/^2 weeks, [1|2] day(s)?$/', $result); <ide> <ide> $time = new $class('+2 months +2 days'); <ide> $result = $time->timeAgoInWords(['end' => '1 month', 'format' => 'yyyy-MM-dd']); <ide> public function testGetSetDefaultLocale($class) <ide> public function testDefaultLocaleEffectsFormatting($class) <ide> { <ide> $result = $class::parseDate('12/03/2015'); <del> $this->assertRegExp('/Dec 3, 2015[ ,]+12:00 AM/', $result->nice()); <add> $this->assertMatchesRegularExpression('/Dec 3, 2015[ ,]+12:00 AM/', $result->nice()); <ide> <ide> $class::setDefaultLocale('fr-FR'); <ide> <ide> $result = $class::parseDate('12/03/2015'); <del> $this->assertRegexp('/12 mars 2015 (?:à )?00:00/', $result->nice()); <add> $this->assertMatchesRegularExpression('/12 mars 2015 (?:à )?00:00/', $result->nice()); <ide> <ide> $expected = 'Y-m-d'; <ide> $result = $class::parseDate('12/03/2015'); <ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php <ide> public function testlogToFileStream() <ide> $fh = fopen($filename, 'r'); <ide> $line = fgets($fh); <ide> $this->assertStringContainsString('Error: oh noes', $line); <del> $this->assertRegExp('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: oh noes/', $line); <add> $this->assertMatchesRegularExpression('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: oh noes/', $line); <ide> } <ide> <ide> /** <ide> public function testDateFormat() <ide> $log->log('error', 'oh noes'); <ide> $fh = fopen($filename, 'r'); <ide> $line = fgets($fh); <del> $this->assertRegExp('/2[0-9]{3}-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+\+\d{2}:\d{2} Error: oh noes/', $line); <add> $this->assertMatchesRegularExpression('/2[0-9]{3}-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+\+\d{2}:\d{2} Error: oh noes/', $line); <ide> } <ide> } <ide><path>tests/TestCase/Log/Engine/FileLogTest.php <ide> public function testLogFileWriting() <ide> $this->assertFileExists(LOGS . 'error.log'); <ide> <ide> $result = file_get_contents(LOGS . 'error.log'); <del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result); <add> $this->assertMatchesRegularExpression('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result); <ide> <ide> $log->log('debug', 'Test warning'); <ide> $this->assertFileExists(LOGS . 'debug.log'); <ide> <ide> $result = file_get_contents(LOGS . 'debug.log'); <del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test warning/', $result); <add> $this->assertMatchesRegularExpression('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test warning/', $result); <ide> <ide> $log->log('random', 'Test warning'); <ide> $this->assertFileExists(LOGS . 'random.log'); <ide> <ide> $result = file_get_contents(LOGS . 'random.log'); <del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Random: Test warning/', $result); <add> $this->assertMatchesRegularExpression('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Random: Test warning/', $result); <ide> } <ide> <ide> /** <ide> public function testRotation() <ide> $this->assertFileExists($path . 'error.log'); <ide> <ide> $result = file_get_contents($path . 'error.log'); <del> $this->assertRegExp('/Warning: Test warning one/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning one/', $result); <ide> $this->assertCount(0, glob($path . 'error.log.*')); <ide> <ide> clearstatcache(); <ide> public function testRotation() <ide> $this->assertCount(1, $files); <ide> <ide> $result = file_get_contents($files[0]); <del> $this->assertRegExp('/this text is under 35 bytes/', $result); <del> $this->assertRegExp('/Warning: Test warning one/', $result); <add> $this->assertMatchesRegularExpression('/this text is under 35 bytes/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning one/', $result); <ide> <ide> sleep(1); <ide> clearstatcache(); <ide> $log->log('warning', 'Test warning third'); <ide> <ide> $result = file_get_contents($path . 'error.log'); <del> $this->assertRegExp('/Warning: Test warning third/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning third/', $result); <ide> <ide> $files = glob($path . 'error.log.*'); <ide> $this->assertCount(2, $files); <ide> <ide> $result = file_get_contents($files[0]); <del> $this->assertRegExp('/this text is under 35 bytes/', $result); <add> $this->assertMatchesRegularExpression('/this text is under 35 bytes/', $result); <ide> <ide> $result = file_get_contents($files[1]); <del> $this->assertRegExp('/Warning: Test warning second/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning second/', $result); <ide> <ide> file_put_contents($path . 'error.log.0000000000', "The oldest log file with over 35 bytes.\n"); <ide> <ide> public function testRotation() <ide> $this->assertCount(2, $files); <ide> <ide> $result = file_get_contents($path . 'error.log'); <del> $this->assertRegExp('/Warning: Test warning fourth/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning fourth/', $result); <ide> <ide> $result = file_get_contents(array_pop($files)); <del> $this->assertRegExp('/Warning: Test warning third/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning third/', $result); <ide> <ide> $result = file_get_contents(array_pop($files)); <del> $this->assertRegExp('/Warning: Test warning second/', $result); <add> $this->assertMatchesRegularExpression('/Warning: Test warning second/', $result); <ide> <ide> file_put_contents($path . 'debug.log', "this text is just greater than 35 bytes\n"); <ide> $log = new FileLog([ <ide> public function testRotation() <ide> $this->assertFileExists($path . 'debug.log'); <ide> <ide> $result = file_get_contents($path . 'debug.log'); <del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test debug/', $result); <add> $this->assertMatchesRegularExpression('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test debug/', $result); <ide> $this->assertFalse(strstr($result, 'greater than 5 bytes')); <ide> $this->assertCount(0, glob($path . 'debug.log.*')); <ide> } <ide> public function testDateFormat() <ide> $log->log('warning', 'Test warning'); <ide> <ide> $result = file_get_contents(LOGS . 'error.log'); <del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+\+\d{2}:\d{2} Warning: Test warning/', $result); <add> $this->assertMatchesRegularExpression('/^2[0-9]{3}-[0-9]+-[0-9]+T[0-9]+:[0-9]+:[0-9]+\+\d{2}:\d{2} Warning: Test warning/', $result); <ide> } <ide> } <ide><path>tests/TestCase/Log/LogTest.php <ide> public function testLogFileWriting() <ide> Log::write(LOG_WARNING, 'Test warning 1'); <ide> Log::write(LOG_WARNING, 'Test warning 2'); <ide> $result = file_get_contents(LOGS . 'error.log'); <del> $this->assertRegExp('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1/', $result); <del> $this->assertRegExp('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 2$/', $result); <add> $this->assertMatchesRegularExpression('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1/', $result); <add> $this->assertMatchesRegularExpression('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 2$/', $result); <ide> unlink(LOGS . 'error.log'); <ide> } <ide> <ide> public function testSelectiveLoggingByLevel() <ide> Log::write('warning', $testMessage); <ide> <ide> $this->assertFileExists(LOGS . 'eggs.log'); <del> $this->assertFileNotExists(LOGS . 'spam.log'); <add> $this->assertFileDoesNotExist(LOGS . 'spam.log'); <ide> <ide> Log::write('debug', $testMessage); <ide> $this->assertFileExists(LOGS . 'spam.log'); <ide> public function testSelectiveLoggingByLevelUsingTypes() <ide> Log::write('warning', $testMessage); <ide> <ide> $this->assertFileExists(LOGS . 'eggs.log'); <del> $this->assertFileNotExists(LOGS . 'spam.log'); <add> $this->assertFileDoesNotExist(LOGS . 'spam.log'); <ide> <ide> Log::write('debug', $testMessage); <ide> $this->assertFileExists(LOGS . 'spam.log'); <ide> public function testScopedLogging() <ide> ]); <ide> <ide> Log::write('debug', 'debug message', 'transactions'); <del> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertFileDoesNotExist(LOGS . 'error.log'); <ide> $this->assertFileExists(LOGS . 'shops.log'); <ide> $this->assertFileExists(LOGS . 'debug.log'); <ide> <ide> public function testScopedLogging() <ide> Log::write('warning', 'warning message', 'orders'); <ide> $this->assertFileExists(LOGS . 'error.log'); <ide> $this->assertFileExists(LOGS . 'shops.log'); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::write('error', 'error message', ['scope' => 'orders']); <ide> $this->assertFileExists(LOGS . 'error.log'); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <del> $this->assertFileNotExists(LOGS . 'shops.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'shops.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> public function testScopedLoggingStrict() <ide> ]); <ide> <ide> Log::write('debug', 'debug message'); <del> $this->assertFileNotExists(LOGS . 'shops.log'); <add> $this->assertFileDoesNotExist(LOGS . 'shops.log'); <ide> $this->assertFileExists(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::write('debug', 'debug message', 'orders'); <ide> $this->assertFileExists(LOGS . 'shops.log'); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> public function testConvenienceScopedLogging() <ide> ]); <ide> <ide> Log::info('info message', 'transactions'); <del> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertFileDoesNotExist(LOGS . 'error.log'); <ide> $this->assertFileExists(LOGS . 'shops.log'); <ide> $this->assertFileExists(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::error('error message', 'orders'); <ide> $this->assertFileExists(LOGS . 'error.log'); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <del> $this->assertFileNotExists(LOGS . 'shops.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'shops.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::warning('warning message', 'orders'); <ide> $this->assertFileExists(LOGS . 'error.log'); <ide> $this->assertFileExists(LOGS . 'shops.log'); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> public function testScopedLoggingExclusive() <ide> ]); <ide> <ide> Log::write('debug', 'transactions message', 'transactions'); <del> $this->assertFileNotExists(LOGS . 'eggs.log'); <add> $this->assertFileDoesNotExist(LOGS . 'eggs.log'); <ide> $this->assertFileExists(LOGS . 'shops.log'); <ide> <ide> $this->_deleteLogs(); <ide> <ide> Log::write('debug', 'eggs message', ['scope' => ['eggs']]); <ide> $this->assertFileExists(LOGS . 'eggs.log'); <del> $this->assertFileNotExists(LOGS . 'shops.log'); <add> $this->assertFileDoesNotExist(LOGS . 'shops.log'); <ide> } <ide> <ide> /** <ide> public function testConvenienceMethods() <ide> $testMessage = 'emergency message'; <ide> Log::emergency($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <del> $this->assertRegExp('/(Emergency|Critical): ' . $testMessage . '/', $contents); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertMatchesRegularExpression('/(Emergency|Critical): ' . $testMessage . '/', $contents); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'alert message'; <ide> Log::alert($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <del> $this->assertRegExp('/(Alert|Critical): ' . $testMessage . '/', $contents); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertMatchesRegularExpression('/(Alert|Critical): ' . $testMessage . '/', $contents); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'critical message'; <ide> Log::critical($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertStringContainsString('Critical: ' . $testMessage, $contents); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'error message'; <ide> Log::error($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertStringContainsString('Error: ' . $testMessage, $contents); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'warning message'; <ide> Log::warning($testMessage); <ide> $contents = file_get_contents(LOGS . 'error.log'); <ide> $this->assertStringContainsString('Warning: ' . $testMessage, $contents); <del> $this->assertFileNotExists(LOGS . 'debug.log'); <add> $this->assertFileDoesNotExist(LOGS . 'debug.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'notice message'; <ide> Log::notice($testMessage); <ide> $contents = file_get_contents(LOGS . 'debug.log'); <del> $this->assertRegExp('/(Notice|Debug): ' . $testMessage . '/', $contents); <del> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertMatchesRegularExpression('/(Notice|Debug): ' . $testMessage . '/', $contents); <add> $this->assertFileDoesNotExist(LOGS . 'error.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'info message'; <ide> Log::info($testMessage); <ide> $contents = file_get_contents(LOGS . 'debug.log'); <del> $this->assertRegExp('/(Info|Debug): ' . $testMessage . '/', $contents); <del> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertMatchesRegularExpression('/(Info|Debug): ' . $testMessage . '/', $contents); <add> $this->assertFileDoesNotExist(LOGS . 'error.log'); <ide> $this->_deleteLogs(); <ide> <ide> $testMessage = 'debug message'; <ide> Log::debug($testMessage); <ide> $contents = file_get_contents(LOGS . 'debug.log'); <ide> $this->assertStringContainsString('Debug: ' . $testMessage, $contents); <del> $this->assertFileNotExists(LOGS . 'error.log'); <add> $this->assertFileDoesNotExist(LOGS . 'error.log'); <ide> $this->_deleteLogs(); <ide> } <ide> <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testRenderWithLayoutAndAttachment() <ide> $this->assertNotEmpty($result); <ide> <ide> $result = $this->Email->getBoundary(); <del> $this->assertRegExp('/^[0-9a-f]{32}$/', $result); <add> $this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Mailer/MailerTest.php <ide> public function testRenderWithLayoutAndAttachment() <ide> $this->assertNotEmpty($result); <ide> <ide> $result = $this->mailer->getBoundary(); <del> $this->assertRegExp('/^[0-9a-f]{32}$/', $result); <add> $this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $result); <ide> } <ide> <ide> public function testSend() <ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testSelectLargeNumbers() <ide> ]) <ide> ->first(); <ide> $this->assertNotEmpty($out, 'Should get a record'); <del> $this->assertRegExp('/^0?\.1234567890123456789$/', $out->fraction); <add> $this->assertMatchesRegularExpression('/^0?\.1234567890123456789$/', $out->fraction); <ide> <ide> $small = 0.1234567890123456789; <ide> $entity = $table->newEntity(['fraction' => $small]); <ide> public function testSelectLargeNumbers() <ide> ->first(); <ide> $this->assertNotEmpty($out, 'Should get a record'); <ide> // There will be loss of precision if too large/small value is set as float instead of string. <del> $this->assertRegExp('/^0?\.123456789012350+$/', $out->fraction); <add> $this->assertMatchesRegularExpression('/^0?\.123456789012350+$/', $out->fraction); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/ORM/TableUuidTest.php <ide> public function testSaveNew($tableName) <ide> ]); <ide> $table = $this->getTableLocator()->get($tableName); <ide> $this->assertSame($entity, $table->save($entity)); <del> $this->assertRegExp('/^[a-f0-9-]{36}$/', $entity->id, 'Should be 36 characters'); <add> $this->assertMatchesRegularExpression('/^[a-f0-9-]{36}$/', $entity->id, 'Should be 36 characters'); <ide> <ide> $row = $table->find('all')->where(['id' => $entity->id])->first(); <ide> $row->id = strtolower($row->id); <ide><path>tests/TestCase/Routing/AssetTest.php <ide> public function testAssetTimestamp() <ide> Configure::write('Asset.timestamp', true); <ide> Configure::write('debug', true); <ide> $result = Asset::assetTimestamp(Configure::read('App.cssBaseUrl') . 'cake.generic.css'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> <ide> Configure::write('Asset.timestamp', 'force'); <ide> Configure::write('debug', false); <ide> $result = Asset::assetTimestamp(Configure::read('App.cssBaseUrl') . 'cake.generic.css'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> <ide> $result = Asset::assetTimestamp(Configure::read('App.cssBaseUrl') . 'cake.generic.css?someparam'); <ide> $this->assertEquals(Configure::read('App.cssBaseUrl') . 'cake.generic.css?someparam', $result); <ide> <ide> $request = Router::getRequest()->withAttribute('webroot', '/some/dir/'); <ide> Router::setRequest($request); <ide> $result = Asset::assetTimestamp('/some/dir/' . Configure::read('App.cssBaseUrl') . 'cake.generic.css'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testAssetUrlTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = Asset::url('cake.generic.css', ['pathPrefix' => Configure::read('App.cssBaseUrl')]); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testAssetTimestampPluginsAndThemes() <ide> $this->loadPlugins(['TestPlugin', 'Company/TestPluginThree']); <ide> <ide> $result = Asset::assetTimestamp('/test_plugin/css/test_plugin_asset.css'); <del> $this->assertRegExp('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin'); <add> $this->assertMatchesRegularExpression('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin'); <ide> <ide> $result = Asset::assetTimestamp('/company/test_plugin_three/css/company.css'); <del> $this->assertRegExp('#/company/test_plugin_three/css/company.css\?[0-9]+$#', $result, 'Missing timestamp plugin'); <add> $this->assertMatchesRegularExpression('#/company/test_plugin_three/css/company.css\?[0-9]+$#', $result, 'Missing timestamp plugin'); <ide> <ide> $result = Asset::assetTimestamp('/test_plugin/css/i_dont_exist.css'); <del> $this->assertRegExp('#/test_plugin/css/i_dont_exist.css$#', $result, 'No error on missing file'); <add> $this->assertMatchesRegularExpression('#/test_plugin/css/i_dont_exist.css$#', $result, 'No error on missing file'); <ide> <ide> $result = Asset::assetTimestamp('/test_theme/js/theme.js'); <del> $this->assertRegExp('#/test_theme/js/theme.js\?[0-9]+$#', $result, 'Missing timestamp theme'); <add> $this->assertMatchesRegularExpression('#/test_theme/js/theme.js\?[0-9]+$#', $result, 'Missing timestamp theme'); <ide> <ide> $result = Asset::assetTimestamp('/test_theme/js/non_existant.js'); <del> $this->assertRegExp('#/test_theme/js/non_existant.js$#', $result, 'No error on missing file'); <add> $this->assertMatchesRegularExpression('#/test_theme/js/non_existant.js$#', $result, 'No error on missing file'); <ide> } <ide> <ide> /** <ide> public function testScriptTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = Asset::scriptUrl('script.js'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.jsBaseUrl') . 'script.js?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.jsBaseUrl') . 'script.js?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testImageTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = Asset::imageUrl('cake.icon.png'); <del> $this->assertRegExp('/' . preg_quote('img/cake.icon.png?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote('img/cake.icon.png?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testCssTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = Asset::cssUrl('cake.generic'); <del> $this->assertRegExp('/' . preg_quote('css/cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote('css/cake.generic.css?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/Route/RouteTest.php <ide> public function testBasicRouteCompiling() <ide> $route = new Route('/:controller/:action', ['controller' => 'posts']); <ide> $result = $route->compile(); <ide> <del> $this->assertRegExp($result, '/posts/edit'); <del> $this->assertRegExp($result, '/posts/super_delete'); <del> $this->assertNotRegExp($result, '/posts'); <del> $this->assertNotRegExp($result, '/posts/super_delete/1'); <add> $this->assertMatchesRegularExpression($result, '/posts/edit'); <add> $this->assertMatchesRegularExpression($result, '/posts/super_delete'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/super_delete/1'); <ide> $this->assertSame($result, $route->compile()); <ide> <ide> $route = new Route('/posts/foo:id', ['controller' => 'posts', 'action' => 'view']); <ide> $result = $route->compile(); <ide> <del> $this->assertRegExp($result, '/posts/foo:1'); <del> $this->assertRegExp($result, '/posts/foo:param'); <del> $this->assertNotRegExp($result, '/posts'); <del> $this->assertNotRegExp($result, '/posts/'); <add> $this->assertMatchesRegularExpression($result, '/posts/foo:1'); <add> $this->assertMatchesRegularExpression($result, '/posts/foo:param'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/'); <ide> <ide> $this->assertEquals(['id'], $route->keys); <ide> <ide> $route = new Route('/:plugin/:controller/:action/*', ['plugin' => 'test_plugin', 'action' => 'index']); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/test_plugin/posts/index'); <del> $this->assertRegExp($result, '/test_plugin/posts/edit/5'); <del> $this->assertRegExp($result, '/test_plugin/posts/edit/5/name:value/nick:name'); <add> $this->assertMatchesRegularExpression($result, '/test_plugin/posts/index'); <add> $this->assertMatchesRegularExpression($result, '/test_plugin/posts/edit/5'); <add> $this->assertMatchesRegularExpression($result, '/test_plugin/posts/edit/5/name:value/nick:name'); <ide> } <ide> <ide> /** <ide> public function testRouteCompileSmallPlaceholders() <ide> ['id' => '\d+', 'x' => '\d+', 'y' => '\d+', 'pass' => ['id', 'x', 'y']] <ide> ); <ide> $pattern = $route->compile(); <del> $this->assertRegExp($pattern, '/fighters/123/move/8/42'); <add> $this->assertMatchesRegularExpression($pattern, '/fighters/123/move/8/42'); <ide> <ide> $result = $route->match([ <ide> 'controller' => 'Fighters', <ide> public function testRouteCompileBraces() <ide> ['controller' => 'Fighters', 'action' => 'move'], <ide> ['id' => '\d+', 'x' => '\d+', 'y' => '\d+', 'pass' => ['id', 'x', 'y']] <ide> ); <del> $this->assertRegExp($route->compile(), '/fighters/123/move/8/42'); <add> $this->assertMatchesRegularExpression($route->compile(), '/fighters/123/move/8/42'); <ide> <ide> $result = $route->match([ <ide> 'controller' => 'Fighters', <ide> public function testRouteCompileBraces() <ide> '/images/{id}/{x}x{y}', <ide> ['controller' => 'Images', 'action' => 'view'] <ide> ); <del> $this->assertRegExp($route->compile(), '/images/123/640x480'); <add> $this->assertMatchesRegularExpression($route->compile(), '/images/123/640x480'); <ide> <ide> $result = $route->match([ <ide> 'controller' => 'Images', <ide> public function testRouteCompileBracesVariableName() <ide> ['controller' => 'Fighters', 'action' => 'move'] <ide> ); <ide> $pattern = $route->compile(); <del> $this->assertNotRegExp($route->compile(), '/fighters/123', 'Placeholders must start with letter'); <add> $this->assertDoesNotMatchRegularExpression($route->compile(), '/fighters/123', 'Placeholders must start with letter'); <ide> <ide> $route = new Route('/fighters/{Id}', ['controller' => 'Fighters', 'action' => 'move']); <del> $this->assertRegExp($route->compile(), '/fighters/123'); <add> $this->assertMatchesRegularExpression($route->compile(), '/fighters/123'); <ide> <ide> $route = new Route('/fighters/{i_d}', ['controller' => 'Fighters', 'action' => 'move']); <del> $this->assertRegExp($route->compile(), '/fighters/123'); <add> $this->assertMatchesRegularExpression($route->compile(), '/fighters/123'); <ide> <ide> $route = new Route('/fighters/{id99}', ['controller' => 'Fighters', 'action' => 'move']); <del> $this->assertRegExp($route->compile(), '/fighters/123'); <add> $this->assertMatchesRegularExpression($route->compile(), '/fighters/123'); <ide> } <ide> <ide> /** <ide> public function testRouteCompileBracesInvalid() <ide> '/fighters/{ id }', <ide> ['controller' => 'Fighters', 'action' => 'move'] <ide> ); <del> $this->assertNotRegExp($route->compile(), '/fighters/123', 'no spaces in placeholder'); <add> $this->assertDoesNotMatchRegularExpression($route->compile(), '/fighters/123', 'no spaces in placeholder'); <ide> <ide> $route = new Route( <ide> '/fighters/{i d}', <ide> ['controller' => 'Fighters', 'action' => 'move'] <ide> ); <del> $this->assertNotRegExp($route->compile(), '/fighters/123', 'no spaces in placeholder'); <add> $this->assertDoesNotMatchRegularExpression($route->compile(), '/fighters/123', 'no spaces in placeholder'); <ide> } <ide> <ide> /** <ide> public function testRouteCompileMixedPlaceholders() <ide> ['controller' => 'Images', 'action' => 'open'] <ide> ); <ide> $pattern = $route->compile(); <del> $this->assertRegExp($pattern, '/images/{open/9', 'Need both {} to enable brace mode'); <add> $this->assertMatchesRegularExpression($pattern, '/images/{open/9', 'Need both {} to enable brace mode'); <ide> $result = $route->match([ <ide> 'controller' => 'Images', <ide> 'action' => 'open', <ide> public function testRouteCompileMixedPlaceholders() <ide> ['id' => '\d+', 'x' => '\d+', 'pass' => ['id', 'x']] <ide> ); <ide> $pattern = $route->compile(); <del> $this->assertRegExp($pattern, '/fighters/123/move/8/:y'); <add> $this->assertMatchesRegularExpression($pattern, '/fighters/123/move/8/:y'); <ide> <ide> $result = $route->match([ <ide> 'controller' => 'Fighters', <ide> public function testRouteParameterOverlap() <ide> { <ide> $route = new Route('/invoices/add/:idd/:id', ['controller' => 'invoices', 'action' => 'add']); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/invoices/add/1/3'); <add> $this->assertMatchesRegularExpression($result, '/invoices/add/1/3'); <ide> <ide> $route = new Route('/invoices/add/:id/:idd', ['controller' => 'invoices', 'action' => 'add']); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/invoices/add/1/3'); <add> $this->assertMatchesRegularExpression($result, '/invoices/add/1/3'); <ide> } <ide> <ide> /** <ide> public function testRouteCompilingWithParamPatterns() <ide> ['id' => Router::ID] <ide> ); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/posts/edit/1'); <del> $this->assertRegExp($result, '/posts/view/518098'); <del> $this->assertNotRegExp($result, '/posts/edit/name-of-post'); <del> $this->assertNotRegExp($result, '/posts/edit/4/other:param'); <add> $this->assertMatchesRegularExpression($result, '/posts/edit/1'); <add> $this->assertMatchesRegularExpression($result, '/posts/view/518098'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/edit/name-of-post'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/edit/4/other:param'); <ide> $this->assertEquals(['id', 'controller', 'action'], $route->keys); <ide> <ide> $route = new Route( <ide> public function testRouteCompilingWithParamPatterns() <ide> ['id' => Router::ID, 'lang' => '[a-z]{3}'] <ide> ); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/eng/posts/edit/1'); <del> $this->assertRegExp($result, '/cze/articles/view/1'); <del> $this->assertNotRegExp($result, '/language/articles/view/2'); <del> $this->assertNotRegExp($result, '/eng/articles/view/name-of-article'); <add> $this->assertMatchesRegularExpression($result, '/eng/posts/edit/1'); <add> $this->assertMatchesRegularExpression($result, '/cze/articles/view/1'); <add> $this->assertDoesNotMatchRegularExpression($result, '/language/articles/view/2'); <add> $this->assertDoesNotMatchRegularExpression($result, '/eng/articles/view/name-of-article'); <ide> $this->assertEquals(['lang', 'id', 'controller', 'action'], $route->keys); <ide> <ide> foreach ([':', '@', ';', '$', '-'] as $delim) { <ide> $route = new Route('/posts/:id' . $delim . ':title'); <ide> $result = $route->compile(); <ide> <del> $this->assertRegExp($result, '/posts/1' . $delim . 'name-of-article'); <del> $this->assertRegExp($result, '/posts/13244' . $delim . 'name-of_Article[]'); <del> $this->assertNotRegExp($result, '/posts/11!nameofarticle'); <del> $this->assertNotRegExp($result, '/posts/11'); <add> $this->assertMatchesRegularExpression($result, '/posts/1' . $delim . 'name-of-article'); <add> $this->assertMatchesRegularExpression($result, '/posts/13244' . $delim . 'name-of_Article[]'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/11!nameofarticle'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/11'); <ide> <ide> $this->assertEquals(['title', 'id'], $route->keys); <ide> } <ide> public function testRouteCompilingWithParamPatterns() <ide> ['id' => Router::ID, 'year' => Router::YEAR, 'title' => '[a-z-_]+'] <ide> ); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/posts/1:name-of-article/2009/'); <del> $this->assertRegExp($result, '/posts/13244:name-of-article/1999'); <del> $this->assertNotRegExp($result, '/posts/hey_now:nameofarticle'); <del> $this->assertNotRegExp($result, '/posts/:nameofarticle/2009'); <del> $this->assertNotRegExp($result, '/posts/:nameofarticle/01'); <add> $this->assertMatchesRegularExpression($result, '/posts/1:name-of-article/2009/'); <add> $this->assertMatchesRegularExpression($result, '/posts/13244:name-of-article/1999'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/hey_now:nameofarticle'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/:nameofarticle/2009'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/:nameofarticle/01'); <ide> $this->assertEquals(['year', 'title', 'id'], $route->keys); <ide> <ide> $route = new Route( <ide> public function testRouteCompilingWithParamPatterns() <ide> ['pass' => ['id', 'url_title'], 'id' => Router::ID] <ide> ); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/posts/some_title_for_article-(uuid:12534)/'); <del> $this->assertRegExp($result, '/posts/some_title_for_article-(uuid:12534)'); <del> $this->assertNotRegExp($result, '/posts/'); <del> $this->assertNotRegExp($result, '/posts/nameofarticle'); <del> $this->assertNotRegExp($result, '/posts/nameofarticle-12347'); <add> $this->assertMatchesRegularExpression($result, '/posts/some_title_for_article-(uuid:12534)/'); <add> $this->assertMatchesRegularExpression($result, '/posts/some_title_for_article-(uuid:12534)'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/nameofarticle'); <add> $this->assertDoesNotMatchRegularExpression($result, '/posts/nameofarticle-12347'); <ide> $this->assertEquals(['url_title', 'id'], $route->keys); <ide> } <ide> <ide> public function testCompileWithUnicodePatterns() <ide> ['pass' => ['slug'], 'multibytePattern' => false, 'slug' => '[A-zА-я\-\ ]+'] <ide> ); <ide> $result = $route->compile(); <del> $this->assertNotRegExp($result, '/test/bla-blan-тест'); <add> $this->assertDoesNotMatchRegularExpression($result, '/test/bla-blan-тест'); <ide> <ide> $route = new Route( <ide> '/test/:slug', <ide> ['controller' => 'Pages', 'action' => 'display'], <ide> ['pass' => ['slug'], 'multibytePattern' => true, 'slug' => '[A-zА-я\-\ ]+'] <ide> ); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/test/bla-blan-тест'); <add> $this->assertMatchesRegularExpression($result, '/test/bla-blan-тест'); <ide> } <ide> <ide> /** <ide> public function testComplexRouteCompilingAndParsing() <ide> ['year' => Router::YEAR, 'month' => Router::MONTH, 'day' => Router::DAY] <ide> ); <ide> $result = $route->compile(); <del> $this->assertRegExp($result, '/posts/08/01/2007/title-of-post'); <add> $this->assertMatchesRegularExpression($result, '/posts/08/01/2007/title-of-post'); <ide> $result = $route->parse('/posts/08/01/2007/title-of-post', 'GET'); <ide> <ide> $this->assertCount(7, $result); <ide> public function testComplexRouteCompilingAndParsing() <ide> ); <ide> $result = $route->compile(); <ide> <del> $this->assertRegExp($result, '/some_extra/page/this_is_the_slug'); <del> $this->assertRegExp($result, '/page/this_is_the_slug'); <add> $this->assertMatchesRegularExpression($result, '/some_extra/page/this_is_the_slug'); <add> $this->assertMatchesRegularExpression($result, '/page/this_is_the_slug'); <ide> $this->assertEquals(['slug', 'extra'], $route->keys); <ide> $this->assertEquals(['extra' => '[a-z1-9_]*', 'slug' => '[a-z1-9_]+', 'action' => 'view', '_ext' => []], $route->options); <ide> $expected = [ <ide> public function testComplexRouteCompilingAndParsing() <ide> $this->assertNull($route->parse('/chaw_test/wiki', 'GET')); <ide> <ide> $result = $route->compile(); <del> $this->assertNotRegExp($result, '/some_project/source'); <del> $this->assertRegExp($result, '/source/view'); <del> $this->assertRegExp($result, '/source/view/other/params'); <del> $this->assertNotRegExp($result, '/chaw_test/wiki'); <del> $this->assertNotRegExp($result, '/source/weird_action'); <add> $this->assertDoesNotMatchRegularExpression($result, '/some_project/source'); <add> $this->assertMatchesRegularExpression($result, '/source/view'); <add> $this->assertMatchesRegularExpression($result, '/source/view/other/params'); <add> $this->assertDoesNotMatchRegularExpression($result, '/chaw_test/wiki'); <add> $this->assertDoesNotMatchRegularExpression($result, '/source/weird_action'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function testBaseUrl() <ide> Router::scope('/', function (RouteBuilder $routes) { <ide> $routes->fallbacks(); <ide> }); <del> $this->assertRegExp('/^http(s)?:\/\//', Router::url('/', true)); <del> $this->assertRegExp('/^http(s)?:\/\//', Router::url(null, true)); <del> $this->assertRegExp('/^http(s)?:\/\//', Router::url(['controller' => 'test', '_full' => true])); <add> $this->assertMatchesRegularExpression('/^http(s)?:\/\//', Router::url('/', true)); <add> $this->assertMatchesRegularExpression('/^http(s)?:\/\//', Router::url(null, true)); <add> $this->assertMatchesRegularExpression('/^http(s)?:\/\//', Router::url(['controller' => 'test', '_full' => true])); <ide> } <ide> <ide> /** <ide> public function testReverseFull() <ide> 'url' => ['url' => 'eng/posts/view/1'], <ide> ]; <ide> $result = Router::reverse($params, true); <del> $this->assertRegExp('/^http(s)?:\/\//', $result); <add> $this->assertMatchesRegularExpression('/^http(s)?:\/\//', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php <ide> public function testExceptionOnLoad() <ide> } <ide> <ide> $this->assertNotNull($e); <del> $this->assertRegExp('/^Unable to insert fixtures for "Mock_TestCase_\w+" test case. message$/D', $e->getMessage()); <add> $this->assertMatchesRegularExpression('/^Unable to insert fixtures for "Mock_TestCase_\w+" test case. message$/D', $e->getMessage()); <ide> $this->assertInstanceOf('PDOException', $e->getPrevious()); <ide> } <ide> <ide> public function testExceptionOnLoadFixture($method, $expectedMessage) <ide> } <ide> <ide> $this->assertNotNull($e); <del> $this->assertRegExp($expectedMessage, $e->getMessage()); <add> $this->assertMatchesRegularExpression($expectedMessage, $e->getMessage()); <ide> $this->assertInstanceOf('PDOException', $e->getPrevious()); <ide> } <ide> <ide><path>tests/TestCase/Utility/SecurityTest.php <ide> public function testRandomBytes() <ide> $value = Security::randomBytes(64); <ide> $this->assertSame(64, strlen($value)); <ide> <del> $this->assertRegExp('/[^0-9a-f]/', $value, 'should return a binary string'); <add> $this->assertMatchesRegularExpression('/[^0-9a-f]/', $value, 'should return a binary string'); <ide> } <ide> <ide> /** <ide> public function testRandomString() <ide> $value = Security::randomString(); <ide> $this->assertSame(64, strlen($value)); <ide> <del> $this->assertRegExp('/^[0-9a-f]+$/', $value, 'should return a ASCII string'); <add> $this->assertMatchesRegularExpression('/^[0-9a-f]+$/', $value, 'should return a ASCII string'); <ide> } <ide> <ide> /** <ide> public function testInsecureRandomBytes() <ide> $value = Security::insecureRandomBytes(64); <ide> $this->assertSame(64, strlen($value)); <ide> <del> $this->assertRegExp('/[^0-9a-f]/', $value, 'should return a binary string'); <add> $this->assertMatchesRegularExpression('/[^0-9a-f]/', $value, 'should return a binary string'); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Utility/XmlTest.php <ide> public function testBuild() <ide> $this->assertSame('value', $obj->firstChild->nodeValue); <ide> <ide> $obj = Xml::build($xml, ['return' => 'domdocument', 'encoding' => '']); <del> $this->assertNotRegExp('/encoding/', $obj->saveXML()); <add> $this->assertDoesNotMatchRegularExpression('/encoding/', $obj->saveXML()); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testGetFormCreate() <ide> 'name' => 'password', 'type' => 'password', <ide> ]]; <ide> $this->assertHtml($expected, $result); <del> $this->assertNotRegExp('/<input[^<>]+[^id|name|type|value]=[^<>]*\/>$/', $result); <add> $this->assertDoesNotMatchRegularExpression('/<input[^<>]+[^id|name|type|value]=[^<>]*\/>$/', $result); <ide> <ide> $result = $this->Form->text('user_form'); <ide> $expected = ['input' => [ <ide> public function testButton() <ide> 'onClick' => "$('#postAddForm').ajaxSubmit({target: '#postTextUpload', url: '/posts/text'});return false;'", <ide> 'escape' => false, <ide> ]); <del> $this->assertNotRegExp('/\&039/', $result); <add> $this->assertDoesNotMatchRegularExpression('/\&039/', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function testScriptTimestamping() <ide> $timestamp = substr((string)strtotime('now'), 0, 8); <ide> <ide> $result = $this->Html->script('__cake_js_test', ['once' => false]); <del> $this->assertRegExp('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <add> $this->assertMatchesRegularExpression('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <ide> <ide> Configure::write('debug', false); <ide> Configure::write('Asset.timestamp', 'force'); <ide> $result = $this->Html->script('__cake_js_test', ['once' => false]); <del> $this->assertRegExp('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <add> $this->assertMatchesRegularExpression('/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <ide> unlink(WWW_ROOT . 'js/__cake_js_test.js'); <ide> Configure::write('Asset.timestamp', false); <ide> } <ide> public function testPluginScriptTimestamping() <ide> $timestamp = substr((string)strtotime('now'), 0, 8); <ide> <ide> $result = $this->Html->script('TestPlugin.__cake_js_test', ['once' => false]); <del> $this->assertRegExp('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <add> $this->assertMatchesRegularExpression('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <ide> <ide> Configure::write('debug', false); <ide> Configure::write('Asset.timestamp', 'force'); <ide> $result = $this->Html->script('TestPlugin.__cake_js_test', ['once' => false]); <del> $this->assertRegExp('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <add> $this->assertMatchesRegularExpression('/test_plugin\/js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"/', $result, 'Timestamp value not found %s'); <ide> unlink($pluginJsPath . DS . '__cake_js_test.js'); <ide> Configure::write('Asset.timestamp', false); <ide> <ide> public function testScript() <ide> $this->assertNull($result, 'Script returned upon duplicate inclusion %s'); <ide> <ide> $result = $this->Html->script(['foo', 'bar', 'baz']); <del> $this->assertNotRegExp('/foo.js/', $result); <add> $this->assertDoesNotMatchRegularExpression('/foo.js/', $result); <ide> <ide> $result = $this->Html->script('foo', ['once' => false]); <ide> $this->assertNotNull($result); <ide> public function testPluginScript() <ide> $this->assertNull($result, 'Script returned upon duplicate inclusion %s'); <ide> <ide> $result = $this->Html->script(['TestPlugin.foo', 'TestPlugin.bar', 'TestPlugin.baz']); <del> $this->assertNotRegExp('/test_plugin\/js\/foo.js/', $result); <add> $this->assertDoesNotMatchRegularExpression('/test_plugin\/js\/foo.js/', $result); <ide> <ide> $result = $this->Html->script('TestPlugin.foo', ['once' => false]); <ide> $this->assertNotNull($result); <ide><path>tests/TestCase/View/Helper/TextHelperTest.php <ide> public function testAutoLink() <ide> $text = 'Text with a partial www.cakephp.org URL and test@cakephp.org email address'; <ide> $result = $this->Text->autoLink($text); <ide> $expected = 'Text with a partial <a href="http://www.cakephp.org">www.cakephp.org</a> URL and <a href="mailto:test@cakephp\.org">test@cakephp\.org</a> email address'; <del> $this->assertRegExp('#^' . $expected . '$#', $result); <add> $this->assertMatchesRegularExpression('#^' . $expected . '$#', $result); <ide> <ide> $text = 'This is a test text with URL http://www.cakephp.org'; <ide> $expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>'; <ide> public function testAutoLinkUrlsOptions() <ide> $text = 'Text with a partial www.cakephp.org URL'; <ide> $expected = 'Text with a partial <a href="http://www.cakephp.org" \s*class="link">www.cakephp.org</a> URL'; <ide> $result = $this->Text->autoLinkUrls($text, ['class' => 'link']); <del> $this->assertRegExp('#^' . $expected . '$#', $result); <add> $this->assertMatchesRegularExpression('#^' . $expected . '$#', $result); <ide> <ide> $text = 'Text with a partial WWW.cakephp.org &copy; URL'; <ide> $expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> &copy; URL'; <ide> $result = $this->Text->autoLinkUrls($text, ['escape' => false]); <del> $this->assertRegExp('#^' . $expected . '$#', $result); <add> $this->assertMatchesRegularExpression('#^' . $expected . '$#', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/Helper/UrlHelperTest.php <ide> public function testAssetTimestamp() <ide> Configure::write('Asset.timestamp', true); <ide> Configure::write('debug', true); <ide> $result = $this->Helper->assetTimestamp(Configure::read('App.cssBaseUrl') . 'cake.generic.css'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> <ide> Configure::write('Asset.timestamp', 'force'); <ide> Configure::write('debug', false); <ide> $result = $this->Helper->assetTimestamp(Configure::read('App.cssBaseUrl') . 'cake.generic.css'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> <ide> $result = $this->Helper->assetTimestamp(Configure::read('App.cssBaseUrl') . 'cake.generic.css?someparam'); <ide> $this->assertEquals(Configure::read('App.cssBaseUrl') . 'cake.generic.css?someparam', $result); <ide> public function testAssetTimestamp() <ide> $this->View->setRequest($request); <ide> Router::setRequest($request); <ide> $result = $this->Helper->assetTimestamp('/some/dir/' . Configure::read('App.cssBaseUrl') . 'cake.generic.css'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testAssetUrlTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = $this->Helper->assetUrl('cake.generic.css', ['pathPrefix' => Configure::read('App.cssBaseUrl')]); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.cssBaseUrl') . 'cake.generic.css?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testAssetTimestampPluginsAndThemes() <ide> $this->loadPlugins(['TestPlugin']); <ide> <ide> $result = $this->Helper->assetTimestamp('/test_plugin/css/test_plugin_asset.css'); <del> $this->assertRegExp('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin'); <add> $this->assertMatchesRegularExpression('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin'); <ide> <ide> $result = $this->Helper->assetTimestamp('/test_plugin/css/i_dont_exist.css'); <del> $this->assertRegExp('#/test_plugin/css/i_dont_exist.css$#', $result, 'No error on missing file'); <add> $this->assertMatchesRegularExpression('#/test_plugin/css/i_dont_exist.css$#', $result, 'No error on missing file'); <ide> <ide> $result = $this->Helper->assetTimestamp('/test_theme/js/theme.js'); <del> $this->assertRegExp('#/test_theme/js/theme.js\?[0-9]+$#', $result, 'Missing timestamp theme'); <add> $this->assertMatchesRegularExpression('#/test_theme/js/theme.js\?[0-9]+$#', $result, 'Missing timestamp theme'); <ide> <ide> $result = $this->Helper->assetTimestamp('/test_theme/js/non_existant.js'); <del> $this->assertRegExp('#/test_theme/js/non_existant.js$#', $result, 'No error on missing file'); <add> $this->assertMatchesRegularExpression('#/test_theme/js/non_existant.js$#', $result, 'No error on missing file'); <ide> } <ide> <ide> /** <ide> public function testScriptTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = $this->Helper->script('script.js'); <del> $this->assertRegExp('/' . preg_quote(Configure::read('App.jsBaseUrl') . 'script.js?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote(Configure::read('App.jsBaseUrl') . 'script.js?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testImageTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = $this->Helper->image('cake.icon.png'); <del> $this->assertRegExp('/' . preg_quote('img/cake.icon.png?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote('img/cake.icon.png?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide> public function testCssTimestampForce() <ide> Configure::write('Asset.timestamp', 'force'); <ide> <ide> $result = $this->Helper->css('cake.generic'); <del> $this->assertRegExp('/' . preg_quote('css/cake.generic.css?', '/') . '[0-9]+/', $result); <add> $this->assertMatchesRegularExpression('/' . preg_quote('css/cake.generic.css?', '/') . '[0-9]+/', $result); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/View/ViewTest.php <ide> public function testAfterLayout() <ide> <ide> $content = 'This is my view output'; <ide> $result = $View->renderLayout($content, 'default'); <del> $this->assertRegExp('/modified in the afterlife/', $result); <del> $this->assertRegExp('/This is my view output/', $result); <add> $this->assertMatchesRegularExpression('/modified in the afterlife/', $result); <add> $this->assertMatchesRegularExpression('/This is my view output/', $result); <ide> } <ide> <ide> /** <ide> public function testRender() <ide> $View->setTemplatePath($this->PostsController->getName()); <ide> $result = $View->render('index'); <ide> <del> $this->assertRegExp("/<meta charset=\"utf-8\"\/>\s*<title>/", $result); <del> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <del> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <add> $this->assertMatchesRegularExpression("/<meta charset=\"utf-8\"\/>\s*<title>/", $result); <add> $this->assertMatchesRegularExpression("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <add> $this->assertMatchesRegularExpression("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <ide> <ide> $this->PostsController->viewBuilder()->setHelpers(['Html']); <ide> $this->PostsController->setRequest( <ide> public function testRender() <ide> $View->setTemplatePath($this->PostsController->getName()); <ide> $result = $View->render('index'); <ide> <del> $this->assertRegExp("/<meta charset=\"utf-8\"\/>\s*<title>/", $result); <del> $this->assertRegExp("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <add> $this->assertMatchesRegularExpression("/<meta charset=\"utf-8\"\/>\s*<title>/", $result); <add> $this->assertMatchesRegularExpression("/<div id=\"content\">\s*posts index\s*<\/div>/", $result); <ide> } <ide> <ide> /** <ide> public function testRenderUsingViewProperty() <ide> <ide> $this->assertSame('cache_form', $View->getTemplate()); <ide> $result = $View->render(); <del> $this->assertRegExp('/Add User/', $result); <add> $this->assertMatchesRegularExpression('/Add User/', $result); <ide> } <ide> <ide> /** <ide> public function testRenderUsingLayoutArgument() <ide> $View->setTemplatePath('Error'); <ide> <ide> $result = $View->render('pdo_error', 'error'); <del> $this->assertRegExp('/this is sql string/', $result); <del> $this->assertRegExp('/it works/', $result); <add> $this->assertMatchesRegularExpression('/this is sql string/', $result); <add> $this->assertMatchesRegularExpression('/it works/', $result); <ide> } <ide> <ide> /** <ide> public function testRenderLayout() <ide> $View = $this->PostsController->createView(TestView::class); <ide> $result = $View->renderLayout('', 'ajax2'); <ide> <del> $this->assertRegExp('/Ajax\!/', $result); <add> $this->assertMatchesRegularExpression('/Ajax\!/', $result); <ide> } <ide> <ide> /** <ide> public function testViewVarOverwritingLocalHelperVar() <ide> $View->setTemplatePath($Controller->getName()); <ide> $result = $View->render('helper_overwrite', false); <ide> <del> $this->assertRegExp('/I am some test html/', $result); <del> $this->assertRegExp('/Test link/', $result); <add> $this->assertMatchesRegularExpression('/I am some test html/', $result); <add> $this->assertMatchesRegularExpression('/Test link/', $result); <ide> } <ide> <ide> /** <ide> public function testViewFileName() <ide> $View->setTemplatePath('Posts'); <ide> <ide> $result = $View->getTemplateFileName('index'); <del> $this->assertRegExp('/Posts(\/|\\\)index.php/', $result); <add> $this->assertMatchesRegularExpression('/Posts(\/|\\\)index.php/', $result); <ide> <ide> $result = $View->getTemplateFileName('TestPlugin.index'); <del> $this->assertRegExp('/Posts(\/|\\\)index.php/', $result); <add> $this->assertMatchesRegularExpression('/Posts(\/|\\\)index.php/', $result); <ide> <ide> $result = $View->getTemplateFileName('/Pages/home'); <del> $this->assertRegExp('/Pages(\/|\\\)home.php/', $result); <add> $this->assertMatchesRegularExpression('/Pages(\/|\\\)home.php/', $result); <ide> <ide> $result = $View->getTemplateFileName('../element/test_element'); <del> $this->assertRegExp('/element(\/|\\\)test_element.php/', $result); <add> $this->assertMatchesRegularExpression('/element(\/|\\\)test_element.php/', $result); <ide> <ide> $expected = TEST_APP . 'templates' . DS . 'Posts' . DS . 'index.php'; <ide> $result = $View->getTemplateFileName('../Posts/index');
44
Javascript
Javascript
use queue for pendingstate
8b200c5e7822b137029db0634094f69d790f2272
<ide><path>src/renderers/shared/fiber/ReactFiber.js <ide> import type { ReactCoroutine, ReactYield } from 'ReactCoroutine'; <ide> import type { TypeOfWork } from 'ReactTypeOfWork'; <ide> import type { PriorityLevel } from 'ReactPriorityLevel'; <add>import type { PendingState } from 'ReactFiberPendingState'; <ide> <ide> var ReactTypeOfWork = require('ReactTypeOfWork'); <ide> var { <ide> export type Fiber = Instance & { <ide> pendingProps: any, // This type will be more specific once we overload the tag. <ide> // TODO: I think that there is a way to merge pendingProps and memoizedProps. <ide> memoizedProps: any, // The props used to create the output. <del> // Local state for class components. May need better naming to disambiguate <del> // from stateNode. <del> pendingState: any, <del> memoizedState: any, // The state used to create the output. <add> // Local state for class components. Either null or a linked list of partial <add> // state objects. <add> pendingState: PendingState, <add> // The state used to create the output. This is a full state object. <add> memoizedState: any, <ide> // Output is the return value of this fiber, or a linked list of return values <ide> // if this returns multiple values. Such as a fragment. <ide> output: any, // This type will be more specific once we overload the tag. <ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> import type { FiberRoot } from 'ReactFiberRoot'; <ide> import type { HostConfig } from 'ReactFiberReconciler'; <ide> import type { Scheduler } from 'ReactFiberScheduler'; <ide> import type { PriorityLevel } from 'ReactPriorityLevel'; <add>import type { PendingState } from 'ReactFiberPendingState'; <ide> <ide> var { <ide> reconcileChildFibers, <ide> var { <ide> NoWork, <ide> OffscreenPriority, <ide> } = require('ReactPriorityLevel'); <add>var { <add> createPendingState, <add> mergePendingState, <add>} = require('ReactFiberPendingState'); <ide> <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getScheduler: () => Scheduler) { <ide> <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getSchedu <ide> return workInProgress.child; <ide> } <ide> <del> function updateFiber(fiber: Fiber, state: any, priorityLevel : PriorityLevel): void { <add> function scheduleUpdate(fiber: Fiber, pendingState: PendingState, priorityLevel : PriorityLevel): void { <ide> const { scheduleLowPriWork } = getScheduler(); <del> fiber.pendingState = state; <del> <add> fiber.pendingState = pendingState; <ide> while (true) { <ide> if (fiber.pendingWorkPriority === NoWork || <ide> fiber.pendingWorkPriority >= priorityLevel) { <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getSchedu <ide> const updater = { <ide> enqueueSetState(instance, partialState) { <ide> const fiber = instance._fiber; <del> <del> const prevState = fiber.pendingState || fiber.memoizedState; <del> const state = Object.assign({}, prevState, partialState); <add> let pendingState = fiber.pendingState; <add> <add> // Append to pending state queue <add> const nextPendingStateNode = createPendingState(partialState); <add> if (pendingState === null) { <add> pendingState = nextPendingStateNode; <add> } else { <add> if (pendingState.tail === null) { <add> pendingState.next = nextPendingStateNode; <add> } else { <add> pendingState.tail.next = nextPendingStateNode; <add> } <add> pendingState.tail = nextPendingStateNode; <add> } <ide> <ide> // Must schedule an update on both alternates, because we don't know tree <ide> // is current. <del> updateFiber(fiber, state, LowPriority); <add> scheduleUpdate(fiber, pendingState, LowPriority); <ide> if (fiber.alternate) { <del> updateFiber(fiber.alternate, state, LowPriority); <add> scheduleUpdate(fiber.alternate, pendingState, LowPriority); <ide> } <ide> }, <ide> }; <ide> <ide> function updateClassComponent(current : ?Fiber, workInProgress : Fiber) { <ide> // A class component update is the result of either new props or new state. <del> // Account for the possibly of missing pending props or state by falling <del> // back to the most recent props or state. <add> // Account for the possibly of missing pending props by falling back to the <add> // memoized props. <ide> var props = workInProgress.pendingProps; <del> var state = workInProgress.pendingState; <ide> if (!props && current) { <ide> props = current.memoizedProps; <ide> } <del> if (!state && current) { <del> state = current.memoizedState; <add> // Compute the state using the memoized state and the pending state queue. <add> var pendingState = workInProgress.pendingState; <add> var state; <add> if (!current) { <add> state = mergePendingState(null, pendingState); <add> } else { <add> state = mergePendingState(current.memoizedState, pendingState); <ide> } <ide> <ide> var instance = workInProgress.stateNode; <ide> if (!instance) { <ide> var ctor = workInProgress.type; <ide> workInProgress.stateNode = instance = new ctor(props); <del> state = workInProgress.pendingState = instance.state || null; <add> state = instance.state || null; <add> // The initial state must be added to the pending state queue in case <add> // setState is called before the initial render. <add> workInProgress.pendingState = createPendingState(state); <ide> // The instance needs access to the fiber so that it can schedule updates <ide> instance._fiber = workInProgress; <ide> instance.updater = updater; <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>, getSchedu <ide> workInProgress.child = workInProgress.progressedChild; <ide> } <ide> <del> if (workInProgress.pendingProps === null || ( <add> if ((workInProgress.pendingProps === null || ( <ide> workInProgress.memoizedProps !== null && <ide> workInProgress.pendingProps === workInProgress.memoizedProps && <del> workInProgress.pendingState === workInProgress.memoizedState <del> )) { <add> )) && <add> workInProgress.pendingState === null <add> ) { <ide> return bailoutOnAlreadyFinishedWork(current, workInProgress); <ide> } <ide> <ide><path>src/renderers/shared/fiber/ReactFiberCompleteWork.js <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> // the linked list of fibers that has the individual output values. <ide> returnFiber.output = (child && !child.sibling) ? child.output : child; <ide> returnFiber.memoizedProps = returnFiber.pendingProps; <del> returnFiber.memoizedState = returnFiber.pendingState; <ide> } <ide> <ide> function recursivelyFillYields(yields, output : ?Fiber | ?ReifiedYield) { <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> return null; <ide> case ClassComponent: <ide> transferOutput(workInProgress.child, workInProgress); <add> // Don't use the pending state queue to compute the memoized state. We <add> // already merged it and assigned it to the instance. Copy it from there. <add> const state = workInProgress.stateNode.state; <add> workInProgress.memoizedState = state; <ide> return null; <ide> case HostContainer: <ide> transferOutput(workInProgress.child, workInProgress); <ide><path>src/renderers/shared/fiber/ReactFiberPendingState.js <add>/** <add> * Copyright 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @providesModule ReactFiberPendingState <add> * @flow <add> */ <add> <add>'use strict'; <add> <add>export type PendingState = { <add> partialState: any, <add> next: PendingState, <add> tail: PendingState <add>} | null; <add> <add>exports.createPendingState = function(partialState: mixed): PendingState { <add> return { <add> partialState, <add> next: null, <add> tail: null, <add> }; <add>}; <add> <add>exports.mergePendingState = function(prevState: any, queue: PendingState): any { <add> if (queue === null) { <add> return prevState; <add> } <add> let state = Object.assign({}, prevState, queue.partialState); <add> while (queue = queue.next) { <add> state = Object.assign(state, queue.partialState); <add> } <add> return state; <add>}; <ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js <ide> describe('ReactIncremental', () => { <ide> <ide> it('can update in the middle of a tree using setState', () => { <ide> let instance; <del> let states = []; <add> class Bar extends React.Component { <add> constructor() { <add> super(); <add> this.state = { a: 'a' }; <add> instance = this; <add> } <add> render() { <add> return <div>{this.props.children}</div>; <add> } <add> } <ide> <add> function Foo() { <add> return ( <add> <div> <add> <Bar /> <add> </div> <add> ); <add> } <add> <add> ReactNoop.render(<Foo />); <add> ReactNoop.flush(); <add> expect(instance.state).toEqual({ a: 'a' }); <add> instance.setState({ b: 'b' }); <add> ReactNoop.flush(); <add> expect(instance.state).toEqual({ a: 'a', b: 'b' }); <add> }); <add> <add> it('can queue multiple state updates', () => { <add> let instance; <ide> class Bar extends React.Component { <ide> constructor() { <ide> super(); <del> this.state = { string: 'a' }; <add> this.state = { a: 'a' }; <ide> instance = this; <ide> } <ide> render() { <del> states.push(this.state.string); <ide> return <div>{this.props.children}</div>; <ide> } <ide> } <ide> describe('ReactIncremental', () => { <ide> <ide> ReactNoop.render(<Foo />); <ide> ReactNoop.flush(); <del> expect(states).toEqual(['a']); <del> instance.setState({ string: 'b' }); <add> // Call setState multiple times before flushing <add> instance.setState({ b: 'b' }); <add> instance.setState({ c: 'c' }); <add> instance.setState({ d: 'd' }); <ide> ReactNoop.flush(); <del> expect(states).toEqual(['a', 'b']); <add> expect(instance.state).toEqual({ a: 'a', b: 'b', c: 'c', d: 'd' }); <ide> }); <ide> });
5
PHP
PHP
check null instead of empty to use all tables
eb988d35045b0d72c0bf61711f9479e3ee270b3a
<ide><path>src/TestSuite/ConnectionHelper.php <ide> public function addTestAliases(): void <ide> /** <ide> * Enables query logging for all database connections. <ide> * <del> * @param array<int, string> $connections Connection names or empty for all. <add> * @param array<int, string>|null $connections Connection names or null for all. <ide> * @return void <ide> */ <del> public function enableQueryLogging(array $connections = []): void <add> public function enableQueryLogging(?array $connections = null): void <ide> { <del> $connections = $connections ? $connections : ConnectionManager::configured(); <add> $connections = $connections ?? ConnectionManager::configured(); <ide> foreach ($connections as $connection) { <ide> $connection = ConnectionManager::get($connection); <ide> if ($connection instanceof Connection) { <ide> public function dropTables(string $connectionName, ?array $tables = null): void <ide> $collection = $connection->getSchemaCollection(); <ide> <ide> $allTables = $collection->listTables(); <del> $tables = $tables ? array_intersect($tables, $allTables) : $allTables; <add> $tables = $tables !== null ? array_intersect($tables, $allTables) : $allTables; <ide> $schemas = array_map(function ($table) use ($collection) { <ide> return $collection->describe($table); <ide> }, $tables); <ide> public function truncateTables(string $connectionName, ?array $tables = null): v <ide> $collection = $connection->getSchemaCollection(); <ide> <ide> $allTables = $collection->listTables(); <del> $tables = $tables ? array_intersect($tables, $allTables) : $allTables; <add> $tables = $tables !== null ? array_intersect($tables, $allTables) : $allTables; <ide> $schemas = array_map(function ($table) use ($collection) { <ide> return $collection->describe($table); <ide> }, $tables);
1
Javascript
Javascript
remove `didtimeout` check from work loop
3f8115cdd1e6ba237619cf8a7d433900dcf413c2
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { <ide> <ide> // This is the entry point for every concurrent task, i.e. anything that <ide> // goes through Scheduler. <del>function performConcurrentWorkOnRoot(root, didTimeout) { <add>function performConcurrentWorkOnRoot(root) { <ide> // Since we know we're in a React event, we can clear the current <ide> // event time. The next update will compute a new event time. <ide> currentEventTime = NoTimestamp; <ide> function performConcurrentWorkOnRoot(root, didTimeout) { <ide> return null; <ide> } <ide> <del> // TODO: We only check `didTimeout` defensively, to account for a Scheduler <del> // bug where `shouldYield` sometimes returns `true` even if `didTimeout` is <del> // true, which leads to an infinite loop. Once the bug in Scheduler is <del> // fixed, we can remove this, since we track expiration ourselves. <del> if (didTimeout) { <del> // Something expired. Flush synchronously until there's no expired <del> // work left. <del> markRootExpired(root, lanes); <del> // This will schedule a synchronous callback. <del> ensureRootIsScheduled(root, now()); <del> return null; <del> } <del> <ide> let exitStatus = renderRootConcurrent(root, lanes); <ide> <ide> if ( <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { <ide> <ide> // This is the entry point for every concurrent task, i.e. anything that <ide> // goes through Scheduler. <del>function performConcurrentWorkOnRoot(root, didTimeout) { <add>function performConcurrentWorkOnRoot(root) { <ide> // Since we know we're in a React event, we can clear the current <ide> // event time. The next update will compute a new event time. <ide> currentEventTime = NoTimestamp; <ide> function performConcurrentWorkOnRoot(root, didTimeout) { <ide> return null; <ide> } <ide> <del> // TODO: We only check `didTimeout` defensively, to account for a Scheduler <del> // bug where `shouldYield` sometimes returns `true` even if `didTimeout` is <del> // true, which leads to an infinite loop. Once the bug in Scheduler is <del> // fixed, we can remove this, since we track expiration ourselves. <del> if (didTimeout) { <del> // Something expired. Flush synchronously until there's no expired <del> // work left. <del> markRootExpired(root, lanes); <del> // This will schedule a synchronous callback. <del> ensureRootIsScheduled(root, now()); <del> return null; <del> } <del> <ide> let exitStatus = renderRootConcurrent(root, lanes); <ide> <ide> if ( <ide><path>packages/react-reconciler/src/__tests__/ReactSchedulerIntegration-test.js <ide> describe( <ide> React = require('react'); <ide> ReactNoop = require('react-noop-renderer'); <ide> Scheduler = require('scheduler'); <del> <del> React = require('react'); <ide> }); <ide> <ide> afterEach(() => { <ide> describe( <ide> <ide> // Expire the task <ide> Scheduler.unstable_advanceTime(10000); <add> // Scheduling a new update is a trick to force the expiration to kick <add> // in. We don't check if a update has been starved at the beginning of <add> // working on it, since there's no point — we're already working on it. <add> // We only check before yielding to the main thread (to avoid starvation <add> // by other main thread work) or when receiving an update (to avoid <add> // starvation by incoming updates). <add> ReactNoop.render(<App />); <add> <ide> // Because the render expired, React should finish the tree without <ide> // consulting `shouldYield` again <ide> expect(Scheduler).toFlushExpired(['B', 'C']);
3
Text
Text
fix incomplete test
970a1c1b568cc0fe4d6297f5166fa5c91c1294e0
<ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/adjacency-list.md <ide> There should be an edge between `Jill` and `Jenny`. <ide> ```js <ide> assert( <ide> undirectedAdjList.Jill.indexOf('Jenny') !== -1 && <del> undirectedAdjList.Jill.indexOf('Jenny') !== -1 <add> undirectedAdjList.Jenny.indexOf('Jill') !== -1 <ide> ); <ide> ``` <ide>
1
Ruby
Ruby
fix keyword arguments warnings
3796cd628f8907b0471172b9cf7e5480e060a4c3
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def mismatched_foreign_key(message, sql:, binds:) <ide> options[:primary_key_column] = column_for(match[:target_table], match[:primary_key]) <ide> end <ide> <del> MismatchedForeignKey.new(options) <add> MismatchedForeignKey.new(**options) <ide> end <ide> <ide> def version_string(full_version_string) <ide><path>activerecord/lib/active_record/validations/associated.rb <ide> module Validations <ide> class AssociatedValidator < ActiveModel::EachValidator #:nodoc: <ide> def validate_each(record, attribute, value) <ide> if Array(value).reject { |r| valid_object?(r) }.any? <del> record.errors.add(attribute, :invalid, options.merge(value: value)) <add> record.errors.add(attribute, :invalid, **options.merge(value: value)) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/autosave_association_test.rb <ide> def test_should_rollback_any_changes_if_an_exception_occurred_while_saving <ide> <ide> # Stub the save method of the @pirate.ship instance to raise an exception <ide> class << @pirate.ship <del> def save(*args) <add> def save(*, **) <ide> super <ide> raise "Oh noes!" <ide> end
3
Python
Python
remove unneeded future imports
b9f1d23cfbb170a4daaaf4042a6b9032ca7a4501
<ide><path>benchmarks/benchmarks/bench_array_coercion.py <del>from __future__ import absolute_import, division, print_function <del> <ide> from .common import Benchmark <ide> <ide> import numpy as np <ide><path>benchmarks/benchmarks/bench_itemselection.py <del>from __future__ import absolute_import, division, print_function <del> <ide> from .common import Benchmark, TYPES1 <ide> <ide> import numpy as np <ide><path>benchmarks/benchmarks/bench_strings.py <del>from __future__ import absolute_import, division, print_function <del> <ide> from .common import Benchmark <ide> <ide> import numpy as np <ide><path>numpy/distutils/armccompiler.py <del>from __future__ import division, absolute_import, print_function <del> <ide> from distutils.unixccompiler import UnixCCompiler <ide> <ide> class ArmCCompiler(UnixCCompiler): <ide><path>numpy/distutils/fcompiler/arm.py <del>from __future__ import division, absolute_import, print_function <del> <ide> import sys <ide> <ide> from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file
5
Javascript
Javascript
remove event dependency from the ajax module
4e7f34f6296111f7f91d621397dfb02c6bf4c41f
<ide><path>src/ajax/xhr.js <ide> var xhrId = 0, <ide> <ide> // Support: IE9 <ide> // Open requests must be manually aborted on unload (#5280) <del>if ( window.ActiveXObject ) { <del> jQuery( window ).on( "unload", function() { <add>// See https://support.microsoft.com/kb/2856746 for more info <add>if ( window.attachEvent ) { <add> window.attachEvent( "onunload", function() { <ide> for ( var key in xhrCallbacks ) { <ide> xhrCallbacks[ key ](); <ide> }
1
Javascript
Javascript
remove preview when press escape
dc28d6315dca01acf824af655fc0adaa8db2d0bf
<ide><path>lib/repl.js <ide> function REPLServer(prompt, <ide> clearPreview(key); <ide> if (!reverseSearch(d, key)) { <ide> ttyWrite(d, key); <del> showPreview(); <add> if (key.name !== 'escape') { <add> showPreview(); <add> } <ide> } <ide> return; <ide> } <ide><path>test/parallel/test-repl-history-navigation.js <ide> const tests = [ <ide> // 10. Word right. Cleanup <ide> '\x1B[0K', '\x1B[3G', '\x1B[7C', ' // n', '\x1B[10G', <ide> // 11. ESCAPE <del> '\x1B[0K', ' // n', '\x1B[10G', '\x1B[0K', <add> '\x1B[0K', <ide> // 12. ENTER <ide> '\r\n', <ide> 'Uncaught ReferenceError: functio is not defined\n',
2
Javascript
Javascript
remove example e2e test that cannot run
1bc99eca08bef4aceb49d4fee7ef9e291f60ff3b
<ide><path>src/ng/interpolate.js <ide> var $interpolateMinErr = minErr('$interpolate'); <ide> //label// <ide> </div> <ide> </doc:source> <del> <doc:scenario> <del> describe('provider', function() { <del> beforeEach(module(function($interpolateProvider) { <del> $interpolateProvider.startSymbol('//'); <del> $interpolateProvider.endSymbol('//'); <del> })); <del> <del> it('should not get confused with same markers', inject(function($interpolate) { <del> expect($interpolate('///').parts).toEqual(['///']); <del> expect($interpolate('////')()).toEqual(''); <del> expect($interpolate('//1//')()).toEqual('1'); <del> })); <del> }); <del> </doc:scenario> <ide> </doc:example> <ide> */ <ide> function $InterpolateProvider() {
1
Javascript
Javascript
point everything at the new meta module
c4b3bceaf6d94a73d1c251bbacc5682474ec989c
<ide><path>packages/ember-metal/lib/alias.js <ide> import { <ide> defineProperty <ide> } from 'ember-metal/properties'; <ide> import { ComputedProperty } from 'ember-metal/computed'; <del>import { <del> meta, <del> inspect <del>} from 'ember-metal/utils'; <add>import { inspect } from 'ember-metal/utils'; <add>import { meta } from 'ember-metal/meta'; <ide> import { <ide> addDependentKeys, <ide> removeDependentKeys <ide><path>packages/ember-metal/lib/chains.js <ide> import Ember from 'ember-metal/core'; // warn, assert, etc; <ide> import { get, normalizeTuple } from 'ember-metal/property_get'; <del>import { meta as metaFor } from 'ember-metal/utils'; <add>import { meta as metaFor } from 'ember-metal/meta'; <ide> import { watchKey, unwatchKey } from 'ember-metal/watch_key'; <ide> <ide> var FIRST_KEY = /^([^\.]+)/; <ide><path>packages/ember-metal/lib/computed.js <ide> import Ember from 'ember-metal/core'; <ide> import { set } from 'ember-metal/property_set'; <del>import { <del> meta, <del> inspect <del>} from 'ember-metal/utils'; <add>import { inspect } from 'ember-metal/utils'; <add>import { meta } from 'ember-metal/meta'; <ide> import expandProperties from 'ember-metal/expand_properties'; <ide> import EmberError from 'ember-metal/error'; <ide> import { <ide><path>packages/ember-metal/lib/events.js <ide> */ <ide> import Ember from 'ember-metal/core'; <ide> import { <del> meta as metaFor, <ide> apply, <ide> applyStr <ide> } from 'ember-metal/utils'; <add>import { meta as metaFor } from 'ember-metal/meta'; <ide> <ide> /* listener flags */ <ide> var ONCE = 1; <ide><path>packages/ember-metal/lib/meta.js <ide> import isEnabled from 'ember-metal/features'; <ide> `writable` variants will give you a mutable object, and they will <ide> create it if it didn't already exist. <ide> <add> The following methods will get generated metaprogrammatically, and <add> I'm including them here for greppability: <add> <add> writableCache, readableCache, writableWatching, readableWatching, <add> peekWatching, clearWatching, writableMixins, readableMixins, <add> peekMixins, clearMixins, writableBindings, readableBindings, <add> peekBindings, clearBindings, writableValues, readableValues, <add> peekValues, clearValues, writableListeners, readableListeners, <add> getAllListeners, writableDeps, readableDeps, getAllDeps <add> writableChainWatchers, readableChainWatchers, writableChains, <add> readableChains <add> <ide> */ <ide> let members = { <del> cache: ownMap, // writableCache, readableCache <del> watching: inheritedMap, // writableWatching, readableWatching, peekWatching, clearWatching <del> mixins: inheritedMap, // writableMixins, readableMixins, peekMixins, clearMixins <del> bindings: inheritedMap, // writableBindings, readableBindings, peekBindings, clearBindings <del> values: inheritedMap, // writableValues, readableValues, peekValues, clearValues <del> listeners: inheritedMapOfLists, // writableListeners, readableListeners, getAllListeners <del> deps: inheritedMapOfMaps, // writableDeps, readableDeps, getAllDeps <del> chainWatchers: ownCustomObject, // writableChainWatchers, readableChainWatchers <del> chains: inheritedCustomObject // writableChains, readableChains <add> cache: ownMap, <add> watching: inheritedMap, <add> mixins: inheritedMap, <add> bindings: inheritedMap, <add> values: inheritedMap, <add> listeners: inheritedMapOfLists, <add> deps: inheritedMapOfMaps, <add> chainWatchers: ownCustomObject, <add> chains: inheritedCustomObject <ide> }; <ide> <ide> let memberNames = Object.keys(members); <ide> function ownMap(name, Meta) { <ide> function getOrCreateOwnMap(key) { <ide> let ret = this[key]; <ide> if (!ret) { <del> ret = this[key] = Object.create(null); <add> ret = this[key] = {}; <ide> } <ide> return ret; <ide> } <ide> function inheritedMap(name, Meta) { <ide> }; <ide> <ide> Meta.prototype['clear' + capitalized] = function() { <del> this[key] = Object.create(null); <add> this[key] = {}; <ide> }; <ide> } <ide> <ide> function getOrCreateInheritedMap(key) { <ide> if (this.parent) { <ide> ret = this[key] = Object.create(getOrCreateInheritedMap.call(this.parent, key)); <ide> } else { <del> ret = this[key] = Object.create(null); <add> ret = this[key] = {}; <ide> } <ide> } <ide> return ret; <ide> function inheritedMapOfMaps(name, Meta) { <ide> let outerMap = getOrCreateInheritedMap.call(this, key); <ide> let innerMap = outerMap[subkey]; <ide> if (!innerMap) { <del> innerMap = outerMap[subkey] = Object.create(null); <add> innerMap = outerMap[subkey] = {}; <ide> } else if (!Object.hasOwnProperty.call(outerMap, subkey)) { <ide> innerMap = outerMap[subkey] = Object.create(innerMap); <ide> } <ide><path>packages/ember-metal/lib/mixin.js <ide> import { get } from 'ember-metal/property_get'; <ide> import { set, trySet } from 'ember-metal/property_set'; <ide> import { <ide> guidFor, <del> meta as metaFor, <ide> wrap, <ide> makeArray <ide> } from 'ember-metal/utils'; <add>import { meta as metaFor } from 'ember-metal/meta'; <ide> import expandProperties from 'ember-metal/expand_properties'; <ide> import { <ide> Descriptor, <ide><path>packages/ember-metal/lib/properties.js <ide> <ide> import Ember from 'ember-metal/core'; <ide> import isEnabled from 'ember-metal/features'; <del>import { meta as metaFor } from 'ember-metal/utils'; <add>import { meta as metaFor } from 'ember-metal/meta'; <ide> import { overrideChains } from 'ember-metal/property_events'; <ide> // .......................................................... <ide> // DESCRIPTOR <ide><path>packages/ember-metal/lib/utils.js <ide> // <ide> 'REMOVE_USE_STRICT: true'; <ide> <del>import { meta } from 'ember-metal/meta'; <del> <ide> /** <ide> @module ember-metal <ide> */ <ide> export function applyStr(t, m, a) { <ide> export { <ide> GUID_KEY, <ide> makeArray, <del> canInvoke, <del> meta // this is temporary until I can refactor all the import sites <add> canInvoke <ide> }; <ide><path>packages/ember-metal/lib/watch_key.js <ide> import isEnabled from 'ember-metal/features'; <ide> import { <ide> meta as metaFor <del>} from 'ember-metal/utils'; <add>} from 'ember-metal/meta'; <ide> import { <ide> MANDATORY_SETTER_FUNCTION, <ide> DEFAULT_GETTER_FUNCTION <ide><path>packages/ember-metal/lib/watch_path.js <ide> import { <ide> meta as metaFor <del>} from 'ember-metal/utils'; <add>} from 'ember-metal/meta'; <ide> import { ChainNode } from 'ember-metal/chains'; <ide> <ide> // get the chains for the current object. If the current object has <ide><path>packages/ember-metal/tests/accessors/mandatory_setters_test.js <ide> import isEnabled from 'ember-metal/features'; <ide> import { get } from 'ember-metal/property_get'; <ide> import { set } from 'ember-metal/property_set'; <ide> import { watch } from 'ember-metal/watching'; <del>import { meta as metaFor } from 'ember-metal/utils'; <add>import { meta as metaFor } from 'ember-metal/meta'; <ide> <ide> QUnit.module('mandatory-setters'); <ide> <ide><path>packages/ember-metal/tests/alias_test.js <ide> import alias from 'ember-metal/alias'; <ide> import { defineProperty } from 'ember-metal/properties'; <ide> import { get } from 'ember-metal/property_get'; <ide> import { set } from 'ember-metal/property_set'; <del>import { meta } from 'ember-metal/utils'; <add>import { meta } from 'ember-metal/meta'; <ide> import { isWatching } from 'ember-metal/watching'; <ide> import { addObserver, removeObserver } from 'ember-metal/observer'; <ide> <ide><path>packages/ember-metal/tests/events_test.js <ide> import { Mixin } from 'ember-metal/mixin'; <del>import { meta } from 'ember-metal/utils'; <add>import { meta } from 'ember-metal/meta'; <ide> <ide> import { <ide> on, <ide><path>packages/ember-metal/tests/meta_test.js <ide> QUnit.skip('meta.listeners basics', function(assert) { <ide> let matching = m.matchingListeners(e => e.eventName === 'hello'); <ide> assert.equal(matching.length, 1); <ide> assert.equal(matching[0].target, t); <del> m.removeFromListeners({ eventName: 'hello', target: t, method: 'm'}); <add> m.removeFromListeners({ eventName: 'hello', target: t, method: 'm' }); <ide> matching = m.matchingListeners(e => e.eventName === 'hello'); <ide> assert.equal(matching.length, 0); <ide> }); <ide> QUnit.skip('meta.listeners inheritance', function(assert) { <ide> let matching = m.matchingListeners(e => e.eventName === 'hello'); <ide> assert.equal(matching.length, 1); <ide> assert.equal(matching[0].target, target); <del> m.removeFromListeners({ eventName: 'hello', target, method: 'm'}); <add> m.removeFromListeners({ eventName: 'hello', target, method: 'm' }); <ide> matching = m.matchingListeners(e => e.eventName === 'hello'); <ide> assert.equal(matching.length, 0); <ide> }); <ide><path>packages/ember-runtime/lib/mixins/-proxy.js <ide> import Ember from 'ember-metal/core'; // Ember.assert <ide> import { get } from 'ember-metal/property_get'; <ide> import { set } from 'ember-metal/property_set'; <del>import { meta } from 'ember-metal/utils'; <add>import { meta } from 'ember-metal/meta'; <ide> import { <ide> addObserver, <ide> removeObserver, <ide><path>packages/ember-runtime/lib/system/core_object.js <ide> import { <ide> generateGuid, <ide> GUID_KEY_PROPERTY, <ide> NEXT_SUPER_PROPERTY, <del> meta, <ide> makeArray <ide> } from 'ember-metal/utils'; <add>import { meta } from 'ember-metal/meta'; <ide> import { finishChains } from 'ember-metal/chains'; <ide> import { sendEvent } from 'ember-metal/events'; <ide> import {
16
Javascript
Javascript
avoid window.print in a microtask
76d29759c5fc023a93281064914f3f642275b6c7
<ide><path>web/mozPrintCallback_polyfill.js <ide> } <ide> } else { <ide> renderProgress(); <del> print.call(window); <del> setTimeout(abort, 20); // Tidy-up <add> // Push window.print in the macrotask queue to avoid being affected by <add> // the deprecation of running print() code in a microtask, see <add> // https://github.com/mozilla/pdf.js/issues/7547. <add> setTimeout(function() { <add> if (!canvases) { <add> return; // Print task cancelled by user. <add> } <add> print.call(window); <add> setTimeout(abort, 20); // Tidy-up <add> }, 0); <ide> } <ide> } <ide>
1
Ruby
Ruby
update #match documentation [ci skip]
8453addedcea6e42a5df3d241225a32698121072
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def root(options = {}) <ide> # <ide> # # Matches any request starting with 'path' <ide> # match 'path' => 'c#a', :anchor => false <add> # <add> # [:format] <add> # Allows you to specify default value for optional +format+ segment <add> # or disable it if you supply +false+ <ide> def match(path, options=nil) <ide> end <ide>
1
Javascript
Javascript
add param for correct category
583f0de9f5662537dab0c650c8aef2e78d74c9a9
<ide><path>packages/learn/src/templates/Challenges/redux/create-question-epic.js <ide> function createQuestionEpic(action$, { getState }, { window }) { <ide> tap(() => { <ide> const state = getState(); <ide> const files = challengeFilesSelector(state); <del> const { title: challengeTitle } = challengeMetaSelector(state); <add> const { <add> title: challengeTitle, <add> challengeType: challengeType <add> } = challengeMetaSelector(state); <ide> const { navigator: { userAgent }, location: { href } } = window; <ide> const textMessage = [ <ide> "**Tell us what's happening:**\n\n\n\n", <ide> function createQuestionEpic(action$, { getState }, { window }) { <ide> '**Link to the challenge:**\n', <ide> href <ide> ].join(''); <del> <add> const categories = ['HTML-CSS', 'JavaScript']; <ide> window.open( <ide> 'https://forum.freecodecamp.org/new-topic' + <del> '?category=help' + <add> '?category=' + <add> window.encodeURIComponent(categories[challengeType] || 'Help') + <ide> '&title=' + <ide> window.encodeURIComponent(challengeTitle) + <ide> '&body=' +
1
Javascript
Javascript
use arrow functions
140d66785dc61304c9df4281ff993fbbd075c829
<ide><path>bin/changelog.js <ide> compareCommits({ <ide> }) <ide> .then(processPages) <ide> .then(console.log) <del> .catch(function(err) { <del> console.error(err); <del> }); <add> .catch(err => console.error(err)); <ide> <ide> function getCommitMessage(commitInfo) { <ide> let message = commitInfo.commit.message; <ide> function getCommitMessage(commitInfo) { <ide> <ide> function processPages(res) { <ide> let contributions = res.commits <del> .filter(function(commitInfo) { <add> .filter(commitInfo => { <ide> let message = commitInfo.commit.message; <ide> <ide> return ( <ide> message.indexOf('Merge pull request #') > -1 || message.indexOf('cherry picked from') > -1 <ide> ); <ide> }) <del> .map(function(commitInfo) { <add> .map(commitInfo => { <ide> let message = getCommitMessage(commitInfo); <ide> let match = message.match(/#(\d+) from (.*)\//); <ide> let result = { <ide> function processPages(res) { <ide> <ide> return result; <ide> }) <del> .sort(function(a, b) { <del> return a.number > b.number; <del> }) <del> .map(function(pr) { <add> .sort((a, b) => a.number > b.number) <add> .map(pr => { <ide> let title = pr.title; <ide> let link; <ide> if (pr.number) { <ide> function processPages(res) { <ide> .join('\n'); <ide> <ide> if (github.hasNextPage(res)) { <del> return github.getNextPage(res).then(function(nextPage) { <add> return github.getNextPage(res).then(nextPage => { <ide> contributions += processPages(nextPage); <ide> }); <ide> } else {
1
Text
Text
fix spelling. [ci skip]
a32298ffb3fbccf41fa15c223710e1011e6fe25e
<ide><path>railties/CHANGELOG.md <ide> <ide> * The [web-console](https://github.com/rails/web-console) gem is now <ide> installed by default for new applications. It can help you debug <del> development exceptions by spawnig an interactive console in its cause <add> development exceptions by spawning an interactive console in its cause <ide> binding. <ide> <ide> *Ryan Dao*, *Genadi Samokovarov*, *Guillermo Iguaran*
1
Go
Go
fix logrus formatting
fa710e504b0e3e51d4031790c18621b02dcd2600
<ide><path>daemon/cluster/cluster.go <ide> func New(config Config) (*Cluster, error) { <ide> <ide> select { <ide> case <-time.After(swarmConnectTimeout): <del> logrus.Errorf("swarm component could not be started before timeout was reached") <add> logrus.Error("swarm component could not be started before timeout was reached") <ide> case <-n.Ready(): <ide> case <-n.done: <ide> return nil, fmt.Errorf("swarm component could not be started: %v", c.err) <ide><path>daemon/daemon.go <ide> func (daemon *Daemon) restore() error { <ide> go func(c *container.Container) { <ide> defer wg.Done() <ide> if err := backportMountSpec(c); err != nil { <del> logrus.Errorf("Failed to migrate old mounts to use new spec format") <add> logrus.Error("Failed to migrate old mounts to use new spec format") <ide> } <ide> <ide> if c.IsRunning() || c.IsPaused() { <ide><path>daemon/daemon_unix.go <ide> func (daemon *Daemon) initNetworkController(config *Config, activeSandboxes map[ <ide> } <ide> <ide> if len(activeSandboxes) > 0 { <del> logrus.Infof("There are old running containers, the network config will not take affect") <add> logrus.Info("There are old running containers, the network config will not take affect") <ide> return controller, nil <ide> } <ide> <ide><path>daemon/graphdriver/aufs/aufs.go <ide> func (a *Driver) Remove(id string) error { <ide> tmpMntPath := path.Join(a.mntPath(), fmt.Sprintf("%s-removing", id)) <ide> if err := os.Rename(mountpoint, tmpMntPath); err != nil && !os.IsNotExist(err) { <ide> if err == syscall.EBUSY { <del> logrus.Warnf("os.Rename err due to EBUSY") <add> logrus.Warn("os.Rename err due to EBUSY") <ide> out, debugErr := debugEBusy(mountpoint) <ide> if debugErr == nil { <ide> logrus.Warnf("debugEBusy returned %v", out) <ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) lookupDeviceWithLock(hash string) (*devInfo, error) { <ide> // This function relies on that device hash map has been loaded in advance. <ide> // Should be called with devices.Lock() held. <ide> func (devices *DeviceSet) constructDeviceIDMap() { <del> logrus.Debugf("devmapper: constructDeviceIDMap()") <del> defer logrus.Debugf("devmapper: constructDeviceIDMap() END") <add> logrus.Debug("devmapper: constructDeviceIDMap()") <add> defer logrus.Debug("devmapper: constructDeviceIDMap() END") <ide> <ide> for _, info := range devices.Devices { <ide> devices.markDeviceIDUsed(info.DeviceID) <ide> func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo) <ide> } <ide> <ide> func (devices *DeviceSet) loadDeviceFilesOnStart() error { <del> logrus.Debugf("devmapper: loadDeviceFilesOnStart()") <del> defer logrus.Debugf("devmapper: loadDeviceFilesOnStart() END") <add> logrus.Debug("devmapper: loadDeviceFilesOnStart()") <add> defer logrus.Debug("devmapper: loadDeviceFilesOnStart() END") <ide> <ide> var scan = func(path string, info os.FileInfo, err error) error { <ide> if err != nil { <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> // https://github.com/docker/docker/issues/4036 <ide> if supported := devicemapper.UdevSetSyncSupport(true); !supported { <ide> if dockerversion.IAmStatic == "true" { <del> logrus.Errorf("devmapper: Udev sync is not supported. This will lead to data loss and unexpected behavior. Install a dynamic binary to use devicemapper or select a different storage driver. For more information, see https://docs.docker.com/engine/reference/commandline/daemon/#daemon-storage-driver-option") <add> logrus.Error("devmapper: Udev sync is not supported. This will lead to data loss and unexpected behavior. Install a dynamic binary to use devicemapper or select a different storage driver. For more information, see https://docs.docker.com/engine/reference/commandline/daemon/#daemon-storage-driver-option") <ide> } else { <del> logrus.Errorf("devmapper: Udev sync is not supported. This will lead to data loss and unexpected behavior. Install a more recent version of libdevmapper or select a different storage driver. For more information, see https://docs.docker.com/engine/reference/commandline/daemon/#daemon-storage-driver-option") <add> logrus.Error("devmapper: Udev sync is not supported. This will lead to data loss and unexpected behavior. Install a more recent version of libdevmapper or select a different storage driver. For more information, see https://docs.docker.com/engine/reference/commandline/daemon/#daemon-storage-driver-option") <ide> } <ide> <ide> if !devices.overrideUdevSyncCheck { <ide><path>daemon/graphdriver/overlay2/overlay.go <ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap <ide> if !opts.overrideKernelCheck { <ide> return nil, graphdriver.ErrNotSupported <ide> } <del> logrus.Warnf("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update") <add> logrus.Warn("Using pre-4.0.0 kernel for overlay2, mount failures may require kernel update") <ide> } <ide> <ide> fsMagic, err := graphdriver.GetFSMagic(home) <ide><path>pkg/discovery/kv/kv.go <ide> func (s *Discovery) Initialize(uris string, heartbeat time.Duration, ttl time.Du <ide> <ide> var config *store.Config <ide> if clusterOpts["kv.cacertfile"] != "" && clusterOpts["kv.certfile"] != "" && clusterOpts["kv.keyfile"] != "" { <del> logrus.Infof("Initializing discovery with TLS") <add> logrus.Info("Initializing discovery with TLS") <ide> tlsConfig, err := tlsconfig.Client(tlsconfig.Options{ <ide> CAFile: clusterOpts["kv.cacertfile"], <ide> CertFile: clusterOpts["kv.certfile"], <ide> func (s *Discovery) Initialize(uris string, heartbeat time.Duration, ttl time.Du <ide> TLS: tlsConfig, <ide> } <ide> } else { <del> logrus.Infof("Initializing discovery without TLS") <add> logrus.Info("Initializing discovery without TLS") <ide> } <ide> <ide> // Creates a new store, will ignore options given <ide><path>plugin/backend.go <ide> func (pm *Manager) Pull(name string, metaHeader http.Header, authConfig *types.A <ide> name = ref.String() <ide> <ide> if p, _ := pm.pluginStore.GetByName(name); p != nil { <del> logrus.Debugf("plugin already exists") <add> logrus.Debug("plugin already exists") <ide> return nil, fmt.Errorf("%s exists", name) <ide> } <ide> <ide><path>plugin/distribution/pull.go <ide> func Pull(ref reference.Named, rs registry.Service, metaheader http.Header, auth <ide> return nil, err <ide> } <ide> if !confirmedV2 { <del> logrus.Debugf("pull.go: !confirmedV2") <add> logrus.Debug("pull.go: !confirmedV2") <ide> return nil, ErrUnsupportedRegistry <ide> } <ide> logrus.Debugf("Trying to pull %s from %s %s", repoInfo.Name(), endpoint.URL, endpoint.Version)
9
Python
Python
add url and typing hint for bfs
d2fa91b18e4f87976a67f99a57929d12fe48cfd9
<add><path>graphs/breadth_first_search_2.py <del><path>graphs/bfs.py <ide> """ <del>BFS. <del> <add>https://en.wikipedia.org/wiki/Breadth-first_search <ide> pseudo-code: <del> <del>BFS(graph G, start vertex s): <add>breadth_first_search(graph G, start vertex s): <ide> // all nodes initially unexplored <ide> mark s as explored <ide> let Q = queue data structure, initialized with s <ide> if w unexplored: <ide> mark w as explored <ide> add w to Q (at the end) <del> <ide> """ <ide> <add>from typing import Set, Dict <add> <ide> G = { <ide> "A": ["B", "C"], <ide> "B": ["A", "D", "E"], <ide> } <ide> <ide> <del>def bfs(graph, start): <add>def breadth_first_search(graph: Dict, start: str) -> Set[str]: <ide> """ <del> >>> ''.join(sorted(bfs(G, 'A'))) <add> >>> ''.join(sorted(breadth_first_search(G, 'A'))) <ide> 'ABCDEF' <ide> """ <del> explored, queue = set(), [start] # collections.deque([start]) <del> explored.add(start) <add> explored = {start} <add> queue = [start] <ide> while queue: <ide> v = queue.pop(0) # queue.popleft() <ide> for w in graph[v]: <ide> def bfs(graph, start): <ide> <ide> <ide> if __name__ == "__main__": <del> print(bfs(G, "A")) <add> print(breadth_first_search(G, "A"))
1
Text
Text
add jhamhader to collaborators
20501275d376f1f3e950c2131dfad71c931f79e7
<ide><path>README.md <ide> information about the governance of the Node.js project, see <ide> * [iWuzHere](https://github.com/iWuzHere) - **Imran Iqbal** &lt;imran@imraniqbal.org&gt; <ide> * [JacksonTian](https://github.com/JacksonTian) - **Jackson Tian** &lt;shvyo1987@gmail.com&gt; <ide> * [jbergstroem](https://github.com/jbergstroem) - **Johan Bergström** &lt;bugs@bergstroem.nu&gt; <add>* [jhamhader](https://github.com/jhamhader) - **Yuval Brik** &lt;yuval@brik.org.il&gt; <ide> * [joaocgreis](https://github.com/joaocgreis) - **João Reis** &lt;reis@janeasystems.com&gt; <ide> * [julianduque](https://github.com/julianduque) - **Julian Duque** &lt;julianduquej@gmail.com&gt; <ide> * [JungMinu](https://github.com/JungMinu) - **Minwoo Jung** &lt;jmwsoft@gmail.com&gt;
1
Mixed
Python
add resume logic to spacy pretrain
9c064e6ad95ac2733fc27a874644b6ad8caecedf
<ide><path>spacy/cli/pretrain.py <ide> from .._ml import Tok2Vec, flatten, chain, create_default_optimizer <ide> from .._ml import masked_language_model <ide> from .. import util <add>from .train import _load_pretrained_tok2vec <ide> <ide> <ide> @plac.annotations( <ide> seed=("Seed for random number generators", "option", "s", int), <ide> n_iter=("Number of iterations to pretrain", "option", "i", int), <ide> n_save_every=("Save model every X batches.", "option", "se", int), <add> init_tok2vec=( <add> "Path to pretrained weights for the token-to-vector parts of the models. See 'spacy pretrain'. Experimental.", <add> "option", <add> "t2v", <add> Path, <add> ), <ide> ) <ide> def pretrain( <ide> texts_loc, <ide> def pretrain( <ide> min_length=5, <ide> seed=0, <ide> n_save_every=None, <add> init_tok2vec=None, <ide> ): <ide> """ <ide> Pre-train the 'token-to-vector' (tok2vec) layer of pipeline components, <ide> def pretrain( <ide> errors around this need some improvement. <ide> """ <ide> config = dict(locals()) <add> for key in config: <add> if isinstance(config[key], Path): <add> config[key] = str(config[key]) <ide> msg = Printer() <ide> util.fix_random_seed(seed) <ide> <ide> def pretrain( <ide> subword_features=True, # Set to False for Chinese etc <ide> ), <ide> ) <add> # Load in pre-trained weights <add> if init_tok2vec is not None: <add> components = _load_pretrained_tok2vec(nlp, init_tok2vec) <add> msg.text("Loaded pretrained tok2vec for: {}".format(components)) <ide> optimizer = create_default_optimizer(model.ops) <ide> tracker = ProgressTracker(frequency=10000) <ide> msg.divider("Pre-training tok2vec layer") <ide><path>website/docs/api/cli.md <ide> $ python -m spacy pretrain [texts_loc] [vectors_model] [output_dir] [--width] <ide> | `--n-iter`, `-i` | option | Number of iterations to pretrain. | <ide> | `--use-vectors`, `-uv` | flag | Whether to use the static vectors as input features. | <ide> | `--n-save_every`, `-se` | option | Save model every X batches. | <add>| `--init-tok2vec`, `-t2v` <Tag variant="new">2.1</Tag> | option | Path to pretrained weights for the token-to-vector parts of the models. See `spacy pretrain`. Experimental.| <ide> | **CREATES** | weights | The pre-trained weights that can be used to initialize `spacy train`. | <ide> <ide> ### JSONL format for raw text {#pretrain-jsonl}
2
Python
Python
update optimizer documentation
bab5d130776b98a6988477ec11fe0c11b0b95d74
<ide><path>optimization.py <ide> def warmup_linear(x, warmup=0.002): <ide> <ide> <ide> class BERTAdam(Optimizer): <del> """Implements Open AI version of Adam algorithm with weight decay fix. <add> """Implements BERT version of Adam algorithm with weight decay fix (and no ). <ide> Params: <del> lr, <del> warmup=-1, <del> t_total=-1, <del> schedule='warmup_linear', <del> b1=0.9, <del> b2=0.999, <del> e=1e-6, <del> weight_decay_rate=0.01, <del> max_grad_norm=1.0 <add> lr: learning rate <add> warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1 <add> t_total: total number of training steps for the learning <add> rate schedule, -1 means constant learning rate. Default: -1 <add> schedule: schedule to use for the warmup (see above). Default: 'warmup_linear' <add> b1: Adams b1. Default: 0.9 <add> b2: Adams b2. Default: 0.999 <add> e: Adams epsilon. Default: 1e-6 <add> weight_decay_rate: Weight decay. Default: 0.01 <add> max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0 <ide> """ <ide> def __init__(self, params, lr, warmup=-1, t_total=-1, schedule='warmup_linear', <ide> b1=0.9, b2=0.999, e=1e-6, weight_decay_rate=0.01,
1
Text
Text
fix an unclear wording in readline.md
20987752a2ed63aa260b5e7e4779c093d4ec09f2
<ide><path>doc/api/readline.md <ide> a `'resize'` event on the `output` if or when the columns ever change <ide> <ide> ### Use of the `completer` Function <ide> <del>When called, the `completer` function is provided the current line entered by <del>the user, and is expected to return an Array with 2 entries: <add>The `completer` function takes the current line entered by the user <add>as an argument, and returns an Array with 2 entries: <ide> <ide> * An Array with matching entries for the completion. <ide> * The substring that was used for the matching.
1
Go
Go
move portmapper and portallocator into libnetwork
5d7b4308012c2d0239c81b9574385a9196c2300e
<ide><path>libnetwork/drivers/bridge/setup_ip_tables.go <ide> import ( <ide> "fmt" <ide> "net" <ide> <del> "github.com/docker/docker/daemon/networkdriver" <del> "github.com/docker/docker/daemon/networkdriver/portmapper" <ide> "github.com/docker/docker/pkg/iptables" <add> "github.com/docker/libnetwork" <add> "github.com/docker/libnetwork/portmapper" <ide> ) <ide> <ide> // DockerChain: DOCKER iptable chain name <ide> func setupIPTables(i *bridgeInterface) error { <ide> return fmt.Errorf("Unexpected request to set IP tables for interface: %s", i.Config.BridgeName) <ide> } <ide> <del> addrv4, _, err := networkdriver.GetIfaceAddr(i.Config.BridgeName) <add> addrv4, _, err := libnetwork.GetIfaceAddr(i.Config.BridgeName) <ide> if err != nil { <ide> return fmt.Errorf("Failed to setup IP tables, cannot acquire Interface address: %s", err.Error()) <ide> } <ide><path>libnetwork/portallocator/portallocator.go <add>package portallocator <add> <add>import ( <add> "errors" <add> "fmt" <add> "net" <add> "sync" <add>) <add> <add>type portMap struct { <add> p map[int]struct{} <add> last int <add>} <add> <add>func newPortMap() *portMap { <add> return &portMap{ <add> p: map[int]struct{}{}, <add> last: EndPortRange, <add> } <add>} <add> <add>type protoMap map[string]*portMap <add> <add>func newProtoMap() protoMap { <add> return protoMap{ <add> "tcp": newPortMap(), <add> "udp": newPortMap(), <add> } <add>} <add> <add>type ipMapping map[string]protoMap <add> <add>const ( <add> // BeginPortRange indicates the first port in port range <add> BeginPortRange = 49153 <add> // EndPortRange indicates the last port in port range <add> EndPortRange = 65535 <add>) <add> <add>var ( <add> // ErrAllPortsAllocated is returned when no more ports are available <add> ErrAllPortsAllocated = errors.New("all ports are allocated") <add> // ErrUnknownProtocol is returned when an unknown protocol was specified <add> ErrUnknownProtocol = errors.New("unknown protocol") <add>) <add> <add>var ( <add> mutex sync.Mutex <add> <add> defaultIP = net.ParseIP("0.0.0.0") <add> globalMap = ipMapping{} <add>) <add> <add>// ErrPortAlreadyAllocated is the returned error information when a requested port is already being used <add>type ErrPortAlreadyAllocated struct { <add> ip string <add> port int <add>} <add> <add>func newErrPortAlreadyAllocated(ip string, port int) ErrPortAlreadyAllocated { <add> return ErrPortAlreadyAllocated{ <add> ip: ip, <add> port: port, <add> } <add>} <add> <add>// IP returns the address to which the used port is associated <add>func (e ErrPortAlreadyAllocated) IP() string { <add> return e.ip <add>} <add> <add>// Port returns the value of the already used port <add>func (e ErrPortAlreadyAllocated) Port() int { <add> return e.port <add>} <add> <add>// IPPort returns the address and the port in the form ip:port <add>func (e ErrPortAlreadyAllocated) IPPort() string { <add> return fmt.Sprintf("%s:%d", e.ip, e.port) <add>} <add> <add>// Error is the implementation of error.Error interface <add>func (e ErrPortAlreadyAllocated) Error() string { <add> return fmt.Sprintf("Bind for %s:%d failed: port is already allocated", e.ip, e.port) <add>} <add> <add>// RequestPort requests new port from global ports pool for specified ip and proto. <add>// If port is 0 it returns first free port. Otherwise it cheks port availability <add>// in pool and return that port or error if port is already busy. <add>func RequestPort(ip net.IP, proto string, port int) (int, error) { <add> mutex.Lock() <add> defer mutex.Unlock() <add> <add> if proto != "tcp" && proto != "udp" { <add> return 0, ErrUnknownProtocol <add> } <add> <add> if ip == nil { <add> ip = defaultIP <add> } <add> ipstr := ip.String() <add> protomap, ok := globalMap[ipstr] <add> if !ok { <add> protomap = newProtoMap() <add> globalMap[ipstr] = protomap <add> } <add> mapping := protomap[proto] <add> if port > 0 { <add> if _, ok := mapping.p[port]; !ok { <add> mapping.p[port] = struct{}{} <add> return port, nil <add> } <add> return 0, newErrPortAlreadyAllocated(ipstr, port) <add> } <add> <add> port, err := mapping.findPort() <add> if err != nil { <add> return 0, err <add> } <add> return port, nil <add>} <add> <add>// ReleasePort releases port from global ports pool for specified ip and proto. <add>func ReleasePort(ip net.IP, proto string, port int) error { <add> mutex.Lock() <add> defer mutex.Unlock() <add> <add> if ip == nil { <add> ip = defaultIP <add> } <add> protomap, ok := globalMap[ip.String()] <add> if !ok { <add> return nil <add> } <add> delete(protomap[proto].p, port) <add> return nil <add>} <add> <add>// ReleaseAll releases all ports for all ips. <add>func ReleaseAll() error { <add> mutex.Lock() <add> globalMap = ipMapping{} <add> mutex.Unlock() <add> return nil <add>} <add> <add>func (pm *portMap) findPort() (int, error) { <add> port := pm.last <add> for i := 0; i <= EndPortRange-BeginPortRange; i++ { <add> port++ <add> if port > EndPortRange { <add> port = BeginPortRange <add> } <add> <add> if _, ok := pm.p[port]; !ok { <add> pm.p[port] = struct{}{} <add> pm.last = port <add> return port, nil <add> } <add> } <add> return 0, ErrAllPortsAllocated <add>} <ide><path>libnetwork/portallocator/portallocator_test.go <add>package portallocator <add> <add>import ( <add> "net" <add> "testing" <add>) <add> <add>func reset() { <add> ReleaseAll() <add>} <add> <add>func TestRequestNewPort(t *testing.T) { <add> defer reset() <add> <add> port, err := RequestPort(defaultIP, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := BeginPortRange; port != expected { <add> t.Fatalf("Expected port %d got %d", expected, port) <add> } <add>} <add> <add>func TestRequestSpecificPort(t *testing.T) { <add> defer reset() <add> <add> port, err := RequestPort(defaultIP, "tcp", 5000) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if port != 5000 { <add> t.Fatalf("Expected port 5000 got %d", port) <add> } <add>} <add> <add>func TestReleasePort(t *testing.T) { <add> defer reset() <add> <add> port, err := RequestPort(defaultIP, "tcp", 5000) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if port != 5000 { <add> t.Fatalf("Expected port 5000 got %d", port) <add> } <add> <add> if err := ReleasePort(defaultIP, "tcp", 5000); err != nil { <add> t.Fatal(err) <add> } <add>} <add> <add>func TestReuseReleasedPort(t *testing.T) { <add> defer reset() <add> <add> port, err := RequestPort(defaultIP, "tcp", 5000) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if port != 5000 { <add> t.Fatalf("Expected port 5000 got %d", port) <add> } <add> <add> if err := ReleasePort(defaultIP, "tcp", 5000); err != nil { <add> t.Fatal(err) <add> } <add> <add> port, err = RequestPort(defaultIP, "tcp", 5000) <add> if err != nil { <add> t.Fatal(err) <add> } <add>} <add> <add>func TestReleaseUnreadledPort(t *testing.T) { <add> defer reset() <add> <add> port, err := RequestPort(defaultIP, "tcp", 5000) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if port != 5000 { <add> t.Fatalf("Expected port 5000 got %d", port) <add> } <add> <add> port, err = RequestPort(defaultIP, "tcp", 5000) <add> <add> switch err.(type) { <add> case ErrPortAlreadyAllocated: <add> default: <add> t.Fatalf("Expected port allocation error got %s", err) <add> } <add>} <add> <add>func TestUnknowProtocol(t *testing.T) { <add> defer reset() <add> <add> if _, err := RequestPort(defaultIP, "tcpp", 0); err != ErrUnknownProtocol { <add> t.Fatalf("Expected error %s got %s", ErrUnknownProtocol, err) <add> } <add>} <add> <add>func TestAllocateAllPorts(t *testing.T) { <add> defer reset() <add> <add> for i := 0; i <= EndPortRange-BeginPortRange; i++ { <add> port, err := RequestPort(defaultIP, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if expected := BeginPortRange + i; port != expected { <add> t.Fatalf("Expected port %d got %d", expected, port) <add> } <add> } <add> <add> if _, err := RequestPort(defaultIP, "tcp", 0); err != ErrAllPortsAllocated { <add> t.Fatalf("Expected error %s got %s", ErrAllPortsAllocated, err) <add> } <add> <add> _, err := RequestPort(defaultIP, "udp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> // release a port in the middle and ensure we get another tcp port <add> port := BeginPortRange + 5 <add> if err := ReleasePort(defaultIP, "tcp", port); err != nil { <add> t.Fatal(err) <add> } <add> newPort, err := RequestPort(defaultIP, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if newPort != port { <add> t.Fatalf("Expected port %d got %d", port, newPort) <add> } <add> <add> // now pm.last == newPort, release it so that it's the only free port of <add> // the range, and ensure we get it back <add> if err := ReleasePort(defaultIP, "tcp", newPort); err != nil { <add> t.Fatal(err) <add> } <add> port, err = RequestPort(defaultIP, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if newPort != port { <add> t.Fatalf("Expected port %d got %d", newPort, port) <add> } <add>} <add> <add>func BenchmarkAllocatePorts(b *testing.B) { <add> defer reset() <add> <add> for i := 0; i < b.N; i++ { <add> for i := 0; i <= EndPortRange-BeginPortRange; i++ { <add> port, err := RequestPort(defaultIP, "tcp", 0) <add> if err != nil { <add> b.Fatal(err) <add> } <add> <add> if expected := BeginPortRange + i; port != expected { <add> b.Fatalf("Expected port %d got %d", expected, port) <add> } <add> } <add> reset() <add> } <add>} <add> <add>func TestPortAllocation(t *testing.T) { <add> defer reset() <add> <add> ip := net.ParseIP("192.168.0.1") <add> ip2 := net.ParseIP("192.168.0.2") <add> if port, err := RequestPort(ip, "tcp", 80); err != nil { <add> t.Fatal(err) <add> } else if port != 80 { <add> t.Fatalf("Acquire(80) should return 80, not %d", port) <add> } <add> port, err := RequestPort(ip, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if port <= 0 { <add> t.Fatalf("Acquire(0) should return a non-zero port") <add> } <add> <add> if _, err := RequestPort(ip, "tcp", port); err == nil { <add> t.Fatalf("Acquiring a port already in use should return an error") <add> } <add> <add> if newPort, err := RequestPort(ip, "tcp", 0); err != nil { <add> t.Fatal(err) <add> } else if newPort == port { <add> t.Fatalf("Acquire(0) allocated the same port twice: %d", port) <add> } <add> <add> if _, err := RequestPort(ip, "tcp", 80); err == nil { <add> t.Fatalf("Acquiring a port already in use should return an error") <add> } <add> if _, err := RequestPort(ip2, "tcp", 80); err != nil { <add> t.Fatalf("It should be possible to allocate the same port on a different interface") <add> } <add> if _, err := RequestPort(ip2, "tcp", 80); err == nil { <add> t.Fatalf("Acquiring a port already in use should return an error") <add> } <add> if err := ReleasePort(ip, "tcp", 80); err != nil { <add> t.Fatal(err) <add> } <add> if _, err := RequestPort(ip, "tcp", 80); err != nil { <add> t.Fatal(err) <add> } <add> <add> port, err = RequestPort(ip, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> port2, err := RequestPort(ip, "tcp", port+1) <add> if err != nil { <add> t.Fatal(err) <add> } <add> port3, err := RequestPort(ip, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if port3 == port2 { <add> t.Fatal("Requesting a dynamic port should never allocate a used port") <add> } <add>} <add> <add>func TestNoDuplicateBPR(t *testing.T) { <add> defer reset() <add> <add> if port, err := RequestPort(defaultIP, "tcp", BeginPortRange); err != nil { <add> t.Fatal(err) <add> } else if port != BeginPortRange { <add> t.Fatalf("Expected port %d got %d", BeginPortRange, port) <add> } <add> <add> if port, err := RequestPort(defaultIP, "tcp", 0); err != nil { <add> t.Fatal(err) <add> } else if port == BeginPortRange { <add> t.Fatalf("Acquire(0) allocated the same port twice: %d", port) <add> } <add>} <ide><path>libnetwork/portmapper/mapper.go <add>package portmapper <add> <add>import ( <add> "errors" <add> "fmt" <add> "net" <add> "sync" <add> <add> log "github.com/Sirupsen/logrus" <add> "github.com/docker/docker/pkg/iptables" <add> "github.com/docker/libnetwork/portallocator" <add>) <add> <add>type mapping struct { <add> proto string <add> userlandProxy userlandProxy <add> host net.Addr <add> container net.Addr <add>} <add> <add>var ( <add> chain *iptables.Chain <add> lock sync.Mutex <add> <add> // udp:ip:port <add> currentMappings = make(map[string]*mapping) <add> <add> newProxy = newProxyCommand <add>) <add> <add>var ( <add> // ErrUnknownBackendAddressType refers to an unknown container or unsupported address type <add> ErrUnknownBackendAddressType = errors.New("unknown container address type not supported") <add> // ErrPortMappedForIP refers to a port already mapped to an ip address <add> ErrPortMappedForIP = errors.New("port is already mapped to ip") <add> // ErrPortNotMapped refers to an unampped port <add> ErrPortNotMapped = errors.New("port is not mapped") <add>) <add> <add>// SetIptablesChain sets the specified chain into portmapper <add>func SetIptablesChain(c *iptables.Chain) { <add> chain = c <add>} <add> <add>// Map maps the specified container transport address to the host's network address and transport port <add>func Map(container net.Addr, hostIP net.IP, hostPort int) (host net.Addr, err error) { <add> lock.Lock() <add> defer lock.Unlock() <add> <add> var ( <add> m *mapping <add> proto string <add> allocatedHostPort int <add> proxy userlandProxy <add> ) <add> <add> switch container.(type) { <add> case *net.TCPAddr: <add> proto = "tcp" <add> if allocatedHostPort, err = portallocator.RequestPort(hostIP, proto, hostPort); err != nil { <add> return nil, err <add> } <add> <add> m = &mapping{ <add> proto: proto, <add> host: &net.TCPAddr{IP: hostIP, Port: allocatedHostPort}, <add> container: container, <add> } <add> <add> proxy = newProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port) <add> case *net.UDPAddr: <add> proto = "udp" <add> if allocatedHostPort, err = portallocator.RequestPort(hostIP, proto, hostPort); err != nil { <add> return nil, err <add> } <add> <add> m = &mapping{ <add> proto: proto, <add> host: &net.UDPAddr{IP: hostIP, Port: allocatedHostPort}, <add> container: container, <add> } <add> <add> proxy = newProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port) <add> default: <add> return nil, ErrUnknownBackendAddressType <add> } <add> <add> // release the allocated port on any further error during return. <add> defer func() { <add> if err != nil { <add> portallocator.ReleasePort(hostIP, proto, allocatedHostPort) <add> } <add> }() <add> <add> key := getKey(m.host) <add> if _, exists := currentMappings[key]; exists { <add> return nil, ErrPortMappedForIP <add> } <add> <add> containerIP, containerPort := getIPAndPort(m.container) <add> if err := forward(iptables.Append, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort); err != nil { <add> return nil, err <add> } <add> <add> cleanup := func() error { <add> // need to undo the iptables rules before we return <add> proxy.Stop() <add> forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort) <add> if err := portallocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil { <add> return err <add> } <add> <add> return nil <add> } <add> <add> if err := proxy.Start(); err != nil { <add> if err := cleanup(); err != nil { <add> return nil, fmt.Errorf("Error during port allocation cleanup: %v", err) <add> } <add> return nil, err <add> } <add> m.userlandProxy = proxy <add> currentMappings[key] = m <add> return m.host, nil <add>} <add> <add>// Unmap removes stored mapping for the specified host transport address <add>func Unmap(host net.Addr) error { <add> lock.Lock() <add> defer lock.Unlock() <add> <add> key := getKey(host) <add> data, exists := currentMappings[key] <add> if !exists { <add> return ErrPortNotMapped <add> } <add> <add> data.userlandProxy.Stop() <add> <add> delete(currentMappings, key) <add> <add> containerIP, containerPort := getIPAndPort(data.container) <add> hostIP, hostPort := getIPAndPort(data.host) <add> if err := forward(iptables.Delete, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil { <add> log.Errorf("Error on iptables delete: %s", err) <add> } <add> <add> switch a := host.(type) { <add> case *net.TCPAddr: <add> return portallocator.ReleasePort(a.IP, "tcp", a.Port) <add> case *net.UDPAddr: <add> return portallocator.ReleasePort(a.IP, "udp", a.Port) <add> } <add> return nil <add>} <add> <add>func getKey(a net.Addr) string { <add> switch t := a.(type) { <add> case *net.TCPAddr: <add> return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "tcp") <add> case *net.UDPAddr: <add> return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "udp") <add> } <add> return "" <add>} <add> <add>func getIPAndPort(a net.Addr) (net.IP, int) { <add> switch t := a.(type) { <add> case *net.TCPAddr: <add> return t.IP, t.Port <add> case *net.UDPAddr: <add> return t.IP, t.Port <add> } <add> return nil, 0 <add>} <add> <add>func forward(action iptables.Action, proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error { <add> if chain == nil { <add> return nil <add> } <add> return chain.Forward(action, sourceIP, sourcePort, proto, containerIP, containerPort) <add>} <ide><path>libnetwork/portmapper/mapper_test.go <add>package portmapper <add> <add>import ( <add> "net" <add> "testing" <add> <add> "github.com/docker/docker/pkg/iptables" <add> "github.com/docker/libnetwork/portallocator" <add>) <add> <add>func init() { <add> // override this func to mock out the proxy server <add> newProxy = newMockProxyCommand <add>} <add> <add>func reset() { <add> chain = nil <add> currentMappings = make(map[string]*mapping) <add>} <add> <add>func TestSetIptablesChain(t *testing.T) { <add> defer reset() <add> <add> c := &iptables.Chain{ <add> Name: "TEST", <add> Bridge: "192.168.1.1", <add> } <add> <add> if chain != nil { <add> t.Fatal("chain should be nil at init") <add> } <add> <add> SetIptablesChain(c) <add> if chain == nil { <add> t.Fatal("chain should not be nil after set") <add> } <add>} <add> <add>func TestMapPorts(t *testing.T) { <add> dstIP1 := net.ParseIP("192.168.0.1") <add> dstIP2 := net.ParseIP("192.168.0.2") <add> dstAddr1 := &net.TCPAddr{IP: dstIP1, Port: 80} <add> dstAddr2 := &net.TCPAddr{IP: dstIP2, Port: 80} <add> <add> srcAddr1 := &net.TCPAddr{Port: 1080, IP: net.ParseIP("172.16.0.1")} <add> srcAddr2 := &net.TCPAddr{Port: 1080, IP: net.ParseIP("172.16.0.2")} <add> <add> addrEqual := func(addr1, addr2 net.Addr) bool { <add> return (addr1.Network() == addr2.Network()) && (addr1.String() == addr2.String()) <add> } <add> <add> if host, err := Map(srcAddr1, dstIP1, 80); err != nil { <add> t.Fatalf("Failed to allocate port: %s", err) <add> } else if !addrEqual(dstAddr1, host) { <add> t.Fatalf("Incorrect mapping result: expected %s:%s, got %s:%s", <add> dstAddr1.String(), dstAddr1.Network(), host.String(), host.Network()) <add> } <add> <add> if _, err := Map(srcAddr1, dstIP1, 80); err == nil { <add> t.Fatalf("Port is in use - mapping should have failed") <add> } <add> <add> if _, err := Map(srcAddr2, dstIP1, 80); err == nil { <add> t.Fatalf("Port is in use - mapping should have failed") <add> } <add> <add> if _, err := Map(srcAddr2, dstIP2, 80); err != nil { <add> t.Fatalf("Failed to allocate port: %s", err) <add> } <add> <add> if Unmap(dstAddr1) != nil { <add> t.Fatalf("Failed to release port") <add> } <add> <add> if Unmap(dstAddr2) != nil { <add> t.Fatalf("Failed to release port") <add> } <add> <add> if Unmap(dstAddr2) == nil { <add> t.Fatalf("Port already released, but no error reported") <add> } <add>} <add> <add>func TestGetUDPKey(t *testing.T) { <add> addr := &net.UDPAddr{IP: net.ParseIP("192.168.1.5"), Port: 53} <add> <add> key := getKey(addr) <add> <add> if expected := "192.168.1.5:53/udp"; key != expected { <add> t.Fatalf("expected key %s got %s", expected, key) <add> } <add>} <add> <add>func TestGetTCPKey(t *testing.T) { <add> addr := &net.TCPAddr{IP: net.ParseIP("192.168.1.5"), Port: 80} <add> <add> key := getKey(addr) <add> <add> if expected := "192.168.1.5:80/tcp"; key != expected { <add> t.Fatalf("expected key %s got %s", expected, key) <add> } <add>} <add> <add>func TestGetUDPIPAndPort(t *testing.T) { <add> addr := &net.UDPAddr{IP: net.ParseIP("192.168.1.5"), Port: 53} <add> <add> ip, port := getIPAndPort(addr) <add> if expected := "192.168.1.5"; ip.String() != expected { <add> t.Fatalf("expected ip %s got %s", expected, ip) <add> } <add> <add> if ep := 53; port != ep { <add> t.Fatalf("expected port %d got %d", ep, port) <add> } <add>} <add> <add>func TestMapAllPortsSingleInterface(t *testing.T) { <add> dstIP1 := net.ParseIP("0.0.0.0") <add> srcAddr1 := &net.TCPAddr{Port: 1080, IP: net.ParseIP("172.16.0.1")} <add> <add> hosts := []net.Addr{} <add> var host net.Addr <add> var err error <add> <add> defer func() { <add> for _, val := range hosts { <add> Unmap(val) <add> } <add> }() <add> <add> for i := 0; i < 10; i++ { <add> for i := portallocator.BeginPortRange; i < portallocator.EndPortRange; i++ { <add> if host, err = Map(srcAddr1, dstIP1, 0); err != nil { <add> t.Fatal(err) <add> } <add> <add> hosts = append(hosts, host) <add> } <add> <add> if _, err := Map(srcAddr1, dstIP1, portallocator.BeginPortRange); err == nil { <add> t.Fatalf("Port %d should be bound but is not", portallocator.BeginPortRange) <add> } <add> <add> for _, val := range hosts { <add> if err := Unmap(val); err != nil { <add> t.Fatal(err) <add> } <add> } <add> <add> hosts = []net.Addr{} <add> } <add>} <ide><path>libnetwork/portmapper/mock_proxy.go <add>package portmapper <add> <add>import "net" <add> <add>func newMockProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int) userlandProxy { <add> return &mockProxyCommand{} <add>} <add> <add>type mockProxyCommand struct { <add>} <add> <add>func (p *mockProxyCommand) Start() error { <add> return nil <add>} <add> <add>func (p *mockProxyCommand) Stop() error { <add> return nil <add>} <ide><path>libnetwork/portmapper/proxy.go <add>package portmapper <add> <add>import ( <add> "flag" <add> "fmt" <add> "io/ioutil" <add> "log" <add> "net" <add> "os" <add> "os/exec" <add> "os/signal" <add> "strconv" <add> "syscall" <add> "time" <add> <add> "github.com/docker/docker/pkg/proxy" <add> "github.com/docker/docker/pkg/reexec" <add>) <add> <add>const userlandProxyCommandName = "docker-proxy" <add> <add>func init() { <add> reexec.Register(userlandProxyCommandName, execProxy) <add>} <add> <add>type userlandProxy interface { <add> Start() error <add> Stop() error <add>} <add> <add>// proxyCommand wraps an exec.Cmd to run the userland TCP and UDP <add>// proxies as separate processes. <add>type proxyCommand struct { <add> cmd *exec.Cmd <add>} <add> <add>// execProxy is the reexec function that is registered to start the userland proxies <add>func execProxy() { <add> f := os.NewFile(3, "signal-parent") <add> host, container := parseHostContainerAddrs() <add> <add> p, err := proxy.NewProxy(host, container) <add> if err != nil { <add> fmt.Fprintf(f, "1\n%s", err) <add> f.Close() <add> os.Exit(1) <add> } <add> go handleStopSignals(p) <add> fmt.Fprint(f, "0\n") <add> f.Close() <add> <add> // Run will block until the proxy stops <add> p.Run() <add>} <add> <add>// parseHostContainerAddrs parses the flags passed on reexec to create the TCP or UDP <add>// net.Addrs to map the host and container ports <add>func parseHostContainerAddrs() (host net.Addr, container net.Addr) { <add> var ( <add> proto = flag.String("proto", "tcp", "proxy protocol") <add> hostIP = flag.String("host-ip", "", "host ip") <add> hostPort = flag.Int("host-port", -1, "host port") <add> containerIP = flag.String("container-ip", "", "container ip") <add> containerPort = flag.Int("container-port", -1, "container port") <add> ) <add> <add> flag.Parse() <add> <add> switch *proto { <add> case "tcp": <add> host = &net.TCPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort} <add> container = &net.TCPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort} <add> case "udp": <add> host = &net.UDPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort} <add> container = &net.UDPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort} <add> default: <add> log.Fatalf("unsupported protocol %s", *proto) <add> } <add> <add> return host, container <add>} <add> <add>func handleStopSignals(p proxy.Proxy) { <add> s := make(chan os.Signal, 10) <add> signal.Notify(s, os.Interrupt, syscall.SIGTERM, syscall.SIGSTOP) <add> <add> for _ = range s { <add> p.Close() <add> <add> os.Exit(0) <add> } <add>} <add> <add>func newProxyCommand(proto string, hostIP net.IP, hostPort int, containerIP net.IP, containerPort int) userlandProxy { <add> args := []string{ <add> userlandProxyCommandName, <add> "-proto", proto, <add> "-host-ip", hostIP.String(), <add> "-host-port", strconv.Itoa(hostPort), <add> "-container-ip", containerIP.String(), <add> "-container-port", strconv.Itoa(containerPort), <add> } <add> <add> return &proxyCommand{ <add> cmd: &exec.Cmd{ <add> Path: reexec.Self(), <add> Args: args, <add> SysProcAttr: &syscall.SysProcAttr{ <add> Pdeathsig: syscall.SIGTERM, // send a sigterm to the proxy if the daemon process dies <add> }, <add> }, <add> } <add>} <add> <add>func (p *proxyCommand) Start() error { <add> r, w, err := os.Pipe() <add> if err != nil { <add> return fmt.Errorf("proxy unable to open os.Pipe %s", err) <add> } <add> defer r.Close() <add> p.cmd.ExtraFiles = []*os.File{w} <add> if err := p.cmd.Start(); err != nil { <add> return err <add> } <add> w.Close() <add> <add> errchan := make(chan error, 1) <add> go func() { <add> buf := make([]byte, 2) <add> r.Read(buf) <add> <add> if string(buf) != "0\n" { <add> errStr, err := ioutil.ReadAll(r) <add> if err != nil { <add> errchan <- fmt.Errorf("Error reading exit status from userland proxy: %v", err) <add> return <add> } <add> <add> errchan <- fmt.Errorf("Error starting userland proxy: %s", errStr) <add> return <add> } <add> errchan <- nil <add> }() <add> <add> select { <add> case err := <-errchan: <add> return err <add> case <-time.After(16 * time.Second): <add> return fmt.Errorf("Timed out proxy starting the userland proxy") <add> } <add>} <add> <add>func (p *proxyCommand) Stop() error { <add> if p.cmd.Process != nil { <add> if err := p.cmd.Process.Signal(os.Interrupt); err != nil { <add> return err <add> } <add> return p.cmd.Wait() <add> } <add> return nil <add>}
7
Javascript
Javascript
add docs about form submission
d1e7a5394ad74e0dc024a50f77fa32b46eac1be2
<ide><path>src/widget/form.js <ide> * element nesting. <ide> * <ide> * <add> * # Submitting a form and preventing default action <add> * <add> * Since the role of forms in client-side Angular applications is different than in old-school <add> * roundtrip apps, it is desirable for the browser not to translate the form submission into a full <add> * page reload that sends the data to the server. Instead some javascript logic should be triggered <add> * to handle the form submission in application specific way. <add> * <add> * For this reason, Angular prevents the default action (form submission to the server) unless the <add> * `<form>` element has an `action` attribute specified. <add> * <add> * You can use one of the following two ways to specify what javascript method should be called when <add> * a form is submitted: <add> * <add> * - ng:submit on the form element (add link to ng:submit) <add> * - ng:click on the first button or input field of type submit (input[type=submit]) <add> * <add> * To prevent double execution of the handler, use only one of ng:submit or ng:click. This is <add> * because of the following form submission rules coming from the html spec: <add> * <add> * - If a form has only one input field then hitting enter in this field triggers form submit <add> * (`ng:submit`) <add> * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter <add> * doesn't trigger submit <add> * - if a form has one or more input fields and one or more buttons or input[type=submit] then <add> * hitting enter in any of the input fields will trigger the click handler on the *first* button or <add> * input[type=submit] (`ng:click`) *and* a submit handler on the enclosing form (`ng:submit`) <add> * <add> * @param {string=} name Name of the form. <add> * <ide> * @example <ide> <doc:example> <ide> <doc:source>
1
Go
Go
use sync.rwmutex for vxlanudpport
38c8a3f84df0d1fbb67c56a74e4b056cb096828f
<ide><path>libnetwork/drivers/overlay/overlayutils/utils.go <ide> import ( <ide> ) <ide> <ide> var ( <add> mutex sync.RWMutex <ide> vxlanUDPPort uint32 <del> mutex sync.Mutex <ide> ) <ide> <ide> const defaultVXLANUDPPort = 4789 <ide> func init() { <ide> <ide> // ConfigVXLANUDPPort configures vxlan udp port number. <ide> func ConfigVXLANUDPPort(vxlanPort uint32) error { <del> mutex.Lock() <del> defer mutex.Unlock() <ide> // if the value comes as 0 by any reason we set it to default value 4789 <ide> if vxlanPort == 0 { <ide> vxlanPort = defaultVXLANUDPPort <ide> func ConfigVXLANUDPPort(vxlanPort uint32) error { <ide> if vxlanPort < 1024 || vxlanPort > 49151 { <ide> return fmt.Errorf("ConfigVxlanUDPPort Vxlan UDP port number is not in valid range %d", vxlanPort) <ide> } <add> mutex.Lock() <ide> vxlanUDPPort = vxlanPort <del> <add> mutex.Unlock() <ide> return nil <ide> } <ide> <ide> // VXLANUDPPort returns Vxlan UDP port number <ide> func VXLANUDPPort() uint32 { <del> mutex.Lock() <del> defer mutex.Unlock() <add> mutex.RLock() <add> defer mutex.RUnlock() <ide> return vxlanUDPPort <ide> }
1
Ruby
Ruby
pass the parent node to the construct method
c4d0e69ad25e596ae3617e8fe96b91097edbfedb
<ide><path>activerecord/lib/active_record/associations/join_dependency.rb <ide> def instantiate(result_set) <ide> parents = {} <ide> <ide> type_caster = result_set.column_type primary_key <del> assoc = join_root.children <ide> <ide> records = result_set.map { |row_hash| <ide> primary_id = type_caster.type_cast row_hash[primary_key] <ide> parent = parents[primary_id] ||= join_root.instantiate(row_hash) <del> construct(parent, assoc, row_hash, result_set) <add> construct(parent, join_root, row_hash, result_set) <ide> parent <ide> }.uniq <ide> <del> remove_duplicate_results!(base_klass, records, assoc) <add> remove_duplicate_results!(base_klass, records, join_root.children) <ide> records <ide> end <ide> <ide> def build_join_association(reflection, parent, join_type) <ide> JoinAssociation.new(reflection, join_root.to_a.length, parent, join_type, alias_tracker) <ide> end <ide> <del> def construct(parent, nodes, row, rs) <del> nodes.each do |node| <del> association = construct_association(parent, node, row, rs) <del> construct(association, node.children, row, rs) if association <add> def construct(ar_parent, parent, row, rs) <add> parent.children.each do |node| <add> association = construct_association(ar_parent, node, row, rs) <add> construct(association, node, row, rs) if association <ide> end <ide> end <ide>
1
Javascript
Javascript
remove sys in new tests
1879d8211d4c05a512ea634126f35e2621831f4b
<ide><path>test/disabled/pipe-test.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> var net = require('net'); <del>var sys = require('sys'); <ide> <ide> var webPort = common.PORT <ide> var tcpPort = webPort + 1; <ide><path>test/simple/test-http-buffer-sanity.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <del>var sys = require('sys'); <add>var util = require('util'); <ide> <ide> var bufferSize = 5 * 1024 * 1024; <ide> var measuredSize = 0;
2
Text
Text
add release notes for 1.2.2 consciousness-inertia
16febf8357c985ab4380ad2f55f3fc966e842f5c
<ide><path>CHANGELOG.md <add><a name="1.2.2"></a> <add># 1.2.2 consciousness-inertia (2013-11-22) <add> <add> <add>## Bug Fixes <add> <add>- **$animate:** <add> - ensure keyframe animations are blocked around the reflow <add> ([6760d7a3](https://github.com/angular/angular.js/commit/6760d7a315d7ea5cbd4f8ab74b200f754a2041f4), <add> [#5018](https://github.com/angular/angular.js/issues/5018)) <add> - ensure transition animations are unblocked before the dom operation occurs <add> ([062fbed8](https://github.com/angular/angular.js/commit/062fbed8fc3f7bc55433f8c6915c27520e6f63c5), <add> [#5014](https://github.com/angular/angular.js/issues/5014), <add> [#4265](https://github.com/angular/angular.js/issues/4265)) <add> - ensure addClass/removeClass animations do not snap during reflow <add> ([76e4db6f](https://github.com/angular/angular.js/commit/76e4db6f3d15199ac1fbe85f9cfa6079a1c4fa56), <add> [#4892](https://github.com/angular/angular.js/issues/4892)) <add> - ensure the DOM operation isn't run twice <add> ([7067a8fb](https://github.com/angular/angular.js/commit/7067a8fb0b18d5b5489006e1960cee721a88b4d2), <add> [#4949](https://github.com/angular/angular.js/issues/4949)) <add>- **$compile:** <add> - secure form[action] & iframe[srcdoc] <add> ([0421cb42](https://github.com/angular/angular.js/commit/0421cb4200e672818ed10996e92311404c150c3a), <add> [#4927](https://github.com/angular/angular.js/issues/4927), <add> [#4933](https://github.com/angular/angular.js/issues/4933)) <add> - ensure CSS classes are added and removed only when necessary <add> ([0cd7e8f2](https://github.com/angular/angular.js/commit/0cd7e8f22721f62b62440bb059ae764ebbe7b42a)) <add>- **$httpBackend:** only IE8 and below can't use `script.onload` for JSONP <add> ([a3172a28](https://github.com/angular/angular.js/commit/a3172a285fd74b5aa6c8d68a4988c767c06f549c), <add> [#4523](https://github.com/angular/angular.js/issues/4523), <add> [#4527](https://github.com/angular/angular.js/issues/4527), <add> [#4922](https://github.com/angular/angular.js/issues/4922)) <add>- **$parse:** allow for new lines in expr when promise unwrapping is on <add> ([40647b17](https://github.com/angular/angular.js/commit/40647b179c473f3f470bb1b3237d6f006269582f), <add> [#4718](https://github.com/angular/angular.js/issues/4718)) <add>- **$resource:** Always return a resource instance when calling class methods on resources. <add> ([f6ecf9a3](https://github.com/angular/angular.js/commit/f6ecf9a3c9090593faf5fa50586c99a56b51c776), <add> [#4545](https://github.com/angular/angular.js/issues/4545), <add> [#5061](https://github.com/angular/angular.js/issues/5061)) <add>- **httpBackend:** should not read response data when request is aborted <add> ([6f1050df](https://github.com/angular/angular.js/commit/6f1050df4fa885bd59ce85adbef7350ea93911a3), <add> [#4913](https://github.com/angular/angular.js/issues/4913), <add> [#4940](https://github.com/angular/angular.js/issues/4940)) <add>- **loader:** expose `$$minErr` to modules such as`ngResource` <add> ([9e89a31b](https://github.com/angular/angular.js/commit/9e89a31b129e40c805178535c244899ffafb77d8), <add> [#5050](https://github.com/angular/angular.js/issues/5050)) <add>- **ngAnimate:** <add> - correctly retain and restore existing styles during and after animation <add> ([c42d0a04](https://github.com/angular/angular.js/commit/c42d0a041890b39fc98afd357ec1307a3a36208d), <add> [#4869](https://github.com/angular/angular.js/issues/4869)) <add> - use a fallback CSS property that doesn't break existing styles <add> ([1d50663b](https://github.com/angular/angular.js/commit/1d50663b38ba042e8d748ffa6d48cfb5e93cfd7e), <add> [#4902](https://github.com/angular/angular.js/issues/4902), <add> [#5030](https://github.com/angular/angular.js/issues/5030)) <add>- **ngClass:** ensure that ngClass only adds/removes the changed classes <add> ([6b8bbe4d](https://github.com/angular/angular.js/commit/6b8bbe4d90640542eed5607a8c91f6b977b1d6c0), <add> [#4960](https://github.com/angular/angular.js/issues/4960), <add> [#4944](https://github.com/angular/angular.js/issues/4944)) <add>- **ngController:** fix issue with ngInclude on the same element <add> ([6288cf5c](https://github.com/angular/angular.js/commit/6288cf5ca471b0615a026fdb4db3ba242c9d8f88), <add> [#4431](https://github.com/angular/angular.js/issues/4431)) <add>- **ngInclude:** <add> - Don't throw when the ngInclude element contains content with directives. <add> ([0a7cbb33](https://github.com/angular/angular.js/commit/0a7cbb33b06778833a4d99b1868cc07690a827a7)) <add> - allow ngInclude to load scripts when jQuery is included <add> ([c47abd0d](https://github.com/angular/angular.js/commit/c47abd0dd7490576f4b84ee51ebaca385c1036da), <add> [#3756](https://github.com/angular/angular.js/issues/3756)) <add>- **ngMock:** fixes httpBackend expectation with body object <add> ([4d16472b](https://github.com/angular/angular.js/commit/4d16472b918a3482942d76f1e273a5aa01f65e83), <add> [#4956](https://github.com/angular/angular.js/issues/4956)) <add>- **ngView:** Don't throw when the ngView element contains content with directives. <add> ([e6521e74](https://github.com/angular/angular.js/commit/e6521e7491242504250b57dd0ee66af49e653c33), <add> [#5069](https://github.com/angular/angular.js/issues/5069)) <add>- **tests:** Correct tests for IE11 <add> ([57924234](https://github.com/angular/angular.js/commit/579242346c4202ea58fc2cae6df232289cbea0bb), <add> [#5046](https://github.com/angular/angular.js/issues/5046)) <add>- **input:** hold listener during text composition <add> ([a4e6d962](https://github.com/angular/angular.js/commit/a4e6d962d78b26f5112d48c4f88c1e6234d0cae7), <add> [#4684](https://github.com/angular/angular.js/issues/4684)) <add> <add> <add> <add> <ide> <a name="1.2.1"></a> <ide> # 1.2.1 underscore-empathy (2013-11-14) <ide>
1
PHP
PHP
change function type in payload
659fd50a651762dcffb9c08bf461cf57105a5159
<ide><path>laravel/session/payload.php <ide> class Payload { <ide> public $session; <ide> <ide> /** <del> * Indicates if the session already exists in storage. <add> * The session driver used to retrieve and store the session payload. <ide> * <del> * @var bool <add> * @var Driver <ide> */ <del> protected $exists = true; <add> public $driver; <ide> <ide> /** <del> * The session driver used to retrieve and store the session payload. <add> * Indicates if the session already exists in storage. <ide> * <del> * @var Driver <add> * @var bool <ide> */ <del> protected $driver; <add> public $exists = true; <ide> <ide> /** <ide> * Create a new session payload instance.
1
Python
Python
fix checkpoint deletion
a515caa331d232897e92282fe96bfceb857e38ff
<ide><path>src/transformers/trainer.py <ide> def _save_checkpoint(self, model, trial, metrics=None): <ide> if self.is_world_process_zero(): <ide> self.state.save_to_json(os.path.join(output_dir, "trainer_state.json")) <ide> <del> # Maybe delete some older checkpoints. <del> if self.is_world_process_zero(): <del> self._rotate_checkpoints(use_mtime=True, output_dir=run_dir) <del> <ide> # Save RNG state in non-distributed training <ide> rng_states = { <ide> "python": random.getstate(), <ide> def _save_checkpoint(self, model, trial, metrics=None): <ide> else: <ide> torch.save(rng_states, os.path.join(output_dir, f"rng_state_{local_rank}.pth")) <ide> <add> # Maybe delete some older checkpoints. <add> if self.is_world_process_zero(): <add> self._rotate_checkpoints(use_mtime=True, output_dir=run_dir) <add> <ide> def _load_optimizer_and_scheduler(self, checkpoint): <ide> """If optimizer and scheduler states exist, load them.""" <ide> if checkpoint is None: <ide> def _sorted_checkpoints( <ide> ordering_and_checkpoint_path.append((os.path.getmtime(path), path)) <ide> else: <ide> regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path) <del> if regex_match and regex_match.groups(): <add> if regex_match is not None and regex_match.groups() is not None: <ide> ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path)) <ide> <ide> checkpoints_sorted = sorted(ordering_and_checkpoint_path) <ide> checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted] <ide> # Make sure we don't delete the best model. <ide> if self.state.best_model_checkpoint is not None: <ide> best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint))) <del> checkpoints_sorted[best_model_index], checkpoints_sorted[-1] = ( <del> checkpoints_sorted[-1], <del> checkpoints_sorted[best_model_index], <del> ) <add> for i in range(best_model_index, len(checkpoints_sorted) - 2): <add> checkpoints_sorted[i], checkpoints_sorted[i + 1] = checkpoints_sorted[i + 1], checkpoints_sorted[i] <ide> return checkpoints_sorted <ide> <ide> def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None: <ide> def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None: <ide> if len(checkpoints_sorted) <= self.args.save_total_limit: <ide> return <ide> <del> number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit) <add> # If save_total_limit=1 with load_best_mode_at_end=True, we could end up deleting the last checkpoint, which <add> # we don't do to allow resuming. <add> save_total_limit = self.args.save_total_limit <add> if ( <add> self.state.best_model_checkpoint is not None <add> and self.args.save_total_limit == 1 <add> and checkpoints_sorted[-1] != self.state.best_model_checkpoint <add> ): <add> save_total_limit = 2 <add> <add> number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit) <ide> checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete] <ide> for checkpoint in checkpoints_to_be_deleted: <ide> logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") <ide><path>tests/test_trainer.py <ide> import re <ide> import tempfile <ide> import unittest <add>from pathlib import Path <ide> <ide> import numpy as np <ide> <ide> require_torch_multi_gpu, <ide> slow, <ide> ) <add>from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR <ide> from transformers.utils.hp_naming import TrialShortNamer <ide> <ide> <ide> def assert_flos_extraction(trainer, wrapped_model_to_check): <ide> trainer.train() <ide> self.assertTrue(isinstance(trainer.state.total_flos, float)) <ide> <add> def check_checkpoint_deletion(self, trainer, output_dir, expected): <add> # Make fake checkpoints <add> for n in [5, 10, 15, 20, 25]: <add> os.makedirs(os.path.join(output_dir, f"{PREFIX_CHECKPOINT_DIR}-{n}"), exist_ok=True) <add> trainer._rotate_checkpoints(output_dir=output_dir) <add> glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{PREFIX_CHECKPOINT_DIR}-*")] <add> values = [int(re.match(f".*{PREFIX_CHECKPOINT_DIR}-([0-9]+)", d).groups()[0]) for d in glob_checkpoints] <add> self.assertSetEqual(set(values), set(expected)) <add> <add> def test_checkpoint_rotation(self): <add> with tempfile.TemporaryDirectory() as tmp_dir: <add> # Without best model at end <add> trainer = get_regression_trainer(output_dir=tmp_dir, save_total_limit=2) <add> self.check_checkpoint_deletion(trainer, tmp_dir, [20, 25]) <add> <add> # With best model at end <add> trainer = get_regression_trainer(output_dir=tmp_dir, load_best_model_at_end=True, save_total_limit=2) <add> trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-5") <add> self.check_checkpoint_deletion(trainer, tmp_dir, [5, 25]) <add> <add> # Edge case: we don't always honor save_total_limit=1 if load_best_model_at_end=True to be able to resume <add> # from checkpoint <add> trainer = get_regression_trainer(output_dir=tmp_dir, load_best_model_at_end=True, save_total_limit=1) <add> trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-25") <add> self.check_checkpoint_deletion(trainer, tmp_dir, [25]) <add> <add> trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-5") <add> self.check_checkpoint_deletion(trainer, tmp_dir, [5, 25]) <add> <ide> def check_mem_metrics(self, trainer, check_func): <ide> metrics = trainer.train().metrics <ide> check_func("init_mem_cpu_alloc_delta", metrics)
2
Javascript
Javascript
swipeablelistview quick actions
763e9cce27177645013f528df5a14c0b6fe05dac
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableQuickActionButton.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * The examples provided by Facebook are for non-commercial testing and <add> * evaluation purposes only. <add> * <add> * Facebook reserves all rights not expressly granted. <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 MERCHANTABILITY, <add> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL <add> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN <add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN <add> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * <add> * <add> * @providesModule SwipeableQuickActionButton <add> * @flow <add> */ <add>'use strict'; <add> <add>const Image = require('Image'); <add>const React = require('React'); <add>const StyleSheet = require('StyleSheet'); <add>const Text = require('Text'); <add>const TouchableHighlight = require('TouchableHighlight'); <add>const View = require('View'); <add> <add>const {PropTypes} = React; <add> <add>const SwipeableQuickActionButton = React.createClass({ <add> propTypes: { <add> accessibilityLabel: PropTypes.string, <add> imageSource: Image.propTypes.source.isRequired, <add> imageStyle: Image.propTypes.style, <add> onPress: PropTypes.func, <add> style: View.propTypes.style, <add> testID: PropTypes.string, <add> text: PropTypes.string, <add> textStyle: Text.propTypes.style, <add> }, <add> <add> render(): ?ReactElement { <add> if (!this.props.imageSource && !this.props.text) { <add> return null; <add> } <add> <add> return ( <add> <TouchableHighlight <add> onPress={this.props.onPress} <add> testID={this.props.testID} <add> underlayColor="transparent"> <add> <View style={[styles.button, this.props.style]}> <add> <Image <add> accessibilityLabel={this.props.accessibilityLabel} <add> source={this.props.imageSource} <add> style={[styles.image, this.props.imageStyle]} <add> /> <add> <Text style={[styles.text, this.props.textStyle]}> <add> {this.props.text} <add> </Text> <add> </View> <add> </TouchableHighlight> <add> ); <add> }, <add>}); <add> <add>const styles = StyleSheet.create({ <add> button: { <add> alignItems: 'center', <add> flex: 1, <add> flexDirection: 'column', <add> justifyContent: 'center', <add> width: 76, <add> }, <add> image: { <add> height: 30, <add> width: 30, <add> }, <add> text: { <add> color: '#ffffff', <add> fontSize: 12, <add> }, <add>}); <add> <add>module.exports = SwipeableQuickActionButton; <ide><path>Libraries/Experimental/SwipeableRow/SwipeableQuickActions.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * The examples provided by Facebook are for non-commercial testing and <add> * evaluation purposes only. <add> * <add> * Facebook reserves all rights not expressly granted. <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 MERCHANTABILITY, <add> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL <add> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN <add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN <add> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * <add> * <add> * @providesModule SwipeableQuickActions <add> * @flow <add> */ <add>'use strict'; <add> <add>const React = require('React'); <add>const StyleSheet = require('StyleSheet'); <add>const View = require('View'); <add> <add>const MAX_QUICK_ACTIONS = 2; <add> <add>const SwipeableQuickActions = React.createClass({ <add> propTypes: { <add> style: View.propTypes.style, <add> }, <add> <add> render(): ReactElement { <add> const children = this.props.children; <add> let buttons = []; <add> <add> // Multiple children <add> if (children instanceof Array) { <add> for (let i = 0; i < children.length && i < MAX_QUICK_ACTIONS; i++) { <add> buttons.push(children[i]); <add> <add> if (i < this.props.children.length - 1) { // Not last button <add> buttons.push(<View key={i} style={styles.divider} />); <add> } <add> } <add> } else { // 1 child <add> buttons = children; <add> } <add> <add> return ( <add> <View style={[styles.background, this.props.style]}> <add> {buttons} <add> </View> <add> ); <add> }, <add>}); <add> <add>const styles = StyleSheet.create({ <add> background: { <add> alignSelf: 'flex-end', <add> flex: 1, <add> flexDirection: 'row', <add> justifyContent: 'flex-end', <add> }, <add> divider: { <add> width: 4, <add> }, <add>}); <add> <add>module.exports = SwipeableQuickActions;
2
PHP
PHP
convert database\type to factory class
6129a49c82152a153713169e9f954c7a7444180d
<ide><path>src/Database/Type.php <ide> namespace Cake\Database; <ide> <ide> use InvalidArgumentException; <del>use PDO; <ide> <ide> /** <del> * Encapsulates all conversion functions for values coming from database into PHP and <del> * going from PHP into database. <add> * Factory for building database type classes. <ide> */ <del>class Type implements TypeInterface <add>class Type <ide> { <ide> <ide> /** <ide> * List of supported database types. A human readable <ide> * identifier is used as key and a complete namespaced class name as value <ide> * representing the class that will do actual type conversions. <ide> * <del> * @var string[]|\Cake\Database\Type[] <add> * @var string[]|\Cake\Database\TypeInterface[] <ide> */ <ide> protected static $_types = [ <ide> 'tinyinteger' => 'Cake\Database\Type\IntegerType', <ide> class Type implements TypeInterface <ide> 'uuid' => 'Cake\Database\Type\UuidType', <ide> ]; <ide> <del> /** <del> * List of basic type mappings, used to avoid having to instantiate a class <del> * for doing conversion on these. <del> * <del> * @var array <del> * @deprecated 3.1 All types will now use a specific class <del> */ <del> protected static $_basicTypes = [ <del> 'string' => ['callback' => [Type::class, 'strval']], <del> 'text' => ['callback' => [Type::class, 'strval']], <del> 'boolean' => [ <del> 'callback' => [Type::class, 'boolval'], <del> 'pdo' => PDO::PARAM_BOOL <del> ], <del> ]; <del> <ide> /** <ide> * Contains a map of type object instances to be reused if needed. <ide> * <ide> * @var \Cake\Database\Type[] <ide> */ <ide> protected static $_builtTypes = []; <ide> <del> /** <del> * Identifier name for this type <del> * <del> * @var string|null <del> */ <del> protected $_name; <del> <del> /** <del> * Constructor <del> * <del> * @param string|null $name The name identifying this type <del> */ <del> public function __construct($name = null) <del> { <del> $this->_name = $name; <del> } <del> <ide> /** <ide> * Returns a Type object capable of converting a type identified by name. <ide> * <ide> public static function clear() <ide> static::$_types = []; <ide> static::$_builtTypes = []; <ide> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function getName() <del> { <del> return $this->_name; <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function getBaseType() <del> { <del> return $this->_name; <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function toDatabase($value, Driver $driver) <del> { <del> return $this->_basicTypeCast($value); <del> } <del> <del> /** <del> * Casts given value from a database type to PHP equivalent <del> * <del> * @param mixed $value Value to be converted to PHP equivalent <del> * @param \Cake\Database\Driver $driver Object from which database preferences and configuration will be extracted <del> * @return mixed <del> */ <del> public function toPHP($value, Driver $driver) <del> { <del> return $this->_basicTypeCast($value); <del> } <del> <del> /** <del> * Checks whether this type is a basic one and can be converted using a callback <del> * If it is, returns converted value <del> * <del> * @param mixed $value Value to be converted to PHP equivalent <del> * @return mixed <del> * @deprecated 3.1 All types should now be a specific class <del> */ <del> protected function _basicTypeCast($value) <del> { <del> deprecationWarning('Type::_basicTypeCast() is deprecated.'); <del> if ($value === null) { <del> return null; <del> } <del> if (!empty(static::$_basicTypes[$this->_name])) { <del> $typeInfo = static::$_basicTypes[$this->_name]; <del> if (isset($typeInfo['callback'])) { <del> return $typeInfo['callback']($value); <del> } <del> } <del> <del> return $value; <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function toStatement($value, Driver $driver) <del> { <del> if ($value === null) { <del> return PDO::PARAM_NULL; <del> } <del> <del> return PDO::PARAM_STR; <del> } <del> <del> /** <del> * Type converter for boolean values. <del> * <del> * Will convert string true/false into booleans. <del> * <del> * @param mixed $value The value to convert to a boolean. <del> * @return bool <del> * @deprecated 3.1.8 This method is now unused. <del> */ <del> public static function boolval($value) <del> { <del> deprecationWarning('Type::boolval() is deprecated.'); <del> if (is_string($value) && !is_numeric($value)) { <del> return strtolower($value) === 'true'; <del> } <del> <del> return !empty($value); <del> } <del> <del> /** <del> * Type converter for string values. <del> * <del> * Will convert values into strings <del> * <del> * @param mixed $value The value to convert to a string. <del> * @return string <del> * @deprecated 3.1.8 This method is now unused. <del> */ <del> public static function strval($value) <del> { <del> deprecationWarning('Type::strval() is deprecated.'); <del> if (is_array($value)) { <del> $value = ''; <del> } <del> <del> return (string)$value; <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function newId() <del> { <del> return null; <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public function marshal($value) <del> { <del> return $this->_basicTypeCast($value); <del> } <del> <del> /** <del> * Returns an array that can be used to describe the internal state of this <del> * object. <del> * <del> * @return array <del> */ <del> public function __debugInfo() <del> { <del> return [ <del> 'name' => $this->_name, <del> ]; <del> } <ide> } <ide><path>tests/TestCase/Database/TypeTest.php <ide> namespace Cake\Test\TestCase\Database; <ide> <ide> use Cake\Database\Type; <add>use Cake\Database\TypeInterface; <ide> use Cake\Database\Type\BoolType; <ide> use Cake\Database\Type\IntegerType; <ide> use Cake\Database\Type\UuidType; <ide> public function tearDown() <ide> public function testBuildBasicTypes($name) <ide> { <ide> $type = Type::build($name); <del> $this->assertInstanceOf('Cake\Database\Type', $type); <add> $this->assertInstanceOf(TypeInterface::class, $type); <ide> $this->assertEquals($name, $type->getName()); <ide> $this->assertEquals($name, $type->getBaseType()); <ide> } <ide> public function testMapAndBuild() <ide> $this->assertEquals($fooType, $map['foo']); <ide> $this->assertEquals($fooType, Type::map('foo')); <ide> <del> $type = Type::build('foo'); <del> $this->assertInstanceOf($fooType, $type); <del> $this->assertEquals('foo', $type->getName()); <del> $this->assertEquals('text', $type->getBaseType()); <del> <ide> Type::map('foo2', $fooType); <ide> $map = Type::map(); <ide> $this->assertSame($fooType, $map['foo2']); <ide> public function testSet() <ide> Type::set('random', $instance); <ide> $this->assertSame($instance, Type::build('random')); <ide> } <del> <del> /** <del> * @return void <del> */ <del> public function testDebugInfo() <del> { <del> $type = new Type('foo'); <del> $result = $type->__debugInfo(); <del> $expected = [ <del> 'name' => 'foo', <del> ]; <del> $this->assertEquals($expected, $result); <del> } <ide> }
2
Javascript
Javascript
remove error message
dc086834b14647acacfd6d1e9a20bf83df34644a
<ide><path>test/pummel/test-net-connect-memleak.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> <add>console.log('Run this test with --expose-gc'); <ide> assert.strictEqual( <ide> typeof global.gc, <del> 'function', <del> 'Run this test with --expose-gc' <add> 'function' <ide> ); <ide> net.createServer(function() {}).listen(common.PORT); <ide>
1
PHP
PHP
add tests for set nest method
3b1dd82603381c946e2a4e1a50a2bcd882c81bbb
<ide><path>lib/Cake/Test/Case/Utility/SetTest.php <ide> public function testNormalizeArrays() { <ide> $expected = array('one' => array('a', 'b', 'c' => 'cee'), 'two' => 2, 'three' => null); <ide> $this->assertEquals($expected, $result); <ide> } <add> <add> public function testNestModel() { <add> $input = array( <add> array( <add> 'ModelName' => array( <add> 'id' => 1, <add> 'parent_id' => null <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 2, <add> 'parent_id' => 1 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 3, <add> 'parent_id' => 1 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 4, <add> 'parent_id' => 1 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 5, <add> 'parent_id' => 1 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 6, <add> 'parent_id' => null <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 7, <add> 'parent_id' => 6 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 8, <add> 'parent_id' => 6 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 9, <add> 'parent_id' => 6 <add> ), <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 10, <add> 'parent_id' => 6 <add> ) <add> ) <add> ); <add> $expected = array( <add> array( <add> 'ModelName' => array( <add> 'id' => 1, <add> 'parent_id' => null <add> ), <add> 'children' => array( <add> array( <add> 'ModelName' => array( <add> 'id' => 2, <add> 'parent_id' => 1 <add> ), <add> 'children' => array() <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 3, <add> 'parent_id' => 1 <add> ), <add> 'children' => array() <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 4, <add> 'parent_id' => 1 <add> ), <add> 'children' => array() <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 5, <add> 'parent_id' => 1 <add> ), <add> 'children' => array() <add> ), <add> <add> ) <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 6, <add> 'parent_id' => null <add> ), <add> 'children' => array( <add> array( <add> 'ModelName' => array( <add> 'id' => 7, <add> 'parent_id' => 6 <add> ), <add> 'children' => array() <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 8, <add> 'parent_id' => 6 <add> ), <add> 'children' => array() <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 9, <add> 'parent_id' => 6 <add> ), <add> 'children' => array() <add> ), <add> array( <add> 'ModelName' => array( <add> 'id' => 10, <add> 'parent_id' => 6 <add> ), <add> 'children' => array() <add> ) <add> ) <add> ) <add> ); <add> $result = Set::nest($input); <add> $this->assertEquals($expected, $result); <add> } <add> <add> public function testNest1Dimensional() { <add> $input = array( <add> array( <add> 'id' => 1, <add> 'parent_id' => null <add> ), <add> array( <add> 'id' => 2, <add> 'parent_id' => 1 <add> ), <add> array( <add> 'id' => 3, <add> 'parent_id' => 1 <add> ), <add> array( <add> 'id' => 4, <add> 'parent_id' => 1 <add> ), <add> array( <add> 'id' => 5, <add> 'parent_id' => 1 <add> ), <add> array( <add> 'id' => 6, <add> 'parent_id' => null <add> ), <add> array( <add> 'id' => 7, <add> 'parent_id' => 6 <add> ), <add> array( <add> 'id' => 8, <add> 'parent_id' => 6 <add> ), <add> array( <add> 'id' => 9, <add> 'parent_id' => 6 <add> ), <add> array( <add> 'id' => 10, <add> 'parent_id' => 6 <add> ) <add> ); <add> $expected = array( <add> array( <add> 'id' => 1, <add> 'parent_id' => null, <add> 'children' => array( <add> array( <add> 'id' => 2, <add> 'parent_id' => 1, <add> 'children' => array() <add> ), <add> array( <add> 'id' => 3, <add> 'parent_id' => 1, <add> 'children' => array() <add> ), <add> array( <add> 'id' => 4, <add> 'parent_id' => 1, <add> 'children' => array() <add> ), <add> array( <add> 'id' => 5, <add> 'parent_id' => 1, <add> 'children' => array() <add> ), <add> <add> ) <add> ), <add> array( <add> 'id' => 6, <add> 'parent_id' => null, <add> 'children' => array( <add> array( <add> 'id' => 7, <add> 'parent_id' => 6, <add> 'children' => array() <add> ), <add> array( <add> 'id' => 8, <add> 'parent_id' => 6, <add> 'children' => array() <add> ), <add> array( <add> 'id' => 9, <add> 'parent_id' => 6, <add> 'children' => array() <add> ), <add> array( <add> 'id' => 10, <add> 'parent_id' => 6, <add> 'children' => array() <add> ) <add> ) <add> ) <add> ); <add> $result = Set::nest($input, array('idPath' => '/id', 'parentPath' => '/parent_id')); <add> $this->assertEquals($expected, $result); <add> } <ide> } <ide><path>lib/Cake/Utility/Set.php <ide> public static function nest($data, $options = array()) { <ide> } <ide> <ide> $alias = key(current($data)); <del> $options = array( <add> $options += array( <ide> 'idPath' => "/$alias/id", <ide> 'parentPath' => "/$alias/parent_id", <ide> 'children' => 'children' <del> ) + $options; <add> ); <ide> <ide> $return = $idMap = array(); <ide> $ids = Set::extract($data, $options['idPath']);
2
Java
Java
use multisourcehelper in photoviewer
adea8d5fc928246ccf8ec5a8b1ccde159c2d6e09
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/imagehelper/MultiSourceHelper.java <ide> private MultiSourceResult( <ide> } <ide> } <ide> <add> public static MultiSourceResult getBestSourceForSize( <add> int width, <add> int height, <add> List<ImageSource> sources) { <add> return getBestSourceForSize(width, height, sources, 1.0d); <add> } <add> <ide> /** <ide> * Chooses the image source with the size closest to the target image size. <ide> * <ide> * @param width the width of the view that will be used to display this image <ide> * @param height the height of the view that will be used to display this image <ide> * @param sources the list of potential image sources to choose from <add> * @param multiplier the area of the view will be multiplied by this number before calculating the <add> * best source; this is useful if the image will be displayed bigger than the view <add> * (e.g. zoomed) <ide> */ <ide> public static MultiSourceResult getBestSourceForSize( <ide> int width, <ide> int height, <del> List<ImageSource> sources) { <add> List<ImageSource> sources, <add> double multiplier) { <ide> // no sources <ide> if (sources.isEmpty()) { <ide> return new MultiSourceResult(null, null); <ide> public static MultiSourceResult getBestSourceForSize( <ide> ImagePipeline imagePipeline = ImagePipelineFactory.getInstance().getImagePipeline(); <ide> ImageSource best = null; <ide> ImageSource bestCached = null; <del> final double viewArea = width * height; <add> final double viewArea = width * height * multiplier; <ide> double bestPrecision = Double.MAX_VALUE; <ide> double bestCachePrecision = Double.MAX_VALUE; <ide> for (ImageSource source : sources) {
1
Python
Python
move complex umath tests in separate file
42e7d63182cdff19b07d03e194137f890e59b1b1
<ide><path>numpy/core/tests/test_umath.py <ide> import numpy.core.umath as ncu <ide> import numpy as np <ide> <del>def assert_equal_spec(x, y): <del> # Handles nan and inf <del> if np.isnan(x) and np.isnan(y): <del> pass <del> elif np.isinf(x) and np.isinf(y): <del> if x * y > 0: <del> pass <del> else: <del> raise AssertionError(""" <del>Items are not equal: <del> ACTUAL: %s <del> DESIRED: %s""" % (str(x), str(y))) <del> else: <del> assert_equal(x, y) <del> <del>def assert_almost_equal_spec(x, y): <del> # Handles nan <del> if np.isnan(x) and np.isnan(y): <del> pass <del> elif np.isinf(x) and np.isinf(y): <del> if x * y > 0: <del> pass <del> else: <del> raise AssertionError(""" <del>Items are not almost equal: <del> ACTUAL: %s <del> DESIRED: %s""" % (str(x), str(y))) <del> else: <del> assert_almost_equal(x, y) <del> <ide> class TestDivision(TestCase): <ide> def test_division_int(self): <ide> # int division should return the floor of the result, a la Python <ide> def test_loss_of_precision(self): <ide> def test_loss_of_precision_longcomplex(self): <ide> self.check_loss_of_precision(np.longcomplex) <ide> <del>class TestClog(TestCase): <del> def test_simple(self): <del> x = np.array([1+0j, 1+2j]) <del> y_r = np.log(np.abs(x)) + 1j * np.angle(x) <del> y = np.log(x) <del> for i in range(len(x)): <del> assert_almost_equal_spec(y[i], y_r[i]) <del> <del> def test_special_values(self): <del> xl = [] <del> yl = [] <del> <del> # From C99 std (Sec 6.3.2) <del> # XXX: check exceptions raised <del> <del> # clog(-0 + i0) returns -inf + i pi and raises the 'divide-by-zero' <del> # floating-point exception. <del> x = np.array([np.NZERO], dtype=np.complex) <del> y = np.complex(-np.inf, np.pi) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(+0 + i0) returns -inf + i0 and raises the 'divide-by-zero' <del> # floating-point exception. <del> x = np.array([0], dtype=np.complex) <del> y = np.complex(-np.inf, 0) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(x + i inf returns +inf + i pi /2, for finite x. <del> x = np.array([complex(1, np.inf)], dtype=np.complex) <del> y = np.complex(np.inf, 0.5 * np.pi) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> x = np.array([complex(-1, np.inf)], dtype=np.complex) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> x = np.array([complex(np.inf, np.inf)], dtype=np.complex) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(x + iNaN) returns NaN + iNaN and optionally raises the <del> # 'invalid' floating- point exception, for finite x. <del> x = np.array([complex(1., np.nan)], dtype=np.complex) <del> y = np.complex(np.nan, np.nan) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> x = np.array([np.inf + np.nan * 1j], dtype=np.complex) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(- inf + iy) returns +inf + ipi , for finite positive-signed y. <del> x = np.array([-np.inf + 1j], dtype=np.complex) <del> y = np.complex(np.inf, np.pi) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(+ inf + iy) returns +inf + i0, for finite positive-signed y. <del> x = np.array([np.inf + 1j], dtype=np.complex) <del> y = np.complex(np.inf, 0) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(- inf + i inf) returns +inf + i3pi /4. <del> x = np.array([complex(-np.inf, np.inf)], dtype=np.complex) <del> y = np.complex(np.inf, 0.75 * np.pi) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(+ inf + i inf) returns +inf + ipi /4. <del> x = np.array([complex(np.inf, np.inf)], dtype=np.complex) <del> y = np.complex(np.inf, 0.25 * np.pi) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(+/- inf + iNaN) returns +inf + iNaN. <del> x = np.array([complex(np.inf, np.nan)], dtype=np.complex) <del> y = np.complex(np.inf, np.nan) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> x = np.array([complex(-np.inf, np.nan)], dtype=np.complex) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(NaN + iy) returns NaN + iNaN and optionally raises the <del> # 'invalid' floating-point exception, for finite y. <del> x = np.array([complex(np.nan, 1)], dtype=np.complex) <del> y = np.complex(np.nan, np.nan) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(NaN + i inf) returns +inf + iNaN. <del> x = np.array([complex(np.nan, np.inf)], dtype=np.complex) <del> y = np.complex(np.inf, np.nan) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(NaN + iNaN) returns NaN + iNaN. <del> x = np.array([complex(np.nan, np.nan)], dtype=np.complex) <del> y = np.complex(np.nan, np.nan) <del> assert_almost_equal_spec(np.log(x), y) <del> xl.append(x) <del> yl.append(y) <del> <del> # clog(conj(z)) = conj(clog(z)). <del> xa = np.array(xl, dtype=np.complex) <del> ya = np.array(yl, dtype=np.complex) <del> for i in range(len(xa)): <del> assert_almost_equal_spec(np.log(np.conj(xa[i])), np.conj(np.log(xa[i]))) <del> <del>class TestCpow(TestCase): <del> def test_simple(self): <del> x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) <del> y_r = x ** 2 <del> y = np.power(x, 2) <del> for i in range(len(x)): <del> assert_almost_equal_spec(y[i], y_r[i]) <del> <del>class TestCabs(TestCase): <del> def test_simple(self): <del> x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) <del> y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan]) <del> y = np.abs(x) <del> for i in range(len(x)): <del> assert_almost_equal_spec(y[i], y_r[i]) <del> <del> def test_fabs(self): <del> # Tesst that np.abs(x +- 0j) == np.abs(x) (as mandated by C99 for cabs) <del> x = np.array([1+0j], dtype=np.complex) <del> assert_array_equal(np.abs(x), np.real(x)) <del> <del> x = np.array([1-0j], dtype=np.complex) <del> assert_array_equal(np.abs(x), np.real(x)) <del> <del> x = np.array([np.inf-0j], dtype=np.complex) <del> assert_array_equal(np.abs(x), np.real(x)) <del> <del> x = np.array([np.nan-0j], dtype=np.complex) <del> assert_array_equal(np.abs(x), np.real(x)) <del> <del> @dec.knownfailureif(True, "Buggy behavior of abs with inf complex") <del> def test_cabs_inf_nan(self): <del> # According to C99 standard, cabs(inf + j * nan) should be inf <del> x = np.array([np.inf + 1j * np.nan, np.inf + 1j * np.inf, <del> np.nan + 1j * np.nan]) <del> y_r = np.array([np.inf, np.inf, np.nan]) <del> y = np.abs(x) <del> for i in range(len(x)): <del> assert_equal_spec(y_r[i], y[i]) <del> <ide> class TestAttributes(TestCase): <ide> def test_attributes(self): <ide> add = ncu.add <ide><path>numpy/core/tests/test_umath_complex.py <add>from numpy.testing import * <add>import numpy.core.umath as ncu <add>import numpy as np <add> <add>def assert_equal_spec(x, y): <add> # Handles nan and inf <add> if np.isnan(x) and np.isnan(y): <add> pass <add> elif np.isinf(x) and np.isinf(y): <add> if x * y > 0: <add> pass <add> else: <add> raise AssertionError(""" <add>Items are not equal: <add> ACTUAL: %s <add> DESIRED: %s""" % (str(x), str(y))) <add> else: <add> assert_equal(x, y) <add> <add>def assert_almost_equal_spec(x, y): <add> # Handles nan <add> if np.isnan(x) and np.isnan(y): <add> pass <add> elif np.isinf(x) and np.isinf(y): <add> if x * y > 0: <add> pass <add> else: <add> raise AssertionError(""" <add>Items are not almost equal: <add> ACTUAL: %s <add> DESIRED: %s""" % (str(x), str(y))) <add> else: <add> assert_almost_equal(x, y) <add> <add>class TestClog(TestCase): <add> def test_simple(self): <add> x = np.array([1+0j, 1+2j]) <add> y_r = np.log(np.abs(x)) + 1j * np.angle(x) <add> y = np.log(x) <add> for i in range(len(x)): <add> assert_almost_equal_spec(y[i], y_r[i]) <add> <add> def test_special_values(self): <add> xl = [] <add> yl = [] <add> <add> # From C99 std (Sec 6.3.2) <add> # XXX: check exceptions raised <add> <add> # clog(-0 + i0) returns -inf + i pi and raises the 'divide-by-zero' <add> # floating-point exception. <add> x = np.array([np.NZERO], dtype=np.complex) <add> y = np.complex(-np.inf, np.pi) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(+0 + i0) returns -inf + i0 and raises the 'divide-by-zero' <add> # floating-point exception. <add> x = np.array([0], dtype=np.complex) <add> y = np.complex(-np.inf, 0) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(x + i inf returns +inf + i pi /2, for finite x. <add> x = np.array([complex(1, np.inf)], dtype=np.complex) <add> y = np.complex(np.inf, 0.5 * np.pi) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> x = np.array([complex(-1, np.inf)], dtype=np.complex) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> x = np.array([complex(np.inf, np.inf)], dtype=np.complex) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(x + iNaN) returns NaN + iNaN and optionally raises the <add> # 'invalid' floating- point exception, for finite x. <add> x = np.array([complex(1., np.nan)], dtype=np.complex) <add> y = np.complex(np.nan, np.nan) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> x = np.array([np.inf + np.nan * 1j], dtype=np.complex) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(- inf + iy) returns +inf + ipi , for finite positive-signed y. <add> x = np.array([-np.inf + 1j], dtype=np.complex) <add> y = np.complex(np.inf, np.pi) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(+ inf + iy) returns +inf + i0, for finite positive-signed y. <add> x = np.array([np.inf + 1j], dtype=np.complex) <add> y = np.complex(np.inf, 0) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(- inf + i inf) returns +inf + i3pi /4. <add> x = np.array([complex(-np.inf, np.inf)], dtype=np.complex) <add> y = np.complex(np.inf, 0.75 * np.pi) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(+ inf + i inf) returns +inf + ipi /4. <add> x = np.array([complex(np.inf, np.inf)], dtype=np.complex) <add> y = np.complex(np.inf, 0.25 * np.pi) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(+/- inf + iNaN) returns +inf + iNaN. <add> x = np.array([complex(np.inf, np.nan)], dtype=np.complex) <add> y = np.complex(np.inf, np.nan) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> x = np.array([complex(-np.inf, np.nan)], dtype=np.complex) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(NaN + iy) returns NaN + iNaN and optionally raises the <add> # 'invalid' floating-point exception, for finite y. <add> x = np.array([complex(np.nan, 1)], dtype=np.complex) <add> y = np.complex(np.nan, np.nan) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(NaN + i inf) returns +inf + iNaN. <add> x = np.array([complex(np.nan, np.inf)], dtype=np.complex) <add> y = np.complex(np.inf, np.nan) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(NaN + iNaN) returns NaN + iNaN. <add> x = np.array([complex(np.nan, np.nan)], dtype=np.complex) <add> y = np.complex(np.nan, np.nan) <add> assert_almost_equal_spec(np.log(x), y) <add> xl.append(x) <add> yl.append(y) <add> <add> # clog(conj(z)) = conj(clog(z)). <add> xa = np.array(xl, dtype=np.complex) <add> ya = np.array(yl, dtype=np.complex) <add> for i in range(len(xa)): <add> assert_almost_equal_spec(np.log(np.conj(xa[i])), np.conj(np.log(xa[i]))) <add> <add>class TestCpow(TestCase): <add> def test_simple(self): <add> x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) <add> y_r = x ** 2 <add> y = np.power(x, 2) <add> for i in range(len(x)): <add> assert_almost_equal_spec(y[i], y_r[i]) <add> <add>class TestCabs(TestCase): <add> def test_simple(self): <add> x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) <add> y_r = np.array([np.sqrt(2.), 2, np.sqrt(5), np.inf, np.nan]) <add> y = np.abs(x) <add> for i in range(len(x)): <add> assert_almost_equal_spec(y[i], y_r[i]) <add> <add> def test_fabs(self): <add> # Tesst that np.abs(x +- 0j) == np.abs(x) (as mandated by C99 for cabs) <add> x = np.array([1+0j], dtype=np.complex) <add> assert_array_equal(np.abs(x), np.real(x)) <add> <add> x = np.array([1-0j], dtype=np.complex) <add> assert_array_equal(np.abs(x), np.real(x)) <add> <add> x = np.array([np.inf-0j], dtype=np.complex) <add> assert_array_equal(np.abs(x), np.real(x)) <add> <add> x = np.array([np.nan-0j], dtype=np.complex) <add> assert_array_equal(np.abs(x), np.real(x)) <add> <add> @dec.knownfailureif(True, "Buggy behavior of abs with inf complex") <add> def test_cabs_inf_nan(self): <add> # According to C99 standard, cabs(inf + j * nan) should be inf <add> x = np.array([np.inf + 1j * np.nan, np.inf + 1j * np.inf, <add> np.nan + 1j * np.nan]) <add> y_r = np.array([np.inf, np.inf, np.nan]) <add> y = np.abs(x) <add> for i in range(len(x)): <add> assert_equal_spec(y_r[i], y[i]) <add> <add>if __name__ == "__main__": <add> run_module_suite()
2
Javascript
Javascript
improve createsecurecontext in _tls_common
f4d7abf3bc75eec0c2c52ab8c149a8eab564a603
<ide><path>lib/_tls_common.js <ide> exports.createSecureContext = function createSecureContext(options, context) { <ide> secureOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE; <ide> <ide> var c = new SecureContext(options.secureProtocol, secureOptions, context); <add> var i; <ide> <ide> if (context) return c; <ide> <ide> // NOTE: It's important to add CA before the cert to be able to load <ide> // cert's issuer in C++ code. <ide> if (options.ca) { <ide> if (Array.isArray(options.ca)) { <del> for (let i = 0, len = options.ca.length; i < len; i++) { <add> for (i = 0; i < options.ca.length; i++) { <ide> c.context.addCACert(options.ca[i]); <ide> } <ide> } else { <ide> exports.createSecureContext = function createSecureContext(options, context) { <ide> <ide> if (options.cert) { <ide> if (Array.isArray(options.cert)) { <del> for (let i = 0; i < options.cert.length; i++) <add> for (i = 0; i < options.cert.length; i++) <ide> c.context.setCert(options.cert[i]); <ide> } else { <ide> c.context.setCert(options.cert); <ide> exports.createSecureContext = function createSecureContext(options, context) { <ide> // which leads to the crash later on. <ide> if (options.key) { <ide> if (Array.isArray(options.key)) { <del> for (let i = 0; i < options.key.length; i++) { <del> var key = options.key[i]; <del> <add> for (i = 0; i < options.key.length; i++) { <add> const key = options.key[i]; <ide> if (key.passphrase) <ide> c.context.setKey(key.pem, key.passphrase); <ide> else <ide> exports.createSecureContext = function createSecureContext(options, context) { <ide> c.context.setECDHCurve(options.ecdhCurve); <ide> <ide> if (options.dhparam) { <del> var warning = c.context.setDHParam(options.dhparam); <add> const warning = c.context.setDHParam(options.dhparam); <ide> if (warning) <ide> internalUtil.trace(warning); <ide> } <ide> <ide> if (options.crl) { <ide> if (Array.isArray(options.crl)) { <del> for (let i = 0, len = options.crl.length; i < len; i++) { <add> for (i = 0; i < options.crl.length; i++) { <ide> c.context.addCRL(options.crl[i]); <ide> } <ide> } else {
1
Javascript
Javascript
add tests for layoutselector
b57e268329b9398b8ac3fdd859243ba6c79ee54e
<ide><path>client/utils/gatsby/layoutSelector.js <ide> export default function layoutSelector({ element, props }) { <ide> } = props; <ide> <ide> if (element.type === FourOhFourPage) { <del> return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>; <add> return ( <add> <DefaultLayout pathname={pathname} showFooter={true}> <add> {element} <add> </DefaultLayout> <add> ); <ide> } <ide> if (/\/certification\//.test(pathname)) { <ide> return ( <ide> <CertificationLayout pathname={pathname}>{element}</CertificationLayout> <ide> ); <ide> } <del> if (/\/guide\//.test(pathname)) { <del> console.log('Hitting guide for some reason. Need a redirect.'); <del> } <ide> <del> const splitPath = pathname.split('/'); <add> const splitPath = pathname.split('/').filter(x => x); <ide> const isSuperBlock = <del> (splitPath.length === 3 && splitPath[1]) || <del> (splitPath.length === 4 && splitPath[2]); <add> (splitPath.length === 2 && splitPath[0]) === 'learn' || <add> (splitPath.length === 3 && splitPath[1]) === 'learn'; <ide> <ide> if (/\/learn\//.test(pathname) && !isSuperBlock) { <ide> return ( <ide> export default function layoutSelector({ element, props }) { <ide> ); <ide> } <ide> <del> return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>; <add> return ( <add> <DefaultLayout pathname={pathname} showFooter={true}> <add> {element} <add> </DefaultLayout> <add> ); <ide> } <ide> <ide> layoutSelector.propTypes = { <ide><path>client/utils/gatsby/layoutSelector.test.js <add>/* global expect */ <add>import React from 'react'; <add>import { Provider } from 'react-redux'; <add>import ShallowRenderer from 'react-test-renderer/shallow'; <add> <add>import layoutSelector from './layoutSelector'; <add>import { createStore } from '../../src/redux/createStore'; <add>import FourOhFourPage from '../../src/pages/404'; <add>import Learn from '../../src/pages/learn'; <add>import Certification from '../../src/pages/certification'; <add> <add>const store = createStore(); <add>function getComponentNameAndProps(elementType, pathname) { <add> const shallow = new ShallowRenderer(); <add> const LayoutReactComponent = layoutSelector({ <add> element: { type: elementType }, <add> props: { <add> location: { <add> pathname <add> } <add> } <add> }); <add> shallow.render(<Provider store={store}>{LayoutReactComponent}</Provider>); <add> const renderedComponent = shallow.getRenderOutput(); <add> return { <add> props: renderedComponent.props, <add> name: renderedComponent.type.WrappedComponent.displayName <add> }; <add>} <add> <add>test('Challenge path should have DefaultLayout and no footer', () => { <add> const challengePath = <add> '/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements'; <add> const compnentObj = getComponentNameAndProps(Learn, challengePath); <add> expect(compnentObj.name).toEqual('DefaultLayout'); <add> expect(compnentObj.props.showFooter).toEqual(false); <add>}); <add> <add>test('SuperBlock path should have DefaultLayout and footer', () => { <add> const superBlockPath = '/learn/responsive-web-design/'; <add> const compnentObj = getComponentNameAndProps(Learn, superBlockPath); <add> expect(compnentObj.name).toEqual('DefaultLayout'); <add> expect(compnentObj.props.showFooter).toEqual(true); <add>}); <add> <add>test('i18l challenge path should have DefaultLayout and no footer', () => { <add> const challengePath = <add> 'espanol/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements/'; <add> const compnentObj = getComponentNameAndProps(Learn, challengePath); <add> expect(compnentObj.name).toEqual('DefaultLayout'); <add> expect(compnentObj.props.showFooter).toEqual(false); <add>}); <add> <add>test('i18l superBlock path should have DefaultLayout and footer', () => { <add> const superBlockPath = '/learn/responsive-web-design/'; <add> const compnentObj = getComponentNameAndProps(Learn, superBlockPath); <add> expect(compnentObj.name).toEqual('DefaultLayout'); <add> expect(compnentObj.props.showFooter).toEqual(true); <add>}); <add> <add>test('404 page should have DefaultLayout and footer', () => { <add> const challengePath = <add> '/espanol/learn/responsive-web-design/basic-html-and-html5/say-hello-to-html-elements/'; <add> const compnentObj = getComponentNameAndProps(FourOhFourPage, challengePath); <add> expect(compnentObj.name).toEqual('DefaultLayout'); <add> expect(compnentObj.props.showFooter).toEqual(true); <add>}); <add> <add>test('Certification path should have CertificationLayout', () => { <add> const challengePath = <add> '/certification/mot01/javascript-algorithms-and-data-structures/'; <add> const compnentObj = getComponentNameAndProps(Certification, challengePath); <add> expect(compnentObj.name).toEqual('CertificationLayout'); <add>});
2
Javascript
Javascript
use createfillquadscene also in outlinepass
1dfd109aee9980547382b121b5e3499e5933ccbc
<ide><path>examples/js/postprocessing/OutlinePass.js <ide> THREE.OutlinePass = function ( resolution, scene, camera, selectedObjects ) { <ide> this.oldClearColor = new THREE.Color(); <ide> this.oldClearAlpha = 1; <ide> <del> this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); <del> this.scene = new THREE.Scene(); <del> <del> this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), null ); <del> this.quad.frustumCulled = false; // Avoid getting clipped <del> this.scene.add( this.quad ); <add> this.fillQuad = THREE.Pass.createFillQuadScene( null ); <ide> <ide> this.tempPulseColor1 = new THREE.Color(); <ide> this.tempPulseColor2 = new THREE.Color(); <ide> THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype <ide> this.renderScene.background = currentBackground; <ide> <ide> // 2. Downsample to Half resolution <del> this.quad.material = this.materialCopy; <add> this.fillQuad.quad.material = this.materialCopy; <ide> this.copyUniforms[ "tDiffuse" ].value = this.renderTargetMaskBuffer.texture; <ide> renderer.setRenderTarget( this.renderTargetMaskDownSampleBuffer ); <ide> renderer.clear(); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> <ide> this.tempPulseColor1.copy( this.visibleEdgeColor ); <ide> this.tempPulseColor2.copy( this.hiddenEdgeColor ); <ide> THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype <ide> } <ide> <ide> // 3. Apply Edge Detection Pass <del> this.quad.material = this.edgeDetectionMaterial; <add> this.fillQuad.quad.material = this.edgeDetectionMaterial; <ide> this.edgeDetectionMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskDownSampleBuffer.texture; <ide> this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height ); <ide> this.edgeDetectionMaterial.uniforms[ "visibleEdgeColor" ].value = this.tempPulseColor1; <ide> this.edgeDetectionMaterial.uniforms[ "hiddenEdgeColor" ].value = this.tempPulseColor2; <ide> renderer.setRenderTarget( this.renderTargetEdgeBuffer1 ); <ide> renderer.clear(); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> <ide> // 4. Apply Blur on Half res <del> this.quad.material = this.separableBlurMaterial1; <add> this.fillQuad.quad.material = this.separableBlurMaterial1; <ide> this.separableBlurMaterial1.uniforms[ "colorTexture" ].value = this.renderTargetEdgeBuffer1.texture; <ide> this.separableBlurMaterial1.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionX; <ide> this.separableBlurMaterial1.uniforms[ "kernelRadius" ].value = this.edgeThickness; <ide> renderer.setRenderTarget( this.renderTargetBlurBuffer1 ); <ide> renderer.clear(); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> this.separableBlurMaterial1.uniforms[ "colorTexture" ].value = this.renderTargetBlurBuffer1.texture; <ide> this.separableBlurMaterial1.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionY; <ide> renderer.setRenderTarget( this.renderTargetEdgeBuffer1 ); <ide> renderer.clear(); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> <ide> // Apply Blur on quarter res <del> this.quad.material = this.separableBlurMaterial2; <add> this.fillQuad.quad.material = this.separableBlurMaterial2; <ide> this.separableBlurMaterial2.uniforms[ "colorTexture" ].value = this.renderTargetEdgeBuffer1.texture; <ide> this.separableBlurMaterial2.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionX; <ide> renderer.setRenderTarget( this.renderTargetBlurBuffer2 ); <ide> renderer.clear(); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> this.separableBlurMaterial2.uniforms[ "colorTexture" ].value = this.renderTargetBlurBuffer2.texture; <ide> this.separableBlurMaterial2.uniforms[ "direction" ].value = THREE.OutlinePass.BlurDirectionY; <ide> renderer.setRenderTarget( this.renderTargetEdgeBuffer2 ); <ide> renderer.clear(); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> <ide> // Blend it additively over the input texture <del> this.quad.material = this.overlayMaterial; <add> this.fillQuad.quad.material = this.overlayMaterial; <ide> this.overlayMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture; <ide> this.overlayMaterial.uniforms[ "edgeTexture1" ].value = this.renderTargetEdgeBuffer1.texture; <ide> this.overlayMaterial.uniforms[ "edgeTexture2" ].value = this.renderTargetEdgeBuffer2.texture; <ide> THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype <ide> if ( maskActive ) renderer.context.enable( renderer.context.STENCIL_TEST ); <ide> <ide> renderer.setRenderTarget( readBuffer ); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> <ide> renderer.setClearColor( this.oldClearColor, this.oldClearAlpha ); <ide> renderer.autoClear = oldAutoClear; <ide> THREE.OutlinePass.prototype = Object.assign( Object.create( THREE.Pass.prototype <ide> <ide> if ( this.renderToScreen ) { <ide> <del> this.quad.material = this.materialCopy; <add> this.fillQuad.quad.material = this.materialCopy; <ide> this.copyUniforms[ "tDiffuse" ].value = readBuffer.texture; <ide> renderer.setRenderTarget( null ); <del> renderer.render( this.scene, this.camera ); <add> renderer.render( this.fillQuad.quad, this.fillQuad.camera ); <ide> <ide> } <ide>
1
Go
Go
skip the import test on aarch64
6395b8b3dcc43be6750e0d90d9bab0a83e4eb20b
<ide><path>integration/image/import_test.go <ide> import ( <ide> "bytes" <ide> "context" <ide> "io" <add> "runtime" <ide> "testing" <ide> <ide> "github.com/docker/docker/api/types" <ide> import ( <ide> <ide> // Ensure we don't regress on CVE-2017-14992. <ide> func TestImportExtremelyLargeImageWorks(t *testing.T) { <add> if runtime.GOARCH == "arm64" { <add> t.Skip("effective test will be time out") <add> } <add> <ide> client := request.NewAPIClient(t) <ide> <ide> // Construct an empty tar archive with about 8GB of junk padding at the <ide> // end. This should not cause any crashes (the padding should be mostly <ide> // ignored). <ide> var tarBuffer bytes.Buffer <add> <ide> tw := tar.NewWriter(&tarBuffer) <ide> if err := tw.Close(); err != nil { <ide> t.Fatal(err)
1
Go
Go
detect file changes to capability bits
87ca750cdc3114a340af1c5bc9394cc5f6242677
<ide><path>archive/changes.go <ide> package archive <ide> <ide> import ( <add> "bytes" <ide> "code.google.com/p/go/src/pkg/archive/tar" <ide> "fmt" <ide> "github.com/dotcloud/docker/utils" <ide> func Changes(layers []string, rw string) ([]Change, error) { <ide> } <ide> <ide> type FileInfo struct { <del> parent *FileInfo <del> name string <del> stat syscall.Stat_t <del> children map[string]*FileInfo <add> parent *FileInfo <add> name string <add> stat syscall.Stat_t <add> children map[string]*FileInfo <add> capability []byte <ide> } <ide> <ide> func (root *FileInfo) LookUp(path string) *FileInfo { <ide> func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { <ide> oldStat.Rdev != newStat.Rdev || <ide> // Don't look at size for dirs, its not a good measure of change <ide> (oldStat.Size != newStat.Size && oldStat.Mode&syscall.S_IFDIR != syscall.S_IFDIR) || <del> !sameFsTimeSpec(getLastModification(oldStat), getLastModification(newStat)) { <add> !sameFsTimeSpec(getLastModification(oldStat), getLastModification(newStat)) || <add> bytes.Compare(oldChild.capability, newChild.capability) != 0 { <ide> change := Change{ <ide> Path: newChild.path(), <ide> Kind: ChangeModify, <ide> func collectFileInfo(sourceDir string) (*FileInfo, error) { <ide> return err <ide> } <ide> <add> info.capability, _ = Lgetxattr(path, "security.capability") <add> <ide> parent.children[info.name] = info <ide> <ide> return nil
1
Javascript
Javascript
add test coverage for texteditor autoheight
9f8f03b10f3d42bab36b585473d766268ea8859d
<ide><path>spec/text-editor-component-spec.js <ide> /** @babel */ <ide> <ide> import {it, fit, ffit, fffit, beforeEach, afterEach, conditionPromise} from './async-spec-helpers' <add>import Grim from 'grim' <ide> import TextEditorElement from '../src/text-editor-element' <ide> import _, {extend, flatten, last, toArray} from 'underscore-plus' <ide> <ide> describe('TextEditorComponent', function () { <ide> }) <ide> <ide> describe('height', function () { <add> describe('when autoHeight is true', function () { <add> it('assigns the editor\'s height to based on its contents', function () { <add> jasmine.attachToDOM(wrapperNode) <add> expect(editor.getAutoHeight()).toBe(true) <add> expect(wrapperNode.offsetHeight).toBe(editor.getLineHeightInPixels() * editor.getScreenLineCount()) <add> editor.insertText('\n\n\n') <add> runAnimationFrames() <add> expect(wrapperNode.offsetHeight).toBe(editor.getLineHeightInPixels() * editor.getScreenLineCount()) <add> }) <add> }) <add> <add> describe('when autoHeight is false', function () { <add> it('does not assign the height of the editor, instead allowing content to scroll', function () { <add> jasmine.attachToDOM(wrapperNode) <add> editor.update({autoHeight: false}) <add> wrapperNode.style.height = '200px' <add> expect(wrapperNode.offsetHeight).toBe(200) <add> editor.insertText('\n\n\n') <add> runAnimationFrames() <add> expect(wrapperNode.offsetHeight).toBe(200) <add> }) <add> }) <add> <ide> describe('when the wrapper view has an explicit height', function () { <ide> it('does not assign a height on the component node', function () { <ide> wrapperNode.style.height = '200px'
1
Text
Text
add another link to mdn for more in-depth info
c5639a010553d3d758fa39aa8861509724b1c998
<ide><path>guide/english/css/colors/index.md <ide> Above shows paragraphs styled bright orange and 20% transparent, h2 elements sal <ide> To get custom colors to use in CSS, you might find a color picker helpful. Some text editors have built-in color pickers, like Visual Studio Code. If you search "color picker" on Google or DuckDuckGo, you will get a color picker that you can use. Google Chrome and Firefox also have color picker add-ons that you can install. Adobe Color CC not only helps you pick a color, but will also help you pick out a color scheme for your web page! It's a good idea to check that you have enough contrast between your text and background colors by using a tool like WebAIM's Color Contrast Checker. <ide> <ide> #### More Information: <add> <ide> - [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value) <ide> - [Adobe Color CC](https://color.adobe.com/) <ide> - [ColorPick Eyedropper on Chrome Web Store](https://chrome.google.com/webstore/detail/colorpick-eyedropper/ohcpnigalekghcmgcdcenkpelffpdolg?hl=en) <ide> - [ColorZilla add-on for Firefox](https://addons.mozilla.org/en-US/firefox/addon/colorzilla/) <ide> - [Explore different Hex colors](https://www.colorhexa.com/) <ide> - [WebAIM Color Contrast Checker](https://webaim.org/resources/contrastchecker/) <add>- [MDN: Further Reading on Colors](https://developer.mozilla.org/en-US/docs/Web/HTML/Applying_color)
1
Python
Python
improve idempotency in mlenginehook.create_model
bfd425157a746402b516f8fc9e48f4ddccd794ce
<ide><path>airflow/providers/google/cloud/hooks/mlengine.py <ide> def create_job( <ide> hook = self.get_conn() <ide> <ide> self._append_label(job) <del> <add> self.log.info("Creating job.") <ide> request = hook.projects().jobs().create( # pylint: disable=no-member <ide> parent='projects/{}'.format(project_id), <ide> body=job) <ide> def _wait_for_job_done(self, project_id: str, job_id: str, interval: int = 30): <ide> :type interval: int <ide> :raises: googleapiclient.errors.HttpError <ide> """ <add> self.log.info("Waiting for job. job_id=%s", job_id) <add> <ide> if interval <= 0: <ide> raise ValueError("Interval must be > 0") <ide> while True: <ide> def create_model( <ide> :raises: googleapiclient.errors.HttpError <ide> """ <ide> hook = self.get_conn() <del> if not model['name']: <add> if 'name' not in model or not model['name']: <ide> raise ValueError("Model name must be provided and " <ide> "could not be an empty string") <ide> project = 'projects/{}'.format(project_id) <ide> <ide> self._append_label(model) <del> <del> request = hook.projects().models().create( # pylint: disable=no-member <del> parent=project, body=model) <del> return request.execute() <add> try: <add> request = hook.projects().models().create( # pylint: disable=no-member <add> parent=project, body=model) <add> respone = request.execute() <add> except HttpError as e: <add> if e.resp.status != 409: <add> raise e <add> str(e) # Fills in the error_details field <add> if not e.error_details or len(e.error_details) != 1: <add> raise e <add> <add> error_detail = e.error_details[0] <add> if error_detail["@type"] != 'type.googleapis.com/google.rpc.BadRequest': <add> raise e <add> <add> if "fieldViolations" not in error_detail or len(error_detail['fieldViolations']) != 1: <add> raise e <add> <add> field_violation = error_detail['fieldViolations'][0] <add> if ( <add> field_violation["field"] != "model.name" or <add> field_violation["description"] != "A model with the same name already exists." <add> ): <add> raise e <add> respone = self.get_model( <add> model_name=model['name'], <add> project_id=project_id <add> ) <add> <add> return respone <ide> <ide> @CloudBaseHook.fallback_to_default_project_id <ide> def get_model( <ide><path>tests/providers/google/cloud/hooks/test_mlengine.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <del> <add>import json <ide> import unittest <ide> from copy import deepcopy <ide> from unittest import mock <ide> <add>import httplib2 <ide> from googleapiclient.errors import HttpError <ide> from mock import PropertyMock <ide> <ide> def test_create_model(self, mock_get_conn): <ide> mock.call().projects().models().create().execute() <ide> ]) <ide> <add> @mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn") <add> def test_create_model_idempotency(self, mock_get_conn): <add> project_id = 'test-project' <add> model_name = 'test-model' <add> model = { <add> 'name': model_name, <add> } <add> model_with_airflow_version = { <add> 'name': model_name, <add> 'labels': {'airflow-version': hook._AIRFLOW_VERSION} <add> } <add> project_path = 'projects/{}'.format(project_id) <add> <add> ( <add> mock_get_conn.return_value. <add> projects.return_value. <add> models.return_value. <add> create.return_value. <add> execute.side_effect <add> ) = [ <add> HttpError( <add> resp=httplib2.Response({"status": 409}), <add> content=json.dumps( <add> { <add> "error": { <add> "code": 409, <add> "message": "Field: model.name Error: A model with the same name already exists.", <add> "status": "ALREADY_EXISTS", <add> "details": [ <add> { <add> "@type": "type.googleapis.com/google.rpc.BadRequest", <add> "fieldViolations": [ <add> { <add> "field": "model.name", <add> "description": "A model with the same name already exists." <add> } <add> ], <add> } <add> ], <add> } <add> } <add> ).encode(), <add> ) <add> ] <add> <add> ( <add> mock_get_conn.return_value. <add> projects.return_value. <add> models.return_value. <add> get.return_value. <add> execute.return_value <add> ) = deepcopy(model) <add> <add> create_model_response = self.hook.create_model( <add> project_id=project_id, model=deepcopy(model) <add> ) <add> <add> self.assertEqual(create_model_response, model) <add> mock_get_conn.assert_has_calls([ <add> mock.call().projects().models().create(body=model_with_airflow_version, parent=project_path), <add> mock.call().projects().models().create().execute(), <add> ]) <add> mock_get_conn.assert_has_calls([ <add> mock.call().projects().models().get(name='projects/test-project/models/test-model'), <add> mock.call().projects().models().get().execute() <add> ]) <add> <ide> @mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn") <ide> def test_create_model_with_labels(self, mock_get_conn): <ide> project_id = 'test-project'
2
Text
Text
improve link documentation
85571af15750e5931172a41c5f6c91add88438f5
<ide><path>docs/api-reference/next/link.md <ide> const pids = ['id1', 'id2', 'id3'] <ide> } <ide> ``` <ide> <del>## Example with `React.forwardRef` <add>## If the child is a custom component that wraps an `<a>` tag <ide> <del>If the child component in `Link` is a function component, you'll need to wrap it in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref) like in the following example: <add>If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you’re using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which might hurt your site’s SEO. <add> <add>```jsx <add>import Link from 'next/link' <add>import styled from 'styled-components' <add> <add>// This creates a custom component that wraps an <a> tag <add>const RedLink = styled.a` <add> color: red; <add>` <add> <add>function NavLink({ href, name }) { <add> // Must add passHref to Link <add> return ( <add> <Link href={href} passHref> <add> <RedLink>{name}</RedLink> <add> </Link> <add> ) <add>} <add> <add>export default NavLink <add>``` <add> <add>> **Note:** If you’re using [emotion](https://emotion.sh/)’s JSX pragma feature (`@jsx jsx`), you must use `passHref` even if you use an `<a>` tag directly. <add> <add>## If the child is a function component <add> <add>If the child of `Link` is a function component, in addition to using `passHref`, you must wrap the component in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref): <ide> <ide> ```jsx <del>import React from 'react' <ide> import Link from 'next/link' <ide> <ide> // `onClick`, `href`, and `ref` need to be passed to the DOM element <ide> const MyButton = React.forwardRef(({ onClick, href }, ref) => { <ide> <ide> function Home() { <ide> return ( <del> <Link href="/about"> <add> <Link href="/about" passHref> <ide> <MyButton /> <ide> </Link> <ide> ) <ide> The default behavior of the `Link` component is to `push` a new URL into the `hi <ide> <ide> The child of `Link` is `<img>` instead of `<a>`. `Link` will send the `onClick` property to `<img>` but won't pass the `href` property. <ide> <del>## Forcing `Link` to expose `href` to its child <del> <del>If the child is an `<a>` tag and doesn't have a `href` attribute we specify it so that the repetition is not needed by the user. However, sometimes, you’ll want to pass an `<a>` tag inside of a wrapper and `Link` won’t recognize it as a _hyperlink_, and, consequently, won’t transfer its `href` to the child. <del> <del>In cases like that, you can add the `passHref` property to `Link`, forcing it to expose its `href` property to the child. Take a look at the following example: <del> <del>```jsx <del>import Link from 'next/link' <del>import Unexpected_A from 'third-library' <del> <del>function NavLink({ href, name }) { <del> return ( <del> <Link href={href} passHref> <del> <Unexpected_A>{name}</Unexpected_A> <del> </Link> <del> ) <del>} <del> <del>export default NavLink <del>``` <del> <del>> **Please note**: using a tag other than `<a>` and failing to pass `passHref` may result in links that appear to navigate correctly, but, when being crawled by search engines, will not be recognized as links (owing to the lack of `href` attribute). This may result in negative effects on your sites SEO. <del> <ide> ## Disable scrolling to the top of the page <ide> <ide> The default behavior of `Link` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, just like a normal `<a>` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `Link`:
1
Javascript
Javascript
move getnativeprops usage inline
0200946112310b320fb90d220c620cf6b83e3fa6
<ide><path>src/renderers/dom/client/wrappers/ReactDOMInput.js <ide> var ReactDOMInput = { <ide> // Make sure we set .type before any other properties (setting .value <ide> // before .type means .value is lost in IE11 and below) <ide> type: undefined, <del> }, props, { <add> }, DisabledInputUtils.getNativeProps(inst, props), { <ide> defaultChecked: undefined, <ide> defaultValue: undefined, <ide> value: value != null ? value : inst._wrapperState.initialValue, <ide> checked: checked != null ? checked : inst._wrapperState.initialChecked, <ide> onChange: inst._wrapperState.onChange, <ide> }); <ide> <del> return DisabledInputUtils.getNativeProps(inst, nativeProps); <add> return nativeProps <ide> }, <ide> <ide> mountWrapper: function(inst, props) {
1
Text
Text
add missing commit and remove empty lines
f41bd7691d5edc9c45b16657379c75748d5f76b7
<ide><path>CHANGELOG.md <ide> content, which is a security risk. <ide> - cope with `$onChanges` hooks throwing <ide> ([3749c858](https://github.com/angular/angular.js/commit/3749c85829406ca57cc5729e80696c7f34134068), <ide> [#14444](https://github.com/angular/angular.js/issues/14444), [#14463](https://github.com/angular/angular.js/issues/14463)) <add>- **$location:** initialize `$$absUrl` to empty string <add> ([294d6793f](https://github.com/angular/angular.js/commit/294d6793fd0e0781a257e35a165e0c6fde082fe7), <add> [#11091](https://github.com/angular/angular.js/issues/11091), [#13565](https://github.com/angular/angular.js/issues/13565), [#14488](https://github.com/angular/angular.js/issues/14488)) <ide> - **$parse:** allow arguments to contain filter chains <ide> ([cc6dcb4b](https://github.com/angular/angular.js/commit/cc6dcb4bc28aadff4f62d76d6451b0f80b928e69), <ide> [#4175](https://github.com/angular/angular.js/issues/4175), [#4168](https://github.com/angular/angular.js/issues/4168), [#14720](https://github.com/angular/angular.js/issues/14720)) <ide> report any regressions or other issues you find as soon as possible. <ide> <ide> - **$parse:** provide a mechanism to access the locals object, `$locals` <ide> ([0ea53503](https://github.com/angular/angular.js/commit/0ea535035a3a1a992948490c3533bffb83235052)) <del> <ide> - **$resource:** add proper support for cancelling requests, `$cancelRequest()` <ide> ([98528be3](https://github.com/angular/angular.js/commit/98528be311b48269ba0e15ba4e3e2ad9b89693a9), <ide> [#9332](https://github.com/angular/angular.js/issues/9332), [#13050](https://github.com/angular/angular.js/issues/13050), [#13058](https://github.com/angular/angular.js/issues/13058), [#13210](https://github.com/angular/angular.js/issues/13210)) <del> <ide> - **ngAnimate:** provide ng-[event]-prepare class for structural animations <ide> ([6e18b50a](https://github.com/angular/angular.js/commit/6e18b50a5b168848cc526081b0a2a16075ee44bd)) <del> <ide> - **ngLocale:** add support for standalone months <ide> ([96c73a06](https://github.com/angular/angular.js/commit/96c73a0672f0e46ae9285c482b057bd03ce135ba), <ide> [#3744](https://github.com/angular/angular.js/issues/3744), [#10247](https://github.com/angular/angular.js/issues/10247), [#12642](https://github.com/angular/angular.js/issues/12642), [#12844](https://github.com/angular/angular.js/issues/12844)) <del> <ide> - **ngMock:** destroy $rootScope after each test <ide> ([b75c0d8d](https://github.com/angular/angular.js/commit/b75c0d8d0549261ece551210a11d8be48c3ab3cc), <ide> [#13433](https://github.com/angular/angular.js/issues/13433)) <del> <ide> - **ngTransclude:** don't overwrite the contents with an unfilled optional slot <ide> ([0812af49](https://github.com/angular/angular.js/commit/0812af49bd4f4fad4067603ff64dbe720bd6e3e5), <ide> [#13426](https://github.com/angular/angular.js/issues/13426)) <del> <ide> - **ngView:** reference resolved locals in scope, `resolveAs: '$resolve'` <ide> ([983b0598](https://github.com/angular/angular.js/commit/983b0598121a8c5a3a51a30120e114d7e3085d4d), <ide> [#13400](https://github.com/angular/angular.js/issues/13400)) <ide> report any regressions or other issues you find as soon as possible. <ide> - support merging special attribute names in `replace` directives <ide> ([a5ff651a](https://github.com/angular/angular.js/commit/a5ff651a59933c2c43b81642454ee458f98e1401), <ide> [#13317](https://github.com/angular/angular.js/issues/13317), [#13318](https://github.com/angular/angular.js/issues/13318)) <del> <ide> - **$http:** throw if url passed is not a string <ide> ([6628b4f1](https://github.com/angular/angular.js/commit/6628b4f1e5835d997290881c6ba394547883a516), <ide> [#12925](https://github.com/angular/angular.js/issues/12925), [#13444](https://github.com/angular/angular.js/issues/13444)) <del> <ide> - **$parse:** <ide> - prevent assignment on constructor properties <ide> ([5a674f3b](https://github.com/angular/angular.js/commit/5a674f3bb9d1118d11b333e3b966c01a571c09e6), <ide> [#13417](https://github.com/angular/angular.js/issues/13417)) <ide> - handle interceptors with `undefined` expressions <ide> ([4473b81c](https://github.com/angular/angular.js/commit/4473b81cdaf16c5509ac53d80b9bdfb0a7ac5f30)) <del> <ide> - **$sanitize:** blacklist SVG `<use>` elements <ide> ([7a668cdd](https://github.com/angular/angular.js/commit/7a668cdd7d08a7016883eb3c671cbcd586223ae8), <ide> [#13453](https://github.com/angular/angular.js/issues/13453)) <del> <ide> - **formatNumber:** cope with large and small number corner cases <ide> ([6a0686d4](https://github.com/angular/angular.js/commit/6a0686d434c41445c50b2d9669073802ede77b3b), <ide> [#13394](https://github.com/angular/angular.js/issues/13394), [#8674](https://github.com/angular/angular.js/issues/8674), [#12709](https://github.com/angular/angular.js/issues/12709), [#8705](https://github.com/angular/angular.js/issues/8705), [#12707](https://github.com/angular/angular.js/issues/12707), [#10246](https://github.com/angular/angular.js/issues/10246), [#10252](https://github.com/angular/angular.js/issues/10252)) <del> <ide> - **input:** add missing chars to URL validation regex <ide> ([e4bb8387](https://github.com/angular/angular.js/commit/e4bb8387952069cca9da06bbc5c87ae576c2bf6f), <ide> [#13379](https://github.com/angular/angular.js/issues/13379), [#13460](https://github.com/angular/angular.js/issues/13460)) <del> <ide> - **ngAnimate:** <ide> - consider options.delay value for closing timeout <ide> ([7ffb2d3c](https://github.com/angular/angular.js/commit/7ffb2d3c17643303a51eb4e324c365af70fe3824), <ide> report any regressions or other issues you find as soon as possible. <ide> - do not alter the provided options data <ide> ([193153c3](https://github.com/angular/angular.js/commit/193153c3d391338a859cb7788ef32a8af05fb920), <ide> [#13040](https://github.com/angular/angular.js/issues/13040), [#13175](https://github.com/angular/angular.js/issues/13175)) <del> <ide> - **ngMock:** clear out `$providerInjector` after each test <ide> ([a72c12bd](https://github.com/angular/angular.js/commit/a72c12bd7052da9f60da74625409374342b50b73), <ide> [#13397](https://github.com/angular/angular.js/issues/13397), [#13416](https://github.com/angular/angular.js/issues/13416)) <del> <ide> - **ngOptions:** don't $dirty multiple select after compilation <ide> ([c7a2028a](https://github.com/angular/angular.js/commit/c7a2028ab38cdfc4d956c50b6f41cbccef302165), <ide> [#13211](https://github.com/angular/angular.js/issues/13211), [#13326](https://github.com/angular/angular.js/issues/13326)) <del> <ide> - **ngTransclude:** <ide> - don't replace existing content if no transcluded content exists <ide> ([c3ae6ed7](https://github.com/angular/angular.js/commit/c3ae6ed78e145a9b0c13de7ef95852ba3c467551),
1
Text
Text
repair advanced feature reference
6f16cef3e2f5bfff569e46ab4f5fde7e7060e0e6
<ide><path>examples/with-google-analytics/README.md <ide> # Example app with analytics <ide> <del>This example shows how to use [Next.js](https://github.com/zeit/next.js) along with [Google Analytics](https://developers.google.com/analytics/devguides/collection/gtagjs/). A custom [\_document](https://github.com/zeit/next.js/#custom-document) is used to inject [tracking snippet](https://developers.google.com/analytics/devguides/collection/gtagjs/) and track [pageviews](https://developers.google.com/analytics/devguides/collection/gtagjs/pages) and [event](https://developers.google.com/analytics/devguides/collection/gtagjs/events). <add>This example shows how to use [Next.js](https://github.com/zeit/next.js) along with [Google Analytics](https://developers.google.com/analytics/devguides/collection/gtagjs/). A custom [\_document](https://nextjs.org/docs/advanced-features/custom-document) is used to inject [tracking snippet](https://developers.google.com/analytics/devguides/collection/gtagjs/) and track [pageviews](https://developers.google.com/analytics/devguides/collection/gtagjs/pages) and [event](https://developers.google.com/analytics/devguides/collection/gtagjs/events). <ide> <ide> ## Deploy your own <ide>
1
PHP
PHP
remove uneeded error suppression tag
86171c80ccdb030f600653f1831141886858168a
<ide><path>src/basics.php <ide> * @return mixed The same $var that was passed <ide> * @link https://book.cakephp.org/3.0/en/development/debugging.html#basic-debugging <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#debug <del> * @psalm-suppress MissingReturnType <ide> */ <ide> function debug($var, $showHtml = null, $showFrom = true) <ide> {
1