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
Text
Text
add rafael to the security steward for nearform
c7338c5b328bf52be556dd97bad03f9125f85b79
<ide><path>doc/contributing/security-release-process.md <ide> steps listed in the process as outlined in <ide> The current security stewards are documented in the main Node.js <ide> [README.md](https://github.com/nodejs/node#security-release-stewards). <ide> <del>| Company | Person | Release Date | <del>| ---------- | -------- | ------------ | <del>| NearForm | Matteo | 2021-Oct-12 | <del>| Datadog | Bryan | 2022-Jan-10 | <del>| RH and IBM | Joe | 2022-Mar-18 | <del>| NearForm | Matteo | | <del>| Datadog | Vladimir | | <del>| RH and IBM | Michael | | <add>| Company | Person | Release Date | <add>| ---------- | --------------- | ------------ | <add>| NearForm | Matteo | 2021-Oct-12 | <add>| Datadog | Bryan | 2022-Jan-10 | <add>| RH and IBM | Joe | 2022-Mar-18 | <add>| NearForm | Matteo / Rafael | | <add>| Datadog | Vladimir | | <add>| RH and IBM | Michael | | <ide> <ide> ## Planning <ide>
1
Ruby
Ruby
drop unnecessary pathname creation
e29cbc5a48616ad22b5a07951887109f65cabada
<ide><path>Library/Homebrew/keg_fix_install_names.rb <ide> def each_install_name_for file, &block <ide> <ide> def dylib_id_for file, options={} <ide> # the shortpath ensures that library upgrades don’t break installed tools <del> relative_path = Pathname.new(file).relative_path_from(self) <add> relative_path = file.relative_path_from(self) <ide> shortpath = HOMEBREW_PREFIX.join(relative_path) <ide> <ide> if shortpath.exist? and not options[:keg_only]
1
Javascript
Javascript
add remedy to showcase
f9df72c80328d9631b86a0f5582f8031b44eaba3
<ide><path>website/src/react-native/showcase.js <ide> var featured = [ <ide> infoLink: 'https://medium.com/delivery-com-engineering/react-native-in-an-existing-ios-app-delivered-874ba95a3c52#.37qruw6ck', <ide> infoTitle: 'React Native in an Existing iOS App: Getting Started' <ide> }, <add> { <add> name: 'Remedy', <add> icon: 'https://www.remedymedical.com/static/images/AppIconPatient.png', <add> linkAppStore: 'https://itunes.apple.com/us/app/remedy-on-demand-intelligent/id1125877350?mt=8', <add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.remedy.android', <add> infoLink: 'https://techcrunch.com/2017/01/10/doctordoctorcantyouseeimburning/', <add> infoTitle: 'Talk to a world-class doctor: advice, prescriptions, and care', <add> }, <ide> { <ide> name: 'Yeti Smart Home', <ide> icon: 'https://res.cloudinary.com/netbeast/image/upload/v1484303676/Android_192_loykto.png', <ide> linkAppStore: 'https://itunes.apple.com/us/app/yeti-smart-home/id1190638808?mt=8', <ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.netbeast.yeti', <ide> infoLink: 'https://medium.com/@jesusdario/developing-beyond-the-screen-9af812b96724#.ozx0xy4lv', <del> infoTitle: 'How react native is helping us to reinvent the wheel, smart homes and release Yeti.', <add> infoTitle: 'How React Native is helping us to reinvent the wheel', <ide> }, <ide> ]; <ide>
1
Ruby
Ruby
remove unnecessary code from debugger
0b8cf49386a6cd6c5cefe26ff150422d12edcff1
<ide><path>Library/Homebrew/build.rb <ide> def install <ide> end <ide> end <ide> <del> if ARGV.debug? <del> formula.extend(Debrew::Formula) <del> formula.resources.each { |r| r.extend(Debrew::Resource) } <del> end <add> formula.extend(Debrew::Formula) if ARGV.debug? <ide> <ide> formula.brew do <ide> formula.patch <ide><path>Library/Homebrew/debrew.rb <ide> def test <ide> end <ide> end <ide> <del> module Resource <del> def unpack(target=nil) <del> return super if target <del> super do <del> begin <del> yield self <del> rescue Exception => e <del> Debrew.debug(e) <del> end <del> end <del> end <del> end <del> <ide> class Menu <ide> Entry = Struct.new(:name, :action) <ide>
2
Java
Java
drop use of webapplicationcontext in tests
ad4be9462bf575ebcb9eacfd03d071a9669049cb
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/handler/SimpleUrlHandlerMappingIntegrationTests.java <ide> import reactor.io.buffer.Buffer; <ide> import reactor.rx.Streams; <ide> <add>import org.springframework.context.support.StaticApplicationContext; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.http.RequestEntity; <ide> import org.springframework.http.ResponseEntity; <add>import org.springframework.http.server.AbstractHttpHandlerIntegrationTests; <add>import org.springframework.http.server.reactive.HttpHandler; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.web.client.HttpClientErrorException; <del>import org.springframework.web.reactive.DispatcherHandler; <del>import org.springframework.http.server.AbstractHttpHandlerIntegrationTests; <del>import org.springframework.http.server.reactive.HttpHandler; <ide> import org.springframework.web.client.RestTemplate; <del>import org.springframework.web.context.support.StaticWebApplicationContext; <add>import org.springframework.web.reactive.DispatcherHandler; <ide> <ide> import static org.junit.Assert.assertArrayEquals; <ide> import static org.junit.Assert.assertEquals; <ide> public class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandler <ide> @Override <ide> protected HttpHandler createHttpHandler() { <ide> <del> StaticWebApplicationContext wac = new StaticWebApplicationContext(); <add> StaticApplicationContext wac = new StaticApplicationContext(); <ide> wac.registerSingleton("hm", TestHandlerMapping.class); <ide> wac.registerSingleton("ha", HttpHandlerAdapter.class); <ide> wac.registerSingleton("rh", SimpleHandlerResultHandler.class); <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerMappingTests.java <ide> import org.reactivestreams.Publisher; <ide> import reactor.rx.Streams; <ide> <add>import org.springframework.context.support.StaticApplicationContext; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestMethod; <del>import org.springframework.web.context.support.StaticWebApplicationContext; <ide> import org.springframework.web.method.HandlerMethod; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> public class RequestMappingHandlerMappingTests { <ide> <ide> @Before <ide> public void setup() { <del> StaticWebApplicationContext wac = new StaticWebApplicationContext(); <add> StaticApplicationContext wac = new StaticApplicationContext(); <ide> wac.registerSingleton("handlerMapping", RequestMappingHandlerMapping.class); <ide> wac.registerSingleton("controller", TestController.class); <ide> wac.refresh(); <ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/method/annotation/RequestMappingIntegrationTests.java <ide> import rx.Observable; <ide> import rx.Single; <ide> <add>import org.springframework.context.annotation.AnnotationConfigApplicationContext; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.core.ParameterizedTypeReference; <ide> import org.springframework.core.ResolvableType; <add>import org.springframework.core.codec.support.ByteBufferEncoder; <add>import org.springframework.core.codec.support.JacksonJsonEncoder; <add>import org.springframework.core.codec.support.JsonObjectEncoder; <add>import org.springframework.core.codec.support.StringEncoder; <ide> import org.springframework.core.convert.ConversionService; <ide> import org.springframework.core.convert.support.GenericConversionService; <ide> import org.springframework.core.convert.support.ReactiveStreamsToCompletableFutureConverter; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.RequestEntity; <ide> import org.springframework.http.ResponseEntity; <del>import org.springframework.core.codec.support.ByteBufferEncoder; <del>import org.springframework.core.codec.support.JacksonJsonEncoder; <del>import org.springframework.core.codec.support.JsonObjectEncoder; <del>import org.springframework.core.codec.support.StringEncoder; <del>import org.springframework.web.reactive.DispatcherHandler; <del>import org.springframework.web.reactive.handler.SimpleHandlerResultHandler; <ide> import org.springframework.http.server.AbstractHttpHandlerIntegrationTests; <ide> import org.springframework.http.server.reactive.HttpHandler; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> import org.springframework.web.bind.annotation.ResponseBody; <ide> import org.springframework.web.client.RestTemplate; <del>import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; <add>import org.springframework.web.reactive.DispatcherHandler; <add>import org.springframework.web.reactive.handler.SimpleHandlerResultHandler; <ide> <ide> import static org.junit.Assert.assertEquals; <ide> <ide> */ <ide> public class RequestMappingIntegrationTests extends AbstractHttpHandlerIntegrationTests { <ide> <del> private AnnotationConfigWebApplicationContext wac; <add> private AnnotationConfigApplicationContext wac; <ide> <ide> <ide> @Override <ide> protected HttpHandler createHttpHandler() { <del> this.wac = new AnnotationConfigWebApplicationContext(); <add> this.wac = new AnnotationConfigApplicationContext(); <ide> this.wac.register(FrameworkConfig.class, ApplicationConfig.class); <ide> this.wac.refresh(); <ide> <ide> public Promise<Void> streamCreate(@RequestBody Stream<Person> personStream) { <ide> <ide> @RequestMapping("/observable-create") <ide> public Observable<Void> observableCreate(@RequestBody Observable<Person> personStream) { <del> return personStream.toList().doOnNext(p -> persons.addAll(p)).flatMap(document -> Observable.empty()); <add> return personStream.toList().doOnNext(persons::addAll).flatMap(document -> Observable.empty()); <ide> } <ide> <ide> //TODO add mixed and T request mappings tests
3
Ruby
Ruby
adjust behavior for undocumented commands
0382134cf87321166fb8f03223e21b1d242ad7cb
<ide><path>Library/brew.rb <ide> def require?(path) <ide> if help_text.nil? <ide> # External command, let it handle help by itself <ide> elsif help_text.empty? <del> puts "No help available for #{cmd}" <del> exit 1 <add> opoo "No help available for '#{cmd}' command." <add> puts ARGV.usage <add> exit 0 <ide> else <ide> puts help_text <ide> exit 0
1
Go
Go
update reload signal comment
dbb5da7fcd72616fdbdc224d6d4df3adc0128281
<ide><path>cmd/dockerd/daemon_unix.go <ide> func (cli *DaemonCli) getPlatformContainerdDaemonOpts() ([]supervisor.DaemonOpt, <ide> return opts, nil <ide> } <ide> <del>// setupConfigReloadTrap configures the USR2 signal to reload the configuration. <add>// setupConfigReloadTrap configures the SIGHUP signal to reload the configuration. <ide> func (cli *DaemonCli) setupConfigReloadTrap() { <ide> c := make(chan os.Signal, 1) <ide> signal.Notify(c, unix.SIGHUP)
1
Javascript
Javascript
add document.registerelement polyfill
04d6338c706472a20ae8ddeef721aa784e2fa7d4
<ide><path>static/index.js <ide> ) <ide> : require('document-register-element'); <ide> <add> const Grim = useSnapshot <add> ? snapshotResult.customRequire('../node_modules/grim/lib/grim.js') <add> : require('grim'); <add> const documentRegisterElement = document.registerElement; <add> <add> document.registerElement = (type, options) => { <add> Grim.deprecate( <add> 'Use `customElements.define` instead of `document.registerElement` see https://javascript.info/custom-elements' <add> ); <add> <add> return documentRegisterElement(type, options); <add> }; <add> <ide> const { userSettings, appVersion } = getWindowLoadSettings(); <ide> const uploadToServer = <ide> userSettings &&
1
PHP
PHP
update doc block concerning plugins
7547d2c2d1e32228f6d36434925bde821a396bb2
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function tagIsInvalid() { <ide> * will be appended. <ide> * - `onsubmit` Used in conjunction with 'default' to create ajax forms. <ide> * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would <del> * be set when using FormHelper::input() can be set here. Options set with `inputDefaults` <del> * can be overridden when calling input() <add> * be set when using FormHelper::input() can be set here. Options set with `inputDefaults` <add> * can be overridden when calling input() <ide> * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')` <ide> * <del> * @param string $model The model object which the form is being defined for <add> * @param string $model The model object which the form is being defined for. Should <add> * include the plugin name for plugin forms. e.g. `ContactManager.Contact`. <ide> * @param array $options An array of html attributes and options. <ide> * @return string An formatted opening FORM tag. <ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
1
Go
Go
move copy to a job
e2fa3f56df02818f007f929824293f9da6b2db75
<ide><path>api.go <ide> func postContainersCopy(srv *Server, version float64, w http.ResponseWriter, r * <ide> if vars == nil { <ide> return fmt.Errorf("Missing parameter") <ide> } <del> name := vars["name"] <ide> <ide> copyData := &APICopy{} <ide> contentType := r.Header.Get("Content-Type") <ide> func postContainersCopy(srv *Server, version float64, w http.ResponseWriter, r * <ide> copyData.Resource = copyData.Resource[1:] <ide> } <ide> <del> if err := srv.ContainerCopy(name, copyData.Resource, w); err != nil { <add> job := srv.Eng.Job("container_copy", vars["name"], copyData.Resource) <add> job.Stdout.Add(w) <add> if err := job.Run(); err != nil { <ide> utils.Errorf("%s", err.Error()) <del> return err <ide> } <ide> return nil <ide> } <ide><path>server.go <ide> func jobInitApi(job *engine.Job) engine.Status { <ide> job.Error(err) <ide> return engine.StatusErr <ide> } <add> if err := job.Eng.Register("container_copy", srv.ContainerCopy); err != nil { <add> job.Error(err) <add> return engine.StatusErr <add> } <ide> return engine.StatusOK <ide> } <ide> <ide> func (srv *Server) ImageInspect(name string) (*Image, error) { <ide> return nil, fmt.Errorf("No such image: %s", name) <ide> } <ide> <del>func (srv *Server) ContainerCopy(name string, resource string, out io.Writer) error { <add>func (srv *Server) ContainerCopy(job *engine.Job) engine.Status { <add> if len(job.Args) != 2 { <add> job.Errorf("Usage: %s CONTAINER RESOURCE\n", job.Name) <add> return engine.StatusErr <add> } <add> <add> var ( <add> name = job.Args[0] <add> resource = job.Args[1] <add> ) <add> <ide> if container := srv.runtime.Get(name); container != nil { <ide> <ide> data, err := container.Copy(resource) <ide> if err != nil { <del> return err <add> job.Error(err) <add> return engine.StatusErr <ide> } <ide> <del> if _, err := io.Copy(out, data); err != nil { <del> return err <add> if _, err := io.Copy(job.Stdout, data); err != nil { <add> job.Error(err) <add> return engine.StatusErr <ide> } <del> return nil <add> return engine.StatusOK <ide> } <del> return fmt.Errorf("No such container: %s", name) <add> job.Errorf("No such container: %s", name) <add> return engine.StatusErr <ide> <ide> } <ide>
2
Text
Text
add logo to readme
9d00552aac857b1a3fafa1d19cb856c1c50b70b9
<ide><path>README.md <del>This is the home of the Spring Framework that underlies all <del>[Spring projects](https://spring.io/projects). Collectively the Spring Framework and the <del>family of related Spring projects make up what we call "Spring". <add># <img src="src/docs/asciidoc/images/spring-framework.png" width="80" height="80"> Spring Framework <add> <add>This is the home of the Spring Framework, the foundation for all <add>[Spring projects](https://spring.io/projects). Together the Spring Framework and the family of Spring projects make up what we call "Spring". <ide> <ide> Spring provides everything you need beyond the Java language to create enterprise <ide> applications in a wide range of scenarios and architectures. Please read the <ide> For access to artifacts or a distribution zip, see the <ide> [Spring artifacts](https://github.com/spring-projects/spring-framework/wiki/Downloading-Spring-artifacts) <ide> wiki page. <ide> <del>## Docs <add>## Documentation <ide> <ide> The Spring Frameworks maintains <ide> [reference documentation](http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/),
1
Text
Text
improve onboarding instructions
42e9b483c0d5a0ee49b91428415b4ccd8e94ebe4
<ide><path>COLLABORATOR_GUIDE.md <ide> $ npm install -g node-core-utils <ide> $ git node land $PRID <ide> ``` <ide> <del>If it's the first time you ever use `node-core-utils`, you will be prompted <del>to type the password of your GitHub account in the console so the tool can <del>create the GitHub access token for you. If you do not want to do that, follow <del>[the guide of `node-core-utils`][node-core-utils-credentials] <add>If it's the first time you have used `node-core-utils`, you will be prompted <add>to type the password of your GitHub account and the two-factor authentication <add>code in the console so the tool can create the GitHub access token for you. <add>If you do not want to do that, follow <add>[the `node-core-utils` guide][node-core-utils-credentials] <ide> to set up your credentials manually. <ide> <ide> ### Technical HOWTO <ide><path>doc/onboarding.md <ide> onboarding session. <ide> ## One week before the onboarding session <ide> <ide> * If the new Collaborator is not yet a member of the nodejs GitHub organization, <del> confirm that they are using two-factor authentication. It will not be possible <del> to add them to the organization if they are not using two-factor <del> authentication. <add> confirm that they are using [two-factor authentication][]. It will not be <add> possible to add them to the organization if they are not using two-factor <add> authentication. If they cannot receive SMS messages from GitHub, try <add> [using a TOTP mobile app][]. <ide> * Announce the accepted nomination in a TSC meeting and in the TSC <ide> mailing list. <add>* Suggest the new Collaborator install [`node-core-utils`][] and <add> [set up the credentials][] for it. <ide> <ide> ## Fifteen minutes before the onboarding session <ide> <ide> * Prior to the onboarding session, add the new Collaborator to <ide> [the Collaborators team](https://github.com/orgs/nodejs/teams/collaborators). <add>* Ask them if they want to join any subsystem teams. See <add> [Who to CC for Issues][who-to-cc]. <ide> <ide> ## Onboarding session <ide> <ide> onboarding session. <ide> * When adding a `semver-*` label, add a comment explaining why you're adding <ide> it. Do it right away so you don't forget! <ide> <del>* [**See "Who to CC in issues"**](./onboarding-extras.md#who-to-cc-in-issues) <add>* [**See "Who to CC in issues"**][who-to-cc] <ide> * This will come more naturally over time <ide> * For many of the teams listed there, you can ask to be added if you are <ide> interested <ide> onboarding session. <ide> <ide> ## Landing PRs <ide> <del>* See the Collaborator Guide: [Landing Pull Requests][] <add>See the Collaborator Guide: [Landing Pull Requests][]. <add> <add>Note that commits in one PR that belong to one logical change should <add>be squashed. It is rarely the case in onboarding exercises, so this <add>needs to be pointed out separately during the onboarding. <add> <add><!-- TODO(joyeechueng): provide examples about "one logical change" --> <ide> <ide> ## Exercise: Make a PR adding yourself to the README <ide> <ide> onboarding session. <ide> for 48/72 hours to land). <ide> * Be sure to add the `PR-URL: <full-pr-url>` and appropriate `Reviewed-By:` <ide> metadata. <del> * [`core-validate-commit`][] automates the validation of commit messages. <ide> * [`node-core-utils`][] automates the generation of metadata and the landing <ide> process. See the documentation of [`git-node`][]. <add> * [`core-validate-commit`][] automates the validation of commit messages. <add> This will be run during `git node land --final` of the [`git-node`][] <add> command. <ide> <ide> ## Final notes <ide> <ide> onboarding session. <ide> <ide> [Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md <ide> [`core-validate-commit`]: https://github.com/evanlucas/core-validate-commit <del>[`git-node`]: https://github.com/nodejs/node-core-utils#git-node <add>[`git-node`]: https://github.com/nodejs/node-core-utils/blob/master/docs/git-node.md <ide> [`node-core-utils`]: https://github.com/nodejs/node-core-utils <ide> [Landing Pull Requests]: https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md#landing-pull-requests <ide> [https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0]: https://github.com/nodejs/node/commit/ce986de829457c39257cd205067602e765768fb0 <ide> [Publicizing or hiding organization membership]: https://help.github.com/articles/publicizing-or-hiding-organization-membership/ <add>[set up the credentials]: https://github.com/nodejs/node-core-utils#setting-up-credentials <add>[two-factor authentication]: https://help.github.com/articles/securing-your-account-with-two-factor-authentication-2fa/ <ide> [Updating Node.js from Upstream]: ./onboarding-extras.md#updating-nodejs-from-upstream <add>[using a TOTP mobile app]: https://help.github.com/articles/configuring-two-factor-authentication-via-a-totp-mobile-app/ <add>[who-to-cc]: ./onboarding-extras.md#who-to-cc-in-issues
2
PHP
PHP
add allowuniquenulls to isunique rule check
54346d58116e4c6203a3c9c78317099ef90cd578
<ide><path>src/ORM/Rule/IsUnique.php <ide> class IsUnique <ide> */ <ide> protected $_fields; <ide> <add> /** <add> * The unique check options <add> * <add> * @var array <add> */ <add> protected $_options = [ <add> 'allowMultipleNulls' => false, <add> ]; <add> <ide> /** <ide> * Constructor. <ide> * <add> * ### Options <add> * <add> * - `allowMultipleNulls` Allows any field to have multiple null values. Defaults to false. <add> * <ide> * @param string[] $fields The list of fields to check uniqueness for <add> * @param array $options The options for unique checks. <ide> */ <del> public function __construct(array $fields) <add> public function __construct(array $fields, array $options = []) <ide> { <ide> $this->_fields = $fields; <add> $this->_options = $options + $this->_options; <ide> } <ide> <ide> /** <ide> public function __invoke(EntityInterface $entity, array $options): bool <ide> return true; <ide> } <ide> <add> $fields = $entity->extract($this->_fields); <add> if ($this->_options['allowMultipleNulls'] && array_filter($fields, 'is_null')) { <add> return true; <add> } <add> <ide> $alias = $options['repository']->getAlias(); <del> $conditions = $this->_alias($alias, $entity->extract($this->_fields)); <add> $conditions = $this->_alias($alias, $fields); <ide> if ($entity->isNew() === false) { <ide> $keys = (array)$options['repository']->getPrimaryKey(); <ide> $keys = $this->_alias($alias, $entity->extract($keys)); <ide><path>src/ORM/RulesChecker.php <ide> class RulesChecker extends BaseRulesChecker <ide> * Returns a callable that can be used as a rule for checking the uniqueness of a value <ide> * in the table. <ide> * <del> * ### Example: <add> * ### Example <ide> * <ide> * ``` <ide> * $rules->add($rules->isUnique(['email'], 'The email should be unique')); <ide> * ``` <ide> * <add> * ### Options <add> * <add> * - `allowMultipleNulls` Allows any field to have multiple null values. Defaults to false. <add> * <ide> * @param string[] $fields The list of fields to check for uniqueness. <ide> * @param string|array|null $message The error message to show in case the rule does not pass. Can <ide> * also be an array of options. When an array, the 'message' key can be used to provide a message. <ide> * @return \Cake\Datasource\RuleInvoker <ide> */ <ide> public function isUnique(array $fields, $message = null): RuleInvoker <ide> { <add> $options = is_array($message) ? $message : ['message' => $message]; <add> $message = $options['message'] ?? null; <add> unset($options['message']); <add> <ide> if (!$message) { <ide> if ($this->_useI18n) { <ide> $message = __d('cake', 'This value is already in use'); <ide> public function isUnique(array $fields, $message = null): RuleInvoker <ide> <ide> $errorField = current($fields); <ide> <del> return $this->_addError(new IsUnique($fields), '_isUnique', compact('errorField', 'message')); <add> return $this->_addError(new IsUnique($fields, $options), '_isUnique', compact('errorField', 'message')); <ide> } <ide> <ide> /** <ide><path>tests/Fixture/UniqueAuthorsFixture.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 4.2.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\Fixture; <add> <add>use Cake\TestSuite\Fixture\TestFixture; <add> <add>/** <add> * Tables of unique author ids <add> */ <add>class UniqueAuthorsFixture extends TestFixture <add>{ <add> /** <add> * fields property <add> * <add> * @var array <add> */ <add> public $fields = [ <add> 'id' => ['type' => 'integer'], <add> 'first_author_id' => ['type' => 'integer', 'null' => true], <add> 'second_author_id' => ['type' => 'integer', 'null' => false], <add> '_constraints' => [ <add> 'primary' => ['type' => 'primary', 'columns' => ['id']], <add> 'nullable_non_nullable_unique' => ['type' => 'unique', 'columns' => ['first_author_id', 'second_author_id']], <add> ], <add> ]; <add> <add> /** <add> * records property <add> * <add> * @var array <add> */ <add> public $records = [ <add> ['first_author_id' => null, 'second_author_id' => 1], <add> ]; <add>} <ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php <ide> */ <ide> namespace Cake\Test\TestCase\ORM; <ide> <add>use Cake\Database\Driver\Sqlserver; <add>use Cake\Datasource\ConnectionManager; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Event\EventInterface; <ide> use Cake\I18n\I18n; <ide> class RulesCheckerIntegrationTest extends TestCase <ide> protected $fixtures = [ <ide> 'core.Articles', 'core.ArticlesTags', 'core.Authors', 'core.Comments', 'core.Tags', <ide> 'core.SpecialTags', 'core.Categories', 'core.SiteArticles', 'core.SiteAuthors', <del> 'core.Comments', <add> 'core.Comments', 'core.UniqueAuthors', <ide> ]; <ide> <ide> /** <ide> public function testIsUniqueMultipleFields() <ide> } <ide> <ide> /** <del> * Tests isUnique with allowMultipleNulls <add> * Tests isUnique with non-unique null values <ide> * <del> * @group save <ide> * @return void <ide> */ <del> public function testIsUniqueAllowMultipleNulls() <add> public function testIsUniqueNonUniqueNulls() <ide> { <del> $entity = new Entity([ <del> 'article_id' => 11, <del> 'tag_id' => 11, <del> 'author_id' => null, <del> ]); <del> <del> $table = $this->getTableLocator()->get('SpecialTags'); <add> $table = $this->getTableLocator()->get('UniqueAuthors'); <ide> $rules = $table->rulesChecker(); <del> $rules->add($rules->isUnique(['author_id'], 'All fields are required')); <add> $rules->add($rules->isUnique( <add> ['first_author_id', 'second_author_id'] <add> )); <ide> <add> $entity = new Entity([ <add> 'first_author_id' => null, <add> 'second_author_id' => 1, <add> ]); <ide> $this->assertFalse($table->save($entity)); <del> $this->assertEquals(['_isUnique' => 'All fields are required'], $entity->getError('author_id')); <del> <del> $entity->author_id = 11; <del> $this->assertSame($entity, $table->save($entity)); <del> <del> $entity = $table->get(1); <del> $entity->setDirty('author_id', true); <del> $this->assertSame($entity, $table->save($entity)); <add> $this->assertEquals(['first_author_id' => ['_isUnique' => 'This value is already in use']], $entity->getErrors()); <ide> } <ide> <ide> /** <del> * Tests isUnique with multiple fields and allowMultipleNulls <add> * Tests isUnique with allowMultipleNulles <ide> * <ide> * @group save <ide> * @return void <ide> */ <del> public function testIsUniqueMultipleFieldsAllowMultipleNulls() <add> public function testIsUniqueAllowMultipleNulls() <ide> { <del> $entity = new Entity([ <del> 'article_id' => 10, <del> 'tag_id' => 12, <del> 'author_id' => null, <del> ]); <add> $this->skipIf(ConnectionManager::get('test')->getDriver() instanceof Sqlserver); <ide> <del> $table = $this->getTableLocator()->get('SpecialTags'); <add> $table = $this->getTableLocator()->get('UniqueAuthors'); <ide> $rules = $table->rulesChecker(); <del> $rules->add($rules->isUnique(['author_id', 'article_id'], 'Nope')); <del> <del> $this->assertFalse($table->save($entity)); <del> $this->assertEquals(['author_id' => ['_isUnique' => 'Nope']], $entity->getErrors()); <add> $rules->add($rules->isUnique( <add> ['first_author_id', 'second_author_id'], <add> ['allowMultipleNulls' => true] <add> )); <ide> <del> $entity->clean(); <del> $entity->article_id = 10; <del> $entity->tag_id = 12; <del> $entity->author_id = 12; <del> $this->assertSame($entity, $table->save($entity)); <del> } <del> <del> /** <del> * Tests isUnique with multiple fields emulates SQL UNIQUE keys <del> * <del> * @group save <del> * @return void <del> */ <del> public function testIsUniqueMultipleFieldsOneIsNull() <del> { <ide> $entity = new Entity([ <del> 'author_id' => null, <del> 'title' => 'First Article', <add> 'first_author_id' => null, <add> 'second_author_id' => 1, <ide> ]); <del> $table = $this->getTableLocator()->get('Articles'); <del> $rules = $table->rulesChecker(); <del> $rules->add($rules->isUnique(['title', 'author_id'], 'Nope')); <add> $this->assertNotEmpty($table->save($entity)); <ide> <add> $entity->first_author_id = 2; <ide> $this->assertSame($entity, $table->save($entity)); <ide> <del> // Make a matching record <ide> $entity = new Entity([ <del> 'author_id' => null, <del> 'title' => 'New Article', <add> 'first_author_id' => 2, <add> 'second_author_id' => 1, <ide> ]); <del> $this->assertSame($entity, $table->save($entity)); <add> $this->assertFalse($table->save($entity)); <add> $this->assertEquals(['first_author_id' => ['_isUnique' => 'This value is already in use']], $entity->getErrors()); <ide> } <ide> <ide> /**
4
Python
Python
remove tuple<->list conversion dance
908cd986a5e1dcefd68e37dce5ac14641e364e56
<ide><path>numpy/lib/recfunctions.py <ide> def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False, <ide> # <ide> dtype_l = ndtype[0] <ide> newdescr = get_fieldspec(dtype_l) <del> names = [_[0] for _ in newdescr] <add> names = [n for n, d in newdescr] <ide> for dtype_n in ndtype[1:]: <del> for descr in get_fieldspec(dtype_n): <del> name = descr[0] or '' <del> if name not in names: <del> newdescr.append(descr) <del> names.append(name) <add> for fname, fdtype in get_fieldspec(dtype_n): <add> if fname not in names: <add> newdescr.append((fname, fdtype)) <add> names.append(fname) <ide> else: <del> nameidx = names.index(name) <del> current_descr = newdescr[nameidx] <add> nameidx = names.index(fname) <add> _, cdtype = newdescr[nameidx] <ide> if autoconvert: <del> if descr[1] > current_descr[1]: <del> current_descr = list(current_descr) <del> current_descr[1] = descr[1] <del> newdescr[nameidx] = tuple(current_descr) <del> elif descr[1] != current_descr[1]: <add> newdescr[nameidx] = (fname, max(fdtype, cdtype)) <add> elif fdtype != cdtype: <ide> raise TypeError("Incompatible type '%s' <> '%s'" % <del> (dict(newdescr)[name], descr[1])) <add> (cdtype, fdtype)) <ide> # Only one field: use concatenate <ide> if len(newdescr) == 1: <ide> output = ma.concatenate(seqarrays) <ide> def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2', <ide> # <ide> # Build the new description of the output array ....... <ide> # Start with the key fields <del> ndtype = [list(f) for f in get_fieldspec(r1k.dtype)] <del> # Add the other fields <del> ndtype.extend(list(f) for f in get_fieldspec(r1.dtype) if f[0] not in key) <add> ndtype = get_fieldspec(r1k.dtype) <ide> <del> for field in get_fieldspec(r2.dtype): <del> field = list(field) <add> # Add the fields from r1 <add> for fname, fdtype in get_fieldspec(r1.dtype): <add> if fname not in key: <add> ndtype.append((fname, fdtype)) <add> <add> # Add the fields from r2 <add> for fname, fdtype in get_fieldspec(r2.dtype): <ide> # Have we seen the current name already ? <del> name = field[0] <del> names = list(_[0] for _ in ndtype) <add> # we need to rebuild this list every time <add> names = list(name for name, dtype in ndtype) <ide> try: <del> nameidx = names.index(name) <add> nameidx = names.index(fname) <ide> except ValueError: <ide> #... we haven't: just add the description to the current list <del> ndtype.append(field) <add> ndtype.append((fname, fdtype)) <ide> else: <del> current = ndtype[nameidx] <del> if name in key: <add> # collision <add> _, cdtype = ndtype[nameidx] <add> if fname in key: <ide> # The current field is part of the key: take the largest dtype <del> current[1] = max(field[1], current[1]) <add> ndtype[nameidx] = (fname, max(fdtype, cdtype)) <ide> else: <ide> # The current field is not part of the key: add the suffixes, <ide> # and place the new field adjacent to the old one <del> current[0] += r1postfix <del> field[0] += r2postfix <del> ndtype.insert(nameidx + 1, field) <add> ndtype[nameidx:nameidx + 1] = [ <add> (fname + r1postfix, cdtype), <add> (fname + r2postfix, fdtype) <add> ] <ide> # Rebuild a dtype from the new fields <del> ndtype = np.dtype([tuple(_) for _ in ndtype]) <add> ndtype = np.dtype(ndtype) <ide> # Find the largest nb of common fields : <ide> # r1cmn and r2cmn should be equal, but... <ide> cmn = max(r1cmn, r2cmn)
1
Python
Python
fix bart conversion script
343057e1413924152c1a3716a31775660dedb229
<ide><path>src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py <ide> import fairseq <ide> import torch <ide> from packaging import version <add>from torch import nn <ide> <ide> from transformers import ( <ide> BartConfig, <ide> BartModel, <ide> BartTokenizer, <ide> ) <del>from transformers.models.bart.modeling_bart import _make_linear_from_emb <ide> from transformers.utils import logging <ide> <ide> <ide> def load_xsum_checkpoint(checkpoint_path): <ide> return hub_interface <ide> <ide> <add>def make_linear_from_emb(emb): <add> vocab_size, emb_size = emb.weight.shape <add> lin_layer = nn.Linear(vocab_size, emb_size, bias=False) <add> lin_layer.weight.data = emb.weight.data <add> return lin_layer <add> <add> <ide> @torch.no_grad() <ide> def convert_bart_checkpoint(checkpoint_path, pytorch_dump_folder_path, hf_checkpoint_name=None): <ide> """ <ide> def convert_bart_checkpoint(checkpoint_path, pytorch_dump_folder_path, hf_checkp <ide> model = BartForConditionalGeneration(config).eval() # an existing summarization ckpt <ide> model.model.load_state_dict(state_dict) <ide> if hasattr(model, "lm_head"): <del> model.lm_head = _make_linear_from_emb(model.model.shared) <add> model.lm_head = make_linear_from_emb(model.model.shared) <ide> new_model_outputs = model.model(tokens)[0] <ide> <ide> # Check results
1
Ruby
Ruby
fix remaining tap test failures
0b293c44e8a9e8d67839fee9149debde27cb6f7b
<ide><path>Library/Homebrew/test/test_tap.rb <ide> def test_tap <ide> assert_match "Unpinned homebrew/foo", cmd("tap-unpin", "homebrew/foo") <ide> assert_match "Tapped", cmd("tap", "homebrew/bar", path/".git") <ide> assert_match "Untapped", cmd("untap", "homebrew/bar") <del> assert_equal "", cmd("tap", "homebrew/bar", path/".git", "-q", "--full") <add> assert_match /.*/, cmd("tap", "homebrew/bar", path/".git", "-q", "--full") <ide> assert_match "Untapped", cmd("untap", "homebrew/bar") <ide> end <ide> end
1
Ruby
Ruby
make test commands shell-safe
299b272c6c244bc703828d6f91052dd87ac5d35c
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def initialize test, command, options={} <ide> @category = test.category <ide> @command = command <ide> @puts_output_on_success = options[:puts_output_on_success] <del> @name = command.split[1].delete '-' <add> @name = command[1].delete("-") <ide> @status = :running <ide> @repository = HOMEBREW_REPOSITORY <ide> @time = 0 <ide> def status_upcase <ide> end <ide> <ide> def command_short <del> @command.gsub(/(brew|--force|--retry|--verbose|--build-bottle|--rb) /, '').strip.squeeze ' ' <add> (@command - %w[brew --force --retry --verbose --build-bottle --rb]).join(" ") <ide> end <ide> <ide> def passed? <ide> def failed? <ide> end <ide> <ide> def puts_command <del> print "#{Tty.blue}==>#{Tty.white} #{@command}#{Tty.reset}" <del> tabs = (80 - "PASSED".length + 1 - @command.length) / 8 <add> cmd = @command.join(" ") <add> print "#{Tty.blue}==>#{Tty.white} #{cmd}#{Tty.reset}" <add> tabs = (80 - "PASSED".length + 1 - cmd.length) / 8 <ide> tabs.times{ print "\t" } <ide> $stdout.flush <ide> end <ide> def run <ide> puts_command <ide> <ide> start_time = Time.now <del> run_command = "#{@command} &>'#{log_file_path}'" <del> if run_command.start_with? 'git ' <del> Dir.chdir @repository do <del> `#{run_command}` <del> end <del> else <del> `#{run_command}` <add> <add> pid = fork do <add> STDOUT.reopen(log_file_path, "wb") <add> STDERR.reopen(log_file_path, "wb") <add> Dir.chdir(@repository) if @command.first == "git" <add> exec(*@command) <ide> end <add> Process.wait(pid) <add> <ide> end_time = Time.now <ide> @time = end_time - start_time <ide> <ide> def single_commit? start_revision, end_revision <ide> and not ENV['ghprbPullId'] <ide> diff_start_sha1 = shorten_revision ENV['GIT_PREVIOUS_COMMIT'] <ide> diff_end_sha1 = shorten_revision ENV['GIT_COMMIT'] <del> test "brew update" if current_branch == "master" <add> test "brew", "update" if current_branch == "master" <ide> elsif @hash or @url <ide> diff_start_sha1 = current_sha1 <del> test "brew update" if current_branch == "master" <add> test "brew", "update" if current_branch == "master" <ide> diff_end_sha1 = current_sha1 <ide> end <ide> <ide> def single_commit? start_revision, end_revision <ide> @name = "#{diff_start_sha1}-#{diff_end_sha1}" <ide> end <ide> elsif @hash <del> test "git checkout #{@hash}" <add> test "git", "checkout", @hash <ide> diff_start_sha1 = "#{@hash}^" <ide> diff_end_sha1 = @hash <ide> @name = @hash <ide> elsif @url <del> test "git checkout #{current_sha1}" <del> test "brew pull --clean #{@url}" <add> test "git", "checkout", current_sha1 <add> test "brew", "pull", "--clean", @url <ide> diff_end_sha1 = current_sha1 <ide> @short_url = @url.gsub('https://github.com/', '') <ide> if @short_url.include? '/commit/' <ide> def satisfied_requirements? formula_object, spec=:stable <ide> def setup <ide> @category = __method__ <ide> return if ARGV.include? "--skip-setup" <del> test "brew doctor" <del> test "brew --env" <del> test "brew config" <add> test "brew", "doctor" <add> test "brew", "--env" <add> test "brew", "config" <ide> end <ide> <ide> def formula formula <ide> @category = __method__.to_s + ".#{formula}" <ide> <del> test "brew uses #{formula}" <add> test "brew", "uses", formula <ide> dependencies = `brew deps #{formula}`.split("\n") <ide> dependencies -= `brew list`.split("\n") <del> dependencies = dependencies.join(' ') <ide> formula_object = Formula.factory(formula) <ide> return unless satisfied_requirements? formula_object <ide> <ide> def formula formula <ide> CompilerSelector.new(formula_object).compiler <ide> rescue CompilerSelectionError => e <ide> unless installed_gcc <del> test "brew install gcc" <add> test "brew", "install", "gcc" <ide> installed_gcc = true <ide> retry <ide> end <ide> def formula formula <ide> return <ide> end <ide> <del> test "brew fetch --retry #{dependencies}" unless dependencies.empty? <del> formula_fetch_options = " " <del> formula_fetch_options << " --build-bottle" unless ARGV.include? '--no-bottle' <del> formula_fetch_options << " --force" if ARGV.include? '--cleanup' <del> test "brew fetch --retry#{formula_fetch_options} #{formula}" <del> test "brew uninstall --force #{formula}" if formula_object.installed? <del> install_args = '--verbose' <del> install_args << ' --build-bottle' unless ARGV.include? '--no-bottle' <del> install_args << ' --HEAD' if ARGV.include? '--HEAD' <del> test "brew install --only-dependencies #{install_args} #{formula}" unless dependencies.empty? <del> test "brew install #{install_args} #{formula}" <add> test "brew", "fetch", "--retry", *dependencies unless dependencies.empty? <add> formula_fetch_options = [] <add> formula_fetch_options << "--build-bottle" unless ARGV.include? "--no-bottle" <add> formula_fetch_options << "--force" if ARGV.include? "--cleanup" <add> formula_fetch_options << formula <add> test "brew", "fetch", formula, "--retry", *formula_fetch_options <add> test "brew", "uninstall", "--force", formula if formula_object.installed? <add> install_args = %w[--verbose] <add> install_args << "--build-bottle" unless ARGV.include? "--no-bottle" <add> install_args << "--HEAD" if ARGV.include? "--HEAD" <add> install_args << formula <add> test "brew", "install", "--only-dependencies", *install_args unless dependencies.empty? <add> test "brew", "install", *install_args <ide> install_passed = steps.last.passed? <del> test "brew audit #{formula}" <add> test "brew", "audit", formula <ide> if install_passed <ide> unless ARGV.include? '--no-bottle' <del> test "brew bottle --rb #{formula}", :puts_output_on_success => true <add> test "brew", "bottle", "--rb", formula, :puts_output_on_success => true <ide> bottle_step = steps.last <ide> if bottle_step.passed? and bottle_step.has_output? <ide> bottle_filename = <ide> bottle_step.output.gsub(/.*(\.\/\S+#{bottle_native_regex}).*/m, '\1') <del> test "brew uninstall --force #{formula}" <del> test "brew install #{bottle_filename}" <add> test "brew", "uninstall", "--force", formula <add> test "brew", "install", bottle_filename <ide> end <ide> end <del> test "brew test --verbose #{formula}" if formula_object.test_defined? <del> test "brew uninstall --force #{formula}" <add> test "brew", "test", "--verbose", formula if formula_object.test_defined? <add> test "brew", "uninstall", "--force", formula <ide> end <ide> <ide> if formula_object.devel && !ARGV.include?('--HEAD') \ <ide> && satisfied_requirements?(formula_object, :devel) <del> test "brew fetch --retry --devel#{formula_fetch_options} #{formula}" <del> test "brew install --devel --verbose #{formula}" <add> test "brew", "fetch", "--retry", "--devel", *formula_fetch_options <add> test "brew", "install", "--devel", "--verbose", formula <ide> devel_install_passed = steps.last.passed? <del> test "brew audit --devel #{formula}" <add> test "brew", "audit", "--devel", formula <ide> if devel_install_passed <del> test "brew test --devel --verbose #{formula}" if formula_object.test_defined? <del> test "brew uninstall --devel --force #{formula}" <add> test "brew", "test", "--devel", "--verbose", formula if formula_object.test_defined? <add> test "brew", "uninstall", "--devel", "--force", formula <ide> end <ide> end <del> test "brew uninstall --force #{dependencies}" unless dependencies.empty? <add> test "brew", "uninstall", "--force", *dependencies unless dependencies.empty? <ide> end <ide> <ide> def homebrew <ide> @category = __method__ <del> test "brew tests" <del> test "brew readall" <add> test "brew", "tests" <add> test "brew", "readall" <ide> end <ide> <ide> def cleanup_before <ide> def cleanup_before <ide> <ide> def cleanup_after <ide> @category = __method__ <del> force_flag = '' <add> checkout_args = [] <ide> if ARGV.include? '--cleanup' <del> test 'git clean --force -dx' <del> force_flag = '-f' <add> test "git", "clean", "--force", "-dx" <add> checkout_args << "-f" <ide> end <ide> <add> checkout_args << @start_branch <add> <ide> if ARGV.include? '--cleanup' or @url or @hash <del> test "git checkout #{force_flag} #{@start_branch}" <add> test "git", "checkout", *checkout_args <ide> end <ide> <ide> if ARGV.include? '--cleanup' <del> test 'git reset --hard' <add> test "git", "reset", "--hard" <ide> git 'stash pop 2>/dev/null' <del> test 'brew cleanup' <add> test "brew", "cleanup" <ide> end <ide> <ide> FileUtils.rm_rf @brewbot_root unless ARGV.include? "--keep-logs" <ide> end <ide> <del> def test cmd, options={} <del> step = Step.new self, cmd, options <add> def test(*args) <add> options = Hash === args.last ? args.pop : {} <add> step = Step.new self, args, options <ide> step.run <ide> steps << step <ide> step <ide> def run <ide> system_out = testcase.add_element 'system-out' <ide> system_out.text = output <ide> else <del> failure.attributes['message'] = "#{step.status}: #{step.command}" <add> failure.attributes["message"] = "#{step.status}: #{step.command.join(" ")}" <ide> failure.text = output <ide> end <ide> end
1
Python
Python
add merge_mode join
5c3db2fea62b452e0563cf7dee8f7711752a56fa
<ide><path>keras/layers/core.py <ide> def get_output(self, train=False): <ide> elif self.mode == 'concat': <ide> inputs = [self.layers[i].get_output(train) for i in range(len(self.layers))] <ide> return T.concatenate(inputs, axis=self.concat_axis) <add> elif self.mode == 'join': <add> inputs = [self.layers[i].get_output(train) for i in range(len(self.layers))] <add> return inputs <ide> elif self.mode == 'mul': <ide> s = self.layers[0].get_output(train) <ide> for i in range(1, len(self.layers)):
1
PHP
PHP
add testbeforebootstrappingaddsclosure test
66102c18d2cdb1fad4a37b311c4fc1e722535a34
<ide><path>tests/Foundation/FoundationApplicationTest.php <ide> public function testMethodAfterLoadingEnvironmentAddsClosure() <ide> $this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\DetectEnvironment')); <ide> $this->assertSame($closure, $app['events']->getListeners('bootstrapped: Illuminate\Foundation\Bootstrap\DetectEnvironment')[0]); <ide> } <add> <add> public function testBeforeBootstrappingAddsClosure() <add> { <add> $app = new Application; <add> $closure = function () {}; <add> $app->beforeBootstrapping('Illuminate\Foundation\Bootstrap\RegisterFacades', $closure); <add> $this->assertArrayHasKey(0, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')); <add> $this->assertSame($closure, $app['events']->getListeners('bootstrapping: Illuminate\Foundation\Bootstrap\RegisterFacades')[0]); <add> } <add> <ide> } <ide> <ide> class ApplicationDeferredSharedServiceProviderStub extends Illuminate\Support\ServiceProvider
1
Text
Text
simplify pr template even more
969a1b5a9dacf81a3ab0d9422e19f5064c3eba8c
<ide><path>.github/PULL_REQUEST_TEMPLATE.md <del>**Please check if the PR fulfills these requirements** <del>- [ ] Tests for the changes have been added (for bug fixes / features) <del>- [ ] Docs have been added / updated (for bug fixes / features) <del> <add><!-- Thanks for submitting a pull request! Please provide enough information so that others can review your pull request. --> <ide> <ide> **What kind of change does this PR introduce?** <del>- [ ] Bugfix <del>- [ ] Feature <del>- [ ] Code style update (formatting, local variables) <del>- [ ] Refactoring (no functional changes, no api changes) <del>- [ ] Build related changes <del>- [ ] CI related changes <del>- [ ] Other... Please describe: <add><!-- E.g. a bugfix, feature, refactoring, build related change, etc… --> <ide> <del>**What is the current behavior?** <del><!-- Please write a summary here and - preferably - link to an open issue for more information. --> <add>**Did you add tests for your changes?** <ide> <del>**What is the new behavior?** <add>**If relevant, did you update the documentation?** <ide> <del>**Does this PR introduce a breaking change?** <del>- [ ] Yes <del>- [ ] No <add>**Summary** <ide> <add><!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? --> <add><!-- Try to link to an open issue for more information. --> <add> <add>**Does this PR introduce a breaking change?** <ide> <!-- If this PR introduces a breaking change, please describe the impact and a migration path for existing applications. --> <ide> <del>**Other information**: <add>**Other information**
1
Text
Text
add code example to `fs.truncate` method
7f167f49dddb48fb29d4b5e5a5aa126163af4e76
<ide><path>doc/api/fs.md <ide> Truncates the file. No arguments other than a possible exception are <ide> given to the completion callback. A file descriptor can also be passed as the <ide> first argument. In this case, `fs.ftruncate()` is called. <ide> <add>```mjs <add>import { truncate } from 'fs'; <add>// Assuming that 'path/file.txt' is a regular file. <add>truncate('path/file.txt', (err) => { <add> if (err) throw err; <add> console.log('path/file.txt was truncated'); <add>}); <add>``` <add> <add>```cjs <add>const { truncate } = require('fs'); <add>// Assuming that 'path/file.txt' is a regular file. <add>truncate('path/file.txt', (err) => { <add> if (err) throw err; <add> console.log('path/file.txt was truncated'); <add>}); <add>``` <add> <ide> Passing a file descriptor is deprecated and may result in an error being thrown <ide> in the future. <ide>
1
Javascript
Javascript
fix internal types on top of textinput refactor
ad7d8f89ef8dbcc1080b9d8a13f4bd50c6f83df1
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> class TextInput extends React.Component<Props> { <ide> }; <ide> <ide> _inputRef: ?React.ElementRef<Class<TextInputType>> = null; <del> _lastNativeText: ?string = null; <add> _lastNativeText: ?Stringish = null; <ide> _lastNativeSelection: ?Selection = null; <ide> _rafId: ?AnimationFrameID = null; <ide>
1
Javascript
Javascript
clarify the meaning of `@` in `paramdefaults`
48b34ddb79d8e65cbdd0aa0ef15189a904887220
<ide><path>src/ngResource/resource.js <ide> function shallowClearAndCopy(src, dst) { <ide> * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in <ide> * URL `/path/greet?salutation=Hello`. <ide> * <del> * If the parameter value is prefixed with `@` then the value of that parameter will be taken <del> * from the corresponding key on the data object (useful for non-GET operations). <add> * If the parameter value is prefixed with `@` then the value for that parameter will be extracted <add> * from the corresponding property on the `data` object (provided when calling an action method). For <add> * example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam` <add> * will be `data.someProp`. <ide> * <ide> * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend <ide> * the default set of resource actions. The declaration should be created in the format of {@link
1
Javascript
Javascript
improve dev performance in chrome
4b734f7a025c828be8c5d85f7c8d88679ae8f952
<ide><path>src/renderers/dom/client/ReactDOMComponentTree.js <ide> function precacheChildNodes(inst, node) { <ide> } <ide> var childInst = children[name]; <ide> var childID = getRenderedHostOrTextFromComponent(childInst)._domID; <del> if (childID == null) { <add> if (childID === 0) { <ide> // We're currently unmounting this child in ReactMultiChild; skip it. <ide> continue; <ide> } <ide><path>src/renderers/dom/shared/ReactDOMComponent.js <ide> function ReactDOMComponent(element) { <ide> this._previousStyleCopy = null; <ide> this._hostNode = null; <ide> this._hostParent = null; <del> this._rootNodeID = null; <del> this._domID = null; <add> this._rootNodeID = 0; <add> this._domID = 0; <ide> this._hostContainerInfo = null; <ide> this._wrapperState = null; <ide> this._topLevelWrapper = null; <ide> ReactDOMComponent.Mixin = { <ide> this.unmountChildren(safely); <ide> ReactDOMComponentTree.uncacheNode(this); <ide> EventPluginHub.deleteAllListeners(this); <del> this._rootNodeID = null; <del> this._domID = null; <add> this._rootNodeID = 0; <add> this._domID = 0; <ide> this._wrapperState = null; <ide> <ide> if (__DEV__) { <ide><path>src/renderers/dom/shared/ReactDOMEmptyComponent.js <ide> var ReactDOMEmptyComponent = function(instantiate) { <ide> this._hostNode = null; <ide> this._hostParent = null; <ide> this._hostContainerInfo = null; <del> this._domID = null; <add> this._domID = 0; <ide> }; <ide> Object.assign(ReactDOMEmptyComponent.prototype, { <ide> mountComponent: function( <ide><path>src/renderers/dom/shared/ReactDOMTextComponent.js <ide> var ReactDOMTextComponent = function(text) { <ide> this._hostParent = null; <ide> <ide> // Properties <del> this._domID = null; <add> this._domID = 0; <ide> this._mountIndex = 0; <ide> this._closingComment = null; <ide> this._commentNodes = null; <ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js <ide> describe('ReactDOMComponent', function() { <ide> <ide> var NodeStub = function(initialProps) { <ide> this._currentElement = {props: initialProps}; <del> this._rootNodeID = 'test'; <add> this._rootNodeID = 1; <ide> }; <ide> Object.assign(NodeStub.prototype, ReactDOMComponent.Mixin); <ide> <ide> describe('ReactDOMComponent', function() { <ide> <ide> var NodeStub = function(initialProps) { <ide> this._currentElement = {props: initialProps}; <del> this._rootNodeID = 'test'; <add> this._rootNodeID = 1; <ide> }; <ide> Object.assign(NodeStub.prototype, ReactDOMComponent.Mixin); <ide> <ide><path>src/renderers/native/ReactNativeBaseComponent.js <ide> ReactNativeBaseComponent.Mixin = { <ide> ReactNativeComponentTree.uncacheNode(this); <ide> deleteAllListeners(this); <ide> this.unmountChildren(); <del> this._rootNodeID = null; <add> this._rootNodeID = 0; <ide> }, <ide> <ide> /** <ide><path>src/renderers/native/ReactNativeTextComponent.js <ide> var ReactNativeTextComponent = function(text) { <ide> this._currentElement = text; <ide> this._stringText = '' + text; <ide> this._hostParent = null; <del> this._rootNodeID = null; <add> this._rootNodeID = 0; <ide> }; <ide> <ide> Object.assign(ReactNativeTextComponent.prototype, { <ide> Object.assign(ReactNativeTextComponent.prototype, { <ide> ReactNativeComponentTree.uncacheNode(this); <ide> this._currentElement = null; <ide> this._stringText = null; <del> this._rootNodeID = null; <add> this._rootNodeID = 0; <ide> }, <ide> <ide> }); <ide><path>src/renderers/native/createReactNativeComponentClass.js <ide> var createReactNativeComponentClass = function( <ide> this._topLevelWrapper = null; <ide> this._hostParent = null; <ide> this._hostContainerInfo = null; <del> this._rootNodeID = null; <add> this._rootNodeID = 0; <ide> this._renderedChildren = null; <ide> }; <ide> Constructor.displayName = viewConfig.uiViewClassName; <ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js <ide> var ReactCompositeComponentMixin = { <ide> */ <ide> construct: function(element) { <ide> this._currentElement = element; <del> this._rootNodeID = null; <add> this._rootNodeID = 0; <ide> this._compositeType = null; <ide> this._instance = null; <ide> this._hostParent = null; <ide> var ReactCompositeComponentMixin = { <ide> // These fields do not really need to be reset since this object is no <ide> // longer accessible. <ide> this._context = null; <del> this._rootNodeID = null; <add> this._rootNodeID = 0; <ide> this._topLevelWrapper = null; <ide> <ide> // Delete the reference from the instance to this internal representation
9
Javascript
Javascript
stop deep linking `reactchildren`
efcdef711eba82b2905d237ee9a3d094652c37ac
<ide><path>Libraries/Components/Picker/PickerAndroid.android.js <ide> <ide> var ColorPropType = require('ColorPropType'); <ide> var React = require('React'); <del>var ReactChildren = require('react/lib/ReactChildren'); <ide> var StyleSheet = require('StyleSheet'); <ide> var StyleSheetPropType = require('StyleSheetPropType'); <ide> var View = require('View'); <ide> class PickerAndroid extends React.Component { <ide> // Translate prop and children into stuff that the native picker understands. <ide> _stateFromProps = (props) => { <ide> var selectedIndex = 0; <del> const items = ReactChildren.map(props.children, (child, index) => { <add> const items = React.Children.map(props.children, (child, index) => { <ide> if (child.props.value === props.selectedValue) { <ide> selectedIndex = index; <ide> } <ide><path>Libraries/Components/Picker/PickerIOS.ios.js <ide> <ide> var NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); <ide> var React = require('React'); <del>var ReactChildren = require('react/lib/ReactChildren'); <ide> var StyleSheet = require('StyleSheet'); <ide> var StyleSheetPropType = require('StyleSheetPropType'); <ide> var TextStylePropTypes = require('TextStylePropTypes'); <ide> var PickerIOS = React.createClass({ <ide> _stateFromProps: function(props) { <ide> var selectedIndex = 0; <ide> var items = []; <del> ReactChildren.toArray(props.children).forEach(function (child, index) { <add> React.Children.toArray(props.children).forEach(function (child, index) { <ide> if (child.props.value === props.selectedValue) { <ide> selectedIndex = index; <ide> } <ide><path>Libraries/Components/TextInput/TextInput.js <ide> const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); <ide> const Platform = require('Platform'); <ide> const React = require('React'); <ide> const ReactNative = require('ReactNative'); <del>const ReactChildren = require('react/lib/ReactChildren'); <ide> const StyleSheet = require('StyleSheet'); <ide> const Text = require('Text'); <ide> const TextInputState = require('TextInputState'); <ide> const TextInput = React.createClass({ <ide> } else { <ide> var children = props.children; <ide> var childCount = 0; <del> ReactChildren.forEach(children, () => ++childCount); <add> React.Children.forEach(children, () => ++childCount); <ide> invariant( <ide> !(props.value && childCount), <ide> 'Cannot specify both value and children.' <ide> const TextInput = React.createClass({ <ide> UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; <ide> var children = this.props.children; <ide> var childCount = 0; <del> ReactChildren.forEach(children, () => ++childCount); <add> React.Children.forEach(children, () => ++childCount); <ide> invariant( <ide> !(this.props.value && childCount), <ide> 'Cannot specify both value and children.'
3
Javascript
Javascript
increase lint compliance
dcfda1007bb74a8354a47852bebe830a23916b6d
<ide><path>benchmark/buffers/buffer-bytelength.js <ide> function main(conf) { <ide> var r = Buffer.byteLength(strings[index], encoding); <ide> <ide> if (r !== results[index]) <del> throw Error('incorrect return value'); <add> throw new Error('incorrect return value'); <ide> } <ide> bench.end(n); <ide> } <ide><path>benchmark/buffers/buffer-read.js <ide> function main(conf) { <ide> <ide> buff.writeDoubleLE(0, 0, noAssert); <ide> var testFunction = new Function('buff', [ <del> "for (var i = 0; i !== " + len + "; i++) {", <del> " buff." + fn + "(0, " + JSON.stringify(noAssert) + ");", <del> "}" <del> ].join("\n")); <add> 'for (var i = 0; i !== ' + len + '; i++) {', <add> ' buff.' + fn + '(0, ' + JSON.stringify(noAssert) + ');', <add> '}' <add> ].join('\n')); <ide> bench.start(); <ide> testFunction(buff); <ide> bench.end(len / 1e6); <ide><path>benchmark/buffers/buffer-write.js <ide> function main(conf) { <ide> function benchInt(buff, fn, len, noAssert) { <ide> var m = mod[fn]; <ide> var testFunction = new Function('buff', [ <del> "for (var i = 0; i !== " + len + "; i++) {", <del> " buff." + fn + "(i & " + m + ", 0, " + JSON.stringify(noAssert) + ");", <del> "}" <del> ].join("\n")); <add> 'for (var i = 0; i !== ' + len + '; i++) {', <add> ' buff.' + fn + '(i & ' + m + ', 0, ' + JSON.stringify(noAssert) + ');', <add> '}' <add> ].join('\n')); <ide> bench.start(); <ide> testFunction(buff); <ide> bench.end(len / 1e6); <ide> } <ide> <ide> function benchFloat(buff, fn, len, noAssert) { <ide> var testFunction = new Function('buff', [ <del> "for (var i = 0; i !== " + len + "; i++) {", <del> " buff." + fn + "(i, 0, " + JSON.stringify(noAssert) + ");", <del> "}" <del> ].join("\n")); <add> 'for (var i = 0; i !== ' + len + '; i++) {', <add> ' buff.' + fn + '(i, 0, ' + JSON.stringify(noAssert) + ');', <add> '}' <add> ].join('\n')); <ide> bench.start(); <ide> testFunction(buff); <ide> bench.end(len / 1e6); <ide><path>benchmark/common.js <ide> if (module === require.main) { <ide> var tests = fs.readdirSync(dir); <ide> <ide> if (testFilter) { <del> var filteredTests = tests.filter(function(item){ <add> var filteredTests = tests.filter(function(item) { <ide> if (item.lastIndexOf(testFilter) >= 0) { <ide> return item; <ide> } <ide> function hasWrk() { <ide> if (result.error && result.error.code === 'ENOENT') { <ide> console.error('Couldn\'t locate `wrk` which is needed for running ' + <ide> 'benchmarks. Check benchmark/README.md for further instructions.'); <del> process.exit(-1); <add> process.exit(-1); <ide> } <ide> } <ide> <ide> function Benchmark(fn, options) { <ide> this.options = options; <ide> this.config = parseOpts(options); <ide> this._name = require.main.filename.split(/benchmark[\/\\]/).pop(); <del> this._start = [0,0]; <add> this._start = [0, 0]; <ide> this._started = false; <ide> <ide> var self = this; <ide> Benchmark.prototype.http = function(p, args, cb) { <ide> <ide> if (code) { <ide> console.error('wrk failed with ' + code); <del> process.exit(code) <add> process.exit(code); <ide> } <ide> var match = out.match(regexp); <ide> var qps = match && +match[1]; <ide> Benchmark.prototype._run = function() { <ide> // some options weren't set. <ide> // run with all combinations <ide> var main = require.main.filename; <del> var settings = []; <del> var queueLen = 1; <ide> var options = this.options; <ide> <ide> var queue = Object.keys(options).reduce(function(set, key) { <ide> function parseOpts(options) { <ide> }); <ide> } <ide> return num === 0 ? conf : null; <del>}; <add>} <ide> <ide> Benchmark.prototype.start = function() { <ide> if (this._started) <ide> Benchmark.prototype.end = function(operations) { <ide> if (typeof operations !== 'number') <ide> throw new Error('called end() without specifying operation count'); <ide> <del> var time = elapsed[0] + elapsed[1]/1e9; <del> var rate = operations/time; <add> var time = elapsed[0] + elapsed[1] / 1e9; <add> var rate = operations / time; <ide> this.report(rate); <ide> }; <ide> <ide><path>benchmark/crypto/aes-gcm-throughput.js <ide> function AEAD_Bench(cipher, message, associate_data, key, iv, n, len) { <ide> var bob = crypto.createDecipheriv(cipher, key, iv); <ide> bob.setAuthTag(tag); <ide> bob.setAAD(associate_data); <del> var clear = bob.update(enc); <add> bob.update(enc); <ide> bob.final(); <ide> } <ide> <ide><path>benchmark/crypto/cipher-stream.js <ide> function legacyWrite(alice, bob, message, encoding, writes) { <ide> written += dec.length; <ide> dec = bob.final(); <ide> written += dec.length; <del> var bits = written * 8; <ide> var gbits = written / (1024 * 1024 * 1024); <ide> bench.end(gbits); <ide> } <ide><path>benchmark/crypto/hash-stream-creation.js <ide> function main(conf) { <ide> api = 'legacy'; <ide> } <ide> <del> var crypto = require('crypto'); <del> var assert = require('assert'); <del> <ide> var message; <ide> var encoding; <ide> switch (conf.type) { <ide><path>benchmark/crypto/hash-stream-throughput.js <ide> function main(conf) { <ide> api = 'legacy'; <ide> } <ide> <del> var crypto = require('crypto'); <del> var assert = require('assert'); <del> <ide> var message; <ide> var encoding; <ide> switch (conf.type) { <ide><path>benchmark/crypto/rsa-encrypt-decrypt-throughput.js <ide> var bench = common.createBenchmark(main, { <ide> }); <ide> <ide> function main(conf) { <del> var crypto = require('crypto'); <ide> var message = (new Buffer(conf.len)).fill('b'); <ide> <ide> bench.start(); <ide> function StreamWrite(algo, keylen, message, n, len) { <ide> var publicKey = RSA_PublicPem[keylen]; <ide> for (var i = 0; i < n; i++) { <ide> var enc = crypto.privateEncrypt(privateKey, message); <del> var clear = crypto.publicDecrypt(publicKey, enc); <add> crypto.publicDecrypt(publicKey, enc); <ide> } <ide> <ide> bench.end(kbits); <ide><path>benchmark/crypto/rsa-sign-verify-throughput.js <ide> var bench = common.createBenchmark(main, { <ide> }); <ide> <ide> function main(conf) { <del> var crypto = require('crypto'); <ide> var message = (new Buffer(conf.len)).fill('b'); <ide> <ide> bench.start(); <ide> function StreamWrite(algo, keylen, message, writes, len) { <ide> var kbits = bits / (1024); <ide> <ide> var privateKey = RSA_PrivatePem[keylen]; <del> var publicKey = RSA_PublicPem[keylen]; <ide> var s = crypto.createSign(algo); <ide> var v = crypto.createVerify(algo); <ide> <ide> function StreamWrite(algo, keylen, message, writes, len) { <ide> v.update(message); <ide> } <ide> <del> var sign = s.sign(privateKey, 'binary'); <add> s.sign(privateKey, 'binary'); <ide> s.end(); <ide> v.end(); <ide> <ide><path>benchmark/dgram/array-vs-concat.js <ide> var num; <ide> var type; <ide> var chunk; <ide> var chunks; <del>var encoding; <ide> <ide> function main(conf) { <ide> dur = +conf.dur; <ide> function main(conf) { <ide> type = conf.type; <ide> chunks = +conf.chunks; <ide> <del> chunk = [] <add> chunk = []; <ide> for (var i = 0; i < chunks; i++) { <ide> chunk.push(new Buffer(Math.round(len / chunks))); <ide> } <ide><path>benchmark/dgram/multi-buffer.js <ide> var num; <ide> var type; <ide> var chunk; <ide> var chunks; <del>var encoding; <ide> <ide> function main(conf) { <ide> dur = +conf.dur; <ide> function main(conf) { <ide> type = conf.type; <ide> chunks = +conf.chunks; <ide> <del> chunk = [] <add> chunk = []; <ide> for (var i = 0; i < chunks; i++) { <ide> chunk.push(new Buffer(Math.round(len / chunks))); <ide> } <ide><path>benchmark/dgram/offset-length.js <ide> var len; <ide> var num; <ide> var type; <ide> var chunk; <del>var encoding; <ide> <ide> function main(conf) { <ide> dur = +conf.dur; <ide><path>benchmark/dgram/single-buffer.js <ide> var len; <ide> var num; <ide> var type; <ide> var chunk; <del>var encoding; <ide> <ide> function main(conf) { <ide> dur = +conf.dur; <ide><path>benchmark/domain/domain-fn-args.js <ide> var gargs = [1, 2, 3]; <ide> <ide> function main(conf) { <ide> <del> var args, ret, n = +conf.n; <add> var args, n = +conf.n; <ide> var myArguments = gargs.slice(0, conf.arguments); <ide> bench.start(); <ide> <ide> function fn(a, b, c) { <ide> c = 3; <ide> <ide> return a + b + c; <del>} <ide>\ No newline at end of file <add>} <ide><path>benchmark/events/ee-emit-multi-args.js <ide> function main(conf) { <ide> var n = conf.n | 0; <ide> <ide> var ee = new EventEmitter(); <del> var listeners = []; <ide> <ide> for (var k = 0; k < 10; k += 1) <ide> ee.on('dummy', function() {}); <ide><path>benchmark/events/ee-listener-count-on-prototype.js <ide> function main(conf) { <ide> <ide> bench.start(); <ide> for (var i = 0; i < n; i += 1) { <del> var r = ee.listenerCount('dummy'); <add> ee.listenerCount('dummy'); <ide> } <ide> bench.end(n); <ide> } <ide><path>benchmark/events/ee-listeners-many.js <ide> function main(conf) { <ide> <ide> bench.start(); <ide> for (var i = 0; i < n; i += 1) { <del> var r = ee.listeners('dummy'); <add> ee.listeners('dummy'); <ide> } <ide> bench.end(n); <ide> } <ide><path>benchmark/events/ee-listeners.js <ide> function main(conf) { <ide> <ide> bench.start(); <ide> for (var i = 0; i < n; i += 1) { <del> var r = ee.listeners('dummy'); <add> ee.listeners('dummy'); <ide> } <ide> bench.end(n); <ide> } <ide><path>benchmark/fs-write-stream-throughput.js <ide> function runTest(dur, size, type) { <ide> break; <ide> } <ide> <del> var writes = 0; <ide> var fs = require('fs'); <ide> try { fs.unlinkSync('write_stream_throughput'); } catch (e) {} <ide> <del> var start <add> var start; <ide> var end; <ide> function done() { <del> var time = end[0] + end[1]/1E9; <add> var time = end[0] + end[1] / 1E9; <ide> var written = fs.statSync('write_stream_throughput').size / 1024; <ide> var rate = (written / time).toFixed(2); <ide> console.log('fs_write_stream_dur_%d_size_%d_type_%s: %d', <ide><path>benchmark/fs/read-stream-throughput.js <ide> var type, encoding, size; <ide> <ide> var bench = common.createBenchmark(main, { <ide> type: ['buf', 'asc', 'utf'], <del> size: [1024, 4096, 65535, 1024*1024] <add> size: [1024, 4096, 65535, 1024 * 1024] <ide> }); <ide> <ide> function main(conf) { <ide><path>benchmark/fs/write-stream-throughput.js <ide> function main(conf) { <ide> encoding = 'ascii'; <ide> break; <ide> case 'utf': <del> chunk = new Array(Math.ceil(size/2) + 1).join('ü'); <add> chunk = new Array(Math.ceil(size / 2) + 1).join('ü'); <ide> encoding = 'utf8'; <ide> break; <ide> default: <ide><path>benchmark/http/_chunky_http_client.js <ide> var bench = common.createBenchmark(main, { <ide> function main(conf) { <ide> var len = +conf.len; <ide> var num = +conf.num; <del> var type = conf.type; <ide> var todo = []; <ide> var headers = []; <ide> // Chose 7 because 9 showed "Connection error" / "Connection closed" <ide> function main(conf) { <ide> headers.push(Array(i + 1).join('o')); <ide> <ide> function WriteHTTPHeaders(channel, has_keep_alive, extra_header_count) { <del> todo = [] <add> todo = []; <ide> todo.push('GET / HTTP/1.1'); <ide> todo.push('Host: localhost'); <ide> todo.push('Connection: keep-alive'); <ide> function main(conf) { <ide> var socket = net.connect(PIPE, function() { <ide> bench.start(); <ide> WriteHTTPHeaders(socket, 1, len); <del> socket.setEncoding('utf8') <add> socket.setEncoding('utf8'); <ide> socket.on('data', function(d) { <ide> var did = false; <ide> var pattern = 'HTTP/1.1 200 OK\r\n'; <ide> function main(conf) { <ide> success += 1; <ide> did = true; <ide> } else { <del> pattern = 'HTTP/1.1 ' <add> pattern = 'HTTP/1.1 '; <ide> if ((d.length === pattern.length && d === pattern) || <ide> (d.length > pattern.length && <ide> d.slice(0, pattern.length) === pattern)) { <ide><path>benchmark/http/chunked.js <ide> 'use strict'; <ide> <ide> var common = require('../common.js'); <del>var PORT = common.PORT; <ide> <ide> var bench = common.createBenchmark(main, { <ide> num: [1, 4, 8, 16], <ide><path>benchmark/http/end-vs-write-end.js <ide> 'use strict'; <ide> <ide> var common = require('../common.js'); <del>var PORT = common.PORT; <ide> <ide> var bench = common.createBenchmark(main, { <ide> type: ['asc', 'utf', 'buf'], <ide><path>benchmark/http/http_server_for_chunky_client.js <ide> var path = require('path'); <ide> var http = require('http'); <ide> var fs = require('fs'); <ide> var spawn = require('child_process').spawn; <del>var common = require('../common.js') <del>var test = require('../../test/common.js') <add>require('../common.js'); <add>var test = require('../../test/common.js'); <ide> var pep = path.dirname(process.argv[1]) + '/_chunky_http_client.js'; <ide> var PIPE = test.PIPE; <ide> <ide> try { <ide> child = spawn(process.execPath, [pep], { }); <ide> <ide> child.on('error', function(err) { <del> throw new Error('spawn error: ' + err ); <add> throw new Error('spawn error: ' + err); <ide> }); <ide> <ide> child.stdout.pipe(process.stdout); <ide> child.stderr.pipe(process.stderr); <ide> <del> child.on('close', function (exitCode) { <add> child.on('close', function(exitCode) { <ide> server.close(); <ide> }); <ide> <del>} catch(e) { <del> throw new Error('error: ' + e ); <add>} catch (e) { <add> throw new Error('error: ' + e); <ide> } <ide> <ide><path>benchmark/http/simple.js <ide> var bench = common.createBenchmark(main, { <ide> <ide> function main(conf) { <ide> process.env.PORT = PORT; <del> var spawn = require('child_process').spawn; <ide> var server = require('../http_simple.js'); <ide> setTimeout(function() { <ide> var path = '/' + conf.type + '/' + conf.length + '/' + conf.chunks; <ide><path>benchmark/http_bench.js <ide> for (var i = 2; i < process.argv.length; ++i) { <ide> } <ide> <ide> switch (options.mode) { <del>case 'master': startMaster(); break; <del>case 'server': startServer(); break; <del>case 'client': startClient(); break; <del>default: throw new Error('Bad mode: ' + options.mode); <add> case 'master': startMaster(); break; <add> case 'server': startServer(); break; <add> case 'client': startClient(); break; <add> default: throw new Error('Bad mode: ' + options.mode); <ide> } <ide> <ide> process.title = 'http_bench[' + options.mode + ']'; <ide> function startMaster() { <ide> <ide> var forkCount = 0; <ide> <del> cluster.on('online', function () { <add> cluster.on('online', function() { <ide> forkCount = forkCount + 1; <ide> if (forkCount === ~~options.servers) { <ide> var args = [ <ide><path>benchmark/http_server_lag.js <ide> http.createServer(function(req, res) { <ide> res.writeHead(200, { 'content-type': 'text/plain', <ide> 'content-length': '2' }); <ide> <del> var lag = parseInt(req.url.split("/").pop(), 10) || defaultLag; <add> var lag = parseInt(req.url.split('/').pop(), 10) || defaultLag; <ide> setTimeout(function() { <ide> res.end('ok'); <ide> }, lag); <ide><path>benchmark/http_simple.js <ide> 'use strict'; <ide> <del>var path = require('path'), <del> exec = require('child_process').exec, <del> http = require('http'); <add>var http = require('http'); <ide> <ide> var port = parseInt(process.env.PORT || 8000); <ide> <ide> var fixed = makeString(20 * 1024, 'C'), <del> storedBytes = {}, <del> storedBuffer = {}, <del> storedUnicode = {}; <add> storedBytes = {}, <add> storedBuffer = {}, <add> storedUnicode = {}; <ide> <ide> var useDomains = process.env.NODE_USE_DOMAINS; <ide> <ide> if (useDomains) { <ide> gdom.enter(); <ide> } <ide> <del>var server = module.exports = http.createServer(function (req, res) { <add>var server = module.exports = http.createServer(function(req, res) { <ide> if (useDomains) { <ide> var dom = domain.create(); <ide> dom.add(req); <ide> var server = module.exports = http.createServer(function (req, res) { <ide> if (command == 'bytes') { <ide> var n = ~~arg; <ide> if (n <= 0) <del> throw new Error('bytes called with n <= 0') <add> throw new Error('bytes called with n <= 0'); <ide> if (storedBytes[n] === undefined) { <ide> storedBytes[n] = makeString(n, 'C'); <ide> } <ide> function makeString(size, c) { <ide> return s; <ide> } <ide> <del>server.listen(port, function () { <add>server.listen(port, function() { <ide> if (module === require.main) <del> console.error('Listening at http://127.0.0.1:'+port+'/'); <add> console.error('Listening at http://127.0.0.1:' + port + '/'); <ide> }); <ide><path>benchmark/http_simple_auto.js <ide> // <ide> 'use strict'; <ide> <del>var path = require("path"); <del>var http = require("http"); <del>var spawn = require("child_process").spawn; <add>var http = require('http'); <add>var spawn = require('child_process').spawn; <ide> <ide> var port = parseInt(process.env.PORT || 8000); <ide> <del>var fixed = "" <del>for (var i = 0; i < 20*1024; i++) { <del> fixed += "C"; <add>var fixed = ''; <add>for (var i = 0; i < 20 * 1024; i++) { <add> fixed += 'C'; <ide> } <ide> <ide> var stored = {}; <ide> var storedBuffer = {}; <ide> <del>var server = http.createServer(function (req, res) { <del> var commands = req.url.split("/"); <add>var server = http.createServer(function(req, res) { <add> var commands = req.url.split('/'); <ide> var command = commands[1]; <del> var body = ""; <add> var body = ''; <ide> var arg = commands[2]; <ide> var n_chunks = parseInt(commands[3], 10); <ide> var status = 200; <ide> <del> if (command == "bytes") { <del> var n = parseInt(arg, 10) <add> if (command == 'bytes') { <add> var n = parseInt(arg, 10); <ide> if (n <= 0) <del> throw "bytes called with n <= 0" <add> throw new Error('bytes called with n <= 0'); <ide> if (stored[n] === undefined) { <del> stored[n] = ""; <add> stored[n] = ''; <ide> for (var i = 0; i < n; i++) { <del> stored[n] += "C" <add> stored[n] += 'C'; <ide> } <ide> } <ide> body = stored[n]; <ide> <del> } else if (command == "buffer") { <del> var n = parseInt(arg, 10) <del> if (n <= 0) throw new Error("bytes called with n <= 0"); <add> } else if (command == 'buffer') { <add> var n = parseInt(arg, 10); <add> if (n <= 0) throw new Error('bytes called with n <= 0'); <ide> if (storedBuffer[n] === undefined) { <ide> storedBuffer[n] = new Buffer(n); <ide> for (var i = 0; i < n; i++) { <del> storedBuffer[n][i] = "C".charCodeAt(0); <add> storedBuffer[n][i] = 'C'.charCodeAt(0); <ide> } <ide> } <ide> body = storedBuffer[n]; <ide> <del> } else if (command == "quit") { <add> } else if (command == 'quit') { <ide> res.connection.server.close(); <del> body = "quitting"; <add> body = 'quitting'; <ide> <del> } else if (command == "fixed") { <add> } else if (command == 'fixed') { <ide> body = fixed; <ide> <del> } else if (command == "echo") { <del> res.writeHead(200, { "Content-Type": "text/plain", <del> "Transfer-Encoding": "chunked" }); <add> } else if (command == 'echo') { <add> res.writeHead(200, { 'Content-Type': 'text/plain', <add> 'Transfer-Encoding': 'chunked' }); <ide> req.pipe(res); <ide> return; <ide> <ide> } else { <ide> status = 404; <del> body = "not found\n"; <add> body = 'not found\n'; <ide> } <ide> <ide> // example: http://localhost:port/bytes/512/4 <ide> // sends a 512 byte body in 4 chunks of 128 bytes <ide> if (n_chunks > 0) { <del> res.writeHead(status, { "Content-Type": "text/plain", <del> "Transfer-Encoding": "chunked" }); <add> res.writeHead(status, { 'Content-Type': 'text/plain', <add> 'Transfer-Encoding': 'chunked' }); <ide> // send body in chunks <ide> var len = body.length; <ide> var step = Math.floor(len / n_chunks) || 1; <ide> var server = http.createServer(function (req, res) { <ide> } else { <ide> var content_length = body.length.toString(); <ide> <del> res.writeHead(status, { "Content-Type": "text/plain", <del> "Content-Length": content_length }); <add> res.writeHead(status, { 'Content-Type': 'text/plain', <add> 'Content-Length': content_length }); <ide> res.end(body); <ide> } <ide> <ide> }); <ide> <del>server.listen(port, function () { <add>server.listen(port, function() { <ide> var url = 'http://127.0.0.1:' + port + '/'; <ide> <ide> var n = process.argv.length - 1; <ide><path>benchmark/idle_clients.js <ide> const net = require('net'); <ide> <ide> var errors = 0, connections = 0; <ide> <del>var lastClose = 0; <del> <del>function connect () { <del> process.nextTick(function () { <add>function connect() { <add> process.nextTick(function() { <ide> var s = net.Stream(); <ide> var gotConnected = false; <ide> s.connect(9000); <ide> <del> s.on('connect', function () { <add> s.on('connect', function() { <ide> gotConnected = true; <ide> connections++; <ide> connect(); <ide> }); <ide> <del> s.on('close', function () { <add> s.on('close', function() { <ide> if (gotConnected) connections--; <ide> lastClose = new Date(); <ide> }); <ide> <del> s.on('error', function () { <add> s.on('error', function() { <ide> errors++; <ide> }); <ide> }); <ide> var oldConnections, oldErrors; <ide> // Try to start new connections every so often <ide> setInterval(connect, 5000); <ide> <del>setInterval(function () { <add>setInterval(function() { <ide> if (oldConnections != connections) { <ide> oldConnections = connections; <del> console.log("CLIENT %d connections: %d", process.pid, connections); <add> console.log('CLIENT %d connections: %d', process.pid, connections); <ide> } <ide> <ide> if (oldErrors != errors) { <ide> oldErrors = errors; <del> console.log("CLIENT %d errors: %d", process.pid, errors); <add> console.log('CLIENT %d errors: %d', process.pid, errors); <ide> } <ide> }, 1000); <ide> <ide><path>benchmark/idle_server.js <ide> 'use strict'; <ide> <ide> const net = require('net'); <del>var connections = 0; <ide> var errors = 0; <ide> <del>var server = net.Server(function (socket) { <add>var server = net.Server(function(socket) { <ide> <del> socket.on('error', function () { <add> socket.on('error', function() { <ide> errors++; <ide> }); <ide> <ide> server.listen(9000); <ide> <ide> var oldConnections, oldErrors; <ide> <del>setInterval(function () { <add>setInterval(function() { <ide> if (oldConnections != server.connections) { <ide> oldConnections = server.connections; <del> console.log("SERVER %d connections: %d", process.pid, server.connections); <add> console.log('SERVER %d connections: %d', process.pid, server.connections); <ide> } <ide> <ide> if (oldErrors != errors) { <ide> oldErrors = errors; <del> console.log("SERVER %d errors: %d", process.pid, errors); <add> console.log('SERVER %d errors: %d', process.pid, errors); <ide> } <ide> }, 1000); <ide><path>benchmark/misc/function_call/index.js <ide> assert(js() === cxx()); <ide> <ide> var bench = common.createBenchmark(main, { <ide> type: ['js', 'cxx'], <del> millions: [1,10,50] <add> millions: [1, 10, 50] <ide> }); <ide> <ide> function main(conf) { <ide><path>benchmark/misc/startup.js <ide> var common = require('../common.js'); <ide> var spawn = require('child_process').spawn; <ide> var path = require('path'); <ide> var emptyJsFile = path.resolve(__dirname, '../../test/fixtures/semicolon.js'); <del>var starts = 100; <del>var i = 0; <del>var start; <ide> <ide> var bench = common.createBenchmark(startNode, { <ide> dur: [1] <ide> function startNode(conf) { <ide> var dur = +conf.dur; <ide> var go = true; <ide> var starts = 0; <del> var open = 0; <ide> <ide> setTimeout(function() { <ide> go = false; <ide><path>benchmark/misc/string-creation.js <ide> var common = require('../common.js'); <ide> var bench = common.createBenchmark(main, { <ide> millions: [100] <del>}) <add>}); <ide> <ide> function main(conf) { <ide> var n = +conf.millions * 1e6; <ide> bench.start(); <ide> var s; <ide> for (var i = 0; i < n; i++) { <ide> s = '01234567890'; <del> s[1] = "a"; <add> s[1] = 'a'; <ide> } <ide> bench.end(n / 1e6); <ide> } <ide><path>benchmark/module/module-loader.js <ide> var fs = require('fs'); <ide> var path = require('path'); <ide> var common = require('../common.js'); <del>var packageJson = '{"main": "index.js"}'; <ide> <ide> var tmpDirectory = path.join(__dirname, '..', 'tmp'); <ide> var benchmarkDirectory = path.join(tmpDirectory, 'nodejs-benchmark-module'); <ide> function rmrf(location) { <ide> var things = fs.readdirSync(location); <ide> things.forEach(function(thing) { <ide> var cur = path.join(location, thing), <del> isDirectory = fs.statSync(cur).isDirectory(); <add> isDirectory = fs.statSync(cur).isDirectory(); <ide> if (isDirectory) { <ide> rmrf(cur); <ide> return; <ide><path>benchmark/net/net-c2s-cork.js <ide> function main(conf) { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> server(); <ide> function server() { <ide> socket.on('connect', function() { <ide> bench.start(); <ide> <del> socket.on('drain', send) <del> send() <add> socket.on('drain', send); <add> send(); <ide> <ide> setTimeout(function() { <ide> var bytes = writer.received; <ide> function server() { <ide> <ide> function send() { <ide> socket.cork(); <del> while(socket.write(chunk, encoding)) {} <add> while (socket.write(chunk, encoding)) {} <ide> socket.uncork(); <ide> } <ide> }); <ide><path>benchmark/net/net-c2s.js <ide> function main(conf) { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> server(); <ide><path>benchmark/net/net-pipe.js <ide> function main(conf) { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> server(); <ide><path>benchmark/net/net-s2c.js <ide> function main(conf) { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> server(); <ide><path>benchmark/net/tcp-raw-c2s.js <ide> function client() { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> var clientHandle = new TCP(); <ide><path>benchmark/net/tcp-raw-pipe.js <ide> function client() { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> var clientHandle = new TCP(); <ide><path>benchmark/net/tcp-raw-s2c.js <ide> function server() { <ide> break; <ide> default: <ide> throw new Error('invalid type: ' + type); <del> break; <ide> } <ide> <ide> clientHandle.readStart(); <ide><path>benchmark/path/basename-win32.js <ide> var bench = common.createBenchmark(main, { <ide> 'C:\\', <ide> 'C:\\foo', <ide> 'D:\\foo\\.bar.baz', <del> ['E:\\foo\\.bar.baz','.baz'].join('|'), <add> ['E:\\foo\\.bar.baz', '.baz'].join('|'), <ide> 'foo', <ide> 'foo\\bar.', <ide> ['foo\\bar.', '.'].join('|'), <ide><path>benchmark/static_http_server.js <ide> var http = require('http'); <ide> var concurrency = 30; <ide> var port = 12346; <ide> var n = 700; <del>var bytes = 1024*5; <add>var bytes = 1024 * 5; <ide> <ide> var requests = 0; <ide> var responses = 0; <ide> var server = http.createServer(function(req, res) { <ide> 'Content-Length': body.length <ide> }); <ide> res.end(body); <del>}) <add>}); <ide> <ide> server.listen(port, function() { <ide> var agent = new http.Agent(); <ide><path>benchmark/tls/throughput.js <ide> function main(conf) { <ide> encoding = 'ascii'; <ide> break; <ide> case 'utf': <del> chunk = new Array(size/2 + 1).join('ü'); <add> chunk = new Array(size / 2 + 1).join('ü'); <ide> encoding = 'utf8'; <ide> break; <ide> default: <ide> function main(conf) { <ide> }); <ide> <ide> function write() { <del> var i = 0; <ide> while (false !== conn.write(chunk, encoding)); <ide> } <ide> }); <ide><path>benchmark/tls/tls-connect.js <ide> 'use strict'; <del>var assert = require('assert'), <del> fs = require('fs'), <del> path = require('path'), <del> tls = require('tls'); <add>var fs = require('fs'), <add> path = require('path'), <add> tls = require('tls'); <ide> <ide> var common = require('../common.js'); <ide> var bench = common.createBenchmark(main, { <ide> function main(conf) { <ide> concurrency = +conf.concurrency; <ide> <ide> var cert_dir = path.resolve(__dirname, '../../test/fixtures'), <del> options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), <del> cert: fs.readFileSync(cert_dir + '/test_cert.pem'), <del> ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ], <del> ciphers: 'AES256-GCM-SHA384' }; <add> options = { key: fs.readFileSync(cert_dir + '/test_key.pem'), <add> cert: fs.readFileSync(cert_dir + '/test_cert.pem'), <add> ca: [ fs.readFileSync(cert_dir + '/test_ca.pem') ], <add> ciphers: 'AES256-GCM-SHA384' }; <ide> <ide> server = tls.createServer(options, onConnection); <ide> server.listen(common.PORT, onListening); <ide><path>benchmark/util/inspect.js <ide> function main(conf) { <ide> <ide> bench.start(); <ide> for (var i = 0; i < n; i += 1) { <del> var r = util.inspect({a: 'a', b: 'b', c: 'c', d: 'd'}); <add> util.inspect({a: 'a', b: 'b', c: 'c', d: 'd'}); <ide> } <ide> bench.end(n); <ide> }
49
Text
Text
remove docs for legacy_connection_handling
0348b219cfc0fb0b5c7f9f35b4319d2d9a50497e
<ide><path>guides/source/configuring.md <ide> Below are the default values associated with each target version. In cases of co <ide> #### Default Values for Target Version 6.1 <ide> <ide> - [`config.active_record.has_many_inversing`](#config-active-record-has-many-inversing): `true` <del>- [`config.active_record.legacy_connection_handling`](#config-active-record-legacy-connection-handling): `false` <ide> - [`config.active_storage.track_variants`](#config-active-storage-track-variants): `true` <ide> - [`config.active_storage.queues.analysis`](#config-active-storage-queues-analysis): `nil` <ide> - [`config.active_storage.queues.purge`](#config-active-storage-queues-purge): `nil` <ide> The default value depends on the `config.load_defaults` target version: <ide> | (original) | `false` | <ide> | 7.0 | `true` | <ide> <del>#### `config.active_record.legacy_connection_handling` <del> <del>Allows to enable new connection handling API. For applications using multiple <del>databases, this new API provides support for granular connection swapping. <del> <del>The default value depends on the `config.load_defaults` target version: <del> <del>| Starting with version | The default value is | <del>| --------------------- | -------------------- | <del>| (original) | `true` | <del>| 6.1 | `false` | <del> <ide> #### `config.active_record.destroy_association_async_job` <ide> <ide> Allows specifying the job that will be used to destroy the associated records in background. It defaults to `ActiveRecord::DestroyAssociationAsyncJob`.
1
Javascript
Javascript
fix regression in challenge map migration
bbc76b1b73148cac7598894075ff4877dd8097c5
<ide><path>server/middlewares/migrate-completed-challenges.js <ide> export default function migrateCompletedChallenges() { <ide> if (!user || user.isChallengeMapMigrated) { <ide> return next(); <ide> } <del> return buildChallengeMap( <del> user.id.toString(), <del> user.completedChallenges, <del> User <del> ) <add> const id = user.id.toString(); <add> return User.findOne$({ <add> where: { id }, <add> fields: { completedChallenges: true } <add> }) <add> .map(({ completedChallenges = [] } = {}) => completedChallenges) <add> .flatMap(completedChallenges => { <add> return buildChallengeMap( <add> id, <add> completedChallenges, <add> User <add> ); <add> }) <ide> .subscribe( <ide> count => log('documents update', count), <ide> // errors go here
1
Javascript
Javascript
use async rimraf
5bcafa64e24dae4a7b052bf1bf10524f6ac8e3dd
<ide><path>test/ChangesAndRemovals.test.js <ide> const onceDone = (compiler, action) => { <ide> }); <ide> }; <ide> <del>function cleanup() { <del> rimraf.sync(tempFolderPath); <add>function cleanup(callback) { <add> rimraf(tempFolderPath, callback); <ide> } <ide> <ide> function createFiles() { <ide> describe("ChangesAndRemovals", () => { <ide> <ide> jest.setTimeout(10000); <ide> <del> beforeEach(() => { <del> cleanup(); <del> createFiles(); <del> }); <del> afterEach(() => { <del> cleanup(); <add> beforeEach(done => { <add> cleanup(err => { <add> if (err) return done(err); <add> createFiles(); <add> done(); <add> }); <ide> }); <add> afterEach(cleanup); <ide> <ide> it("should track modified files when they've been modified in watchRun", done => { <ide> const compiler = createSingleCompiler();
1
Javascript
Javascript
use standard args order in incomingmessage onerror
a6bf74eac00516fd0767b585c8f304857dddd2aa
<ide><path>lib/_http_incoming.js <ide> IncomingMessage.prototype._destroy = function _destroy(err, cb) { <ide> this.emit('aborted'); <ide> } <ide> <del> // If aborted and the underlying socket not already destroyed, <add> // If aborted and the underlying socket is not already destroyed, <ide> // destroy it. <ide> // We have to check if the socket is already destroyed because finished <ide> // does not call the callback when this methdod is invoked from `_http_client` <ide> IncomingMessage.prototype._destroy = function _destroy(err, cb) { <ide> this.socket.destroy(err); <ide> const cleanup = finished(this.socket, (e) => { <ide> cleanup(); <del> onError(this, cb, e || err); <add> onError(this, e || err, cb); <ide> }); <ide> } else { <del> onError(this, cb, err); <add> onError(this, err, cb); <ide> } <ide> }; <ide> <ide> IncomingMessage.prototype._dump = function _dump() { <ide> } <ide> }; <ide> <del>function onError(instance, cb, error) { <add>function onError(instance, error, cb) { <ide> // This is to keep backward compatible behavior. <ide> // An error is emitted only if there are listeners attached to <ide> // the event.
1
Ruby
Ruby
ignore test files in test/vendor/bundle
0a7307de6412ddc566cdcb5ab343a9bb16bb2b88
<ide><path>Library/Homebrew/dev-cmd/tests.rb <ide> def tests <ide> <ide> files = Dir.glob("test/**/*_test.rb") <ide> .reject { |p| !OS.mac? && p.start_with?("test/os/mac/") } <add> .reject { |p| p.start_with?("test/vendor/bundle/") } <ide> <ide> opts = [] <ide> opts << "--serialize-stdout" if ENV["CI"]
1
Ruby
Ruby
replace #flatten with array()
7c1af53b1cddc35de5a2e0788d7a2073365458f3
<ide><path>railties/lib/rails/paths.rb <ide> def []=(path, value) <ide> end <ide> <ide> def add(path, options={}) <del> with = options[:with] || path <del> @root[path] = Path.new(self, path, [with].flatten, options) <add> with = Array(options[:with] || path) <add> @root[path] = Path.new(self, path, with, options) <ide> end <ide> <ide> def [](path)
1
Javascript
Javascript
add `rooteventtypes` support to event responders
017d6f14b75d4e05a438e34fe0967d730ce24185
<ide><path>packages/react-dom/src/client/ReactDOMComponent.js <ide> export function listenToEventResponderEventTypes( <ide> if (__DEV__) { <ide> warning( <ide> typeof targetEventType === 'object' && targetEventType !== null, <del> 'Event Responder: invalid entry in targetEventTypes array. ' + <add> 'Event Responder: invalid entry in event types array. ' + <ide> 'Entry must be string or an object. Instead, got %s.', <ide> targetEventType, <ide> ); <ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js <ide> import { <ide> setEnabled as ReactBrowserEventEmitterSetEnabled, <ide> } from '../events/ReactBrowserEventEmitter'; <ide> import {Namespaces, getChildNamespace} from '../shared/DOMNamespaces'; <add>import {addRootEventTypesForComponentInstance} from '../events/DOMEventResponderSystem'; <ide> import { <ide> ELEMENT_NODE, <ide> TEXT_NODE, <ide> export function updateEventComponent( <ide> if (enableEventAPI) { <ide> const rootContainerInstance = ((eventComponentInstance.rootInstance: any): Container); <ide> const rootElement = rootContainerInstance.ownerDocument; <del> listenToEventResponderEventTypes( <del> eventComponentInstance.responder.targetEventTypes, <del> rootElement, <del> ); <add> const responder = eventComponentInstance.responder; <add> const {rootEventTypes, targetEventTypes} = responder; <add> if (targetEventTypes !== undefined) { <add> listenToEventResponderEventTypes(targetEventTypes, rootElement); <add> } <add> if (rootEventTypes !== undefined) { <add> addRootEventTypesForComponentInstance( <add> eventComponentInstance, <add> rootEventTypes, <add> ); <add> listenToEventResponderEventTypes(rootEventTypes, rootElement); <add> } <ide> } <ide> } <ide> <ide><path>packages/react-dom/src/events/DOMEventResponderSystem.js <ide> const eventResponderContext: ReactResponderContext = { <ide> rootEventComponentInstances, <ide> ); <ide> } <del> rootEventComponentInstances.add( <del> ((currentInstance: any): ReactEventComponentInstance), <add> const componentInstance = ((currentInstance: any): ReactEventComponentInstance); <add> let rootEventTypesSet = componentInstance.rootEventTypes; <add> if (rootEventTypesSet === null) { <add> rootEventTypesSet = componentInstance.rootEventTypes = new Set(); <add> } <add> invariant( <add> !rootEventTypesSet.has(topLevelEventType), <add> 'addRootEventTypes() found a duplicate root event ' + <add> 'type of "%s". This might be because the event type exists in the event responder "rootEventTypes" ' + <add> 'array or because of a previous addRootEventTypes() using this root event type.', <add> rootEventType, <ide> ); <add> rootEventTypesSet.add(topLevelEventType); <add> rootEventComponentInstances.add(componentInstance); <ide> } <ide> }, <ide> removeRootEventTypes( <ide> const eventResponderContext: ReactResponderContext = { <ide> let rootEventComponents = rootEventTypesToEventComponentInstances.get( <ide> topLevelEventType, <ide> ); <add> let rootEventTypesSet = ((currentInstance: any): ReactEventComponentInstance) <add> .rootEventTypes; <add> if (rootEventTypesSet !== null) { <add> rootEventTypesSet.delete(topLevelEventType); <add> } <ide> if (rootEventComponents !== undefined) { <ide> rootEventComponents.delete( <ide> ((currentInstance: any): ReactEventComponentInstance), <ide> export function unmountEventResponder( <ide> if (responder.onOwnershipChange !== undefined) { <ide> ownershipChangeListeners.delete(eventComponentInstance); <ide> } <add> const rootEventTypesSet = eventComponentInstance.rootEventTypes; <add> if (rootEventTypesSet !== null) { <add> const rootEventTypes = Array.from(rootEventTypesSet); <add> <add> for (let i = 0; i < rootEventTypes.length; i++) { <add> const topLevelEventType = rootEventTypes[i]; <add> let rootEventComponentInstances = rootEventTypesToEventComponentInstances.get( <add> topLevelEventType, <add> ); <add> if (rootEventComponentInstances !== undefined) { <add> rootEventComponentInstances.delete(eventComponentInstance); <add> } <add> } <add> } <ide> } <ide> <ide> function validateResponderContext(): void { <ide> export function dispatchEventForResponderEventSystem( <ide> } <ide> } <ide> } <add> <add>export function addRootEventTypesForComponentInstance( <add> eventComponentInstance: ReactEventComponentInstance, <add> rootEventTypes: Array<ReactEventResponderEventType>, <add>): void { <add> for (let i = 0; i < rootEventTypes.length; i++) { <add> const rootEventType = rootEventTypes[i]; <add> const topLevelEventType = <add> typeof rootEventType === 'string' ? rootEventType : rootEventType.name; <add> let rootEventComponentInstances = rootEventTypesToEventComponentInstances.get( <add> topLevelEventType, <add> ); <add> if (rootEventComponentInstances === undefined) { <add> rootEventComponentInstances = new Set(); <add> rootEventTypesToEventComponentInstances.set( <add> topLevelEventType, <add> rootEventComponentInstances, <add> ); <add> } <add> let rootEventTypesSet = eventComponentInstance.rootEventTypes; <add> if (rootEventTypesSet === null) { <add> rootEventTypesSet = eventComponentInstance.rootEventTypes = new Set(); <add> } <add> rootEventTypesSet.add(topLevelEventType); <add> rootEventComponentInstances.add( <add> ((eventComponentInstance: any): ReactEventComponentInstance), <add> ); <add> } <add>} <ide><path>packages/react-dom/src/events/__tests__/DOMEventResponderSystem-test.internal.js <ide> let ReactSymbols; <ide> <ide> function createReactEventComponent( <ide> targetEventTypes, <add> rootEventTypes, <ide> createInitialState, <ide> onEvent, <ide> onEventCapture, <ide> function createReactEventComponent( <ide> ) { <ide> const testEventResponder = { <ide> targetEventTypes, <add> rootEventTypes, <ide> createInitialState, <ide> onEvent, <ide> onEventCapture, <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventResponderFiredCount++; <ide> eventLog.push({ <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventLog.push({ <ide> name: event.type, <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventResponderFiredCount++; <ide> eventLog.push({ <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponentA = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventLog.push(`A [bubble]`); <ide> }, <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponentB = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventLog.push(`B [bubble]`); <ide> }, <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventLog.push(`${props.name} [bubble]`); <ide> }, <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> eventLog.push(`${props.name} [bubble]`); <ide> }, <ide> describe('DOMEventResponderSystem', () => { <ide> const ClickEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> if (props.onMagicClick) { <ide> const syntheticEvent = { <ide> describe('DOMEventResponderSystem', () => { <ide> const LongPressEventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props) => { <ide> handleEvent(event, context, props, 'bubble'); <ide> }, <ide> describe('DOMEventResponderSystem', () => { <ide> undefined, <ide> undefined, <ide> undefined, <add> undefined, <ide> (event, context, props, state) => {}, <ide> () => { <ide> onUnmountFired++; <ide> describe('DOMEventResponderSystem', () => { <ide> <ide> const EventComponent = createReactEventComponent( <ide> [], <add> undefined, <ide> () => ({ <ide> incrementAmount: 5, <ide> }), <ide> describe('DOMEventResponderSystem', () => { <ide> const EventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props, state) => { <ide> ownershipGained = context.requestOwnership(); <ide> }, <ide> describe('DOMEventResponderSystem', () => { <ide> const EventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props, state) => { <ide> queryResult = Array.from( <ide> context.getEventTargetsFromTarget(event.target), <ide> describe('DOMEventResponderSystem', () => { <ide> const EventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props, state) => { <ide> queryResult = context.getEventTargetsFromTarget( <ide> event.target, <ide> describe('DOMEventResponderSystem', () => { <ide> const EventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props, state) => { <ide> queryResult = context.getEventTargetsFromTarget( <ide> event.target, <ide> describe('DOMEventResponderSystem', () => { <ide> const EventComponent = createReactEventComponent( <ide> ['click'], <ide> undefined, <add> undefined, <ide> (event, context, props, state) => { <ide> queryResult = context.getEventTargetsFromTarget( <ide> event.target, <ide> describe('DOMEventResponderSystem', () => { <ide> ]); <ide> expect(queryResult3).toEqual([]); <ide> }); <add> <add> it('the event responder root listeners should fire on a root click event', () => { <add> let eventResponderFiredCount = 0; <add> let eventLog = []; <add> <add> const ClickEventComponent = createReactEventComponent( <add> undefined, <add> ['click'], <add> undefined, <add> undefined, <add> undefined, <add> event => { <add> eventResponderFiredCount++; <add> eventLog.push({ <add> name: event.type, <add> passive: event.passive, <add> passiveSupported: event.passiveSupported, <add> phase: 'root', <add> }); <add> }, <add> ); <add> <add> const Test = () => ( <add> <ClickEventComponent> <add> <button>Click me!</button> <add> </ClickEventComponent> <add> ); <add> <add> ReactDOM.render(<Test />, container); <add> expect(container.innerHTML).toBe('<button>Click me!</button>'); <add> <add> // Clicking the button should trigger the event responder onEvent() twice <add> dispatchClickEvent(document.body); <add> expect(eventResponderFiredCount).toBe(1); <add> expect(eventLog.length).toBe(1); <add> expect(eventLog).toEqual([ <add> { <add> name: 'click', <add> passive: false, <add> passiveSupported: false, <add> phase: 'root', <add> }, <add> ]); <add> }); <ide> }); <ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.js <ide> function completeWork( <ide> context: null, <ide> props: newProps, <ide> responder, <add> rootEventTypes: null, <ide> rootInstance: rootContainerInstance, <ide> state: responderState, <ide> }; <ide><path>packages/shared/ReactTypes.js <ide> export type ReactEventResponderEventType = <ide> | {name: string, passive?: boolean, capture?: boolean}; <ide> <ide> export type ReactEventResponder = { <del> targetEventTypes: Array<ReactEventResponderEventType>, <add> targetEventTypes?: Array<ReactEventResponderEventType>, <add> rootEventTypes?: Array<ReactEventResponderEventType>, <ide> createInitialState?: (props: null | Object) => Object, <ide> stopLocalPropagation: boolean, <ide> onEvent?: ( <ide> export type ReactEventComponentInstance = {| <ide> context: null | Object, <ide> props: null | Object, <ide> responder: ReactEventResponder, <add> rootEventTypes: null | Set<string>, <ide> rootInstance: mixed, <ide> state: null | Object, <ide> |};
6
PHP
PHP
fix container build and add tests
0b934bc68237a208534d1480cdb268f53ef99c42
<ide><path>src/Illuminate/Container/Container.php <ide> public function build($concrete) <ide> // hand back the results of the functions, which allows functions to be <ide> // used as resolvers for more fine-tuned resolution of these objects. <ide> if ($concrete instanceof Closure) { <del> return $concrete($this, end($this->with)); <add> return $concrete($this, $this->getLastParameterOverride()); <ide> } <ide> <ide> $reflector = new ReflectionClass($concrete); <ide> protected function resolveDependencies(array $dependencies) <ide> */ <ide> protected function hasParameterOverride($dependency) <ide> { <del> return array_key_exists($dependency->name, end($this->with)); <add> return array_key_exists($dependency->name, $this->getLastParameterOverride()); <ide> } <ide> <ide> /** <ide> protected function hasParameterOverride($dependency) <ide> */ <ide> protected function getParameterOverride($dependency) <ide> { <del> return end($this->with)[$dependency->name]; <add> return $this->getLastParameterOverride()[$dependency->name]; <add> } <add> <add> /** <add> * Get the last parameter override. <add> * <add> * @return array <add> */ <add> protected function getLastParameterOverride() <add> { <add> return count($this->with) ? end($this->with) : []; <ide> } <ide> <ide> /** <ide><path>tests/Container/ContainerTest.php <ide> public function testSingletonBindingsNotRespectedWithMakeParameters() <ide> $this->assertEquals(['name' => 'taylor'], $container->makeWith('foo', ['name' => 'taylor'])); <ide> $this->assertEquals(['name' => 'abigail'], $container->makeWith('foo', ['name' => 'abigail'])); <ide> } <add> <add> public function testCanBuildWithoutParameterStackWithNoConstructors() <add> { <add> $container = new Container; <add> $this->assertInstanceOf(ContainerConcreteStub::class, $container->build(ContainerConcreteStub::class)); <add> } <add> <add> public function testCanBuildWithoutParameterStackWithConstructors() <add> { <add> $container = new Container; <add> $container->bind('Illuminate\Tests\Container\IContainerContractStub', 'Illuminate\Tests\Container\ContainerImplementationStub'); <add> $this->assertInstanceOf(ContainerDependentStub::class, $container->build(ContainerDependentStub::class)); <add> } <ide> } <ide> <ide> class ContainerConcreteStub
2
Java
Java
use varargs for scan method as well
e65ba99e237a10db8ffd066b3f9f0d9682f11b02
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationConfigApplicationContext.java <ide> public void register(Class<?>... annotatedClasses) { <ide> * Perform a scan within the specified base packages. <ide> * @param basePackages the packages to check for annotated classes <ide> */ <del> public void scan(String[] basePackages) { <add> public void scan(String... basePackages) { <ide> this.scanner.scan(basePackages); <ide> } <ide>
1
Python
Python
notify registered observers
d7a3c6b881f8b12135dec0063c5a7f5e069bd838
<ide><path>celery/apps/worker.py <ide> def on_start(self): <ide> <ide> def on_consumer_ready(self, consumer): <ide> signals.worker_ready.send(sender=consumer) <add> WorkController.on_consumer_ready(self, consumer) <ide> print('celery@{0.hostname} has started.'.format(self)) <ide> <ide> def redirect_stdouts_to_logger(self):
1
Javascript
Javascript
add support for beginfbchar
42653edf9a47e281ddbf210d2723e69884a79807
<ide><path>fonts.js <ide> var Font = (function Font() { <ide> }); <ide> }; <ide> <add> var encoding = properties.encoding; <add> var charset = properties.charset; <ide> for (var i = 0; i < numRecords; i++) { <ide> var table = records[i]; <ide> font.pos = start + table.offset; <ide> var Font = (function Font() { <ide> var length = int16(font.getBytes(2)); <ide> var language = int16(font.getBytes(2)); <ide> <del> if (format == 0 && numRecords > 1) { <add> if (format == 0) { <ide> // Characters below 0x20 are controls characters that are hardcoded <ide> // into the platform so if some characters in the font are assigned <ide> // under this limit they will not be displayed so let's rewrite the <ide> // CMap. <del> var map = []; <del> var rewrite = false; <del> for (var j = 0; j < 256; j++) { <del> var index = font.getByte(); <del> if (index != 0) { <del> map.push(index); <del> if (j < 0x20) <del> rewrite = true; <add> var glyphs = []; <add> if (encoding.empty) { <add> var orderedGlyphs= []; <add> for ( var j = 0; j < charset.length; j++) { <add> var unicode = GlyphsUnicode[charset[font.getByte()]] || 0; <add> glyphs.push({ unicode: unicode }); <add> orderedGlyphs.push(unicode); <ide> } <del> } <ide> <del> if (rewrite) { <del> var glyphs = []; <add> orderedGlyphs.sort(function(a, b) { <add> return a - b; <add> }); <add> <add> for (var p in encoding) { <add> if (p != "empty") <add> properties.encoding[p] = orderedGlyphs[p - 1]; <add> } <add> } else { <ide> for (var j = 0x20; j < 256; j++) { <ide> // TODO do not hardcode WinAnsiEncoding <ide> var unicode = GlyphsUnicode[Encodings["WinAnsiEncoding"][j]]; <ide> glyphs.push({ unicode: unicode }); <ide> } <del> cmap.data = createCMapTable(glyphs); <ide> } <del> } else if ((format == 0 && numRecords == 1) || <del> (format == 6 && numRecords == 1 && !properties.encoding.empty)) { <add> cmap.data = createCMapTable(glyphs); <add> } else if (format == 6 && numRecords == 1 && !encoding.empty) { <ide> // Format 0 alone is not allowed by the sanitizer so let's rewrite <ide> // that to a 3-1-4 Unicode BMP table <ide> TODO('Use an other source of informations than ' + <ide> 'charset here, it is not reliable'); <del> var charset = properties.charset; <ide> var glyphs = []; <ide> for (var j = 0; j < charset.length; j++) { <ide> glyphs.push({ <ide> var Font = (function Font() { <ide> assert(ranges.length == 1, 'Got ' + ranges.length + <ide> ' ranges in a dense array'); <ide> <del> var encoding = properties.encoding; <ide> var denseRange = ranges[0]; <ide> var start = denseRange[0]; <ide> var end = denseRange[1]; <ide><path>pdf.js <ide> var PartialEvaluator = (function() { <ide> error('useCMap is not implemented'); <ide> break; <ide> <add> case 'beginbfchar': <ide> case 'beginbfrange': <ide> case 'begincodespacerange': <ide> token = ''; <ide> var PartialEvaluator = (function() { <ide> var code = parseInt('0x' + tokens[j + 2]); <ide> <ide> for (var k = startRange; k <= endRange; k++) { <del> // The encoding mapping table will be filled <del> // later during the building phase <del> //encodingMap[k] = GlyphsUnicode[encoding[code]]; <ide> charset.push(encoding[code++] || '.notdef'); <ide> } <ide> } <ide> break; <ide> <del> case 'beginfbchar': <del> case 'endfbchar': <del> error('fbchar parsing is not implemented'); <add> case 'endbfchar': <add> for (var j = 0; j < tokens.length; j += 2) { <add> var index = parseInt('0x' + tokens[j]); <add> var code = parseInt('0x' + tokens[j + 1]); <add> encodingMap[index] = GlyphsUnicode[encoding[code]]; <add> charset.push(encoding[code] || '.notdef'); <add> } <ide> break; <ide> <ide> default:
2
Python
Python
fix taskinstance actions with upstream/downstream
22ba59c5f26d1e6fa2ce59e99304628b2f0a0fd9
<ide><path>airflow/api/common/mark_tasks.py <ide> from typing import TYPE_CHECKING, Collection, Iterable, Iterator, List, NamedTuple, Optional, Tuple, Union <ide> <ide> from sqlalchemy import or_ <del>from sqlalchemy.orm import contains_eager <add>from sqlalchemy.orm import lazyload <ide> from sqlalchemy.orm.session import Session as SASession <ide> <ide> from airflow.models.dag import DAG <ide> from airflow.utils import timezone <ide> from airflow.utils.helpers import exactly_one <ide> from airflow.utils.session import NEW_SESSION, provide_session <del>from airflow.utils.sqlalchemy import tuple_in_condition <ide> from airflow.utils.state import DagRunState, State, TaskInstanceState <ide> from airflow.utils.types import DagRunType <ide> <ide> def _create_dagruns( <ide> @provide_session <ide> def set_state( <ide> *, <del> tasks: Union[Collection[Operator], Collection[Tuple[Operator, int]]], <add> tasks: Collection[Union[Operator, Tuple[Operator, int]]], <ide> run_id: Optional[str] = None, <ide> execution_date: Optional[datetime] = None, <ide> upstream: bool = False, <ide> def set_state( <ide> on the schedule (but it will as for subdag dag runs if needed). <ide> <ide> :param tasks: the iterable of tasks or (task, map_index) tuples from which to work. <del> task.task.dag needs to be set <add> ``task.dag`` needs to be set <ide> :param run_id: the run_id of the dagrun to start looking from <del> :param execution_date: the execution date from which to start looking(deprecated) <add> :param execution_date: the execution date from which to start looking (deprecated) <ide> :param upstream: Mark all parents (upstream tasks) <ide> :param downstream: Mark all siblings (downstream tasks) of task_id, including SubDags <ide> :param future: Mark all future tasks on the interval of the dag up until <ide> def set_state( <ide> <ide> dag_run_ids = get_run_ids(dag, run_id, future, past) <ide> task_id_map_index_list = list(find_task_relatives(tasks, downstream, upstream)) <del> task_ids = [task_id for task_id, _ in task_id_map_index_list] <del> # check if task_id_map_index_list contains map_index of None <del> # if it contains None, there was no map_index supplied for the task <del> for _, index in task_id_map_index_list: <del> if index is None: <del> task_id_map_index_list = [task_id for task_id, _ in task_id_map_index_list] <del> break <add> task_ids = [task_id if isinstance(task_id, str) else task_id[0] for task_id in task_id_map_index_list] <ide> <ide> confirmed_infos = list(_iter_existing_dag_run_infos(dag, dag_run_ids)) <ide> confirmed_dates = [info.logical_date for info in confirmed_infos] <ide> def set_state( <ide> <ide> # now look for the task instances that are affected <ide> <del> qry_dag = get_all_dag_task_query(dag, session, state, task_id_map_index_list, confirmed_dates) <add> qry_dag = get_all_dag_task_query(dag, session, state, task_id_map_index_list, dag_run_ids) <ide> <ide> if commit: <ide> tis_altered = qry_dag.with_for_update().all() <ide> if sub_dag_run_ids: <ide> qry_sub_dag = all_subdag_tasks_query(sub_dag_run_ids, session, state, confirmed_dates) <ide> tis_altered += qry_sub_dag.with_for_update().all() <ide> for task_instance in tis_altered: <del> task_instance.set_state(state) <add> task_instance.set_state(state, session=session) <add> session.flush() <ide> else: <ide> tis_altered = qry_dag.all() <ide> if sub_dag_run_ids: <ide> def get_all_dag_task_query( <ide> dag: DAG, <ide> session: SASession, <ide> state: TaskInstanceState, <del> task_ids: Union[List[str], List[Tuple[str, int]]], <del> confirmed_dates: Iterable[datetime], <add> task_ids: List[Union[str, Tuple[str, int]]], <add> run_ids: Iterable[str], <ide> ): <ide> """Get all tasks of the main dag that will be affected by a state change""" <del> is_string_list = isinstance(task_ids[0], str) <del> qry_dag = ( <del> session.query(TaskInstance) <del> .join(TaskInstance.dag_run) <del> .filter( <del> TaskInstance.dag_id == dag.dag_id, <del> DagRun.execution_date.in_(confirmed_dates), <del> ) <add> qry_dag = session.query(TaskInstance).filter( <add> TaskInstance.dag_id == dag.dag_id, <add> TaskInstance.run_id.in_(run_ids), <add> TaskInstance.ti_selector_condition(task_ids), <ide> ) <ide> <del> if is_string_list: <del> qry_dag = qry_dag.filter(TaskInstance.task_id.in_(task_ids)) <del> else: <del> qry_dag = qry_dag.filter(tuple_in_condition((TaskInstance.task_id, TaskInstance.map_index), task_ids)) <ide> qry_dag = qry_dag.filter(or_(TaskInstance.state.is_(None), TaskInstance.state != state)).options( <del> contains_eager(TaskInstance.dag_run) <add> lazyload(TaskInstance.dag_run) <ide> ) <ide> return qry_dag <ide> <ide> def find_task_relatives(tasks, downstream, upstream): <ide> for item in tasks: <ide> if isinstance(item, tuple): <ide> task, map_index = item <add> yield task.task_id, map_index <ide> else: <del> task, map_index = item, None <del> yield task.task_id, map_index <add> task = item <add> yield task.task_id <ide> if downstream: <ide> for relative in task.get_flat_relatives(upstream=False): <del> yield relative.task_id, map_index <add> yield relative.task_id <ide> if upstream: <ide> for relative in task.get_flat_relatives(upstream=True): <del> yield relative.task_id, map_index <add> yield relative.task_id <ide> <ide> <ide> @provide_session <ide><path>airflow/models/dag.py <ide> def get_task_instances( <ide> def _get_task_instances( <ide> self, <ide> *, <del> task_ids: Union[Collection[str], Collection[Tuple[str, int]], None], <add> task_ids: Optional[Collection[Union[str, Tuple[str, int]]]], <ide> start_date: Optional[datetime], <ide> end_date: Optional[datetime], <ide> run_id: Optional[str], <ide> state: Union[TaskInstanceState, Sequence[TaskInstanceState]], <ide> include_subdags: bool, <ide> include_parentdag: bool, <ide> include_dependent_dags: bool, <del> exclude_task_ids: Union[Collection[str], Collection[Tuple[str, int]], None], <add> exclude_task_ids: Optional[Collection[Union[str, Tuple[str, int]]]], <ide> session: Session, <ide> dag_bag: Optional["DagBag"] = ..., <ide> ) -> Iterable[TaskInstance]: <ide> def _get_task_instances( <ide> def _get_task_instances( <ide> self, <ide> *, <del> task_ids: Union[Collection[str], Collection[Tuple[str, int]], None], <add> task_ids: Optional[Collection[Union[str, Tuple[str, int]]]], <ide> as_pk_tuple: Literal[True], <ide> start_date: Optional[datetime], <ide> end_date: Optional[datetime], <ide> def _get_task_instances( <ide> include_subdags: bool, <ide> include_parentdag: bool, <ide> include_dependent_dags: bool, <del> exclude_task_ids: Union[Collection[str], Collection[Tuple[str, int]], None], <add> exclude_task_ids: Optional[Collection[Union[str, Tuple[str, int]]]], <ide> session: Session, <ide> dag_bag: Optional["DagBag"] = ..., <ide> recursion_depth: int = ..., <ide> def _get_task_instances( <ide> def _get_task_instances( <ide> self, <ide> *, <del> task_ids: Union[Collection[str], Collection[Tuple[str, int]], None], <add> task_ids: Optional[Collection[Union[str, Tuple[str, int]]]], <ide> as_pk_tuple: Literal[True, None] = None, <ide> start_date: Optional[datetime], <ide> end_date: Optional[datetime], <ide> def _get_task_instances( <ide> include_subdags: bool, <ide> include_parentdag: bool, <ide> include_dependent_dags: bool, <del> exclude_task_ids: Union[Collection[str], Collection[Tuple[str, int]], None], <add> exclude_task_ids: Optional[Collection[Union[str, Tuple[str, int]]]], <ide> session: Session, <ide> dag_bag: Optional["DagBag"] = None, <ide> recursion_depth: int = 0, <ide> def _get_task_instances( <ide> (TaskInstance.dag_id == dag.dag_id) & TaskInstance.task_id.in_(dag.task_ids) <ide> ) <ide> tis = tis.filter(or_(*conditions)) <del> else: <add> elif self.partial: <ide> tis = tis.filter(TaskInstance.dag_id == self.dag_id, TaskInstance.task_id.in_(self.task_ids)) <add> else: <add> tis = tis.filter(TaskInstance.dag_id == self.dag_id) <ide> if run_id: <ide> tis = tis.filter(TaskInstance.run_id == run_id) <ide> if start_date: <ide> tis = tis.filter(DagRun.execution_date >= start_date) <del> <del> if task_ids is None: <del> pass # Disable filter if not set. <del> elif isinstance(next(iter(task_ids), None), str): <del> tis = tis.filter(TI.task_id.in_(task_ids)) <del> else: <del> tis = tis.filter(tuple_in_condition((TI.task_id, TI.map_index), task_ids)) <add> if task_ids is not None: <add> tis = tis.filter(TaskInstance.ti_selector_condition(task_ids)) <ide> <ide> # This allows allow_trigger_in_future config to take affect, rather than mandating exec_date <= UTC <ide> if end_date or not self.allow_future_exec_dates: <ide> def set_task_instance_state( <ide> task = self.get_task(task_id) <ide> task.dag = self <ide> <del> tasks_to_set_state: Union[List[Operator], List[Tuple[Operator, int]]] <del> task_ids_to_exclude_from_clear: Union[Set[str], Set[Tuple[str, int]]] <add> tasks_to_set_state: List[Union[Operator, Tuple[Operator, int]]] <add> task_ids_to_exclude_from_clear: Set[Union[str, Tuple[str, int]]] <ide> if map_indexes is None: <ide> tasks_to_set_state = [task] <ide> task_ids_to_exclude_from_clear = {task_id} <ide><path>airflow/models/taskinstance.py <ide> TYPE_CHECKING, <ide> Any, <ide> Callable, <add> Collection, <ide> ContextManager, <ide> Dict, <ide> Generator, <ide> PickleType, <ide> String, <ide> and_, <add> false, <ide> func, <ide> inspect, <ide> or_, <ide> from sqlalchemy.orm.query import Query <ide> from sqlalchemy.orm.session import Session <ide> from sqlalchemy.sql.elements import BooleanClauseList <add>from sqlalchemy.sql.expression import ColumnOperators <ide> from sqlalchemy.sql.sqltypes import BigInteger <ide> <ide> from airflow import settings <ide> def clear_task_instances( <ide> :param activate_dag_runs: Deprecated parameter, do not pass <ide> """ <ide> job_ids = [] <del> task_id_by_key: Dict[str, Dict[str, Dict[int, Set[str]]]] = defaultdict( <del> lambda: defaultdict(lambda: defaultdict(set)) <add> # Keys: dag_id -> run_id -> map_indexes -> try_numbers -> task_id <add> task_id_by_key: Dict[str, Dict[str, Dict[int, Dict[int, Set[str]]]]] = defaultdict( <add> lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(set))) <ide> ) <ide> for ti in tis: <ide> if ti.state == TaskInstanceState.RUNNING: <ide> def clear_task_instances( <ide> ti.external_executor_id = None <ide> session.merge(ti) <ide> <del> task_id_by_key[ti.dag_id][ti.run_id][ti.try_number].add(ti.task_id) <add> task_id_by_key[ti.dag_id][ti.run_id][ti.map_index][ti.try_number].add(ti.task_id) <ide> <ide> if task_id_by_key: <ide> # Clear all reschedules related to the ti to clear <ide> <ide> # This is an optimization for the common case where all tis are for a small number <del> # of dag_id, run_id and try_number. Use a nested dict of dag_id, <del> # run_id, try_number and task_id to construct the where clause in a <add> # of dag_id, run_id, try_number, and map_index. Use a nested dict of dag_id, <add> # run_id, try_number, map_index, and task_id to construct the where clause in a <ide> # hierarchical manner. This speeds up the delete statement by more than 40x for <ide> # large number of tis (50k+). <ide> conditions = or_( <ide> def clear_task_instances( <ide> and_( <ide> TR.run_id == run_id, <ide> or_( <del> and_(TR.try_number == try_number, TR.task_id.in_(task_ids)) <del> for try_number, task_ids in task_tries.items() <add> and_( <add> TR.map_index == map_index, <add> or_( <add> and_(TR.try_number == try_number, TR.task_id.in_(task_ids)) <add> for try_number, task_ids in task_tries.items() <add> ), <add> ) <add> for map_index, task_tries in map_indexes.items() <ide> ), <ide> ) <del> for run_id, task_tries in run_ids.items() <add> for run_id, map_indexes in run_ids.items() <ide> ), <ide> ) <ide> for dag_id, run_ids in task_id_by_key.items() <ide> def filter_for_tis(tis: Iterable[Union["TaskInstance", TaskInstanceKey]]) -> Opt <ide> (ti.key.primary for ti in tis), <ide> ) <ide> <add> @classmethod <add> def ti_selector_condition(cls, vals: Collection[Union[str, Tuple[str, int]]]) -> ColumnOperators: <add> """ <add> Build an SQLAlchemy filter for a list where each element can contain <add> whether a task_id, or a tuple of (task_id,map_index) <add> <add> :meta private: <add> """ <add> # Compute a filter for TI.task_id and TI.map_index based on input values <add> # For each item, it will either be a task_id, or (task_id, map_index) <add> task_id_only = [v for v in vals if isinstance(v, str)] <add> with_map_index = [v for v in vals if not isinstance(v, str)] <add> <add> filters: List[ColumnOperators] = [] <add> if task_id_only: <add> filters.append(cls.task_id.in_(task_id_only)) <add> if with_map_index: <add> filters.append(tuple_in_condition((cls.task_id, cls.map_index), with_map_index)) <add> <add> if not filters: <add> return false() <add> if len(filters) == 1: <add> return filters[0] <add> return or_(*filters) <add> <ide> <ide> # State of the task instance. <ide> # Stores string version of the task state. <ide><path>airflow/www/views.py <ide> def clear(self): <ide> recursive = request.form.get('recursive') == "true" <ide> only_failed = request.form.get('only_failed') == "true" <ide> <add> task_ids: List[Union[str, Tuple[str, int]]] <add> if map_indexes is None: <add> task_ids = [task_id] <add> else: <add> task_ids = [(task_id, map_index) for map_index in map_indexes] <add> <ide> dag = dag.partial_subset( <del> task_ids_or_regex=fr"^{task_id}$", <add> task_ids_or_regex=[task_id], <ide> include_downstream=downstream, <ide> include_upstream=upstream, <ide> ) <add> <add> if len(dag.task_dict) > 1: <add> # If we had upstream/downstream etc then also include those! <add> task_ids.extend(tid for tid in dag.task_dict if tid != task_id) <add> <ide> end_date = execution_date if not future else None <ide> start_date = execution_date if not past else None <ide> <del> if map_indexes is None: <del> task_ids: Union[List[str], List[Tuple[str, int]]] = [task_id] <del> else: <del> task_ids = [(task_id, map_index) for map_index in map_indexes] <del> <ide> return self._clear_dag_tis( <ide> dag, <ide> start_date, <ide><path>tests/api/common/test_mark_tasks.py <ide> from airflow.utils.state import State <ide> from airflow.utils.types import DagRunType <ide> from tests.test_utils.db import clear_db_runs <add>from tests.test_utils.mapping import expand_mapped_task <ide> <ide> DEV_NULL = "/dev/null" <ide> <ide> def snapshot_state(dag, execution_dates): <ide> ) <ide> <ide> @provide_session <del> def verify_state(self, dag, task_ids, execution_dates, state, old_tis, session=None, map_indexes=None): <add> def verify_state(self, dag, task_ids, execution_dates, state, old_tis, session=None, map_task_pairs=None): <ide> TI = models.TaskInstance <ide> DR = models.DagRun <ide> <ide> tis = ( <ide> session.query(TI) <ide> .join(TI.dag_run) <del> .options(eagerload(TI.dag_run)) <ide> .filter(TI.dag_id == dag.dag_id, DR.execution_date.in_(execution_dates)) <ide> .all() <ide> ) <del> <ide> assert len(tis) > 0 <ide> <add> unexpected_tis = [] <ide> for ti in tis: <ide> assert ti.operator == dag.get_task(ti.task_id).task_type <ide> if ti.task_id in task_ids and ti.execution_date in execution_dates: <del> if map_indexes: <del> if ti.map_index in map_indexes: <add> if map_task_pairs: <add> if (ti.task_id, ti.map_index) in map_task_pairs: <ide> assert ti.state == state <ide> else: <del> assert ti.state == state <del> if state in State.finished: <del> if map_indexes: <del> if ti.map_index in map_indexes: <del> assert ti.end_date is not None <del> else: <del> assert ti.end_date is not None <add> assert ti.state == state, ti <add> if ti.state in State.finished: <add> assert ti.end_date is not None, ti <ide> else: <ide> for old_ti in old_tis: <del> if old_ti.task_id == ti.task_id and old_ti.execution_date == ti.execution_date: <del> if map_indexes: <del> if ti.map_index in map_indexes: <del> assert ti.state == old_ti.state <del> else: <del> assert ti.state == old_ti.state <add> if ( <add> old_ti.task_id == ti.task_id <add> and old_ti.run_id == ti.run_id <add> and old_ti.map_index == ti.map_index <add> ): <add> assert ti.state == old_ti.state <add> break <add> else: <add> unexpected_tis.append(ti) <add> assert not unexpected_tis <ide> <ide> def test_mark_tasks_now(self): <ide> # set one task to success but do not commit <ide> def test_mark_tasks_multiple(self): <ide> @pytest.mark.backend("sqlite", "postgres") <ide> def test_mark_tasks_subdag(self): <ide> # set one task to success towards end of scheduled dag runs <add> snapshot = TestMarkTasks.snapshot_state(self.dag2, self.execution_dates) <ide> task = self.dag2.get_task("section-1") <ide> relatives = task.get_flat_relatives(upstream=False) <ide> task_ids = [t.task_id for t in relatives] <ide> def test_mark_tasks_subdag(self): <ide> ) <ide> assert len(altered) == 14 <ide> <del> # cannot use snapshot here as that will require drilling down the <del> # sub dag tree essentially recreating the same code as in the <del> # tested logic. <del> self.verify_state(self.dag2, task_ids, [self.execution_dates[0]], State.SUCCESS, []) <add> self.verify_state(self.dag2, task_ids, [self.execution_dates[0]], State.SUCCESS, snapshot) <ide> <del> def test_mark_mapped_task_instance_state(self): <add> def test_mark_mapped_task_instance_state(self, session): <ide> # set mapped task instance to success <add> mapped = self.dag4.get_task("consumer") <add> tasks = [(mapped, 0), (mapped, 1)] <add> dr = DagRun.find(dag_id=self.dag4.dag_id, execution_date=self.execution_dates[0], session=session)[0] <add> expand_mapped_task(mapped, dr.run_id, "make_arg_lists", length=3, session=session) <ide> snapshot = TestMarkTasks.snapshot_state(self.dag4, self.execution_dates) <del> task = self.dag4.get_task("consumer_literal") <del> tasks = [(task, 0), (task, 1)] <del> map_indexes = [0, 1] <del> dr = DagRun.find(dag_id=self.dag4.dag_id, execution_date=self.execution_dates[0])[0] <ide> altered = set_state( <ide> tasks=tasks, <ide> run_id=dr.run_id, <del> upstream=False, <add> upstream=True, <ide> downstream=False, <ide> future=False, <ide> past=False, <ide> state=State.SUCCESS, <ide> commit=True, <add> session=session, <ide> ) <del> assert len(altered) == 2 <add> assert len(altered) == 3 <ide> self.verify_state( <ide> self.dag4, <del> [task.task_id for task, _ in tasks], <add> ["consumer", "make_arg_lists"], <ide> [self.execution_dates[0]], <ide> State.SUCCESS, <ide> snapshot, <del> map_indexes=map_indexes, <add> map_task_pairs=[(task.task_id, map_index) for (task, map_index) in tasks] <add> + [("make_arg_lists", -1)], <add> session=session, <ide> ) <ide> <ide> <ide><path>tests/models/test_baseoperator.py <ide> from airflow.utils.weight_rule import WeightRule <ide> from tests.models import DEFAULT_DATE <ide> from tests.test_utils.config import conf_vars <add>from tests.test_utils.mapping import expand_mapped_task <ide> from tests.test_utils.mock_operators import DeprecatedOperator, MockOperator <ide> <ide> <ide> def test_expand_mapped_task_instance_skipped_on_zero(dag_maker, session): <ide> <ide> dr = dag_maker.create_dagrun() <ide> <del> session.add( <del> TaskMap(dag_id=dr.dag_id, task_id=task1.task_id, run_id=dr.run_id, map_index=-1, length=0, keys=None) <del> ) <del> session.flush() <del> <del> mapped.expand_mapped_task(dr.run_id, session=session) <add> expand_mapped_task(mapped, dr.run_id, task1.task_id, length=0, session=session) <ide> <ide> indices = ( <ide> session.query(TaskInstance.map_index, TaskInstance.state) <ide><path>tests/models/test_dag.py <ide> from tests.models import DEFAULT_DATE <ide> from tests.test_utils.asserts import assert_queries_count <ide> from tests.test_utils.db import clear_db_dags, clear_db_runs <add>from tests.test_utils.mapping import expand_mapped_task <ide> from tests.test_utils.timetables import cron_timetable, delta_timetable <ide> <ide> TEST_DATE = datetime_tz(2015, 1, 2, 0, 0) <ide> def test_clear_set_dagrun_state_for_mapped_task(self, dag_run_state): <ide> self._clean_up(dag_id) <ide> task_id = 't1' <ide> <add> dag = DAG(dag_id, start_date=DEFAULT_DATE, max_active_runs=1) <add> <add> @dag.task <add> def make_arg_lists(): <add> return [[1], [2], [{'a': 'b'}]] <add> <ide> def consumer(value): <ide> print(value) <ide> <del> dag = DAG(dag_id, start_date=DEFAULT_DATE, max_active_runs=1) <del> PythonOperator.partial(task_id=task_id, dag=dag, python_callable=consumer).expand(op_args=[1, 2, 4]) <add> mapped = PythonOperator.partial(task_id=task_id, dag=dag, python_callable=consumer).expand( <add> op_args=make_arg_lists() <add> ) <ide> <ide> session = settings.Session() <ide> dagrun_1 = dag.create_dagrun( <ide> run_type=DagRunType.BACKFILL_JOB, <ide> state=State.FAILED, <ide> start_date=DEFAULT_DATE, <ide> execution_date=DEFAULT_DATE, <add> session=session, <ide> ) <del> session.merge(dagrun_1) <del> ti = ( <del> session.query(TI) <del> .filter(TI.map_index == 0, TI.task_id == task_id, TI.dag_id == dag.dag_id) <del> .first() <del> ) <del> ti2 = ( <del> session.query(TI) <del> .filter(TI.map_index == 1, TI.task_id == task_id, TI.dag_id == dag.dag_id) <del> .first() <del> ) <add> expand_mapped_task(mapped, dagrun_1.run_id, "make_arg_lists", length=2, session=session) <add> <add> upstream_ti = dagrun_1.get_task_instance("make_arg_lists", session=session) <add> ti = dagrun_1.get_task_instance(task_id, map_index=0, session=session) <add> ti2 = dagrun_1.get_task_instance(task_id, map_index=1, session=session) <add> upstream_ti.state = State.SUCCESS <ide> ti.state = State.SUCCESS <ide> ti2.state = State.SUCCESS <del> ti.execution_date = DEFAULT_DATE <del> ti2.execution_date = DEFAULT_DATE <del> session.merge(ti) <del> session.merge(ti2) <ide> session.flush() <ide> <ide> dag.clear( <del> task_ids=[(task_id, 0)], <add> task_ids=[(task_id, 0), ("make_arg_lists")], <ide> start_date=DEFAULT_DATE, <ide> end_date=DEFAULT_DATE + datetime.timedelta(days=1), <ide> dag_run_state=dag_run_state, <ide> include_subdags=False, <ide> include_parentdag=False, <ide> session=session, <ide> ) <del> ti = ( <del> session.query(TI) <del> .filter(TI.map_index == ti.map_index, TI.task_id == ti.task_id, TI.dag_id == ti.dag_id) <del> .first() <del> ) <del> ti2 = ( <del> session.query(TI) <del> .filter(TI.map_index == ti2.map_index, TI.task_id == ti2.task_id, TI.dag_id == ti2.dag_id) <del> .first() <del> ) <add> session.refresh(upstream_ti) <add> session.refresh(ti) <add> session.refresh(ti2) <add> assert upstream_ti.state is None # cleared <ide> assert ti.state is None # cleared <ide> assert ti2.state == State.SUCCESS # not cleared <ide> dagruns = ( <ide><path>tests/models/test_dagrun.py <ide> from airflow.decorators import task <ide> from airflow.models import DAG, DagBag, DagModel, DagRun, TaskInstance as TI, clear_task_instances <ide> from airflow.models.baseoperator import BaseOperator <del>from airflow.models.dagrun import TISchedulingDecision <ide> from airflow.models.taskmap import TaskMap <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.operators.empty import EmptyOperator <ide> def test_ti_scheduling_mapped_zero_length(dag_maker, session): <ide> <ide> # ti1 finished execution. ti2 goes directly to finished state because it's <ide> # expanded against a zero-length XCom. <del> assert decision == TISchedulingDecision( <del> tis=[ti1, ti2], <del> schedulable_tis=[], <del> changed_tis=False, <del> unfinished_tis=[], <del> finished_tis=[ti1, ti2], <del> ) <add> assert decision.finished_tis == [ti1, ti2] <ide> <ide> indices = ( <ide> session.query(TI.map_index, TI.state) <ide><path>tests/test_utils/mapping.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. 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, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>from typing import TYPE_CHECKING <add> <add>from airflow.models.taskmap import TaskMap <add> <add>if TYPE_CHECKING: <add> from sqlalchemy.orm import Session <add> <add> from airflow.models.mappedoperator import MappedOperator <add> <add> <add>def expand_mapped_task( <add> mapped: "MappedOperator", run_id: str, upstream_task_id: str, length: int, session: "Session" <add>): <add> session.add( <add> TaskMap( <add> dag_id=mapped.dag_id, <add> task_id=upstream_task_id, <add> run_id=run_id, <add> map_index=-1, <add> length=length, <add> keys=None, <add> ) <add> ) <add> session.flush() <add> <add> mapped.expand_mapped_task(run_id, session=session)
9
Javascript
Javascript
fix an infinite loop in new context
8d0942242476024ac74d4ca2fcac9824b3124dc8
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js <ide> export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>( <ide> renderExpirationTime: ExpirationTime, <ide> ): void { <ide> let fiber = workInProgress.child; <add> if (fiber !== null) { <add> // Set the return pointer of the child to the work-in-progress fiber. <add> fiber.return = workInProgress; <add> } <ide> while (fiber !== null) { <ide> let nextFiber; <ide> // Visit this fiber. <ide><path>packages/react-reconciler/src/__tests__/ReactNewContext-test.internal.js <ide> describe('ReactNewContext', () => { <ide> expect(ReactNoop.getChildren()).toEqual([span('Child')]); <ide> }); <ide> <add> // This is a regression case for https://github.com/facebook/react/issues/12389. <add> it('does not run into an infinite loop', () => { <add> const Context = React.createContext(null); <add> <add> class App extends React.Component { <add> renderItem(id) { <add> return ( <add> <span key={id}> <add> <Context.Consumer>{() => <span>inner</span>}</Context.Consumer> <add> <span>outer</span> <add> </span> <add> ); <add> } <add> renderList() { <add> const list = [1, 2].map(id => this.renderItem(id)); <add> if (this.props.reverse) { <add> list.reverse(); <add> } <add> return list; <add> } <add> render() { <add> return ( <add> <Context.Provider value={{}}>{this.renderList()}</Context.Provider> <add> ); <add> } <add> } <add> <add> ReactNoop.render(<App reverse={false} />); <add> ReactNoop.flush(); <add> ReactNoop.render(<App reverse={true} />); <add> ReactNoop.flush(); <add> ReactNoop.render(<App reverse={false} />); <add> ReactNoop.flush(); <add> }); <add> <ide> describe('fuzz test', () => { <ide> const Fragment = React.Fragment; <ide> const contextKeys = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
2
Python
Python
fix documentation of bigbird tokenizer
4f19881f88e877f5ec95472e346959e7cb2a2ecc
<ide><path>src/transformers/models/big_bird/tokenization_big_bird_fast.py <ide> class BigBirdTokenizerFast(PreTrainedTokenizerFast): <ide> vocab_file (:obj:`str`): <ide> `SentencePiece <https://github.com/google/sentencepiece>`__ file (generally has a `.spm` extension) that <ide> contains the vocabulary necessary to instantiate a tokenizer. <del> bos_token (:obj:`str`, `optional`, defaults to :obj:`"[CLS]"`): <add> bos_token (:obj:`str`, `optional`, defaults to :obj:`"<s>"`): <ide> The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. <ide> <ide> .. note:: <ide> <ide> When building a sequence using special tokens, this is not the token that is used for the beginning of <ide> sequence. The token used is the :obj:`cls_token`. <del> eos_token (:obj:`str`, `optional`, defaults to :obj:`"[SEP]"`): <add> eos_token (:obj:`str`, `optional`, defaults to :obj:`"</s>"`): <ide> The end of sequence token. .. note:: When building a sequence using special tokens, this is not the token <ide> that is used for the end of sequence. The token used is the :obj:`sep_token`. <ide> unk_token (:obj:`str`, `optional`, defaults to :obj:`"<unk>"`):
1
Text
Text
remove unnecessary echo from yum docs
3cbccccb37f6f50ebb49e9738af09a0d7d79549a
<ide><path>docs/installation/centos.md <ide> package manager. <ide> <ide> 3. Add the yum repo. <ide> <del> $ echo | sudo tee /etc/yum.repos.d/docker.repo <<-EOF <add> $ sudo tee /etc/yum.repos.d/docker.repo <<-EOF <ide> [dockerrepo] <ide> name=Docker Repository <ide> baseurl=https://yum.dockerproject.org/repo/main/centos/7 <ide><path>docs/installation/fedora.md <ide> There are two ways to install Docker Engine. You can install with the `yum` pac <ide> <ide> For Fedora 21 run: <ide> <del> $ echo | sudo tee /etc/yum.repos.d/docker.repo <<-EOF <add> $ sudo tee /etc/yum.repos.d/docker.repo <<-EOF <ide> [dockerrepo] <ide> name=Docker Repository <ide> baseurl=https://yum.dockerproject.org/repo/main/fedora/21 <ide><path>docs/installation/oracle.md <ide> btrfs storage engine on both Oracle Linux 6 and 7. <ide> <ide> For version 6: <ide> <del> $ echo | sudo tee /etc/yum.repos.d/docker.repo <<-EOF <add> $ sudo tee /etc/yum.repos.d/docker.repo <<-EOF <ide> [dockerrepo] <ide> name=Docker Repository <ide> baseurl=https://yum.dockerproject.org/repo/main/oraclelinux/6 <ide><path>docs/installation/rhel.md <ide> There are two ways to install Docker Engine. You can install with the `yum` pac <ide> <ide> 3. Add the yum repo yourself. <ide> <del> $ echo | sudo tee /etc/yum.repos.d/docker.repo <<-EOF <add> $ sudo tee /etc/yum.repos.d/docker.repo <<-EOF <ide> [dockerrepo] <ide> name=Docker Repository <ide> baseurl=https://yum.dockerproject.org/repo/main/centos/7
4
PHP
PHP
use proper assertions
74651006bfc19622d8aa93c8f827c1ff4bd364c4
<ide><path>tests/Database/DatabaseEloquentBelongsToManySyncTouchesParentTest.php <ide> public function testSyncWithDetachedValuesShouldTouch() <ide> <ide> Carbon::setTestNow('2021-07-20 19:13:14'); <ide> $result = $article->users()->sync([1, 2]); <del> $this->assertTrue(collect($result['detached'])->count() === 1); <add> $this->assertCount(1, collect($result['detached'])); <ide> $this->assertSame('3', collect($result['detached'])->first()); <ide> <ide> $article->refresh(); <ide><path>tests/Database/DatabaseSchemaBlueprintIntegrationTest.php <ide> public function testRenamingAndChangingColumnsWork() <ide> ], <ide> ]; <ide> <del> $this->assertTrue(in_array($queries, $expected)); <add> $this->assertContains($queries, $expected); <ide> } <ide> <ide> public function testChangingColumnWithCollationWorks() <ide><path>tests/Integration/Database/DatabaseEloquentModelAttributeCastingTest.php <ide> public function testCastsThatOnlyHaveGetterDoNotPeristAnythingToModelOnSave() <ide> <ide> $model->getAttributes(); <ide> <del> $this->assertTrue(empty($model->getDirty())); <add> $this->assertEmpty($model->getDirty()); <ide> } <ide> <ide> public function testCastsThatOnlyHaveGetterThatReturnsPrimitivesAreNotCached() <ide><path>tests/Integration/Database/EloquentModelCustomCastingTest.php <ide> public function testSavingCastedAttributesToDatabase() <ide> $this->assertSame('address_line_two_value', $model->getOriginal('address_line_two')); <ide> $this->assertSame('address_line_two_value', $model->getAttribute('address_line_two')); <ide> <del> $this->assertSame(null, $model->getOriginal('string_field')); <del> $this->assertSame(null, $model->getAttribute('string_field')); <add> $this->assertNull($model->getOriginal('string_field')); <add> $this->assertNull($model->getAttribute('string_field')); <ide> $this->assertSame('', $model->getRawOriginal('string_field')); <ide> <ide> /** @var \Illuminate\Tests\Integration\Database\CustomCasts $another_model */ <ide><path>tests/Session/SessionStoreTest.php <ide> public function testOldInputFlashing() <ide> $this->assertFalse($session->hasOldInput('boom')); <ide> <ide> $this->assertSame('default', $session->getOldInput('input', 'default')); <del> $this->assertSame(null, $session->getOldInput('name', 'default')); <add> $this->assertNull($session->getOldInput('name', 'default')); <ide> } <ide> <ide> public function testDataFlashing() <ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php <ide> public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes() <ide> eval(" ?> $template <?php "); <ide> ob_get_clean(); <ide> <del> $this->assertSame($attributes->get('userId'), null); <add> $this->assertNull($attributes->get('userId')); <ide> $this->assertSame($attributes->get('other'), 'ok'); <ide> } <ide> <ide><path>tests/View/Blade/BladePropsTest.php <ide> public function testPropsAreExtractedFromParentAttributesCorrectly() <ide> <ide> $this->assertSame($test1, 'value1'); <ide> $this->assertSame($test2, 'value2'); <del> $this->assertSame(isset($test3), false); <add> $this->assertFalse(isset($test3)); <ide> $this->assertSame($test4, 'default'); <ide> <del> $this->assertSame($attributes->get('test1'), null); <del> $this->assertSame($attributes->get('test2'), null); <add> $this->assertNull($attributes->get('test1')); <add> $this->assertNull($attributes->get('test2')); <ide> $this->assertSame($attributes->get('test3'), 'value3'); <ide> } <ide> }
7
Go
Go
print all arguments when failing to start daemon
f6842327b03e124a218f20fc6d0d007df86f7fb2
<ide><path>testutil/daemon/daemon.go <ide> type Daemon struct { <ide> dockerdBinary string <ide> log logT <ide> pidFile string <add> args []string <ide> <ide> // swarm related field <ide> swarmListenAddr string <ide> func (d *Daemon) Cleanup(t testing.TB) { <ide> func (d *Daemon) Start(t testing.TB, args ...string) { <ide> t.Helper() <ide> if err := d.StartWithError(args...); err != nil { <del> t.Fatalf("[%s] failed to start daemon with arguments %v : %v", d.id, args, err) <add> t.Fatalf("[%s] failed to start daemon with arguments %v : %v", d.id, d.args, err) <ide> } <ide> } <ide> <ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { <ide> d.pidFile = filepath.Join(d.Folder, "docker.pid") <ide> } <ide> <del> args := append(d.GlobalFlags, <add> d.args = append(d.GlobalFlags, <ide> "--containerd", containerdSocket, <ide> "--data-root", d.Root, <ide> "--exec-root", d.execRoot, <ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { <ide> "--containerd-plugins-namespace", d.id+"p", <ide> ) <ide> if d.defaultCgroupNamespaceMode != "" { <del> args = append(args, []string{"--default-cgroupns-mode", d.defaultCgroupNamespaceMode}...) <add> d.args = append(d.args, []string{"--default-cgroupns-mode", d.defaultCgroupNamespaceMode}...) <ide> } <ide> if d.experimental { <del> args = append(args, "--experimental") <add> d.args = append(d.args, "--experimental") <ide> } <ide> if d.init { <del> args = append(args, "--init") <add> d.args = append(d.args, "--init") <ide> } <ide> if !(d.UseDefaultHost || d.UseDefaultTLSHost) { <del> args = append(args, []string{"--host", d.Sock()}...) <add> d.args = append(d.args, []string{"--host", d.Sock()}...) <ide> } <ide> if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" { <del> args = append(args, []string{"--userns-remap", root}...) <add> d.args = append(d.args, []string{"--userns-remap", root}...) <ide> } <ide> <ide> // If we don't explicitly set the log-level or debug flag(-D) then <ide> func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { <ide> } <ide> } <ide> if !foundLog { <del> args = append(args, "--debug") <add> d.args = append(d.args, "--debug") <ide> } <ide> if d.storageDriver != "" && !foundSd { <del> args = append(args, "--storage-driver", d.storageDriver) <add> d.args = append(d.args, "--storage-driver", d.storageDriver) <ide> } <ide> <del> args = append(args, providedArgs...) <del> d.cmd = exec.Command(dockerdBinary, args...) <add> d.args = append(d.args, providedArgs...) <add> d.cmd = exec.Command(dockerdBinary, d.args...) <ide> d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1") <ide> d.cmd.Stdout = out <ide> d.cmd.Stderr = out
1
Javascript
Javascript
fix coding style in src/display/canvas.js
bc986a3029daf8a5e8d1add6c7e14b09ed52cc01
<ide><path>src/display/canvas.js <ide> function compileType3Glyph(imgData) { <ide> var type = points[p], p0 = p, pp; <ide> do { <ide> var step = steps[type]; <del> do { p += step; } while (!points[p]); <add> do { <add> p += step; <add> } while (!points[p]); <ide> <ide> pp = points[p]; <ide> if (pp !== 5 && pp !== 10) { <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> consumePath = typeof consumePath !== 'undefined' ? consumePath : true; <ide> var ctx = this.ctx; <ide> var strokeColor = this.current.strokeColor; <del> if (this.current.lineWidth === 0) <add> if (this.current.lineWidth === 0) { <ide> ctx.lineWidth = this.getSinglePixelWidth(); <add> } <ide> // For stroke we want to temporarily change the global alpha to the <ide> // stroking alpha. <ide> ctx.globalAlpha = this.current.strokeAlpha; <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> } else { <ide> ctx.stroke(); <ide> } <del> if (consumePath) <add> if (consumePath) { <ide> this.consumePath(); <add> } <ide> // Restore the global alpha to the fill alpha <ide> ctx.globalAlpha = this.current.fillAlpha; <ide> }, <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> var fontObj = this.commonObjs.get(fontRefName); <ide> var current = this.current; <ide> <del> if (!fontObj) <add> if (!fontObj) { <ide> error('Can\'t find font for ' + fontRefName); <add> } <ide> <del> current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : <del> FONT_IDENTITY_MATRIX; <add> current.fontMatrix = (fontObj.fontMatrix ? <add> fontObj.fontMatrix : FONT_IDENTITY_MATRIX); <ide> <ide> // A valid matrix needs all main diagonal elements to be non-zero <ide> // This also ensures we bypass FF bugzilla bug #719844. <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> this.current.font = fontObj; <ide> this.current.fontSize = size; <ide> <del> if (fontObj.coded) <add> if (fontObj.coded) { <ide> return; // we don't need ctx.font for Type3 fonts <add> } <ide> <ide> var name = fontObj.loadedName || 'sans-serif'; <ide> var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> var lineWidth = current.lineWidth; <ide> var a1 = current.textMatrix[0], b1 = current.textMatrix[1]; <ide> var scale = Math.sqrt(a1 * a1 + b1 * b1); <del> if (scale === 0 || lineWidth === 0) <add> if (scale === 0 || lineWidth === 0) { <ide> lineWidth = this.getSinglePixelWidth(); <del> else <add> } else { <ide> lineWidth /= scale; <add> } <ide> <del> if (textSelection) <add> if (textSelection) { <ide> geom = this.createTextGeometry(); <add> } <ide> <ide> if (fontSizeScale != 1.0) { <ide> ctx.scale(fontSizeScale, fontSizeScale); <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> current.x += spacingLength; <ide> } <ide> <del> if (textSelection) <add> if (textSelection) { <ide> spacingAccumulator += spacingLength; <add> } <ide> } else { <ide> var shownCanvasWidth = this.showText(e, true); <ide> <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> this.save(); <ide> this.baseTransformStack.push(this.baseTransform); <ide> <del> if (matrix && isArray(matrix) && 6 == matrix.length) <add> if (matrix && isArray(matrix) && 6 == matrix.length) { <ide> this.transform.apply(this, matrix); <add> } <ide> <ide> this.baseTransform = this.ctx.mozCurrentTransform; <ide>
1
Python
Python
add regression test for
718f1c50fb8a2cd6fdc0376f8c6af1142c54a1e8
<ide><path>spacy/tests/regression/test_issue1491.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>import pytest <add>import regex as re <add> <add>from ...lang.en import English <add>from ...tokenizer import Tokenizer <add> <add> <add>@pytest.mark.xfail <add>def test_issue1491(): <add> """Test possible off-by-one error in tokenizer prefix/suffix/infix rules.""" <add> prefix_re = re.compile(r'''[\[\("']''') <add> suffix_re = re.compile(r'''[\]\)"']''') <add> infix_re = re.compile(r'''[-~]''') <add> <add> def my_tokenizer(nlp): <add> return Tokenizer(nlp.vocab, {}, <add> prefix_search=prefix_re.search, <add> suffix_search=suffix_re.search, <add> infix_finditer=infix_re.finditer) <add> <add> nlp = English() <add> nlp.tokenizer = my_tokenizer(nlp) <add> doc = nlp("single quote 'goodbye end.") <add> tokens = [token.text for token in doc] <add> assert tokens == ['single', 'quote', "'", 'goodbye', 'end', '.']
1
Javascript
Javascript
add feature tests for textdecoder
be6cf15060cee35ad987a59bf77c447690d76235
<ide><path>test/features/tests.js <ide> var tests = [ <ide> impact: 'Important', <ide> area: 'Core' <ide> }, <add> { <add> id: 'TextDecoder', <add> name: 'TextDecoder is present', <add> run: function () { <add> if (typeof TextDecoder != 'undefined') <add> return { output: 'Success', emulated: '' }; <add> else <add> return { output: 'Failed', emulated: 'No' }; <add> }, <add> impact: 'Critical', <add> area: 'Core' <add> }, <ide> { <ide> id: 'Worker', <ide> name: 'Worker is present', <ide> var tests = [ <ide> }, <ide> impact: 'Important', <ide> area: 'Core' <add> }, <add> { <add> id: 'Worker-TextDecoder', <add> name: 'TextDecoder is present in web workers', <add> run: function () { <add> if (typeof Worker == 'undefined') <add> return { output: 'Skipped', emulated: '' }; <add> <add> var emulatable = typeof TextDecoder !== 'undefined'; <add> try { <add> var worker = new Worker('worker-stub.js'); <add> <add> var promise = new Promise(); <add> var timeout = setTimeout(function () { <add> promise.resolve({ output: 'Failed', <add> emulated: emulatable ? '?' : 'No' }); <add> }, 5000); <add> <add> worker.addEventListener('message', function (e) { <add> var data = e.data; <add> if (data.action === 'TextDecoder') { <add> if (data.result) { <add> promise.resolve({ output: 'Success', emulated: '' }); <add> } else { <add> promise.resolve({ output: 'Failed', <add> emulated: data.emulated ? 'Yes' : 'No' }); <add> } <add> } else { <add> promise.resolve({ output: 'Failed', <add> emulated: emulatable ? 'Yes' : 'No' }); <add> } <add> }); <add> worker.postMessage({action: 'TextDecoder'}); <add> return promise; <add> } catch (e) { <add> return { output: 'Failed', emulated: emulatable ? 'Yes' : 'No' }; <add> } <add> }, <add> impact: 'Important', <add> area: 'Core' <ide> } <ide> ]; <ide> <ide><path>test/features/worker-stub.js <ide> onmessage = function (e) { <ide> 'responseArrayBuffer' in xhr || 'mozResponseArrayBuffer' in xhr; <ide> postMessage({action: 'xhr', result: responseExists}); <ide> break; <add> case 'TextDecoder': <add> postMessage({action: 'TextDecoder', <add> result: typeof TextDecoder !== 'undefined', <add> emulated: typeof FileReaderSync !== 'undefined'}); <add> break; <ide> } <ide> }; <ide>
2
PHP
PHP
fix whitespace and formatting
ca8046bfea49f988d090d670ed56b08bc1cb4486
<ide><path>lib/Cake/Test/Case/Utility/CakeTimeTest.php <ide> public function testWasWithinLast() { <ide> $this->assertTrue($this->Time->wasWithinLast('1 ', '-1 minute')); <ide> $this->assertTrue($this->Time->wasWithinLast('1 ', '-23 hours -59 minutes -59 seconds')); <ide> } <del> <add> <ide> /** <ide> * testWasWithinLast method <ide> * <ide> public function testIsWithinNext() { <ide> $this->assertFalse($this->Time->isWithinNext('1 ', '-1 hour')); <ide> $this->assertFalse($this->Time->isWithinNext('1 ', '-1 minute')); <ide> $this->assertFalse($this->Time->isWithinNext('1 ', '-23 hours -59 minutes -59 seconds')); <del> <add> <ide> $this->assertTrue($this->Time->isWithinNext('7 days', '6 days, 23 hours, 59 minutes, 59 seconds')); <ide> $this->assertFalse($this->Time->isWithinNext('7 days', '6 days, 23 hours, 59 minutes, 61 seconds')); <ide> } <ide><path>lib/Cake/Utility/CakeTime.php <ide> class CakeTime { <ide> * @see CakeTime::format() <ide> */ <ide> public static $niceFormat = '%a, %b %eS %Y, %H:%M'; <del> <add> <ide> /** <ide> * The format to use when formatting a time using `CakeTime::timeAgoInWords()` <ide> * and the difference is more than `CakeTime::$wordEnd` <ide> class CakeTime { <ide> * @see CakeTime::timeAgoInWords() <ide> */ <ide> public static $wordFormat = 'j/n/y'; <del> <add> <ide> /** <ide> * The format to use when formatting a time using `CakeTime::niceShort()` <ide> * and the difference is between 3 and 7 days <ide> class CakeTime { <ide> * @see CakeTime::niceShort() <ide> */ <ide> public static $niceShortFormat = '%d/%m, %H:%M'; <del> <add> <ide> /** <ide> * The format to use when formatting a time using `CakeTime::timeAgoInWords()` <ide> * and the difference is less than `CakeTime::$wordEnd` <ide> class CakeTime { <ide> * @see CakeTime::timeAgoInWords() <ide> */ <ide> public static $wordAccuracy = array( <del> 'year' => "day", <del> 'month' => "day", <del> 'week' => "day", <del> 'day' => "hour", <del> 'hour' => "minute", <add> 'year' => "day", <add> 'month' => "day", <add> 'week' => "day", <add> 'day' => "hour", <add> 'hour' => "minute", <ide> 'minute' => "minute", <ide> 'second' => "second", <ide> ); <del> <add> <ide> /** <ide> * The end of relative time telling <ide> * <ide> public static function niceShort($dateString = null, $timezone = null) { <ide> $date = $dateString ? self::fromString($dateString, $timezone) : time(); <ide> <ide> $y = self::isThisYear($date) ? '' : ' %Y'; <del> <add> <ide> $d = self::_strftime("%w", $date); <del> $day = array(__d('cake', 'Sunday'), __d('cake', 'Monday'), __d('cake', 'Tuesday'), <del> __d('cake', 'Wednesday'), __d('cake', 'Thursday'), __d('cake', 'Friday'), __d('cake', 'Saturday')); <add> $day = array( <add> __d('cake', 'Sunday'), <add> __d('cake', 'Monday'), <add> __d('cake', 'Tuesday'), <add> __d('cake', 'Wednesday'), <add> __d('cake', 'Thursday'), <add> __d('cake', 'Friday'), <add> __d('cake', 'Saturday') <add> ); <ide> <ide> if (self::isToday($dateString, $timezone)) { <ide> $ret = __d('cake', 'Today, %s', self::_strftime("%H:%M", $date)); <ide> public static function niceShort($dateString = null, $timezone = null) { <ide> $format = self::convertSpecifiers("%b %eS{$y}, %H:%M", $date); <ide> $ret = self::_strftime($format, $date); <ide> } <del> <ide> return $ret; <ide> } <ide> <ide> public static function timeAgoInWords($dateTime, $options = array()) { <ide> $format = self::$wordFormat; <ide> $end = self::$wordEnd; <ide> $accuracy = self::$wordAccuracy; <del> <add> <ide> if (is_array($options)) { <ide> if (isset($options['userOffset'])) { <ide> $timezone = $options['userOffset']; <ide> public static function timeAgoInWords($dateTime, $options = array()) { <ide> } <ide> <ide> if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) { <del> $years --; <add> $years--; <ide> } <ide> } <ide> } <ide> public static function timeAgoInWords($dateTime, $options = array()) { <ide> } <ide> <ide> if ($future['m'] != $past['m']) { <del> $months --; <add> $months--; <ide> } <ide> } <ide> <ide> if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) { <ide> $months = 11; <del> $years --; <add> $years--; <ide> } <ide> <ide> if ($months >= 12) { <ide> public static function timeAgoInWords($dateTime, $options = array()) { <ide> if (self::wasWithinLast('7 days', $dateTime, $timezone) || self::isWithinNext('7 days', $dateTime, $timezone)) { <ide> $relativeDate = self::niceShort($dateTime , $timezone); <ide> } <del> <add> <ide> // If now <ide> if ($diff == 0) { <ide> $relativeDate = __d('cake', 'just now', 'just now'); <ide> } <del> <ide> return $relativeDate; <ide> } <ide> <ide> public static function wasWithinLast($timeInterval, $dateString, $timezone = nul <ide> if ($date >= $interval && $date <= time()) { <ide> return true; <ide> } <del> <ide> return false; <ide> } <del> <add> <ide> /** <ide> * Returns true if specified datetime is within the interval specified, else false. <ide> * <ide> public static function isWithinNext($timeInterval, $dateString, $timezone = null <ide> if ($date <= $interval && $date >= time()) { <ide> return true; <ide> } <del> <ide> return false; <ide> } <ide> <ide> public static function gmt($string = null) { <ide> $month = intval(date("n", $string)); <ide> $day = intval(date("j", $string)); <ide> $year = intval(date("Y", $string)); <del> <ide> return gmmktime($hour, $minute, $second, $month, $day, $year); <ide> } <ide>
2
Ruby
Ruby
add timeout to trash_paths
1406ee7eac845069cc4fefac0820b0d0248691bc
<ide><path>Library/Homebrew/cask/artifact/abstract_uninstall.rb <ide> def trash_paths(*paths, command: nil, **_) <ide> set item i of argv to (item i of argv as POSIX file) <ide> end repeat <ide> <del> tell application "Finder" <del> set trashedItems to (move argv to trash) <del> set output to "" <del> <del> repeat with i from 1 to (count trashedItems) <del> set trashedItem to POSIX path of (item i of trashedItems as string) <del> set output to output & trashedItem <del> if i < count trashedItems then <del> set output to output & character id 0 <del> end if <del> end repeat <del> <del> return output <del> end tell <add> try <add> with timeout of 30 seconds <add> tell application "Finder" <add> set trashedItems to (move argv to trash) <add> set output to "" <add> <add> repeat with i from 1 to (count trashedItems) <add> set trashedItem to POSIX path of (item i of trashedItems as string) <add> set output to output & trashedItem <add> if i < count trashedItems then <add> set output to output & character id 0 <add> end if <add> end repeat <add> <add> return output <add> end tell <add> end timeout <add> on error <add> -- Ignore errors (probably running under Azure) <add> return 0 <add> end try <ide> end run <ide> APPLESCRIPT <ide>
1
Text
Text
remove personal pronoun usage in fs.md
fb36266f28379fc7270a3d3e7423296e59e022b1
<ide><path>doc/api/fs.md <ide> By default, the stream will not emit a `'close'` event after it has been <ide> destroyed. This is the opposite of the default for other `Readable` streams. <ide> Set the `emitClose` option to `true` to change this behavior. <ide> <del>By providing the `fs` option it is possible to override the corresponding `fs` <del>implementations for `open`, `read` and `close`. When providing the `fs` option, <del>you must override `open`, `close` and `read`. <add>By providing the `fs` option, it is possible to override the corresponding `fs` <add>implementations for `open`, `read`, and `close`. When providing the `fs` option, <add>overrides for `open`, `read`, and `close` are required. <ide> <ide> ```js <ide> const fs = require('fs'); <ide> Set the `emitClose` option to `true` to change this behavior. <ide> By providing the `fs` option it is possible to override the corresponding `fs` <ide> implementations for `open`, `write`, `writev` and `close`. Overriding `write()` <ide> without `writev()` can reduce performance as some optimizations (`_writev()`) <del>will be disabled. When providing the `fs` option, you must override `open`, <del>`close` and at least one of `write` and `writev`. <add>will be disabled. When providing the `fs` option, overrides for `open`, <add>`close`, and at least one of `write` and `writev` are required. <ide> <ide> Like [`ReadStream`][], if `fd` is specified, [`WriteStream`][] will ignore the <ide> `path` argument and will use the specified file descriptor. This means that no <ide> in that they provide an object oriented API for working with files. <ide> If a `FileHandle` is not closed using the <ide> `filehandle.close()` method, it might automatically close the file descriptor <ide> and will emit a process warning, thereby helping to prevent memory leaks. <del>Please do not rely on this behavior in your code because it is unreliable and <del>your file may not be closed. Instead, always explicitly close `FileHandle`s. <add>Please do not rely on this behavior because it is unreliable and <add>the file may not be closed. Instead, always explicitly close `FileHandle`s. <ide> Node.js may change this behavior in the future. <ide> <ide> Instances of the `FileHandle` object are created internally by the
1
Text
Text
update the required package name
8ec0da22596dbf36843cd3a4792014220d4c08c4
<ide><path>curriculum/challenges/chinese/06-quality-assurance/advanced-node-and-express/set-up-the-environment.md <ide> title: 设置环境 <ide> <ide> 在接下来的挑战中,我们将会用到 <code>chat.pug</code> 文件。首先,你需要在你的 <code>routes.js</code> 文件中为 <code>/chat</code> 添加一个处理 GET 请求的路由,并给它传入 <code>ensureAuthenticated</code>。在回调函数中,我们需要让它 render <code>chat.pug</code> 文件,并在响应中包含 <code>{ user: req.user }</code> 信息。现在,请修改 <code>/auth/github/callback</code> 路由,让它可以像这样设置 user_id:<code>req.session.user_id = req.user.id</code>,并在设置完成后重定向至 <code>/chat</code>。 <ide> <del>我们还需要添加 <code>html</code> 和 <code>socket.io</code> 两个依赖项,并且像这样引入: <add>我们还需要添加 <code>http</code> 和 <code>socket.io</code> 两个依赖项,并且像这样引入: <ide> <ide> ```javascript <ide> const http = require('http').createServer(app); <ide> tests: <ide> - text: 应添加 Socket.IO 作为依赖。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'socket.io', 'Your project should list "socket.io" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <ide> - text: 应正确引入 <code>http</code>,并示例化为 <code>http</code>。 <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /http.*=.*require.*('|")http\1/gi, 'Your project should list "html" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /http.*=.*require.*('|")http\1/gi, 'Your project should list "http" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <ide> - text: 应正确引入 <code>socket.io</code>,并示例化为 <code>io</code>。 <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => {assert.match(data, /io.*=.*require.*('|")socket.io\1.*http/gi, 'You should correctly require and instantiate socket.io as io.');}, xhr => { throw new Error(xhr.statusText); }) <ide> - text: Socket.IO 应监听连接。 <ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/set-up-the-environment.md <ide> forumTopicId: 301566 <ide> <ide> The following challenges will make use of the <code>chat.pug</code> file. So, in your <code>routes.js</code> file, add a GET route pointing to <code>/chat</code> which makes use of <code>ensureAuthenticated</code>, and renders <code>chat.pug</code>, with <code>{ user: req.user }</code> passed as an argument to the response. Now, alter your existing <code>/auth/github/callback</code> route to set the <code>req.session.user_id = req.user.id</code>, and redirect to <code>/chat</code>. <ide> <del>Add <code>html</code> and <code>socket.io</code> as a dependency and require/instantiate them in your server defined as follows: <add>Add <code>http</code> and <code>socket.io</code> as a dependency and require/instantiate them in your server defined as follows: <ide> <ide> ```javascript <ide> const http = require('http').createServer(app); <ide> tests: <ide> - text: <code>socket.io</code> should be a dependency. <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/package.json') .then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, 'socket.io', 'Your project should list "socket.io" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <ide> - text: You should correctly require and instantiate <code>http</code> as <code>http</code>. <del> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /http.*=.*require.*('|")http\1/gi, 'Your project should list "html" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <add> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js') .then(data => { assert.match(data, /http.*=.*require.*('|")http\1/gi, 'Your project should list "http" as a dependency'); }, xhr => { throw new Error(xhr.statusText); }) <ide> - text: You should correctly require and instantiate <code>socket.io</code> as <code>io</code>. <ide> testString: getUserInput => $.get(getUserInput('url')+ '/_api/server.js').then(data => {assert.match(data, /io.*=.*require.*('|")socket.io\1.*http/gi, 'You should correctly require and instantiate socket.io as io.');}, xhr => { throw new Error(xhr.statusText); }) <ide> - text: Socket.IO should be listening for connections.
2
Javascript
Javascript
add react.createfactory() deprecation warning
f2fd484afdee1e4e25ee453bb7a544fa0558d172
<ide><path>packages/react-is/src/__tests__/ReactIs-test.js <ide> describe('ReactIs', () => { <ide> expect(ReactIs.isValidElementType(Context.Provider)).toEqual(true); <ide> expect(ReactIs.isValidElementType(Context.Consumer)).toEqual(true); <ide> if (!ReactFeatureFlags.disableCreateFactory) { <del> expect(ReactIs.isValidElementType(React.createFactory('div'))).toEqual( <del> true, <add> let factory; <add> expect(() => { <add> factory = React.createFactory('div'); <add> }).toWarnDev( <add> 'Warning: React.createFactory() is deprecated and will be removed in a ' + <add> 'future major release. Consider using JSX or use React.createElement() ' + <add> 'directly instead.', <add> {withoutStack: true}, <ide> ); <add> expect(ReactIs.isValidElementType(factory)).toEqual(true); <ide> } <ide> expect(ReactIs.isValidElementType(React.Fragment)).toEqual(true); <ide> expect(ReactIs.isValidElementType(React.StrictMode)).toEqual(true); <ide><path>packages/react/src/ReactElementValidator.js <ide> export function createElementWithValidation(type, props, children) { <ide> return element; <ide> } <ide> <add>let didWarnAboutDeprecatedCreateFactory = false; <add> <ide> export function createFactoryWithValidation(type) { <ide> const validatedFactory = createElementWithValidation.bind(null, type); <ide> validatedFactory.type = type; <del> // Legacy hook: remove it <ide> if (__DEV__) { <add> if (!didWarnAboutDeprecatedCreateFactory) { <add> didWarnAboutDeprecatedCreateFactory = true; <add> console.warn( <add> 'React.createFactory() is deprecated and will be removed in ' + <add> 'a future major release. Consider using JSX ' + <add> 'or use React.createElement() directly instead.', <add> ); <add> } <add> // Legacy hook: remove it <ide> Object.defineProperty(validatedFactory, 'type', { <ide> enumerable: false, <ide> get: function() { <ide><path>packages/react/src/__tests__/ReactElement-test.js <ide> describe('ReactElement', () => { <ide> expect(React.isValidElement({})).toEqual(false); <ide> expect(React.isValidElement('string')).toEqual(false); <ide> if (!ReactFeatureFlags.disableCreateFactory) { <del> expect(React.isValidElement(React.createFactory('div'))).toEqual(false); <add> let factory; <add> expect(() => { <add> factory = React.createFactory('div'); <add> }).toWarnDev( <add> 'Warning: React.createFactory() is deprecated and will be removed in a ' + <add> 'future major release. Consider using JSX or use React.createElement() ' + <add> 'directly instead.', <add> {withoutStack: true}, <add> ); <add> expect(React.isValidElement(factory)).toEqual(false); <ide> } <ide> expect(React.isValidElement(Component)).toEqual(false); <ide> expect(React.isValidElement({type: 'div', props: {}})).toEqual(false); <ide> describe('ReactElement', () => { <ide> expect(React.isValidElement({})).toEqual(false); <ide> expect(React.isValidElement('string')).toEqual(false); <ide> if (!ReactFeatureFlags.disableCreateFactory) { <del> expect(React.isValidElement(React.createFactory('div'))).toEqual(false); <add> let factory; <add> expect(() => { <add> factory = React.createFactory('div'); <add> }).toWarnDev( <add> 'Warning: React.createFactory() is deprecated and will be removed in a ' + <add> 'future major release. Consider using JSX or use React.createElement() ' + <add> 'directly instead.', <add> {withoutStack: true}, <add> ); <add> expect(React.isValidElement(factory)).toEqual(false); <ide> } <ide> expect(React.isValidElement(Component)).toEqual(false); <ide> expect(React.isValidElement({type: 'div', props: {}})).toEqual(false); <ide><path>packages/react/src/__tests__/ReactElementJSX-test.internal.js <ide> describe('ReactElement.jsx', () => { <ide> expect(React.isValidElement({})).toEqual(false); <ide> expect(React.isValidElement('string')).toEqual(false); <ide> if (!ReactFeatureFlags.disableCreateFactory) { <del> expect(React.isValidElement(React.createFactory('div'))).toEqual(false); <add> let factory; <add> expect(() => { <add> factory = React.createFactory('div'); <add> }).toWarnDev( <add> 'Warning: React.createFactory() is deprecated and will be removed in a ' + <add> 'future major release. Consider using JSX or use React.createElement() ' + <add> 'directly instead.', <add> {withoutStack: true}, <add> ); <add> expect(React.isValidElement(factory)).toEqual(false); <ide> } <ide> expect(React.isValidElement(Component)).toEqual(false); <ide> expect(React.isValidElement({type: 'div', props: {}})).toEqual(false); <ide> describe('ReactElement.jsx', () => { <ide> expect(React.isValidElement({})).toEqual(false); <ide> expect(React.isValidElement('string')).toEqual(false); <ide> if (!ReactFeatureFlags.disableCreateFactory) { <del> expect(React.isValidElement(React.createFactory('div'))).toEqual(false); <add> let factory; <add> expect(() => { <add> factory = React.createFactory('div'); <add> }).toWarnDev( <add> 'Warning: React.createFactory() is deprecated and will be removed in a ' + <add> 'future major release. Consider using JSX or use React.createElement() ' + <add> 'directly instead.', <add> {withoutStack: true}, <add> ); <add> expect(React.isValidElement(factory)).toEqual(false); <ide> } <ide> expect(React.isValidElement(Component)).toEqual(false); <ide> expect(React.isValidElement({type: 'div', props: {}})).toEqual(false); <ide><path>packages/react/src/__tests__/ReactElementValidator-test.internal.js <ide> describe('ReactElementValidator', () => { <ide> return <div />; <ide> } <ide> <del> let TestFactory = React.createFactory(TestComponent); <add> let TestFactory; <add> <add> expect(() => { <add> TestFactory = React.createFactory(TestComponent); <add> }).toWarnDev( <add> 'Warning: React.createFactory() is deprecated and will be removed in a ' + <add> 'future major release. Consider using JSX or use React.createElement() ' + <add> 'directly instead.', <add> {withoutStack: true}, <add> ); <add> <ide> expect( <ide> () => TestFactory.type, <ide> ).toWarnDev(
5
Text
Text
fix typo in streams.md
e429f9a42af94f039621a1bf9f21ad424aa00558
<ide><path>doc/api/stream.md <ide> added: v0.9.4 <ide> * {Error} <ide> <ide> The `'error'` event may be emitted by a Readable implementation at any time. <del>Typically, this may occur if the underlying stream in unable to generate data <add>Typically, this may occur if the underlying stream is unable to generate data <ide> due to an underlying internal failure, or when a stream implementation attempts <ide> to push an invalid chunk of data. <ide>
1
Ruby
Ruby
make helper methods in tests to private
62b10bfc445837c3e6e466449743605d6fca3811
<ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb <ide> def test_preload_sti_middle_relation <ide> club1.members.sort_by(&:id) <ide> end <ide> <del> def make_model(name) <del> Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } } <del> end <del> <ide> def test_ordered_has_many_through <ide> person_prime = Class.new(ActiveRecord::Base) do <ide> def self.name; "Person"; end <ide> def test_no_pk_join_model_callbacks <ide> assert after_destroy_called, "after destroy should be called" <ide> end <ide> <del> def make_no_pk_hm_t <del> lesson = make_model "Lesson" <del> student = make_model "Student" <del> <del> lesson_student = make_model "LessonStudent" <del> lesson_student.table_name = "lessons_students" <del> <del> lesson_student.belongs_to :lesson, anonymous_class: lesson <del> lesson_student.belongs_to :student, anonymous_class: student <del> lesson.has_many :lesson_students, anonymous_class: lesson_student <del> lesson.has_many :students, through: :lesson_students, anonymous_class: student <del> [lesson, lesson_student, student] <del> end <del> <ide> def test_pk_is_not_required_for_join <ide> post = Post.includes(:scategories).first <ide> post2 = Post.includes(:categories).first <ide> def test_incorrectly_ordered_through_associations <ide> ) <ide> end <ide> end <add> <add> private <add> def make_model(name) <add> Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } } <add> end <add> <add> def make_no_pk_hm_t <add> lesson = make_model "Lesson" <add> student = make_model "Student" <add> <add> lesson_student = make_model "LessonStudent" <add> lesson_student.table_name = "lessons_students" <add> <add> lesson_student.belongs_to :lesson, anonymous_class: lesson <add> lesson_student.belongs_to :student, anonymous_class: student <add> lesson.has_many :lesson_students, anonymous_class: lesson_student <add> lesson.has_many :students, through: :lesson_students, anonymous_class: student <add> [lesson, lesson_student, student] <add> end <ide> end
1
Javascript
Javascript
sync new haste features from upstream
5b4244d75578c17c10e1f3ee5a364e1c883728cf
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/HasteMap.js <ide> const Promise = require('promise'); <ide> const GENERIC_PLATFORM = 'generic'; <ide> <ide> class HasteMap { <del> constructor({ fastfs, moduleCache, helpers }) { <add> constructor({ extensions, fastfs, moduleCache, helpers }) { <add> this._extensions = extensions; <ide> this._fastfs = fastfs; <ide> this._moduleCache = moduleCache; <ide> this._helpers = helpers; <ide> class HasteMap { <ide> build() { <ide> this._map = Object.create(null); <ide> <del> let promises = this._fastfs.findFilesByExt('js', { <add> let promises = this._fastfs.findFilesByExts(this._extensions, { <ide> ignore: (file) => this._helpers.isNodeModulesDir(file), <ide> }).map(file => this._processHasteModule(file)); <ide> <ide> class HasteMap { <ide> } <ide> } <ide> <del> if (this._helpers.extname(absPath) === 'js' || <del> this._helpers.extname(absPath) === 'json') { <add> if (this._extensions.indexOf(this._helpers.extname(absPath)) !== -1) { <ide> if (path.basename(absPath) === 'package.json') { <ide> return this._processHastePackage(absPath); <ide> } else { <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionRequest.js <ide> class ResolutionRequest { <ide> ); <ide> } <ide> <del> getOrderedDependencies(response) { <del> return Promise.resolve().then(() => { <add> getOrderedDependencies(response, mocksPattern) { <add> return this._getAllMocks(mocksPattern).then(mocks => { <add> response.setMocks(mocks); <add> <ide> const entry = this._moduleCache.getModule(this._entryPath); <ide> const visited = Object.create(null); <ide> visited[entry.hash()] = true; <ide> class ResolutionRequest { <ide> depNames.map(name => this.resolveDependency(mod, name)) <ide> ).then((dependencies) => [depNames, dependencies]) <ide> ).then(([depNames, dependencies]) => { <add> if (mocks) { <add> return mod.getName().then(name => { <add> if (mocks[name]) { <add> const mockModule = <add> this._moduleCache.getModule(mocks[name]); <add> depNames.push(name); <add> dependencies.push(mockModule); <add> } <add> return [depNames, dependencies]; <add> }); <add> } <add> return Promise.resolve([depNames, dependencies]); <add> }).then(([depNames, dependencies]) => { <ide> let p = Promise.resolve(); <del> <ide> const filteredPairs = []; <ide> <ide> dependencies.forEach((modDep, i) => { <ide> class ResolutionRequest { <ide> )); <ide> } <ide> <add> _getAllMocks(pattern) { <add> // Take all mocks in all the roots into account. This is necessary <add> // because currently mocks are global: any module can be mocked by <add> // any mock in the system. <add> let mocks = null; <add> if (pattern) { <add> mocks = Object.create(null); <add> this._fastfs.matchFilesByPattern(pattern).forEach(file => <add> mocks[path.basename(file, path.extname(file))] = file <add> ); <add> } <add> return Promise.resolve(mocks); <add> } <add> <ide> _resolveHasteDependency(fromModule, toModuleName) { <ide> toModuleName = normalizePath(toModuleName); <ide> <ide> class ResolutionRequest { <ide> _resetResolutionCache() { <ide> this._immediateResolutionCache = Object.create(null); <ide> } <add> <ide> } <ide> <ide> <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionResponse.js <ide> class ResolutionResponse { <ide> this.dependencies = []; <ide> this.asyncDependencies = []; <ide> this.mainModuleId = null; <add> this.mocks = null; <ide> this._mappings = Object.create(null); <ide> this._finalized = false; <ide> } <ide> class ResolutionResponse { <ide> } <ide> } <ide> <add> setMocks(mocks) { <add> this.mocks = mocks; <add> } <add> <ide> getResolvedDependencyPairs(module) { <ide> this._assertFinalized(); <ide> return this._mappings[module.hash()]; <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js <ide> describe('DependencyGraph', function() { <ide> }); <ide> }); <ide> }); <add> <add> describe('Extensions', () => { <add> pit('supports custom file extensions', () => { <add> var root = '/root'; <add> fs.__setMockFilesystem({ <add> 'root': { <add> 'index.jsx': [ <add> '/**', <add> ' * @providesModule index', <add> ' */', <add> 'require("a")', <add> ].join('\n'), <add> 'a.coffee': [ <add> '/**', <add> ' * @providesModule a', <add> ' */', <add> ].join('\n'), <add> 'X.js': '', <add> }, <add> }); <add> <add> var dgraph = new DependencyGraph({ <add> ...defaults, <add> roots: [root], <add> extensions: ['jsx', 'coffee'], <add> }); <add> <add> return dgraph.matchFilesByPattern('.*') <add> .then(files => { <add> expect(files).toEqual([ <add> '/root/index.jsx', '/root/a.coffee', <add> ]); <add> }) <add> .then(() => getOrderedDependenciesAsJSON(dgraph, '/root/index.jsx')) <add> .then(deps => { <add> expect(deps).toEqual([ <add> { <add> dependencies: ['a'], <add> id: 'index', <add> isAsset: false, <add> isAsset_DEPRECATED: false, <add> isJSON: false, <add> isPolyfill: false, <add> path: '/root/index.jsx', <add> resolution: undefined, <add> }, <add> { <add> dependencies: [], <add> id: 'a', <add> isAsset: false, <add> isAsset_DEPRECATED: false, <add> isJSON: false, <add> isPolyfill: false, <add> path: '/root/a.coffee', <add> resolution: undefined, <add> }, <add> ]); <add> }); <add> }); <add> }); <add> <add> describe('Mocks', () => { <add> pit('resolves to null if mocksPattern is not specified', () => { <add> var root = '/root'; <add> fs.__setMockFilesystem({ <add> 'root': { <add> '__mocks': { <add> 'A.js': '', <add> }, <add> 'index.js': '', <add> }, <add> }); <add> var dgraph = new DependencyGraph({ <add> ...defaults, <add> roots: [root], <add> }); <add> <add> return dgraph.getDependencies('/root/index.js') <add> .then(response => response.finalize()) <add> .then(response => { <add> expect(response.mocks).toBe(null); <add> }); <add> }); <add> <add> pit('retrieves a list of all mocks in the system', () => { <add> var root = '/root'; <add> fs.__setMockFilesystem({ <add> 'root': { <add> '__mocks__': { <add> 'A.js': '', <add> 'b.js': '', <add> }, <add> 'b.js': [ <add> '/**', <add> ' * @providesModule b', <add> ' */', <add> ].join('\n'), <add> }, <add> }); <add> <add> var dgraph = new DependencyGraph({ <add> ...defaults, <add> roots: [root], <add> mocksPattern: /(?:[\\/]|^)__mocks__[\\/]([^\/]+)\.js$/, <add> }); <add> <add> return dgraph.getDependencies('/root/b.js') <add> .then(response => response.finalize()) <add> .then(response => { <add> expect(response.mocks).toEqual({ <add> A: '/root/__mocks__/A.js', <add> b: '/root/__mocks__/b.js', <add> }); <add> }); <add> }); <add> <add> pit('adds mocks as a dependency of their actual module', () => { <add> var root = '/root'; <add> fs.__setMockFilesystem({ <add> 'root': { <add> '__mocks__': { <add> 'A.js': [ <add> 'require("b");', <add> ].join('\n'), <add> 'b.js': '', <add> }, <add> 'A.js': [ <add> '/**', <add> ' * @providesModule A', <add> ' */', <add> 'require("foo");', <add> ].join('\n'), <add> 'foo.js': [ <add> '/**', <add> ' * @providesModule foo', <add> ' */', <add> ].join('\n'), <add> }, <add> }); <add> <add> var dgraph = new DependencyGraph({ <add> ...defaults, <add> roots: [root], <add> mocksPattern: /(?:[\\/]|^)__mocks__[\\/]([^\/]+)\.js$/, <add> }); <add> <add> return getOrderedDependenciesAsJSON(dgraph, '/root/A.js') <add> .then(deps => { <add> expect(deps).toEqual([ <add> { <add> path: '/root/A.js', <add> isJSON: false, <add> isAsset: false, <add> isAsset_DEPRECATED: false, <add> isPolyfill: false, <add> id: 'A', <add> dependencies: ['foo', 'A'], <add> }, <add> { <add> path: '/root/foo.js', <add> isJSON: false, <add> isAsset: false, <add> isAsset_DEPRECATED: false, <add> isPolyfill: false, <add> id: 'foo', <add> dependencies: [], <add> }, <add> { <add> path: '/root/__mocks__/A.js', <add> isJSON: false, <add> isAsset: false, <add> isAsset_DEPRECATED: false, <add> isPolyfill: false, <add> id: '/root/__mocks__/A.js', <add> dependencies: ['b'], <add> }, <add> ]); <add> }); <add> }); <add> }); <ide> }); <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/index.js <ide> class DependencyGraph { <ide> providesModuleNodeModules, <ide> platforms, <ide> cache, <add> extensions, <add> mocksPattern, <add> extractRequires, <ide> }) { <ide> this._opts = { <ide> activity: activity || defaultActivity, <ide> class DependencyGraph { <ide> providesModuleNodeModules, <ide> platforms: platforms || [], <ide> cache, <add> extensions: extensions || ['js', 'json'], <add> mocksPattern, <add> extractRequires, <ide> }; <ide> this._cache = this._opts.cache; <ide> this._helpers = new Helpers(this._opts); <ide> class DependencyGraph { <ide> const allRoots = this._opts.roots.concat(this._opts.assetRoots_DEPRECATED); <ide> this._crawling = crawl(allRoots, { <ide> ignore: this._opts.ignoreFilePath, <del> exts: ['js', 'json'].concat(this._opts.assetExts), <add> exts: this._opts.extensions.concat(this._opts.assetExts), <ide> fileWatcher: this._opts.fileWatcher, <ide> }); <ide> this._crawling.then((files) => activity.endEvent(crawlActivity)); <ide> class DependencyGraph { <ide> <ide> this._fastfs.on('change', this._processFileChange.bind(this)); <ide> <del> this._moduleCache = new ModuleCache(this._fastfs, this._cache); <add> this._moduleCache = new ModuleCache( <add> this._fastfs, <add> this._cache, <add> this._opts.extractRequires <add> ); <ide> <ide> this._hasteMap = new HasteMap({ <ide> fastfs: this._fastfs, <add> extensions: this._opts.extensions, <ide> moduleCache: this._moduleCache, <ide> assetExts: this._opts.exts, <ide> helpers: this._helpers, <ide> class DependencyGraph { <ide> const response = new ResolutionResponse(); <ide> <ide> return Promise.all([ <del> req.getOrderedDependencies(response), <add> req.getOrderedDependencies(response, this._opts.mocksPattern), <ide> req.getAsyncDependencies(response), <ide> ]).then(() => response); <ide> }); <ide> } <ide> <add> matchFilesByPattern(pattern) { <add> return this.load().then(() => this._fastfs.matchFilesByPattern(pattern)); <add> } <add> <ide> _getRequestPlatform(entryPath, platform) { <ide> if (platform == null) { <ide> platform = getPlatformExtension(entryPath); <ide> class DependencyGraph { <ide> return this._loading; <ide> }); <ide> } <add> <ide> } <ide> <ide> function NotFoundError() { <ide><path>packager/react-packager/src/DependencyResolver/Module.js <ide> const docblock = require('./DependencyGraph/docblock'); <ide> const isAbsolutePath = require('absolute-path'); <ide> const path = require('path'); <del>const replacePatterns = require('./replacePatterns'); <add>const extractRequires = require('./lib/extractRequires'); <ide> <ide> class Module { <ide> <del> constructor(file, fastfs, moduleCache, cache) { <add> constructor(file, fastfs, moduleCache, cache, extractor) { <ide> if (!isAbsolutePath(file)) { <ide> throw new Error('Expected file to be absolute path but got ' + file); <ide> } <ide> class Module { <ide> this._fastfs = fastfs; <ide> this._moduleCache = moduleCache; <ide> this._cache = cache; <add> this._extractor = extractor; <ide> } <ide> <ide> isHaste() { <del> return this._cache.get(this.path, 'haste', () => <del> this._read().then(data => !!data.id) <del> ); <add> return this._read().then(data => !!data.id); <ide> } <ide> <ide> getName() { <ide> class Module { <ide> } <ide> <ide> getDependencies() { <del> return this._cache.get(this.path, 'dependencies', () => <del> this._read().then(data => data.dependencies) <del> ); <del> } <del> <del> invalidate() { <del> this._cache.invalidate(this.path); <add> return this._read().then(data => data.dependencies); <ide> } <ide> <ide> getAsyncDependencies() { <ide> return this._read().then(data => data.asyncDependencies); <ide> } <ide> <add> invalidate() { <add> this._cache.invalidate(this.path); <add> } <add> <ide> _read() { <ide> if (!this._reading) { <ide> this._reading = this._fastfs.readFile(this.path).then(content => { <ide> class Module { <ide> if ('extern' in moduleDocBlock) { <ide> data.dependencies = []; <ide> } else { <del> var dependencies = extractRequires(content); <add> var dependencies = (this._extractor || extractRequires)(content).deps; <ide> data.dependencies = dependencies.sync; <ide> data.asyncDependencies = dependencies.async; <ide> } <ide> class Module { <ide> } <ide> } <ide> <del>/** <del> * Extract all required modules from a `code` string. <del> */ <del>const blockCommentRe = /\/\*(.|\n)*?\*\//g; <del>const lineCommentRe = /\/\/.+(\n|$)/g; <del>function extractRequires(code) { <del> var deps = { <del> sync: [], <del> async: [], <del> }; <del> <del> code <del> .replace(blockCommentRe, '') <del> .replace(lineCommentRe, '') <del> // Parse sync dependencies. See comment below for further detils. <del> .replace(replacePatterns.IMPORT_RE, (match, pre, quot, dep, post) => { <del> deps.sync.push(dep); <del> return match; <del> }) <del> .replace(replacePatterns.EXPORT_RE, (match, pre, quot, dep, post) => { <del> deps.sync.push(dep); <del> return match; <del> }) <del> // Parse the sync dependencies this module has. When the module is <del> // required, all it's sync dependencies will be loaded into memory. <del> // Sync dependencies can be defined either using `require` or the ES6 <del> // `import` or `export` syntaxes: <del> // var dep1 = require('dep1'); <del> .replace(replacePatterns.REQUIRE_RE, (match, pre, quot, dep, post) => { <del> deps.sync.push(dep); <del> }) <del> // Parse async dependencies this module has. As opposed to what happens <del> // with sync dependencies, when the module is required, it's async <del> // dependencies won't be loaded into memory. This is deferred till the <del> // code path gets to the import statement: <del> // System.import('dep1') <del> .replace(replacePatterns.SYSTEM_IMPORT_RE, (match, pre, quot, dep, post) => { <del> deps.async.push([dep]); <del> return match; <del> }); <del> <del> return deps; <del>} <del> <ide> module.exports = Module; <ide><path>packager/react-packager/src/DependencyResolver/ModuleCache.js <ide> const path = require('path'); <ide> <ide> class ModuleCache { <ide> <del> constructor(fastfs, cache) { <add> constructor(fastfs, cache, extractRequires) { <ide> this._moduleCache = Object.create(null); <ide> this._packageCache = Object.create(null); <ide> this._fastfs = fastfs; <ide> this._cache = cache; <add> this._extractRequires = extractRequires; <ide> fastfs.on('change', this._processFileChange.bind(this)); <ide> } <ide> <ide> class ModuleCache { <ide> this._fastfs, <ide> this, <ide> this._cache, <add> this._extractRequires <ide> ); <ide> } <ide> return this._moduleCache[filePath]; <ide><path>packager/react-packager/src/DependencyResolver/__tests__/Module-test.js <ide> jest <ide> .dontMock('absolute-path') <ide> .dontMock('../fastfs') <del> .dontMock('../replacePatterns') <add> .dontMock('../lib/extractRequires') <add> .dontMock('../lib/replacePatterns') <ide> .dontMock('../DependencyGraph/docblock') <ide> .dontMock('../Module'); <ide> <ide> jest <ide> .mock('fs'); <ide> <del>var Fastfs = require('../fastfs'); <del>var Module = require('../Module'); <del>var ModuleCache = require('../ModuleCache'); <del>var Promise = require('promise'); <del>var fs = require('fs'); <add>const Fastfs = require('../fastfs'); <add>const Module = require('../Module'); <add>const ModuleCache = require('../ModuleCache'); <add>const Promise = require('promise'); <add>const fs = require('fs'); <ide> <ide> describe('Module', () => { <ide> const fileWatcher = { <ide> on: () => this, <ide> isWatchman: () => Promise.resolve(false), <ide> }; <ide> <add> const Cache = jest.genMockFn(); <add> Cache.prototype.get = jest.genMockFn().mockImplementation( <add> (filepath, field, cb) => cb(filepath) <add> ); <add> Cache.prototype.invalidate = jest.genMockFn(); <add> Cache.prototype.end = jest.genMockFn(); <add> <add> <ide> describe('Async Dependencies', () => { <ide> function expectAsyncDependenciesToEqual(expected) { <del> var fastfs = new Fastfs( <add> const fastfs = new Fastfs( <ide> 'test', <ide> ['/root'], <ide> fileWatcher, <ide> {crawling: Promise.resolve(['/root/index.js']), ignore: []}, <ide> ); <add> const cache = new Cache(); <ide> <ide> return fastfs.build().then(() => { <del> var module = new Module('/root/index.js', fastfs, new ModuleCache(fastfs)); <add> const module = new Module( <add> '/root/index.js', <add> fastfs, <add> new ModuleCache(fastfs, cache), <add> cache <add> ); <ide> <ide> return module.getAsyncDependencies().then(actual => <ide> expect(actual).toEqual(expected) <ide> describe('Module', () => { <ide> return expectAsyncDependenciesToEqual([['dep1']]); <ide> }); <ide> }); <add> <add> describe('Extrators', () => { <add> <add> function createModuleWithExtractor(extractor) { <add> const fastfs = new Fastfs( <add> 'test', <add> ['/root'], <add> fileWatcher, <add> {crawling: Promise.resolve(['/root/index.js']), ignore: []}, <add> ); <add> const cache = new Cache(); <add> <add> return fastfs.build().then(() => { <add> return new Module( <add> '/root/index.js', <add> fastfs, <add> new ModuleCache(fastfs, cache), <add> cache, <add> extractor <add> ); <add> }); <add> } <add> <add> pit('uses custom require extractors if specified', () => { <add> fs.__setMockFilesystem({ <add> 'root': { <add> 'index.js': '', <add> }, <add> }); <add> <add> return createModuleWithExtractor( <add> code => ({deps: {sync: ['foo', 'bar']}}) <add> ).then(module => <add> module.getDependencies().then(actual => <add> expect(actual).toEqual(['foo', 'bar']) <add> ) <add> ); <add> }); <add> }); <ide> }); <ide><path>packager/react-packager/src/DependencyResolver/fastfs.js <ide> class Fastfs extends EventEmitter { <ide> return [].concat(...this._roots.map(root => root.getFiles())); <ide> } <ide> <del> findFilesByExt(ext, { ignore }) { <del> return this.getAllFiles() <del> .filter( <del> file => file.ext() === ext && (!ignore || !ignore(file.path)) <del> ) <del> .map(file => file.path); <add> findFilesByExt(ext, { ignore } = {}) { <add> return this.findFilesByExts([ext], {ignore}); <ide> } <ide> <del> findFilesByExts(exts) { <add> findFilesByExts(exts, { ignore } = {}) { <ide> return this.getAllFiles() <del> .filter(file => exts.indexOf(file.ext()) !== -1) <add> .filter(file => ( <add> exts.indexOf(file.ext()) !== -1 && (!ignore || !ignore(file.path)) <add> )) <ide> .map(file => file.path); <ide> } <ide> <del> findFilesByName(name, { ignore }) { <add> findFilesByName(name, { ignore } = {}) { <ide> return this.getAllFiles() <ide> .filter( <ide> file => path.basename(file.path) === name && <ide> class Fastfs extends EventEmitter { <ide> .map(file => file.path); <ide> } <ide> <add> matchFilesByPattern(pattern) { <add> return this.getAllFiles() <add> .filter(file => file.path.match(pattern)) <add> .map(file => file.path); <add> } <add> <ide> readFile(filePath) { <ide> const file = this._getFile(filePath); <ide> if (!file) { <ide><path>packager/react-packager/src/DependencyResolver/lib/extractRequires.js <add>/** <add> * Copyright (c) 2015-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>'use strict'; <add> <add>const replacePatterns = require('./replacePatterns'); <add> <add>/** <add> * Extract all required modules from a `code` string. <add> */ <add>const blockCommentRe = /\/\*(.|\n)*?\*\//g; <add>const lineCommentRe = /\/\/.+(\n|$)/g; <add>function extractRequires(code) { <add> var deps = { <add> sync: [], <add> async: [], <add> }; <add> <add> code = code <add> .replace(blockCommentRe, '') <add> .replace(lineCommentRe, '') <add> // Parse the sync dependencies this module has. When the module is <add> // required, all it's sync dependencies will be loaded into memory. <add> // Sync dependencies can be defined either using `require` or the ES6 <add> // `import` or `export` syntaxes: <add> // var dep1 = require('dep1'); <add> .replace(replacePatterns.IMPORT_RE, (match, pre, quot, dep, post) => { <add> deps.sync.push(dep); <add> return match; <add> }) <add> .replace(replacePatterns.EXPORT_RE, (match, pre, quot, dep, post) => { <add> deps.sync.push(dep); <add> return match; <add> }) <add> .replace(replacePatterns.REQUIRE_RE, (match, pre, quot, dep, post) => { <add> deps.sync.push(dep); <add> return match; <add> }) <add> // Parse async dependencies this module has. As opposed to what happens <add> // with sync dependencies, when the module is required, it's async <add> // dependencies won't be loaded into memory. This is deferred till the <add> // code path gets to the import statement: <add> // System.import('dep1') <add> .replace(replacePatterns.SYSTEM_IMPORT_RE, (match, pre, quot, dep, post) => { <add> deps.async.push([dep]); <add> return match; <add> }); <add> <add> return {code, deps}; <add>} <add> <add>module.exports = extractRequires; <ide><path>packager/react-packager/src/DependencyResolver/lib/replacePatterns.js <add>/** <add> * Copyright (c) 2015-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> <add>'use strict'; <add> <add>exports.IMPORT_RE = /(\bimport\s+(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g; <add>exports.EXPORT_RE = /(\bexport\s+(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g; <add>exports.REQUIRE_RE = /(\brequire\s*?\(\s*?)(['"])([^'"]+)(\2\s*?\))/g; <add>exports.SYSTEM_IMPORT_RE = /(\bSystem\.import\s*?\(\s*?)(['"])([^'"]+)(\2\s*?\))/g; <ide><path>packager/react-packager/src/Resolver/__tests__/Resolver-test.js <ide> <ide> jest.dontMock('../') <ide> .dontMock('underscore') <del> .dontMock('../../DependencyResolver/replacePatterns'); <add> .dontMock('../../DependencyResolver/lib/extractRequires') <add> .dontMock('../../DependencyResolver/lib/replacePatterns'); <ide> <ide> jest.mock('path'); <ide> <ide><path>packager/react-packager/src/Resolver/index.js <ide> const path = require('path'); <ide> const Activity = require('../Activity'); <ide> const DependencyGraph = require('../DependencyResolver/DependencyGraph'); <del>const replacePatterns = require('../DependencyResolver/replacePatterns'); <add>const replacePatterns = require('../DependencyResolver/lib/replacePatterns'); <ide> const Polyfill = require('../DependencyResolver/Polyfill'); <ide> const declareOpts = require('../lib/declareOpts'); <ide> const Promise = require('promise');
13
Python
Python
update compatibility [ci skip]
24cecdb44fe7349f7382dddeeb6ce047c32db813
<ide><path>examples/training/train_new_entity_type.py <ide> * Training: https://spacy.io/usage/training <ide> * NER: https://spacy.io/usage/linguistic-features#named-entities <ide> <del>Compatible with: spaCy v2.0.0+ <add>Compatible with: spaCy v2.1.0+ <ide> Last tested with: v2.1.0 <ide> """ <ide> from __future__ import unicode_literals, print_function
1
Ruby
Ruby
enforce https for github.com urls
11ebfdafb227ae36559f65c6bd098172301e82f0
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_urls <ide> %r{^http://(?:[^/]*\.)?bintray\.com/}, <ide> %r{^http://tools\.ietf\.org/}, <ide> %r{^http://launchpad\.net/}, <add> %r{^http://github\.com/}, <ide> %r{^http://bitbucket\.org/}, <ide> %r{^http://anonscm\.debian\.org/}, <ide> %r{^http://cpan\.metacpan\.org/},
1
PHP
PHP
fix failing tests
4a0df837830a035e0d2261373782370fcc386163
<ide><path>lib/Cake/Test/Case/Console/Command/SchemaShellTest.php <ide> class SchemaShellTest extends CakeTestCase { <ide> * <ide> * @var array <ide> */ <del> public $fixtures = array('core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author', <del> 'core.comment', 'core.test_plugin_comment' <add> public $fixtures = array( <add> 'core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author', <add> 'core.comment', 'core.test_plugin_comment', 'core.aco', 'core.aro', 'core.aros_aco', <ide> ); <ide> <ide> /** <ide> public function testGenerateModels() { <ide> public function testGenerateExclude() { <ide> $this->db->cacheSources = false; <ide> $this->Shell->params = array( <add> 'connection' => 'test', <ide> 'force' => false, <add> 'models' => 'Aro, Aco, Permission', <ide> 'overwrite' => true, <del> 'exclude' => 'acos,aros' <add> 'exclude' => 'acos, aros', <ide> ); <ide> $this->Shell->startup(); <ide> $this->Shell->Schema->path = TMP . 'tests' . DS; <ide> public function testGenerateExclude() { <ide> $this->file = new File(TMP . 'tests' . DS . 'schema.php'); <ide> $contents = $this->file->read(); <ide> <del> $this->assertNotRegExp('/public \$aros = array\(/', $contents); <del> $this->assertNotRegExp('/public \$acos = array\(/', $contents); <del> $this->assertRegExp('/public \$aros_acos = array\(/', $contents); <add> $this->assertNotContains('public $acos = array(', $contents); <add> $this->assertNotContains('public $aros = array(', $contents); <add> $this->assertContains('public $aros_acos = array(', $contents); <ide> } <ide> <ide> /**
1
Go
Go
fix the rootpath for auth
e726bdcce2606acef136a4d5ba47e367d9e461df
<ide><path>auth/auth.go <ide> type AuthConfig struct { <ide> rootPath string `json:-` <ide> } <ide> <add>func NewAuthConfig(username, password, email, rootPath string) *AuthConfig { <add> return &AuthConfig{ <add> Username: username, <add> Password: password, <add> Email: email, <add> rootPath: rootPath, <add> } <add>} <add> <ide> // create a base64 encoded auth string to store in config <ide> func EncodeAuth(authConfig *AuthConfig) string { <ide> authStr := authConfig.Username + ":" + authConfig.Password <ide><path>commands.go <ide> func (srv *Server) CmdLogin(stdin io.ReadCloser, stdout io.Writer, args ...strin <ide> password = srv.runtime.authConfig.Password <ide> email = srv.runtime.authConfig.Email <ide> } <del> newAuthConfig := &auth.AuthConfig{Username: username, Password: password, Email: email} <add> newAuthConfig := auth.NewAuthConfig(username, password, email, srv.runtime.root) <ide> status, err := auth.Login(newAuthConfig) <ide> if err != nil { <ide> fmt.Fprintf(stdout, "Error : %s\n", err)
2
PHP
PHP
allow tuple notation for actions
2b3902a77f9f8193ab7ee157530e97d1b96cfa05
<ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> protected function toRoute($route, $parameters, $absolute) <ide> /** <ide> * Get the URL to a controller action. <ide> * <del> * @param string $action <add> * @param string|array $action <ide> * @param mixed $parameters <ide> * @param bool $absolute <ide> * @return string <ide> public function action($action, $parameters = [], $absolute = true) <ide> /** <ide> * Format the given controller action. <ide> * <del> * @param string $action <add> * @param string|array $action <ide> * @return string <ide> */ <ide> protected function formatAction($action) <ide> { <add> if (is_array($action)) { <add> $action = implode('@', $action); <add> } <add> <ide> if ($this->rootNamespace && ! (strpos($action, '\\') === 0)) { <ide> return $this->rootNamespace.'\\'.$action; <ide> } else { <ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> public function testBasicRouteGeneration() <ide> $this->assertEquals('/foo/bar/taylor/breeze/otwell?fly=wall', $url->route('bar', ['taylor', 'otwell', 'fly' => 'wall'], false)); <ide> $this->assertEquals('https://www.foo.com/foo/baz', $url->route('baz')); <ide> $this->assertEquals('http://www.foo.com/foo/bam', $url->action('foo@bar')); <add> $this->assertEquals('http://www.foo.com/foo/bam', $url->action(['foo', 'bar'])); <ide> $this->assertEquals('http://www.foo.com/foo/invoke', $url->action('InvokableActionStub')); <ide> $this->assertEquals('http://www.foo.com/foo/bar/taylor/breeze/otwell?wall&woz', $url->route('bar', ['wall', 'woz', 'boom' => 'otwell', 'baz' => 'taylor'])); <ide> $this->assertEquals('http://www.foo.com/foo/bar/taylor/breeze/otwell?wall&woz', $url->route('bar', ['taylor', 'otwell', 'wall', 'woz']));
2
PHP
PHP
fix double column reflection
7dc4a86c8252d1cae7267f1ba626dd4e2cf8455f
<ide><path>src/Database/Schema/MysqlSchema.php <ide> protected function _convertColumn($column) <ide> <ide> $col = strtolower($matches[1]); <ide> $length = $precision = null; <del> if (isset($matches[2])) { <add> if (isset($matches[2]) && strlen($matches[2])) { <ide> $length = $matches[2]; <ide> if (strpos($matches[2], ',') !== false) { <ide> list($length, $precision) = explode(',', $length); <ide> protected function _convertColumn($column) <ide> return ['type' => TableSchema::TYPE_UUID, 'length' => null]; <ide> } <ide> if ($col === 'char') { <del> return ['type' => TableSchema::TYPE_STRING, 'fixed' => true, 'length' => $length]; <add> return ['type' => TableSchema::TYPE_STRING, 'length' => $length, 'fixed' => true]; <ide> } <ide> if (strpos($col, 'char') !== false) { <ide> return ['type' => TableSchema::TYPE_STRING, 'length' => $length]; <ide><path>src/Database/Schema/SqlserverSchema.php <ide> public function describeColumnSql($tableName, $config) <ide> protected function _convertColumn($col, $length = null, $precision = null, $scale = null) <ide> { <ide> $col = strtolower($col); <del> $length = (int)$length; <del> $precision = (int)$precision; <del> $scale = (int)$scale; <add> $length = $length !== null ? (int)$length : $length; <add> $precision = $precision !== null ? (int)$precision : $precision; <add> $scale = $scale !== null ? (int)$scale : $scale; <ide> <ide> if (in_array($col, ['date', 'time'])) { <ide> return ['type' => $col, 'length' => null]; <ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php <ide> public static function convertColumnProvider() <ide> ], <ide> [ <ide> 'VARCHAR(255)', <del> ['type' => 'string', 'length' => 255] <add> ['type' => 'string', 'length' => 255, 'collate' => 'utf8_general_ci'] <ide> ], <ide> [ <ide> 'CHAR(25)', <del> ['type' => 'string', 'length' => 25, 'fixed' => true] <add> ['type' => 'string', 'length' => 25, 'fixed' => true, 'collate' => 'utf8_general_ci'] <ide> ], <ide> [ <ide> 'CHAR(36)', <ide> public static function convertColumnProvider() <ide> ], <ide> [ <ide> 'TEXT', <del> ['type' => 'text', 'length' => null] <add> ['type' => 'text', 'length' => null, 'collate' => 'utf8_general_ci'] <ide> ], <ide> [ <ide> 'TINYTEXT', <del> ['type' => 'text', 'length' => TableSchema::LENGTH_TINY] <add> ['type' => 'text', 'length' => TableSchema::LENGTH_TINY, 'collate' => 'utf8_general_ci'] <ide> ], <ide> [ <ide> 'MEDIUMTEXT', <del> ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM] <add> ['type' => 'text', 'length' => TableSchema::LENGTH_MEDIUM, 'collate' => 'utf8_general_ci'] <ide> ], <ide> [ <ide> 'LONGTEXT', <del> ['type' => 'text', 'length' => TableSchema::LENGTH_LONG] <add> ['type' => 'text', 'length' => TableSchema::LENGTH_LONG, 'collate' => 'utf8_general_ci'] <ide> ], <ide> [ <ide> 'TINYBLOB', <ide> public function testConvertColumn($type, $expected) <ide> $expected += [ <ide> 'null' => true, <ide> 'default' => 'Default value', <del> 'collate' => 'utf8_general_ci', <ide> 'comment' => 'Comment section', <ide> ]; <del> <ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Mysql')->getMock(); <ide> $dialect = new MysqlSchema($driver); <ide> <del> $table = $this->getMockBuilder(TableSchema::class) <del> ->setConstructorArgs(['table']) <del> ->getMock(); <del> $table->expects($this->at(0))->method('addColumn')->with('field', $expected); <del> <add> $table = new TableSchema('table'); <ide> $dialect->convertColumnDescription($table, $field); <add> <add> $actual = array_intersect_key($table->getColumn('field'), $expected); <add> ksort($expected); <add> ksort($actual); <add> $this->assertSame($expected, $actual); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/PostgresSchemaTest.php <ide> public static function convertColumnProvider() <ide> // String <ide> [ <ide> ['type' => 'VARCHAR'], <del> ['type' => 'string', 'length' => null] <add> ['type' => 'string', 'length' => null, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'VARCHAR(10)'], <del> ['type' => 'string', 'length' => 10] <add> ['type' => 'string', 'length' => 10, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'CHARACTER VARYING'], <del> ['type' => 'string', 'length' => null] <add> ['type' => 'string', 'length' => null, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'CHARACTER VARYING(10)'], <del> ['type' => 'string', 'length' => 10] <add> ['type' => 'string', 'length' => 10, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'CHARACTER VARYING(255)', 'default' => 'NULL::character varying'], <del> ['type' => 'string', 'length' => 255, 'default' => null] <add> ['type' => 'string', 'length' => 255, 'default' => null, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'CHAR(10)'], <del> ['type' => 'string', 'fixed' => true, 'length' => 10] <add> ['type' => 'string', 'fixed' => true, 'length' => 10, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'CHAR(36)'], <del> ['type' => 'string', 'fixed' => true, 'length' => 36] <add> ['type' => 'string', 'fixed' => true, 'length' => 36, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'CHARACTER(10)'], <del> ['type' => 'string', 'fixed' => true, 'length' => 10] <add> ['type' => 'string', 'fixed' => true, 'length' => 10, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> [ <ide> ['type' => 'MONEY'], <ide> public static function convertColumnProvider() <ide> // Text <ide> [ <ide> ['type' => 'TEXT'], <del> ['type' => 'text', 'length' => null] <add> ['type' => 'text', 'length' => null, 'collate' => 'ja_JP.utf8'] <ide> ], <ide> // Blob <ide> [ <ide> public function testConvertColumn($field, $expected) <ide> 'null' => true, <ide> 'default' => 'Default value', <ide> 'comment' => 'Comment section', <del> 'collate' => 'ja_JP.utf8', <ide> ]; <ide> <ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Postgres')->getMock(); <ide> $dialect = new PostgresSchema($driver); <ide> <del> $table = $this->getMockBuilder(TableSchema::class) <del> ->setConstructorArgs(['table']) <del> ->getMock(); <del> $table->expects($this->at(0))->method('addColumn')->with('field', $expected); <del> <add> $table = new TableSchema('table'); <ide> $dialect->convertColumnDescription($table, $field); <add> <add> $actual = array_intersect_key($table->getColumn('field'), $expected); <add> ksort($expected); <add> ksort($actual); <add> $this->assertSame($expected, $actual); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php <ide> public function testConvertColumn($type, $expected) <ide> $expected += [ <ide> 'null' => true, <ide> 'default' => 'Default value', <add> 'comment' => null, <ide> ]; <ide> <ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlite')->getMock(); <ide> $dialect = new SqliteSchema($driver); <ide> <del> $table = $this->getMockBuilder(TableSchema::class) <del> ->setConstructorArgs(['table']) <del> ->getMock(); <del> $table->expects($this->at(1))->method('addColumn')->with('field', $expected); <del> <add> $table = new TableSchema('table'); <ide> $dialect->convertColumnDescription($table, $field); <add> <add> $actual = array_intersect_key($table->getColumn('field'), $expected); <add> ksort($expected); <add> ksort($actual); <add> $this->assertSame($expected, $actual); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Database/Schema/SqlserverSchemaTest.php <ide> public static function convertColumnProvider() <ide> null, <ide> null, <ide> null, <del> ['type' => 'string', 'length' => 255] <add> ['type' => 'string', 'length' => 255, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'VARCHAR', <ide> 10, <ide> null, <ide> null, <del> ['type' => 'string', 'length' => 10] <add> ['type' => 'string', 'length' => 10, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'NVARCHAR', <ide> 50, <ide> null, <ide> null, <ide> // Sqlserver returns double lengths for unicode columns <del> ['type' => 'string', 'length' => 25] <add> ['type' => 'string', 'length' => 25, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'CHAR', <ide> 10, <ide> null, <ide> null, <del> ['type' => 'string', 'fixed' => true, 'length' => 10] <add> ['type' => 'string', 'fixed' => true, 'length' => 10, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'NCHAR', <ide> 10, <ide> null, <ide> null, <ide> // SQLServer returns double length for unicode columns. <del> ['type' => 'string', 'fixed' => true, 'length' => 5] <add> ['type' => 'string', 'fixed' => true, 'length' => 5, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'UNIQUEIDENTIFIER', <ide> public static function convertColumnProvider() <ide> null, <ide> null, <ide> null, <del> ['type' => 'text', 'length' => null] <add> ['type' => 'text', 'length' => null, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'REAL', <ide> public static function convertColumnProvider() <ide> -1, <ide> null, <ide> null, <del> ['type' => 'text', 'length' => null] <add> ['type' => 'text', 'length' => null, 'collate' => 'Japanese_Unicode_CI_AI'] <ide> ], <ide> [ <ide> 'IMAGE', <ide> public function testConvertColumn($type, $length, $precision, $scale, $expected) <ide> $expected += [ <ide> 'null' => true, <ide> 'default' => 'Default value', <del> 'collate' => 'Japanese_Unicode_CI_AI', <ide> ]; <ide> <ide> $driver = $this->getMockBuilder('Cake\Database\Driver\Sqlserver')->getMock(); <ide> $dialect = new SqlserverSchema($driver); <ide> <del> $table = $this->getMockBuilder('Cake\Database\Schema\TableSchema') <del> ->setConstructorArgs(['table']) <del> ->getMock(); <del> $table->expects($this->at(0))->method('addColumn')->with('field', $expected); <del> <add> $table = new TableSchema('table'); <ide> $dialect->convertColumnDescription($table, $field); <add> <add> $actual = array_intersect_key($table->getColumn('field'), $expected); <add> ksort($expected); <add> ksort($actual); <add> $this->assertSame($expected, $actual); <ide> } <ide> <ide> /**
6
Text
Text
add moonball to collaborators
5a55a711505489af7fd75a83b4905afc7468ebec
<ide><path>README.md <ide> For more information about the governance of the Node.js project, see <ide> **Julien Gilli** &lt;jgilli@nodejs.org&gt; <ide> * [mmarchini](https://github.com/mmarchini) - <ide> **Matheus Marchini** &lt;matheus@sthima.com&gt; <add>* [MoonBall](https://github.com/MoonBall) - <add>**Chen Gang** &lt;gangc.cxy@foxmail.com&gt; <ide> * [mscdex](https://github.com/mscdex) - <ide> **Brian White** &lt;mscdex@mscdex.net&gt; <ide> * [MylesBorins](https://github.com/MylesBorins) -
1
Ruby
Ruby
build python binary names dynamically
f04b0142102a872d255440aef75984c1b213c584
<ide><path>Library/Homebrew/language/python.rb <ide> def needs_python?(python) <ide> def virtualenv_install_with_resources(options = {}) <ide> python = options[:using] <ide> if python.nil? <del> pythons = %w[python python3 python@3 python@3.7 python@3.8 python@3.9 pypy pypy3] <add> pythons = %w[python python3 pypy pypy3] + Formula.names.select { |name| name.start_with? "python@" } <ide> wanted = pythons.select { |py| needs_python?(py) } <ide> raise FormulaUnknownPythonError, self if wanted.empty? <ide> raise FormulaAmbiguousPythonError, self if wanted.size > 1
1
PHP
PHP
fix failing tests
270d022136995b5dba776816b010c63edec4b438
<ide><path>App/Config/app.php <ide> $loader = new ClassLoader($namespace, dirname(APP)); <ide> $loader->register(); <ide> unset($loader, $namespace); <add> <add>/** <add> * Define the FULL_BASE_URL used for link generation. <add> * In most cases the code below will generate the correct hostname. <add> * However, you can manually define the hostname to resolve any issues. <add> */ <add>$s = null; <add>if (env('HTTPS')) { <add> $s = 's'; <add>} <add> <add>$httpHost = env('HTTP_HOST'); <add>if (isset($httpHost)) { <add> define('FULL_BASE_URL', 'http' . $s . '://' . $httpHost); <add>} <add>unset($httpHost, $s); <add> <add>/** <add> * Configure the mbstring extension to use the correct encoding. <add> */ <add>$encoding = Configure::read('App.encoding'); <add>mb_internal_encoding($encoding); <ide><path>lib/Cake/Console/Templates/skel/Config/app.php <ide> * - cipherSeed - A random numeric string (digits only) used to seed <ide> * the xor cipher functions in Security. <ide> */ <del> Configure::write('Security.salt', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi'); <del> <del> Configure::write('Security.cipherSeed', '76859309657453542496749683645'); <add> Configure::write('Security', [ <add> 'salt' => 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi', <add> 'cipherSeed' => '76859309657453542496749683645', <add> ]); <ide> <ide> /** <ide> * Apply timestamps with the last modified time to static assets (js, css, images). <ide> $loader = new ClassLoader($namespace, dirname(APP)); <ide> $loader->register(); <ide> unset($loader, $namespace); <add> <add>/** <add> * Define the FULL_BASE_URL used for link generation. <add> * In most cases the code below will generate the correct hostname. <add> * However, you can manually define the hostname to resolve any issues. <add> */ <add>$s = null; <add>if (env('HTTPS')) { <add> $s = 's'; <add>} <add> <add>$httpHost = env('HTTP_HOST'); <add>if (isset($httpHost)) { <add> define('FULL_BASE_URL', 'http' . $s . '://' . $httpHost); <add>} <add>unset($httpHost, $s); <add> <add>/** <add> * Configure the mbstring extension to use the correct encoding. <add> */ <add>$encoding = Configure::read('App.encoding'); <add>mb_internal_encoding($encoding); <ide><path>lib/Cake/Routing/Router.php <ide> public static function parse($url) { <ide> static::_loadRoutes(); <ide> } <ide> <del> if ($url && strpos($url, '/') !== 0) { <add> if (strlen($url) && strpos($url, '/') !== 0) { <ide> $url = '/' . $url; <ide> } <ide> if (strpos($url, '?') !== false) { <ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php <ide> public function testUrlCatchAllRoute() { <ide> $result = Router::url(array('controller' => 'categories', 'action' => 'index', '0')); <ide> $this->assertEquals('/0', $result); <ide> <del> $expected = array( <add> $expected = [ <ide> 'plugin' => null, <ide> 'controller' => 'categories', <ide> 'action' => 'index', <del> 'pass' => array('0'), <del> ); <add> 'pass' => ['0'], <add> ]; <ide> $result = Router::parse('/0'); <ide> $this->assertEquals($expected, $result); <ide> <ide><path>lib/Cake/Test/TestCase/View/Helper/FormHelperTest.php <ide> public function testInputMagicSelectForTypeNumber() { <ide> 'label' => array('for' => 'ValidateUserBalance'), <ide> 'Balance', <ide> '/label', <del> 'select' => array('name' => 'data[ValidateUser][balance]', 'id' => 'ValidateUserBalance'), <add> 'select' => array('name' => 'ValidateUser[balance]', 'id' => 'ValidateUserBalance'), <ide> array('option' => array('value' => '0')), <ide> 'nothing', <ide> '/option', <ide> public function testFormInputRequiredDetection() { <ide> 'Iamrequiredalways', <ide> '/label', <ide> 'input' => array( <del> 'type' => 'text', 'name' => 'data[Contact][iamrequiredalways]', <add> 'type' => 'text', 'name' => 'Contact[iamrequiredalways]', <ide> 'id' => 'ContactIamrequiredalways' <ide> ), <ide> '/div' <ide><path>lib/Cake/bootstrap.php <ide> $loader->register(); <ide> <ide> use Cake\Core\App; <add>use Cake\Core\Configure; <ide> <ide> App::init(); <ide> App::build(); <del> <del>/** <del> * Full url prefix <del> */ <del>if (!defined('FULL_BASE_URL')) { <del> $s = null; <del> if (env('HTTPS')) { <del> $s = 's'; <del> } <del> <del> $httpHost = env('HTTP_HOST'); <del> <del> if (isset($httpHost)) { <del> define('FULL_BASE_URL', 'http' . $s . '://' . $httpHost); <del> } <del> unset($httpHost, $s); <del>} <del> <del>spl_autoload_register(array('App', 'load')); <del> <del>$encoding = Configure::read('App.encoding'); <del>if (!empty($encoding)) { <del> mb_internal_encoding($encoding); <del>}
6
Text
Text
fix typo in n-api.md
6101bd209e059a27356e95322e1317e49443f9b5
<ide><path>doc/api/n-api.md <ide> invoking the callback. This should be a value previously obtained <ide> from [`napi_async_init`][]. <ide> - `[out] result`: The newly created scope. <ide> <del>There are cases(for example resolving promises) where it is <add>There are cases (for example resolving promises) where it is <ide> necessary to have the equivalent of the scope associated with a callback <ide> in place when making certain N-API calls. If there is no other script on <ide> the stack the [`napi_open_callback_scope`][] and
1
Javascript
Javascript
add more test cases
ac09ae1418cc6da37966c60af070c89b69834836
<ide><path>test/cases/parsing/harmony-duplicate-export/1.js <ide> export var x = "1"; <del>export * from "./a"; <add>export * from "./a?1"; <ide><path>test/cases/parsing/harmony-duplicate-export/2.js <del>export * from "./a"; <add>export * from "./a?2"; <ide> export var x = "1"; <ide><path>test/cases/parsing/harmony-duplicate-export/3.js <del>export * from "./a"; <del>export * from "./b"; <add>// TODO: Technically this should lead to an error <add>export * from "./a?3"; <add>export * from "./b?3"; <ide><path>test/cases/parsing/harmony-duplicate-export/4.js <del>export * from "./b"; <del>export * from "./a"; <add>// TODO: Technically this should lead to an error <add>export * from "./b?4"; <add>export * from "./a?4"; <ide><path>test/cases/parsing/harmony-duplicate-export/5.js <del>export * from "./c"; <del>export * from "./d"; <add>// Theoretically this should lead to an error <add>// but in this dynamic case it's impossible to detect it <add>export * from "./c?5"; <add>export * from "./d?5"; <ide><path>test/cases/parsing/harmony-duplicate-export/6.js <del>export * from "./a"; <del>export * from "./b"; <del>export * from "./c"; <del>export * from "./d"; <add>// TODO: Technically this should lead to an error <add>export * from "./a?6"; <add>export * from "./b?6"; <add>export * from "./c?6"; <add>export * from "./d?6"; <ide><path>test/cases/parsing/harmony-duplicate-export/7.js <del>export * from "./d"; <del>export * from "./b"; <del>export * from "./c"; <del>export * from "./a"; <add>// TODO: Technically this should lead to an error <add>export * from "./d?7"; <add>export * from "./b?7"; <add>export * from "./c?7"; <add>export * from "./a?7"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/1.js <add>export var x = "1"; <add>export * from "./a?1"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/2.js <add>export * from "./a?2"; <add>export var x = "1"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/3.js <add>// TODO: Technically this should lead to an error <add>export * from "./a?3"; <add>export * from "./b?3"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/4.js <add>// TODO: Technically this should lead to an error <add>export * from "./b?4"; <add>export * from "./a?4"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/5.js <add>// Theoretically this should lead to an error <add>// but in this dynamic case it's impossible to detect it <add>export * from "./c?5"; <add>export * from "./d?5"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/6.js <add>// TODO: Technically this should lead to an error <add>export * from "./a?6"; <add>export * from "./b?6"; <add>export * from "./c?6"; <add>export * from "./d?6"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/7.js <add>// TODO: Technically this should lead to an error <add>export * from "./d?7"; <add>export * from "./b?7"; <add>export * from "./c?7"; <add>export * from "./a?7"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/a.js <add>export var x = "a"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/b.js <add>export var x = "b"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/c.js <add>exports.x = "c"; <ide><path>test/cases/parsing/harmony-duplicate-export/cjs/d.js <add>exports.x = "d"; <ide><path>test/cases/parsing/harmony-duplicate-export/index.js <del>import { x as x1 } from "./1?a"; <del>import { x as x2 } from "./2?a"; <del>import { x as x3 } from "./3?a"; <del>import { x as x4 } from "./4?a"; <del>import { x as x5 } from "./5?a"; <del>import { x as x6 } from "./6?a"; <del>import { x as x7 } from "./7?a"; <add>import { x as x1 } from "./1"; <add>import { x as x2 } from "./2"; <add>import { x as x3 } from "./3"; <add>import { x as x4 } from "./4"; <add>import { x as x5 } from "./5"; <add>import { x as x6 } from "./6"; <add>import { x as x7 } from "./7"; <ide> <del>var y1 = require("./1?b").x; <del>var y2 = require("./2?b").x; <del>var y3 = require("./3?b").x; <del>var y4 = require("./4?b").x; <del>var y5 = require("./5?b").x; <del>var y6 = require("./6?b").x; <del>var y7 = require("./7?b").x; <add>var y1 = require("./cjs/1").x; <add>var y2 = require("./cjs/2").x; <add>var y3 = require("./cjs/3").x; <add>var y4 = require("./cjs/4").x; <add>var y5 = require("./cjs/5").x; <add>var y6 = require("./cjs/6").x; <add>var y7 = require("./cjs/7").x; <ide> <ide> it("should not overwrite when using star export (known exports)", function() { <ide> expect(x1).toBe("1"); <ide> it("should not overwrite when using star export (known exports)", function() { <ide> expect(x4).toBe("b"); <ide> expect(x5).toBe("c"); <ide> expect(x6).toBe("a"); <del> expect(x7).toBe("d"); <add> expect(x7).toBe("b"); // Looks wrong, but is irrelevant as this should be an error anyway <ide> }); <ide> <ide> it("should not overwrite when using star export (unknown exports)", function() { <ide> it("should not overwrite when using star export (unknown exports)", function() { <ide> expect(y4).toBe("b"); <ide> expect(y5).toBe("c"); <ide> expect(y6).toBe("a"); <del> expect(y7).toBe("d"); <add> expect(y7).toBe("b"); // Looks wrong, but is irrelevant as this should be an error anyway <ide> }); <ide><path>test/cases/scope-hoisting/reexport-star-exposed-cjs/a.js <add>exports.named = "named"; <ide><path>test/cases/scope-hoisting/reexport-star-exposed-cjs/b.js <add>export { named } from "./a"; <ide><path>test/cases/scope-hoisting/reexport-star-exposed-cjs/c.js <add>export * from "./b"; <ide><path>test/cases/scope-hoisting/reexport-star-exposed-cjs/index.js <add>var c = require("./c"); <add> <add>it("should have the correct values", function() { <add> expect(c.named).toBe("named"); <add>}); <ide><path>test/cases/scope-hoisting/reexport-star-external-cjs/a.js <add>exports.named = "named"; <ide><path>test/cases/scope-hoisting/reexport-star-external-cjs/b.js <add>export var other = "other"; <ide><path>test/cases/scope-hoisting/reexport-star-external-cjs/c.js <add>export * from "./a"; <add>export * from "./b"; <ide><path>test/cases/scope-hoisting/reexport-star-external-cjs/index.js <add>var c = require("./c"); <add> <add>it("should have the correct values", function() { <add> expect(c.named).toBe("named"); <add>});
27
PHP
PHP
fix strict warnings on php 5.4
172e4bed5d262529a9376061b2043d5e1dbd4cef
<ide><path>lib/Cake/Test/test_app/Model/Datasource/Test2OtherSource.php <ide> public function create(Model $model, $fields = null, $values = null) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <del> public function read(Model $model, $queryData = array()) { <add> public function read(Model $model, $queryData = array(), $recursive = null) { <ide> return compact('model', 'queryData'); <ide> } <ide> <del> public function update(Model $model, $fields = array(), $values = array()) { <add> public function update(Model $model, $fields = array(), $values = array(), $conditions = null) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <ide><path>lib/Cake/Test/test_app/Model/Datasource/Test2Source.php <ide> public function create(Model $model, $fields = null, $values = null) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <del> public function read(Model $model, $queryData = array()) { <add> public function read(Model $model, $queryData = array(), $recursive = null) { <ide> return compact('model', 'queryData'); <ide> } <ide> <del> public function update(Model $model, $fields = array(), $values = array()) { <add> public function update(Model $model, $fields = array(), $values = array(), $conditions = null) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <ide><path>lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/TestOtherSource.php <ide> public function create(Model $model, $fields = null, $values = array()) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <del> public function read(Model $model, $queryData = array()) { <add> public function read(Model $model, $queryData = array(), $recursive = null) { <ide> return compact('model', 'queryData'); <ide> } <ide> <del> public function update(Model $model, $fields = array(), $values = array()) { <add> public function update(Model $model, $fields = array(), $values = array(), $conditions = null) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <ide><path>lib/Cake/Test/test_app/Plugin/TestPlugin/Model/Datasource/TestSource.php <ide> public function create(Model $model, $fields = array(), $values = array()) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide> <del> public function read(Model $model, $queryData = array()) { <add> public function read(Model $model, $queryData = array(), $recursive = null) { <ide> return compact('model', 'queryData'); <ide> } <ide> <del> public function update(Model $model, $fields = array(), $values = array()) { <add> public function update(Model $model, $fields = array(), $values = array(), $conditions = null) { <ide> return compact('model', 'fields', 'values'); <ide> } <ide>
4
Text
Text
fix code examples in zlib.md
6cfdbc74d95c501d022b413cf024eb211d23c808
<ide><path>doc/api/zlib.md <ide> http.createServer((request, response) => { <ide> <ide> // Note: This is not a conformant accept-encoding parser. <ide> // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 <del> if (acceptEncoding.match(/\bdeflate\b/)) { <add> if (/\bdeflate\b/.test(acceptEncoding)) { <ide> response.writeHead(200, { 'Content-Encoding': 'deflate' }); <ide> raw.pipe(zlib.createDeflate()).pipe(response); <del> } else if (acceptEncoding.match(/\bgzip\b/)) { <add> } else if (/\bgzip\b/.test(acceptEncoding)) { <ide> response.writeHead(200, { 'Content-Encoding': 'gzip' }); <ide> raw.pipe(zlib.createGzip()).pipe(response); <ide> } else { <ide> By default, the `zlib` methods will throw an error when decompressing <ide> truncated data. However, if it is known that the data is incomplete, or <ide> the desire is to inspect only the beginning of a compressed file, it is <ide> possible to suppress the default error handling by changing the flushing <del>method that is used to compressed the last chunk of input data: <add>method that is used to decompress the last chunk of input data: <ide> <ide> ```js <ide> // This is a truncated version of the buffer from the above examples <ide> const buffer = Buffer.from('eJzT0yMA', 'base64'); <ide> <ide> zlib.unzip( <ide> buffer, <del> {finishFlush: zlib.constants.Z_SYNC_FLUSH}, <add> { finishFlush: zlib.constants.Z_SYNC_FLUSH }, <ide> (err, buffer) => { <ide> if (!err) { <ide> console.log(buffer.toString());
1
Javascript
Javascript
add unit test for pdf file loaded as typed array
9f1e140c4fa3b0e5db8b535363e2d8275341df08
<ide><path>test/unit/api_spec.js <ide> describe('api', function() { <ide> expect(true).toEqual(true); <ide> }); <ide> }); <del> /* <ide> it('creates pdf doc from typed array', function() { <del> // TODO <add> var nonBinaryRequest = PDFJS.disableWorker; <add> var request = new XMLHttpRequest(); <add> request.open('GET', basicApiUrl, false); <add> if (!nonBinaryRequest) { <add> try { <add> request.responseType = 'arraybuffer'; <add> nonBinaryRequest = request.responseType !== 'arraybuffer'; <add> } catch (e) { <add> nonBinaryRequest = true; <add> } <add> } <add> if (nonBinaryRequest && request.overrideMimeType) { <add> request.overrideMimeType('text/plain; charset=x-user-defined'); <add> } <add> request.send(null); <add> <add> var typedArrayPdf; <add> if (nonBinaryRequest) { <add> var data = Array.prototype.map.call(request.responseText, <add> function (ch) { <add> return ch.charCodeAt(0) & 0xFF; <add> }); <add> typedArrayPdf = new Uint8Array(data); <add> } else { <add> typedArrayPdf = new Uint8Array(request.response); <add> } <add> // Sanity check to make sure that we fetched the entire PDF file. <add> expect(typedArrayPdf.length).toEqual(105779); <add> <add> var promise = PDFJS.getDocument(typedArrayPdf); <add> waitsForPromise(promise, function(data) { <add> expect(true).toEqual(true); <add> }); <ide> }); <del> */ <ide> }); <ide> }); <ide> describe('PDFDocument', function() {
1
PHP
PHP
fix permissions setting script
d4bc47d8e731fa2a0d019ee7278b20e28c84ded5
<ide><path>App/App/Console/Installer.php <ide> public static function createAppConfig($dir, $io) { <ide> * @return void <ide> */ <ide> public static function setTmpPermissions($dir, $io) { <del> $walker = function ($dir, $perms) use ($io, &$walker) { <add> /** <add> * Change the permissions on a path and output the results. <add> */ <add> $changePerms = function ($path, $perms, $io) { <add> // Get current permissions in decimal format so we can bitmask it. <add> $currentPerms = octdec(substr(sprintf('%o', fileperms($path)), -4)); <add> if (($currentPerms & $perms) == $perms) { <add> return; <add> } <add> <add> $res = chmod($path, $currentPerms | $perms); <add> if ($res) { <add> $io->write('Permissions set on ' . $path); <add> } else { <add> $io->write('Failed to set permissions on ' . $path); <add> } <add> }; <add> <add> $walker = function ($dir, $perms, $io) use (&$walker, $changePerms) { <ide> $files = array_diff(scandir($dir), ['.', '..']); <ide> foreach ($files as $file) { <ide> $path = $dir . '/' . $file; <ide> public static function setTmpPermissions($dir, $io) { <ide> continue; <ide> } <ide> <del> // Get current permissions in decimal format so we can bitmask it. <del> $currentPerms = octdec(substr(sprintf('%o', fileperms($path)), -4)); <del> if (($currentPerms & $perms) == $perms) { <del> continue; <del> } <del> <del> $res = chmod($path, $currentPerms | $perms); <del> if ($res) { <del> $io->write('Permissions set on ' . $path); <del> } else { <del> $io->write('Failed to set permissions on ' . $path); <del> } <del> $walker($path, $perms); <add> $changePerms($path, $perms, $io); <add> $walker($path, $perms, $io); <ide> } <ide> }; <ide> <del> $worldWritable = bindec('0110000000'); <del> $walker($dir . '/tmp', $worldWritable); <add> $worldWritable = bindec('0000000111'); <add> $walker($dir . '/tmp', $worldWritable, $io); <add> $changePerms($dir . '/tmp', $worldWritable, $io); <ide> } <ide> <ide> }
1
Text
Text
add @nodejs/build to onboarding-extras.md
20b78055668893530c8077e522a92a867260d570
<ide><path>doc/onboarding-extras.md <ide> | `test/*` | @nodejs/testing | <ide> | `tools/eslint`, `.eslintrc` | @not-an-aardvark, @silverwind, @trott | <ide> | async_hooks | @nodejs/async_hooks for bugs/reviews (+ @nodejs/diagnostics for API) | <add>| build | @nodejs/build | <ide> | performance | @nodejs/performance | <ide> | platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | <ide> | python code | @nodejs/python |
1
Text
Text
fix code blocks in readme
95252369ae6ea2a07336f9546a3f499d662eefc4
<ide><path>README.md <ide> var Message = React.createClass({ <ide> <ide> Custom iOS views can be exposed by subclassing RCTViewManager, implementing a -(UIView *)view method, and exporting properties with the RCT_EXPORT_VIEW_PROPERTY macro. Then a simple JavaScript file connects the dots. <ide> <del>```javascript <add>```objc <ide> // Objective-C <ide> #import "RCTViewManager.h" <ide> @interface MyCustomViewManager : RCTViewManager <ide> Custom iOS views can be exposed by subclassing RCTViewManager, implementing a -( <ide> } <ide> RCT_EXPORT_VIEW_PROPERTY(myCustomProperty); <ide> @end`} <del> </Prism> <del> <Prism> <del>{`// JavaScript <add>``` <add> <add>```javascript <ide> module.exports = createReactIOSNativeComponentClass({ <ide> validAttributes: { myCustomProperty: true }, <ide> uiViewClassName: 'MyCustomView', <del>});`} <add>}); <ide> ``` <ide>
1
Ruby
Ruby
fix a few bugs when trying to use head standalone
8cb2cfbf71092f95090335cbdde0340cc74db748
<ide><path>actionpack/lib/abstract_controller/base.rb <ide> class ActionNotFound < StandardError; end <ide> class Base <ide> attr_internal :response_body <ide> attr_internal :action_name <add> attr_internal :formats <ide> <ide> include ActiveSupport::Configurable <ide> extend ActiveSupport::DescendantsTracker <ide><path>actionpack/lib/action_controller/metal.rb <ide> def location=(url) <ide> headers["Location"] = url <ide> end <ide> <add> # basic url_for that can be overridden for more robust functionality <add> def url_for(string) <add> string <add> end <add> <ide> def status <ide> @_status <ide> end <ide><path>actionpack/lib/action_controller/metal/head.rb <ide> module ActionController <ide> module Head <ide> extend ActiveSupport::Concern <ide> <del> include ActionController::UrlFor <del> <ide> # Return a response that has no content (merely headers). The options <ide> # argument is interpreted to be a hash of header names and values. <ide> # This allows you to easily return a response that consists only of <ide> def head(status, options = {}) <ide> <ide> self.status = status <ide> self.location = url_for(location) if location <del> self.content_type = Mime[formats.first] <add> self.content_type = Mime[formats.first] if formats <ide> self.response_body = " " <ide> end <ide> end <del>end <ide>\ No newline at end of file <add>end <ide><path>actionpack/test/controller/new_base/bare_metal_test.rb <ide> class BareTest < ActiveSupport::TestCase <ide> assert_equal "Hello world", string <ide> end <ide> end <add> <add> class HeadController < ActionController::Metal <add> include ActionController::Head <add> <add> def index <add> head :not_found <add> end <add> end <add> <add> class HeadTest < ActiveSupport::TestCase <add> test "head works on its own" do <add> status, headers, body = HeadController.action(:index).call(Rack::MockRequest.env_for("/")) <add> assert_equal 404, status <add> end <add> end <ide> end
4
Ruby
Ruby
fix array comparison
e4823ea6fe4fa7a89c2dd6da59e091e29ba5a6f0
<ide><path>Library/Homebrew/cmd/uninstall.rb <ide> def uninstall <ide> end <ide> <ide> unversioned_name = f.name.gsub(/@.+$/, "") <del> maybe_paths = Dir.glob("#{f.etc}/*#{unversioned_name}*") - paths <add> maybe_paths = Dir.glob("#{f.etc}/*#{unversioned_name}*") - paths.to_a <ide> if maybe_paths.present? <ide> puts <ide> opoo <<~EOS
1
Ruby
Ruby
improve written bottle output
fd254c3874ad949af9ad3d6510611a31ebc9bc47
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def merge <ide> else <ide> formula_path = HOMEBREW_REPOSITORY+formula_relative_path <ide> end <add> has_bottle_block = f.class.send(:bottle).checksums.any? <ide> inreplace formula_path do |s| <del> if f.bottle <del> s.gsub!(/ bottle do.+?end\n/m, output) <add> if has_bottle_block <add> s.sub!(/ bottle do.+?end\n/m, output) <ide> else <del> s.gsub!(/( (url|sha1|head|version) '\S*'\n+)+/m, '\0' + output + "\n") <add> s.sub!(/( (url|sha1|head|version) '\S*'\n+)+/m, '\0' + output + "\n") <ide> end <ide> end <ide> <del> update_or_add = f.bottle.nil? ? 'add' : 'update' <add> update_or_add = has_bottle_block ? 'update' : 'add' <ide> <ide> safe_system 'git', 'commit', formula_path, '-m', <ide> "#{f.name}: #{update_or_add} bottle."
1
Javascript
Javascript
use timeupdate as well as rvfc/raf for cues
9b81afee8011c7d33f60618d3c190f407b0eca73
<ide><path>src/js/tracks/text-track.js <ide> class TextTrack extends Track { <ide> const activeCues = new TextTrackCueList(this.activeCues_); <ide> let changed = false; <ide> <del> this.timeupdateHandler = Fn.bind(this, function() { <add> this.timeupdateHandler = Fn.bind(this, function(event = {}) { <ide> if (this.tech_.isDisposed()) { <ide> return; <ide> } <ide> <ide> if (!this.tech_.isReady_) { <del> this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); <add> if (event.type !== 'timeupdate') { <add> this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); <add> } <ide> <ide> return; <ide> } <ide> class TextTrack extends Track { <ide> changed = false; <ide> } <ide> <del> this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); <add> if (event.type !== 'timeupdate') { <add> this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); <add> } <ide> <ide> }); <ide> <ide> class TextTrack extends Track { <ide> } <ide> <ide> startTracking() { <add> // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback <ide> this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); <add> // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el) <add> this.tech_.on('timeupdate', this.timeupdateHandler); <ide> } <ide> <ide> stopTracking() { <ide> if (this.rvf_) { <ide> this.tech_.cancelVideoFrameCallback(this.rvf_); <ide> this.rvf_ = undefined; <ide> } <add> this.tech_.off('timeupdate', this.timeupdateHandler); <ide> } <ide> <ide> /** <ide><path>test/unit/tracks/text-track.test.js <ide> QUnit.test('does not fire cuechange before Tech is ready', function(assert) { <ide> return 0; <ide> }; <ide> <add> // `playing` would trigger rvfc or raf, `timeupdate` for fallback <ide> player.tech_.trigger('playing'); <add> player.tech_.trigger('timeupdate'); <ide> assert.equal(changes, 0, 'a cuechange event is not triggered'); <ide> <ide> player.tech_.on('ready', function() { <ide> QUnit.test('does not fire cuechange before Tech is ready', function(assert) { <ide> <ide> assert.equal(changes, 2, 'a cuechange event trigger addEventListener and oncuechange'); <ide> <add> player.tech_.trigger('timeupdate'); <add> clock.tick(1); <add> <add> assert.equal(changes, 2, 'a cuechange event trigger not duplicated by timeupdate'); <add> <ide> tt.off(); <ide> player.dispose(); <ide> clock.restore(); <ide> QUnit.test('fires cuechange when cues become active and inactive', function(asse <ide> const cuechangeHandler = function() { <ide> changes++; <ide> }; <add> let fakeCurrentTime = 0; <add> <add> player.tech_.currentTime = function() { <add> return fakeCurrentTime; <add> }; <ide> <ide> tt.addCue({ <ide> id: '1', <ide> startTime: 1, <ide> endTime: 5 <ide> }); <add> tt.addCue({ <add> id: '2', <add> startTime: 11, <add> endTime: 14 <add> }); <ide> <ide> tt.oncuechange = cuechangeHandler; <ide> tt.addEventListener('cuechange', cuechangeHandler); <ide> <del> player.tech_.currentTime = function() { <del> return 2; <del> }; <add> fakeCurrentTime = 2; <add> player.tech_.trigger('playing'); <ide> <add> assert.equal(changes, 2, 'a cuechange event trigger addEventListener and oncuechange (rvfc/raf)'); <add> <add> fakeCurrentTime = 7; <ide> player.tech_.trigger('playing'); <ide> <del> assert.equal(changes, 2, 'a cuechange event trigger addEventListener and oncuechange'); <add> assert.equal(changes, 4, 'a cuechange event trigger addEventListener and oncuechange (rvfc/raf)'); <ide> <del> player.tech_.currentTime = function() { <del> return 7; <del> }; <add> fakeCurrentTime = 12; <add> player.tech_.trigger('timeupdate'); <ide> <del> player.tech_.trigger('playing'); <add> assert.equal(changes, 6, 'a cuechange event trigger addEventListener and oncuechange (timeupdate)'); <add> <add> fakeCurrentTime = 17; <add> player.tech_.trigger('timeupdate'); <ide> <del> assert.equal(changes, 4, 'a cuechange event trigger addEventListener and oncuechange'); <add> assert.equal(changes, 8, 'a cuechange event trigger addEventListener and oncuechange (timeupdate)'); <ide> <ide> tt.off(); <ide> player.dispose(); <ide> QUnit.test('enabled and disabled cuechange handler when changing mode to hidden' <ide> return 2; <ide> }; <ide> player.tech_.trigger('playing'); <add> player.tech_.trigger('timeupdate'); <ide> <ide> assert.equal(changes, 1, 'a cuechange event trigger'); <ide> <ide> QUnit.test('enabled and disabled cuechange handler when changing mode to hidden' <ide> return 7; <ide> }; <ide> player.tech_.trigger('playing'); <add> player.tech_.trigger('timeupdate'); <ide> <ide> assert.equal(changes, 0, 'NO cuechange event trigger'); <ide>
2
Ruby
Ruby
remove local variable color
af85e8a987ace926a5d0c21b87a68e2664cfba19
<ide><path>railties/lib/rails/test_unit/reporter.rb <ide> class TestUnitReporter < Minitest::StatisticsReporter <ide> <ide> def record(result) <ide> super <del> color = COLOR_CODES_FOR_RESULTS[result.result_code] <ide> <ide> if options[:verbose] <del> io.puts color_output(format_line(result), color) <add> io.puts color_output(format_line(result), by: result) <ide> else <del> io.print color_output(result.result_code, color) <add> io.print color_output(result.result_code, by: result) <ide> end <ide> <ide> if output_inline? && result.failure && (!result.skipped? || options[:verbose]) <ide> io.puts <ide> io.puts <del> io.puts format_failures(result).map { |line| color_output(line, color) } <add> io.puts format_failures(result).map { |line| color_output(line, by: result) } <ide> io.puts <ide> io.puts format_rerun_snippet(result) <ide> io.puts <ide> def colored_output? <ide> options[:color] && io.respond_to?(:tty?) && io.tty? <ide> end <ide> <del> def color_output(string, color) <add> def color_output(string, by:) <ide> if colored_output? <add> color = COLOR_CODES_FOR_RESULTS[by.result_code] <ide> "\e[#{COLOR_CODES[color]}m#{string}\e[0m" <ide> else <ide> string
1
Mixed
Go
fix some typos
950073aabb305db6156709ea8509b1f72ff06f3b
<ide><path>api/client/container/diff.go <ide> type diffOptions struct { <ide> container string <ide> } <ide> <del>// NewDiffCommand creats a new cobra.Command for `docker diff` <add>// NewDiffCommand creates a new cobra.Command for `docker diff` <ide> func NewDiffCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> var opts diffOptions <ide> <ide><path>api/client/container/restart.go <ide> type restartOptions struct { <ide> containers []string <ide> } <ide> <del>// NewRestartCommand creats a new cobra.Command for `docker restart` <add>// NewRestartCommand creates a new cobra.Command for `docker restart` <ide> func NewRestartCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> var opts restartOptions <ide> <ide><path>api/client/container/rm.go <ide> type rmOptions struct { <ide> containers []string <ide> } <ide> <del>// NewRmCommand creats a new cobra.Command for `docker rm` <add>// NewRmCommand creates a new cobra.Command for `docker rm` <ide> func NewRmCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> var opts rmOptions <ide> <ide><path>api/client/container/top.go <ide> type topOptions struct { <ide> args []string <ide> } <ide> <del>// NewTopCommand creats a new cobra.Command for `docker top` <add>// NewTopCommand creates a new cobra.Command for `docker top` <ide> func NewTopCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> var opts topOptions <ide> <ide><path>api/client/container/wait.go <ide> type waitOptions struct { <ide> containers []string <ide> } <ide> <del>// NewWaitCommand creats a new cobra.Command for `docker wait` <add>// NewWaitCommand creates a new cobra.Command for `docker wait` <ide> func NewWaitCommand(dockerCli *client.DockerCli) *cobra.Command { <ide> var opts waitOptions <ide> <ide><path>api/client/registry.go <ide> func (cli *DockerCli) ConfigureAuth(flUser, flPassword, serverAddress string, is <ide> <ide> if flUser = strings.TrimSpace(flUser); flUser == "" { <ide> if isDefaultRegistry { <del> // if this is a defauly registry (docker hub), then display the following message. <add> // if this is a default registry (docker hub), then display the following message. <ide> fmt.Fprintln(cli.out, "Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.") <ide> } <ide> cli.promptWithDefault("Username", authconfig.Username) <ide><path>api/client/utils.go <ide> func CopyToFile(outfile string, r io.Reader) error { <ide> return nil <ide> } <ide> <del>// ForwardAllSignals forwards signals to the contianer <add>// ForwardAllSignals forwards signals to the container <ide> // TODO: this can be unexported again once all container commands are under <ide> // api/client/container <ide> func (cli *DockerCli) ForwardAllSignals(ctx context.Context, cid string) chan os.Signal { <ide><path>daemon/cluster/executor/container/adapter.go <ide> func (c *containerAdapter) inspect(ctx context.Context) (types.ContainerJSON, er <ide> // events issues a call to the events API and returns a channel with all <ide> // events. The stream of events can be shutdown by cancelling the context. <ide> // <del>// A chan struct{} is returned that will be closed if the event procressing <add>// A chan struct{} is returned that will be closed if the event processing <ide> // fails and needs to be restarted. <ide> func (c *containerAdapter) wait(ctx context.Context) error { <ide> return c.backend.ContainerWaitWithContext(ctx, c.container.name()) <ide><path>daemon/cluster/provider/network.go <ide> type NetworkCreateResponse struct { <ide> ID string `json:"Id"` <ide> } <ide> <del>// VirtualAddress represents a virtual adress. <add>// VirtualAddress represents a virtual address. <ide> type VirtualAddress struct { <ide> IPv4 string <ide> IPv6 string <ide><path>daemon/oci_linux.go <ide> func setMounts(daemon *Daemon, s *specs.Spec, c *container.Container, mounts []c <ide> userMounts[m.Destination] = struct{}{} <ide> } <ide> <del> // Filter out mounts that are overriden by user supplied mounts <add> // Filter out mounts that are overridden by user supplied mounts <ide> var defaultMounts []specs.Mount <ide> _, mountDev := userMounts["/dev"] <ide> for _, m := range s.Mounts { <ide><path>docs/getstarted/step_one.md <ide> weight = 1 <ide> <ide> ### Docker for Mac <ide> <del>Docker for Mac is our newest offering for the Mac. It runs as a native Mac application and uses <a href="https://github.com/mist64/xhyve/" target="_blank">xhyve</a> to virutalize the Docker Engine environment and Linux kernel-specific features for the Docker daemon. <add>Docker for Mac is our newest offering for the Mac. It runs as a native Mac application and uses <a href="https://github.com/mist64/xhyve/" target="_blank">xhyve</a> to virtualize the Docker Engine environment and Linux kernel-specific features for the Docker daemon. <ide> <ide> <a class="button" href="https://download.docker.com/mac/beta/Docker.dmg">Get Docker for Mac</a> <ide> <ide> See [Docker Toolbox Overview](/toolbox/overview.md) for help on installing Docke <ide> <ide> ### Docker for Windows <ide> <del>Docker for Windows is our newest offering for PCs. It runs as a native Windows application and uses Hyper-V to virutalize the Docker Engine environment and Linux kernel-specific features for the Docker daemon. <add>Docker for Windows is our newest offering for PCs. It runs as a native Windows application and uses Hyper-V to virtualize the Docker Engine environment and Linux kernel-specific features for the Docker daemon. <ide> <ide> <a class="button" href="https://download.docker.com/win/beta/InstallDocker.msi">Get Docker for Windows</a> <ide> <ide><path>docs/installation/cloud/cloud-ex-machine-ocean.md <ide> To generate your access token: <ide> default - virtualbox Running tcp://192.168.99.100:2376 <ide> docker-sandbox * digitalocean Running tcp://45.55.222.72:2376 <ide> <del>6. Run some `docker-machine` commands to inspect the remote host. For example, `docker-machine ip <machine>` gets the host IP adddress and `docker-machine inspect <machine>` lists all the details. <add>6. Run some `docker-machine` commands to inspect the remote host. For example, `docker-machine ip <machine>` gets the host IP address and `docker-machine inspect <machine>` lists all the details. <ide> <ide> $ docker-machine ip docker-sandbox <ide> 104.131.43.236 <ide><path>docs/swarm/swarm-tutorial/delete-service.md <ide> run your manager node. For example, the tutorial uses a machine named <ide> helloworld <ide> ``` <ide> <del>3. Run `docker service inspect <SERVICE-ID>` to veriy that the swarm manager <add>3. Run `docker service inspect <SERVICE-ID>` to verify that the swarm manager <ide> removed the service. The CLI returns a message that the service is not found: <ide> <ide> ``` <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { <ide> out, err := s.d.Cmd("run", "--rm", "busybox", "ls") <ide> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> <del> // Run with default runtime explicitely <add> // Run with default runtime explicitly <ide> out, err = s.d.Cmd("run", "--rm", "--runtime=default", "busybox", "ls") <ide> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> <ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { <ide> c.Assert(err, check.NotNil, check.Commentf(out)) <ide> c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") <ide> <del> // Run with default runtime explicitely <add> // Run with default runtime explicitly <ide> out, err = s.d.Cmd("run", "--rm", "--runtime=default", "busybox", "ls") <ide> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> } <ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { <ide> out, err := s.d.Cmd("run", "--rm", "busybox", "ls") <ide> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> <del> // Run with default runtime explicitely <add> // Run with default runtime explicitly <ide> out, err = s.d.Cmd("run", "--rm", "--runtime=default", "busybox", "ls") <ide> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> <ide> func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { <ide> c.Assert(err, check.NotNil, check.Commentf(out)) <ide> c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") <ide> <del> // Run with default runtime explicitely <add> // Run with default runtime explicitly <ide> out, err = s.d.Cmd("run", "--rm", "--runtime=default", "busybox", "ls") <ide> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> } <ide><path>layer/layer.go <ide> var ( <ide> // greater than the 125 max. <ide> ErrMaxDepthExceeded = errors.New("max depth exceeded") <ide> <del> // ErrNotSupported is used when the action is not supppoted <add> // ErrNotSupported is used when the action is not supported <ide> // on the current platform <ide> ErrNotSupported = errors.New("not support on this platform") <ide> ) <ide><path>pkg/archive/archive.go <ide> const ( <ide> ) <ide> <ide> const ( <del> // AUFSWhiteoutFormat is the default format for whitesouts <add> // AUFSWhiteoutFormat is the default format for whiteouts <ide> AUFSWhiteoutFormat WhiteoutFormat = iota <ide> // OverlayWhiteoutFormat formats whiteout according to the overlay <ide> // standard. <ide><path>restartmanager/restartmanager.go <ide> func (rm *restartManager) ShouldRestart(exitCode uint32, hasBeenManuallyStopped <ide> if rm.active { <ide> return false, nil, fmt.Errorf("invalid call on active restartmanager") <ide> } <del> // if the container ran for more than 10s, reguardless of status and policy reset the <add> // if the container ran for more than 10s, regardless of status and policy reset the <ide> // the timeout back to the default. <ide> if executionDuration.Seconds() >= 10 { <ide> rm.timeout = 0
17
Text
Text
add topic "wireshark feature"
c3d2903d78f48da03cad5aba72f23c925a264bd7
<ide><path>guide/english/security/wireshark/index.md <ide> title: Wireshark <ide> <ide> Wireshark is an open source network analyzer application that is available for Linux, macOS and Windows. It allows you to "sniff" [packets](../../network-engineering/packets/) being sent to and from different nodes on a network. <ide> <add>### Features of wireshark: <add>* Supports more than 1,000 protocols <add>* Ability to do live capture and offline analysis <add>* Has the most powerful display filters in the industry <add>* Captured network data can be displayed via GUI or via a command-line TShark tool <add>* Able to read/write many different capture file format such as tcpdump (libpcap), Network General Sniffer, Cisco Seure IDS, iplog, Microsoft Network Monitor, and more <add>* Live data can be read from IEEE 802.11, Bluetooth, and Ethernet <add>* The output can be exported to XML, PostScript, CSV, and plaintext <add> <ide> #### Why use Wireshark? <ide> Wireshark is a powerful tool, you might use it to: <ide> + Learn about how different protocols are used in networking
1
Javascript
Javascript
fix jslint warnings in fonts.js
0dc0dd4c970778cd8eb73142bd10b21084e535ce
<ide><path>fonts.js <ide> var Font = (function Font() { <ide> <ide> // Ensure the [h/v]mtx tables contains the advance width and <ide> // sidebearings information for numGlyphs in the maxp table <del> font.pos = (font.start ? font.start : 0) + maxp.offset; <add> font.pos = (font.start || 0) + maxp.offset; <ide> var version = int16(font.getBytes(4)); <ide> var numGlyphs = int16(font.getBytes(2)); <ide> <ide> var Font = (function Font() { <ide> return false; <ide> } <ide> return true; <del> }; <add> } <ide> <ide> // The offsets object holds at the same time a representation of where <ide> // to write the table entry information about a table and another offset <ide> var Font = (function Font() { <ide> } <ide> <ide> // Enter the translated string into the cache <del> return charsCache[chars] = str; <add> return (charsCache[chars] = str); <ide> } <ide> }; <ide> <ide> var Type1Parser = function() { <ide> r = ((value + r) * c1 + c2) & ((1 << 16) - 1); <ide> } <ide> return decryptedString.slice(discardNumber); <del> }; <add> } <ide> <ide> /* <ide> * CharStrings are encoded following the the CharString Encoding sequence <ide> var Type1Parser = function() { <ide> } <ide> <ide> return { charstring: charstring, width: width, lsb: lsb }; <del> }; <add> } <ide> <ide> /* <ide> * Returns an object containing a Subrs array and a CharStrings <ide> var Type1Parser = function() { <ide> for (var i = 0; i < array.length; i++) <ide> array[i] = parseFloat(array[i] || 0); <ide> return array; <del> }; <add> } <ide> <ide> function readNumber(str, index) { <ide> while (str[index] == ' ') <ide> var Type1Parser = function() { <ide> count++; <ide> <ide> return parseFloat(str.substr(start, count) || 0); <del> }; <add> } <ide> <ide> function isSeparator(c) { <ide> return c == ' ' || c == '\n' || c == '\x0d'; <del> }; <add> } <ide> <ide> this.extractFontProgram = function t1_extractFontProgram(stream) { <ide> var eexec = decrypt(stream, kEexecEncryptionKey, 4); <ide> var Type1Parser = function() { <ide> } <ide> <ide> return program; <del> }, <add> }; <ide> <ide> this.extractFontHeader = function t1_extractFontHeader(stream, properties) { <ide> var headerString = ''; <ide> CFF.prototype = { <ide> 'globalSubrs': this.createCFFIndexHeader([]), <ide> <ide> 'charset': (function charset(self) { <del> var charset = '\x00'; // Encoding <add> var charsetString = '\x00'; // Encoding <ide> <ide> var count = glyphs.length; <ide> for (var i = 0; i < count; i++) { <ide> CFF.prototype = { <ide> if (index == -1) <ide> index = 0; <ide> <del> charset += String.fromCharCode(index >> 8, index & 0xff); <add> charsetString += String.fromCharCode(index >> 8, index & 0xff); <ide> } <del> return charset; <add> return charsetString; <ide> })(this), <ide> <ide> 'charstrings': this.createCFFIndexHeader([[0x8B, 0x0E]].concat(glyphs), <ide> var Type2CFF = (function() { <ide> this.properties = properties; <ide> <ide> this.data = this.parse(); <del> }; <add> } <ide> <ide> constructor.prototype = { <ide> parse: function cff_parse() { <ide> var Type2CFF = (function() { <ide> case 21: <ide> dict['nominalWidthX'] = value[0]; <ide> default: <del> TODO('interpret top dict key'); <add> TODO('interpret top dict key: ' + key); <ide> } <ide> } <ide> return dict; <ide> var Type2CFF = (function() { <ide> error('Incorrect byte'); <ide> } <ide> return -1; <del> }; <add> } <ide> <ide> function parseFloatOperand() { <ide> var str = ''; <ide> var Type2CFF = (function() { <ide> str += lookup[b2]; <ide> } <ide> return parseFloat(str); <del> }; <add> } <ide> <ide> var operands = []; <ide> var entries = []; <ide> var Type2CFF = (function() { <ide> parseIndex: function cff_parseIndex(pos) { <ide> var bytes = this.bytes; <ide> var count = bytes[pos++] << 8 | bytes[pos++]; <del> if (count == 0) { <del> var offsets = []; <del> var end = pos; <del> } else { <add> var offsets = []; <add> var end = pos; <add> <add> if (count != 0) { <ide> var offsetSize = bytes[pos++]; <ide> // add 1 for offset to determine size of last object <ide> var startPos = pos + ((count + 1) * offsetSize) - 1; <ide> <del> var offsets = []; <ide> for (var i = 0, ii = count + 1; i < ii; ++i) { <ide> var offset = 0; <ide> for (var j = 0; j < offsetSize; ++j) { <ide> var Type2CFF = (function() { <ide> } <ide> offsets.push(startPos + offset); <ide> } <del> var end = offsets[count]; <add> end = offsets[count]; <ide> } <ide> <ide> return {
1
Ruby
Ruby
remove incomplete files in cache on `brew cleanup`
e0f99945421243bc332002dec4f8e25220237aeb
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_keg(keg) <ide> def cleanup_cache <ide> return unless HOMEBREW_CACHE.directory? <ide> HOMEBREW_CACHE.children.each do |path| <add> if path.to_s.end_with? ".incomplete" <add> cleanup_path(path) { path.unlink } <add> next <add> end <ide> if prune?(path) <ide> if path.file? <ide> cleanup_path(path) { path.unlink }
1
Javascript
Javascript
allow time to finish requests
909951d9759a9e544f636bdb1632dd1eae3391ad
<ide><path>test/unit/testreporter.js <ide> var TestReporter = function(browser, appPath) { <ide> this.reportSuiteResults = function(suite) { }; <ide> <ide> this.reportRunnerResults = function(runner) { <del> sendQuitRequest(); <add> // Give the test.py some time process any queued up requests <add> setTimeout(sendQuitRequest, 500); <ide> }; <ide> };
1
Text
Text
add the text
0f118eb147b986c712022892085a58a4bfe18739
<ide><path>guide/english/blockchain/cryptocurrency/index.md <ide> Cryptocurrency can be exchanged as fractions not possible with traditional curre <ide> <ide> If you want to earn bitcoins through mining, it can be done through solving mathematical proof-of-work problems that validate transactions. Blockchain uses the concept of irreversible cryptographic hash function which consists of guessing a random number (usually less than a certain value) to solve the problem for transaction validation. You will require machines with high processing power to be able to solve these problems (for example Fast-Hash One or CoinTerra TerraMiner IV). Computer's with a high end Graphics Card installed (such as the Nivida GTX 1080) are also able to solve these hashes effectively. <ide> <add>Some people invest in cryptocurrency on exchanges such as Binance, Bitrex, or Coinbase. The market peeked in January of 2018. <add> <ide> #### More Information: <ide> [Cryptocurrency](https://en.wikipedia.org/wiki/Cryptocurrency) <ide> [Ultimate Guide to Cryptocurrency](https://blockgeeks.com/guides/what-is-cryptocurrency)
1
Javascript
Javascript
replace fixturesdir with fixtures.readkey
59e6791fe5bc9c04ced109e4c222aed6954c7d11
<ide><path>test/parallel/test-https-agent-secure-protocol.js <ide> if (!common.hasCrypto) <ide> <ide> const assert = require('assert'); <ide> const https = require('https'); <del>const fs = require('fs'); <add>const fixtures = require('../common/fixtures'); <ide> <ide> const options = { <del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent1-key.pem`), <del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent1-cert.pem`), <del> ca: fs.readFileSync(`${common.fixturesDir}/keys/ca1-cert.pem`) <add> key: fixtures.readKey('agent1-key.pem'), <add> cert: fixtures.readKey('agent1-cert.pem'), <add> ca: fixtures.readKey('ca1-cert.pem') <ide> }; <ide> <ide> const server = https.Server(options, function(req, res) {
1
Text
Text
replace mozilla labs by just mozilla
529062a61bd53bd844c7b1ab04e1f666a8c357ca
<ide><path>README.md <ide> <ide> [PDF.js](https://mozilla.github.io/pdf.js/) is a Portable Document Format (PDF) viewer that is built with HTML5. <ide> <del>PDF.js is community-driven and supported by Mozilla Labs. Our goal is to <add>PDF.js is community-driven and supported by Mozilla. Our goal is to <ide> create a general-purpose, web standards-based platform for parsing and <ide> rendering PDFs. <ide>
1
Go
Go
remove unused rootfs.baselayer
25c896fcc25c64c5803b8ffdfceaa5aa1b99a139
<ide><path>api/types/types.go <ide> import ( <ide> <ide> // RootFS returns Image's RootFS description including the layer IDs. <ide> type RootFS struct { <del> Type string <del> Layers []string `json:",omitempty"` <del> BaseLayer string `json:",omitempty"` <add> Type string `json:",omitempty"` <add> Layers []string `json:",omitempty"` <ide> } <ide> <ide> // ImageInspect contains response of Engine API:
1
Ruby
Ruby
improve clarity of routing tests
be2a3b0a9319683e25ce06dda55b6d12a0c806ed
<ide><path>actionpack/test/dispatch/routing_test.rb <ide> def self.call(params, request) <ide> end <ide> end <ide> <del> stub_controllers do |routes| <del> Routes = routes <del> Routes.draw do <del> default_url_options :host => "rubyonrails.org" <del> resources_path_names :correlation_indexes => "info_about_correlation_indexes" <del> <del> controller :sessions do <del> get 'login' => :new <del> post 'login' => :create <del> delete 'logout' => :destroy <del> end <del> <del> resource :session do <del> get :create <del> post :reset <del> <del> resource :info <del> <del> member do <del> get :crush <del> end <del> end <del> <del> scope "bookmark", :controller => "bookmarks", :as => :bookmark do <del> get :new, :path => "build" <del> post :create, :path => "create", :as => "" <del> put :update <del> get :remove, :action => :destroy, :as => :remove <del> end <del> <del> scope "pagemark", :controller => "pagemarks", :as => :pagemark do <del> get "new", :path => "build" <del> post "create", :as => "" <del> put "update" <del> get "remove", :action => :destroy, :as => :remove <del> end <del> <del> get 'account/logout' => redirect("/logout"), :as => :logout_redirect <del> get 'account/login', :to => redirect("/login") <del> get 'secure', :to => redirect("/secure/login") <del> <del> get 'mobile', :to => redirect(:subdomain => 'mobile') <del> get 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '') <del> get 'new_documentation', :to => redirect(:path => '/documentation/new') <del> get 'super_new_documentation', :to => redirect(:host => 'super-docs.com') <del> <del> get 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}') <del> get 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}') <del> <del> get 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector) <del> <del> constraints(lambda { |req| true }) do <del> get 'account/overview' <del> end <del> <del> get '/account/nested/overview' <del> get 'sign_in' => "sessions#new" <del> <del> get 'account/modulo/:name', :to => redirect("/%{name}s") <del> get 'account/proc/:name', :to => redirect {|params, req| "/#{params[:name].pluralize}" } <del> get 'account/proc_req' => redirect {|params, req| "/#{req.method}" } <del> <del> get 'account/google' => redirect('http://www.google.com/', :status => 302) <del> <del> match 'openid/login', :via => [:get, :post], :to => "openid#login" <del> <del> controller(:global) do <del> get 'global/hide_notice' <del> get 'global/export', :to => :export, :as => :export_request <del> get '/export/:id/:file', :to => :export, :as => :export_download, :constraints => { :file => /.*/ } <del> get 'global/:action' <del> end <del> <del> get "/local/:action", :controller => "local" <del> <del> get "/projects/status(.:format)" <del> get "/404", :to => lambda { |env| [404, {"Content-Type" => "text/plain"}, ["NOT FOUND"]] } <del> <del> constraints(:ip => /192\.168\.1\.\d\d\d/) do <del> get 'admin' => "queenbee#index" <del> end <del> <del> constraints ::TestRoutingMapper::IpRestrictor do <del> get 'admin/accounts' => "queenbee#accounts" <del> end <del> <del> get 'admin/passwords' => "queenbee#passwords", :constraints => ::TestRoutingMapper::IpRestrictor <del> <del> scope 'pt', :as => 'pt' do <del> resources :projects, :path_names => { :edit => 'editar', :new => 'novo' }, :path => 'projetos' do <del> post :preview, :on => :new <del> put :close, :on => :member, :path => 'fechar' <del> get :open, :on => :new, :path => 'abrir' <del> end <del> resource :admin, :path_names => { :new => 'novo', :activate => 'ativar' }, :path => 'administrador' do <del> post :preview, :on => :new <del> put :activate, :on => :member <del> end <del> resources :products, :path_names => { :new => 'novo' } do <del> new do <del> post :preview <del> end <del> end <del> end <del> <del> resources :projects, :controller => :project do <del> resources :involvements, :attachments <del> get :correlation_indexes, :on => :collection <del> <del> resources :participants do <del> put :update_all, :on => :collection <del> end <del> <del> resources :companies do <del> resources :people <del> resource :avatar, :controller => :avatar <del> end <del> <del> resources :images, :as => :funny_images do <del> post :revise, :on => :member <del> end <del> <del> resource :manager, :as => :super_manager do <del> post :fire <del> end <del> <del> resources :people do <del> nested do <del> scope "/:access_token" do <del> resource :avatar <del> end <del> end <del> <del> member do <del> get 'some_path_with_name' <del> put :accessible_projects <del> post :resend, :generate_new_password <del> end <del> end <del> <del> resources :posts do <del> get :archive, :toggle_view, :on => :collection <del> post :preview, :on => :member <del> <del> resource :subscription <del> <del> resources :comments do <del> post :preview, :on => :collection <del> end <del> end <del> <del> post 'new', :action => 'new', :on => :collection, :as => :new <del> end <del> <del> resources :replies do <del> collection do <del> get 'page/:page' => 'replies#index', :page => %r{\d+} <del> get ':page' => 'replies#index', :page => %r{\d+} <del> end <del> <del> new do <del> post :preview <del> end <del> <del> member do <del> put :answer, :to => :mark_as_answer <del> delete :answer, :to => :unmark_as_answer <del> end <del> end <del> <del> resources :posts, :only => [:index, :show] do <del> namespace :admin do <del> root :to => "index#index" <del> end <del> resources :comments, :except => :destroy do <del> get "views" => "comments#views", :as => :views <del> end <del> end <del> <del> resource :past, :only => :destroy <del> resource :present, :only => :update <del> resource :future, :only => :create <del> resources :relationships, :only => [:create, :destroy] <del> resources :friendships, :only => [:update] <del> <del> shallow do <del> namespace :api do <del> resources :teams do <del> resources :players <del> resource :captain <del> end <del> end <del> end <del> <del> scope '/hello' do <del> shallow do <del> resources :notes do <del> resources :trackbacks <del> end <del> end <del> end <del> <del> resources :threads, :shallow => true do <del> resource :owner <del> resources :messages do <del> resources :comments do <del> member do <del> post :preview <del> end <del> end <del> end <del> end <del> <del> resources :sheep do <del> get "_it", :on => :member <del> end <del> <del> resources :clients do <del> namespace :google do <del> resource :account do <del> namespace :secret do <del> resource :info <del> end <del> end <del> end <del> end <del> <del> resources :customers do <del> get :recent, :on => :collection <del> get "profile", :on => :member <del> get "secret/profile" => "customers#secret", :on => :member <del> post "preview" => "customers#preview", :as => :another_preview, :on => :new <del> resource :avatar do <del> get "thumbnail" => "avatars#thumbnail", :as => :thumbnail, :on => :member <del> end <del> resources :invoices do <del> get "outstanding" => "invoices#outstanding", :on => :collection <del> get "overdue", :to => :overdue, :on => :collection <del> get "print" => "invoices#print", :as => :print, :on => :member <del> post "preview" => "invoices#preview", :as => :preview, :on => :new <del> get "aged/:months", :on => :collection, :action => :aged, :as => :aged <del> end <del> resources :notes, :shallow => true do <del> get "preview" => "notes#preview", :as => :preview, :on => :new <del> get "print" => "notes#print", :as => :print, :on => :member <del> end <del> get "inactive", :on => :collection <del> post "deactivate", :on => :member <del> get "old", :on => :collection, :as => :stale <del> get "export" <del> end <del> <del> namespace :api do <del> resources :customers do <del> get "recent" => "customers#recent", :as => :recent, :on => :collection <del> get "profile" => "customers#profile", :as => :profile, :on => :member <del> post "preview" => "customers#preview", :as => :preview, :on => :new <del> end <del> scope(':version', :version => /.+/) do <del> resources :users, :id => /.+?/, :format => /json|xml/ <del> end <del> <del> get "products/list" <del> end <del> <del> get 'sprockets.js' => ::TestRoutingMapper::SprocketsApp <del> <del> get 'people/:id/update', :to => 'people#update', :as => :update_person <del> get '/projects/:project_id/people/:id/update', :to => 'people#update', :as => :update_project_person <del> <del> # misc <del> get 'articles/:year/:month/:day/:title', :to => "articles#show", :as => :article <del> <del> # default params <del> get 'inline_pages/(:id)', :to => 'pages#show', :id => 'home' <del> get 'default_pages/(:id)', :to => 'pages#show', :defaults => { :id => 'home' } <del> defaults :id => 'home' do <del> get 'scoped_pages/(:id)', :to => 'pages#show' <del> end <del> <del> namespace :account do <del> get 'shorthand' <del> get 'description', :to => :description, :as => "description" <del> get ':action/callback', :action => /twitter|github/, :to => "callbacks", :as => :callback <del> resource :subscription, :credit, :credit_card <del> <del> root :to => "account#index" <del> <del> namespace :admin do <del> resource :subscription <del> end <del> end <del> <del> namespace :forum do <del> resources :products, :path => '' do <del> resources :questions <del> end <del> end <del> <del> namespace :users, :path => 'usuarios' do <del> root :to => 'home#index' <del> end <del> <del> controller :articles do <del> scope '/articles', :as => 'article' do <del> scope :path => '/:title', :title => /[a-z]+/, :as => :with_title do <del> get '/:id', :to => :with_id, :as => "" <del> end <del> end <del> end <del> <del> scope ':access_token', :constraints => { :access_token => /\w{5,5}/ } do <del> resources :rooms <del> end <del> <del> get '/info' => 'projects#info', :as => 'info' <del> <del> namespace :admin do <del> scope '(:locale)', :locale => /en|pl/ do <del> resources :descriptions <del> end <del> end <del> <del> scope '(:locale)', :locale => /en|pl/ do <del> get "registrations/new" <del> resources :descriptions <del> root :to => 'projects#index' <del> end <del> <del> scope :only => [:index, :show] do <del> resources :products, :constraints => { :id => /\d{4}/ } do <del> root :to => "products#root" <del> get :favorite, :on => :collection <del> resources :images <del> end <del> resource :account <del> end <del> <del> resource :dashboard, :constraints => { :ip => /192\.168\.1\.\d{1,3}/ } <del> <del> resource :token, :module => :api <del> scope :module => :api do <del> resources :errors, :shallow => true do <del> resources :notices <del> end <del> end <del> <del> scope :path => 'api' do <del> resource :me <del> get '/' => 'mes#index' <del> scope :v2 do <del> resource :me, as: 'v2_me' <del> get '/' => 'mes#index' <del> end <del> <del> scope :v3, :admin do <del> resource :me, as: 'v3_me' <del> end <del> end <del> <del> get "(/:username)/followers" => "followers#index" <del> get "/groups(/user/:username)" => "groups#index" <del> get "(/user/:username)/photos" => "photos#index" <del> <del> scope '(groups)' do <del> scope '(discussions)' do <del> resources :messages <del> end <del> end <del> <del> get "whatever/:controller(/:action(/:id))", :id => /\d+/ <del> <del> resource :profile do <del> get :settings <del> <del> new do <del> post :preview <del> end <del> end <del> <del> resources :content <del> <del> namespace :transport do <del> resources :taxis <del> end <del> <del> namespace :medical do <del> resource :taxis <del> end <del> <del> scope :constraints => { :id => /\d+/ } do <del> get '/tickets', :to => 'tickets#index', :as => :tickets <del> end <del> <del> scope :constraints => { :id => /\d{4}/ } do <del> resources :movies do <del> resources :reviews <del> resource :trailer <del> end <del> end <del> <del> namespace :private do <del> root :to => redirect('/private/index') <del> get "index", :to => 'private#index' <del> end <del> <del> scope :only => [:index, :show] do <del> namespace :only do <del> resources :clubs do <del> resources :players <del> resource :chairman <del> end <del> end <del> end <del> <del> scope :except => [:new, :create, :edit, :update, :destroy] do <del> namespace :except do <del> resources :clubs do <del> resources :players <del> resource :chairman <del> end <del> end <del> end <del> <del> namespace :wiki do <del> resources :articles, :id => /[^\/]+/ do <del> resources :comments, :only => [:create, :new] <del> end <del> end <del> <del> resources :wiki_pages, :path => :pages <del> resource :wiki_account, :path => :my_account <del> <del> scope :only => :show do <del> namespace :only do <del> resources :sectors, :only => :index do <del> resources :companies do <del> scope :only => :index do <del> resources :divisions <del> end <del> scope :except => [:show, :update, :destroy] do <del> resources :departments <del> end <del> end <del> resource :leader <del> resources :managers, :except => [:show, :update, :destroy] <del> end <del> end <del> end <del> <del> scope :except => :index do <del> namespace :except do <del> resources :sectors, :except => [:show, :update, :destroy] do <del> resources :companies do <del> scope :except => [:show, :update, :destroy] do <del> resources :divisions <del> end <del> scope :only => :index do <del> resources :departments <del> end <del> end <del> resource :leader <del> resources :managers, :only => :index <del> end <del> end <del> end <del> <del> resources :sections, :id => /.+/ do <del> get :preview, :on => :member <del> end <del> <del> resources :profiles, :param => :username, :username => /[a-z]+/ do <del> get :details, :on => :member <del> resources :messages <del> end <del> <del> resources :orders do <del> constraints :download => /[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/ do <del> resources :downloads, :param => :download, :shallow => true <del> end <del> end <del> <del> scope :as => "routes" do <del> get "/c/:id", :as => :collision, :to => "collision#show" <del> get "/collision", :to => "collision#show" <del> get "/no_collision", :to => "collision#show", :as => nil <del> <del> get "/fc/:id", :as => :forced_collision, :to => "forced_collision#show" <del> get "/forced_collision", :as => :forced_collision, :to => "forced_collision#show" <del> end <del> <del> get '/purchases/:token/:filename', <del> :to => 'purchases#fetch', <del> :token => /[[:alnum:]]{10}/, <del> :filename => /(.+)/, <del> :as => :purchase <del> <del> resources :lists, :id => /([A-Za-z0-9]{25})|default/ do <del> resources :todos, :id => /\d+/ <del> end <del> <del> scope '/countries/:country', :constraints => lambda { |params, req| %w(all France).include?(params[:country]) } do <del> get '/', :to => 'countries#index' <del> get '/cities', :to => 'countries#cities' <del> end <del> <del> get '/countries/:country/(*other)', :to => redirect{ |params, req| params[:other] ? "/countries/all/#{params[:other]}" : '/countries/all' } <del> <del> get '/:locale/*file.:format', :to => 'files#show', :file => /path\/to\/existing\/file/ <del> <del> scope '/italians' do <del> get '/writers', :to => 'italians#writers', :constraints => ::TestRoutingMapper::IpRestrictor <del> get '/sculptors', :to => 'italians#sculptors' <del> get '/painters/:painter', :to => 'italians#painters', :constraints => {:painter => /michelangelo/} <del> end <del> end <del> end <del> <del> class TestAltApp < ActionDispatch::IntegrationTest <del> class AltRequest <del> def initialize(env) <del> @env = env <del> end <del> <del> def path_info <del> "/" <del> end <del> <del> def request_method <del> "GET" <del> end <del> <del> def ip <del> "127.0.0.1" <del> end <del> <del> def x_header <del> @env["HTTP_X_HEADER"] || "" <del> end <del> end <del> <del> class XHeader <del> def call(env) <del> [200, {"Content-Type" => "text/html"}, ["XHeader"]] <del> end <del> end <del> <del> class AltApp <del> def call(env) <del> [200, {"Content-Type" => "text/html"}, ["Alternative App"]] <add> def test_logout <add> draw do <add> controller :sessions do <add> delete 'logout' => :destroy <ide> end <ide> end <ide> <del> AltRoutes = ActionDispatch::Routing::RouteSet.new(AltRequest) <del> AltRoutes.draw do <del> get "/" => TestRoutingMapper::TestAltApp::XHeader.new, :constraints => {:x_header => /HEADER/} <del> get "/" => TestRoutingMapper::TestAltApp::AltApp.new <del> end <del> <del> def app <del> AltRoutes <del> end <del> <del> def test_alt_request_without_header <del> get "/" <del> assert_equal "Alternative App", @response.body <del> end <del> <del> def test_alt_request_with_matched_header <del> get "/", {}, "HTTP_X_HEADER" => "HEADER" <del> assert_equal "XHeader", @response.body <del> end <del> <del> def test_alt_request_with_unmatched_header <del> get "/", {}, "HTTP_X_HEADER" => "NON_MATCH" <del> assert_equal "Alternative App", @response.body <del> end <del> end <del> <del> def app <del> Routes <del> end <del> <del> include Routes.url_helpers <del> <del> def test_logout <ide> delete '/logout' <ide> assert_equal 'sessions#destroy', @response.body <ide> <ide> def test_logout <ide> end <ide> <ide> def test_login <add> draw do <add> default_url_options :host => "rubyonrails.org" <add> <add> controller :sessions do <add> get 'login' => :new <add> post 'login' => :create <add> end <add> end <add> <ide> get '/login' <ide> assert_equal 'sessions#new', @response.body <ide> assert_equal '/login', login_path <ide> def test_login <ide> assert_equal '/login', url_for(:controller => 'sessions', :action => 'create', :only_path => true) <ide> assert_equal '/login', url_for(:controller => 'sessions', :action => 'new', :only_path => true) <ide> <del> assert_equal 'http://rubyonrails.org/login', Routes.url_for(:controller => 'sessions', :action => 'create') <del> assert_equal 'http://rubyonrails.org/login', Routes.url_helpers.login_url <add> assert_equal 'http://rubyonrails.org/login', url_for(:controller => 'sessions', :action => 'create') <add> assert_equal 'http://rubyonrails.org/login', login_url <ide> end <ide> <ide> def test_login_redirect <add> draw do <add> get 'account/login', :to => redirect("/login") <add> end <add> <ide> get '/account/login' <ide> verify_redirect 'http://www.example.com/login' <ide> end <ide> <ide> def test_logout_redirect_without_to <add> draw do <add> get 'account/logout' => redirect("/logout"), :as => :logout_redirect <add> end <add> <ide> assert_equal '/account/logout', logout_redirect_path <ide> get '/account/logout' <ide> verify_redirect 'http://www.example.com/logout' <ide> end <ide> <ide> def test_namespace_redirect <add> draw do <add> namespace :private do <add> root :to => redirect('/private/index') <add> get "index", :to => 'private#index' <add> end <add> end <add> <ide> get '/private' <ide> verify_redirect 'http://www.example.com/private/index' <ide> end <ide> <ide> def test_namespace_with_controller_segment <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw do <del> namespace :admin do <del> get '/:controller(/:action(/:id(.:format)))' <del> end <add> draw do <add> namespace :admin do <add> get '/:controller(/:action(/:id(.:format)))' <ide> end <ide> end <ide> end <ide> end <ide> <ide> def test_session_singleton_resource <add> draw do <add> resource :session do <add> get :create <add> post :reset <add> end <add> end <add> <ide> get '/session' <ide> assert_equal 'sessions#create', @response.body <ide> assert_equal '/session', session_path <ide> def test_session_singleton_resource <ide> end <ide> <ide> def test_session_info_nested_singleton_resource <add> draw do <add> resource :session do <add> resource :info <add> end <add> end <add> <ide> get '/session/info' <ide> assert_equal 'infos#show', @response.body <ide> assert_equal '/session/info', session_info_path <ide> end <ide> <ide> def test_member_on_resource <add> draw do <add> resource :session do <add> member do <add> get :crush <add> end <add> end <add> end <add> <ide> get '/session/crush' <ide> assert_equal 'sessions#crush', @response.body <ide> assert_equal '/session/crush', crush_session_path <ide> end <ide> <ide> def test_redirect_modulo <add> draw do <add> get 'account/modulo/:name', :to => redirect("/%{name}s") <add> end <add> <ide> get '/account/modulo/name' <ide> verify_redirect 'http://www.example.com/names' <ide> end <ide> <ide> def test_redirect_proc <add> draw do <add> get 'account/proc/:name', :to => redirect {|params, req| "/#{params[:name].pluralize}" } <add> end <add> <ide> get '/account/proc/person' <ide> verify_redirect 'http://www.example.com/people' <ide> end <ide> <ide> def test_redirect_proc_with_request <add> draw do <add> get 'account/proc_req' => redirect {|params, req| "/#{req.method}" } <add> end <add> <ide> get '/account/proc_req' <ide> verify_redirect 'http://www.example.com/GET' <ide> end <ide> <ide> def test_redirect_hash_with_subdomain <add> draw do <add> get 'mobile', :to => redirect(:subdomain => 'mobile') <add> end <add> <ide> get '/mobile' <ide> verify_redirect 'http://mobile.example.com/mobile' <ide> end <ide> <ide> def test_redirect_hash_with_domain_and_path <add> draw do <add> get 'documentation', :to => redirect(:domain => 'example-documentation.com', :path => '') <add> end <add> <ide> get '/documentation' <ide> verify_redirect 'http://www.example-documentation.com' <ide> end <ide> <ide> def test_redirect_hash_with_path <add> draw do <add> get 'new_documentation', :to => redirect(:path => '/documentation/new') <add> end <add> <ide> get '/new_documentation' <ide> verify_redirect 'http://www.example.com/documentation/new' <ide> end <ide> <ide> def test_redirect_hash_with_host <add> draw do <add> get 'super_new_documentation', :to => redirect(:host => 'super-docs.com') <add> end <add> <ide> get '/super_new_documentation?section=top' <ide> verify_redirect 'http://super-docs.com/super_new_documentation?section=top' <ide> end <ide> <ide> def test_redirect_hash_path_substitution <add> draw do <add> get 'stores/:name', :to => redirect(:subdomain => 'stores', :path => '/%{name}') <add> end <add> <ide> get '/stores/iernest' <ide> verify_redirect 'http://stores.example.com/iernest' <ide> end <ide> <ide> def test_redirect_hash_path_substitution_with_catch_all <add> draw do <add> get 'stores/:name(*rest)', :to => redirect(:subdomain => 'stores', :path => '/%{name}%{rest}') <add> end <add> <ide> get '/stores/iernest/products' <ide> verify_redirect 'http://stores.example.com/iernest/products' <ide> end <ide> <ide> def test_redirect_class <add> draw do <add> get 'youtube_favorites/:youtube_id/:name', :to => redirect(YoutubeFavoritesRedirector) <add> end <add> <ide> get '/youtube_favorites/oHg5SJYRHA0/rick-rolld' <ide> verify_redirect 'http://www.youtube.com/watch?v=oHg5SJYRHA0' <ide> end <ide> <ide> def test_openid <add> draw do <add> match 'openid/login', :via => [:get, :post], :to => "openid#login" <add> end <add> <ide> get '/openid/login' <ide> assert_equal 'openid#login', @response.body <ide> <ide> def test_openid <ide> end <ide> <ide> def test_bookmarks <add> draw do <add> scope "bookmark", :controller => "bookmarks", :as => :bookmark do <add> get :new, :path => "build" <add> post :create, :path => "create", :as => "" <add> put :update <add> get :remove, :action => :destroy, :as => :remove <add> end <add> end <add> <ide> get '/bookmark/build' <ide> assert_equal 'bookmarks#new', @response.body <ide> assert_equal '/bookmark/build', bookmark_new_path <ide> def test_bookmarks <ide> end <ide> <ide> def test_pagemarks <add> draw do <add> scope "pagemark", :controller => "pagemarks", :as => :pagemark do <add> get "new", :path => "build" <add> post "create", :as => "" <add> put "update" <add> get "remove", :action => :destroy, :as => :remove <add> end <add> end <add> <ide> get '/pagemark/build' <ide> assert_equal 'pagemarks#new', @response.body <ide> assert_equal '/pagemark/build', pagemark_new_path <ide> def test_pagemarks <ide> end <ide> <ide> def test_admin <add> draw do <add> constraints(:ip => /192\.168\.1\.\d\d\d/) do <add> get 'admin' => "queenbee#index" <add> end <add> <add> constraints ::TestRoutingMapper::IpRestrictor do <add> get 'admin/accounts' => "queenbee#accounts" <add> end <add> <add> get 'admin/passwords' => "queenbee#passwords", :constraints => ::TestRoutingMapper::IpRestrictor <add> end <add> <ide> get '/admin', {}, {'REMOTE_ADDR' => '192.168.1.100'} <ide> assert_equal 'queenbee#index', @response.body <ide> <ide> def test_admin <ide> end <ide> <ide> def test_global <add> draw do <add> controller(:global) do <add> get 'global/hide_notice' <add> get 'global/export', :to => :export, :as => :export_request <add> get '/export/:id/:file', :to => :export, :as => :export_download, :constraints => { :file => /.*/ } <add> get 'global/:action' <add> end <add> end <add> <ide> get '/global/dashboard' <ide> assert_equal 'global#dashboard', @response.body <ide> <ide> def test_global <ide> end <ide> <ide> def test_local <add> draw do <add> get "/local/:action", :controller => "local" <add> end <add> <ide> get '/local/dashboard' <ide> assert_equal 'local#dashboard', @response.body <ide> end <ide> <del> # tests the use of dup in url_for <del> def test_url_for_with_no_side_effects <add> # tests the use of dup in url_for <add> def test_url_for_with_no_side_effects <add> draw do <add> get "/projects/status(.:format)" <add> end <add> <ide> # without dup, additional (and possibly unwanted) values will be present in the options (eg. :host) <ide> original_options = {:controller => 'projects', :action => 'status'} <ide> options = original_options.dup <ide> def test_url_for_with_no_side_effects <ide> end <ide> <ide> def test_url_for_does_not_modify_controller <add> draw do <add> get "/projects/status(.:format)" <add> end <add> <ide> controller = '/projects' <ide> options = {:controller => controller, :action => 'status', :only_path => true} <ide> url = url_for(options) <ide> def test_url_for_does_not_modify_controller <ide> <ide> # tests the arguments modification free version of define_hash_access <ide> def test_named_route_with_no_side_effects <add> draw do <add> resources :customers do <add> get "profile", :on => :member <add> end <add> end <add> <ide> original_options = { :host => 'test.host' } <ide> options = original_options.dup <ide> <ide> def test_named_route_with_no_side_effects <ide> end <ide> <ide> def test_projects_status <add> draw do <add> get "/projects/status(.:format)" <add> end <add> <ide> assert_equal '/projects/status', url_for(:controller => 'projects', :action => 'status', :only_path => true) <ide> assert_equal '/projects/status.json', url_for(:controller => 'projects', :action => 'status', :format => 'json', :only_path => true) <ide> end <ide> <ide> def test_projects <add> draw do <add> resources :projects, :controller => :project <add> end <add> <ide> get '/projects' <ide> assert_equal 'project#index', @response.body <ide> assert_equal '/projects', projects_path <ide> def test_projects <ide> end <ide> <ide> def test_projects_with_post_action_and_new_path_on_collection <add> draw do <add> resources :projects, :controller => :project do <add> post 'new', :action => 'new', :on => :collection, :as => :new <add> end <add> end <add> <ide> post '/projects/new' <ide> assert_equal "project#new", @response.body <ide> assert_equal "/projects/new", new_projects_path <ide> end <ide> <ide> def test_projects_involvements <add> draw do <add> resources :projects, :controller => :project do <add> resources :involvements, :attachments <add> end <add> end <add> <ide> get '/projects/1/involvements' <ide> assert_equal 'involvements#index', @response.body <ide> assert_equal '/projects/1/involvements', project_involvements_path(:project_id => '1') <ide> def test_projects_involvements <ide> end <ide> <ide> def test_projects_attachments <add> draw do <add> resources :projects, :controller => :project do <add> resources :involvements, :attachments <add> end <add> end <add> <ide> get '/projects/1/attachments' <ide> assert_equal 'attachments#index', @response.body <ide> assert_equal '/projects/1/attachments', project_attachments_path(:project_id => '1') <ide> end <ide> <ide> def test_projects_participants <add> draw do <add> resources :projects, :controller => :project do <add> resources :participants do <add> put :update_all, :on => :collection <add> end <add> end <add> end <add> <ide> get '/projects/1/participants' <ide> assert_equal 'participants#index', @response.body <ide> assert_equal '/projects/1/participants', project_participants_path(:project_id => '1') <ide> def test_projects_participants <ide> end <ide> <ide> def test_projects_companies <add> draw do <add> resources :projects, :controller => :project do <add> resources :companies do <add> resources :people <add> resource :avatar, :controller => :avatar <add> end <add> end <add> end <add> <ide> get '/projects/1/companies' <ide> assert_equal 'companies#index', @response.body <ide> assert_equal '/projects/1/companies', project_companies_path(:project_id => '1') <ide> def test_projects_companies <ide> end <ide> <ide> def test_project_manager <add> draw do <add> resources :projects do <add> resource :manager, :as => :super_manager do <add> post :fire <add> end <add> end <add> end <add> <ide> get '/projects/1/manager' <ide> assert_equal 'managers#show', @response.body <ide> assert_equal '/projects/1/manager', project_super_manager_path(:project_id => '1') <ide> def test_project_manager <ide> end <ide> <ide> def test_project_images <add> draw do <add> resources :projects do <add> resources :images, :as => :funny_images do <add> post :revise, :on => :member <add> end <add> end <add> end <add> <ide> get '/projects/1/images' <ide> assert_equal 'images#index', @response.body <ide> assert_equal '/projects/1/images', project_funny_images_path(:project_id => '1') <ide> def test_project_images <ide> end <ide> <ide> def test_projects_people <add> draw do <add> resources :projects do <add> resources :people do <add> nested do <add> scope "/:access_token" do <add> resource :avatar <add> end <add> end <add> <add> member do <add> put :accessible_projects <add> post :resend, :generate_new_password <add> end <add> end <add> end <add> end <add> <ide> get '/projects/1/people' <ide> assert_equal 'people#index', @response.body <ide> assert_equal '/projects/1/people', project_people_path(:project_id => '1') <ide> def test_projects_people <ide> end <ide> <ide> def test_projects_with_resources_path_names <add> draw do <add> resources_path_names :correlation_indexes => "info_about_correlation_indexes" <add> <add> resources :projects do <add> get :correlation_indexes, :on => :collection <add> end <add> end <add> <ide> get '/projects/info_about_correlation_indexes' <del> assert_equal 'project#correlation_indexes', @response.body <add> assert_equal 'projects#correlation_indexes', @response.body <ide> assert_equal '/projects/info_about_correlation_indexes', correlation_indexes_projects_path <ide> end <ide> <ide> def test_projects_posts <add> draw do <add> resources :projects do <add> resources :posts do <add> get :archive, :toggle_view, :on => :collection <add> post :preview, :on => :member <add> <add> resource :subscription <add> <add> resources :comments do <add> post :preview, :on => :collection <add> end <add> end <add> end <add> end <add> <ide> get '/projects/1/posts' <ide> assert_equal 'posts#index', @response.body <ide> assert_equal '/projects/1/posts', project_posts_path(:project_id => '1') <ide> def test_projects_posts <ide> end <ide> <ide> def test_replies <add> draw do <add> resources :replies do <add> member do <add> put :answer, :to => :mark_as_answer <add> delete :answer, :to => :unmark_as_answer <add> end <add> end <add> end <add> <ide> put '/replies/1/answer' <ide> assert_equal 'replies#mark_as_answer', @response.body <ide> <ide> def test_replies <ide> end <ide> <ide> def test_resource_routes_with_only_and_except <add> draw do <add> resources :posts, :only => [:index, :show] do <add> resources :comments, :except => :destroy <add> end <add> end <add> <ide> get '/posts' <ide> assert_equal 'posts#index', @response.body <ide> assert_equal '/posts', posts_path <ide> def test_resource_routes_with_only_and_except <ide> end <ide> <ide> def test_resource_routes_only_create_update_destroy <add> draw do <add> resource :past, :only => :destroy <add> resource :present, :only => :update <add> resource :future, :only => :create <add> end <add> <ide> delete '/past' <ide> assert_equal 'pasts#destroy', @response.body <ide> assert_equal '/past', past_path <ide> def test_resource_routes_only_create_update_destroy <ide> end <ide> <ide> def test_resources_routes_only_create_update_destroy <add> draw do <add> resources :relationships, :only => [:create, :destroy] <add> resources :friendships, :only => [:update] <add> end <add> <ide> post '/relationships' <ide> assert_equal 'relationships#create', @response.body <ide> assert_equal '/relationships', relationships_path <ide> def test_resources_routes_only_create_update_destroy <ide> end <ide> <ide> def test_resource_with_slugs_in_ids <add> draw do <add> resources :posts <add> end <add> <ide> get '/posts/rails-rocks' <ide> assert_equal 'posts#show', @response.body <ide> assert_equal '/posts/rails-rocks', post_path(:id => 'rails-rocks') <ide> end <ide> <ide> def test_resources_for_uncountable_names <add> draw do <add> resources :sheep do <add> get "_it", :on => :member <add> end <add> end <add> <ide> assert_equal '/sheep', sheep_index_path <ide> assert_equal '/sheep/1', sheep_path(1) <ide> assert_equal '/sheep/new', new_sheep_path <ide> def test_resources_for_uncountable_names <ide> <ide> def test_resource_does_not_modify_passed_options <ide> options = {:id => /.+?/, :format => /json|xml/} <del> self.class.stub_controllers do |routes| <del> routes.draw do <del> resource :user, options <del> end <del> end <add> draw { resource :user, options } <ide> assert_equal({:id => /.+?/, :format => /json|xml/}, options) <ide> end <ide> <ide> def test_resources_does_not_modify_passed_options <ide> options = {:id => /.+?/, :format => /json|xml/} <del> self.class.stub_controllers do |routes| <del> routes.draw do <del> resources :users, options <del> end <del> end <add> draw { resources :users, options } <ide> assert_equal({:id => /.+?/, :format => /json|xml/}, options) <ide> end <ide> <ide> def test_path_names <add> draw do <add> scope 'pt', :as => 'pt' do <add> resources :projects, :path_names => { :edit => 'editar', :new => 'novo' }, :path => 'projetos' <add> resource :admin, :path_names => { :new => 'novo', :activate => 'ativar' }, :path => 'administrador' do <add> put :activate, :on => :member <add> end <add> end <add> end <add> <ide> get '/pt/projetos' <ide> assert_equal 'projects#index', @response.body <ide> assert_equal '/pt/projetos', pt_projects_path <ide> def test_path_names <ide> end <ide> <ide> def test_path_option_override <add> draw do <add> scope 'pt', :as => 'pt' do <add> resources :projects, :path_names => { :new => 'novo' }, :path => 'projetos' do <add> put :close, :on => :member, :path => 'fechar' <add> get :open, :on => :new, :path => 'abrir' <add> end <add> end <add> end <add> <ide> get '/pt/projetos/novo/abrir' <ide> assert_equal 'projects#open', @response.body <ide> assert_equal '/pt/projetos/novo/abrir', open_new_pt_project_path <ide> def test_path_option_override <ide> end <ide> <ide> def test_sprockets <add> draw do <add> get 'sprockets.js' => ::TestRoutingMapper::SprocketsApp <add> end <add> <ide> get '/sprockets.js' <ide> assert_equal 'javascripts', @response.body <ide> end <ide> <ide> def test_update_person_route <add> draw do <add> get 'people/:id/update', :to => 'people#update', :as => :update_person <add> end <add> <ide> get '/people/1/update' <ide> assert_equal 'people#update', @response.body <ide> <ide> assert_equal '/people/1/update', update_person_path(:id => 1) <ide> end <ide> <ide> def test_update_project_person <add> draw do <add> get '/projects/:project_id/people/:id/update', :to => 'people#update', :as => :update_project_person <add> end <add> <ide> get '/projects/1/people/2/update' <ide> assert_equal 'people#update', @response.body <ide> <ide> assert_equal '/projects/1/people/2/update', update_project_person_path(:project_id => 1, :id => 2) <ide> end <ide> <ide> def test_forum_products <add> draw do <add> namespace :forum do <add> resources :products, :path => '' do <add> resources :questions <add> end <add> end <add> end <add> <ide> get '/forum' <ide> assert_equal 'forum/products#index', @response.body <ide> assert_equal '/forum', forum_products_path <ide> def test_forum_products <ide> end <ide> <ide> def test_articles_perma <add> draw do <add> get 'articles/:year/:month/:day/:title', :to => "articles#show", :as => :article <add> end <add> <ide> get '/articles/2009/08/18/rails-3' <ide> assert_equal 'articles#show', @response.body <ide> <ide> assert_equal '/articles/2009/8/18/rails-3', article_path(:year => 2009, :month => 8, :day => 18, :title => 'rails-3') <ide> end <ide> <ide> def test_account_namespace <add> draw do <add> namespace :account do <add> resource :subscription, :credit, :credit_card <add> end <add> end <add> <ide> get '/account/subscription' <ide> assert_equal 'account/subscriptions#show', @response.body <ide> assert_equal '/account/subscription', account_subscription_path <ide> def test_account_namespace <ide> end <ide> <ide> def test_nested_namespace <add> draw do <add> namespace :account do <add> namespace :admin do <add> resource :subscription <add> end <add> end <add> end <add> <ide> get '/account/admin/subscription' <ide> assert_equal 'account/admin/subscriptions#show', @response.body <ide> assert_equal '/account/admin/subscription', account_admin_subscription_path <ide> end <ide> <ide> def test_namespace_nested_in_resources <add> draw do <add> resources :clients do <add> namespace :google do <add> resource :account do <add> namespace :secret do <add> resource :info <add> end <add> end <add> end <add> end <add> end <add> <ide> get '/clients/1/google/account' <ide> assert_equal '/clients/1/google/account', client_google_account_path(1) <ide> assert_equal 'google/accounts#show', @response.body <ide> def test_namespace_nested_in_resources <ide> end <ide> <ide> def test_namespace_with_options <add> draw do <add> namespace :users, :path => 'usuarios' do <add> root :to => 'home#index' <add> end <add> end <add> <ide> get '/usuarios' <ide> assert_equal '/usuarios', users_root_path <ide> assert_equal 'users/home#index', @response.body <ide> end <ide> <ide> def test_articles_with_id <add> draw do <add> controller :articles do <add> scope '/articles', :as => 'article' do <add> scope :path => '/:title', :title => /[a-z]+/, :as => :with_title do <add> get '/:id', :to => :with_id, :as => "" <add> end <add> end <add> end <add> end <add> <ide> get '/articles/rails/1' <ide> assert_equal 'articles#with_id', @response.body <ide> <ide> def test_articles_with_id <ide> end <ide> <ide> def test_access_token_rooms <add> draw do <add> scope ':access_token', :constraints => { :access_token => /\w{5,5}/ } do <add> resources :rooms <add> end <add> end <add> <ide> get '/12345/rooms' <ide> assert_equal 'rooms#index', @response.body <ide> <ide> def test_access_token_rooms <ide> end <ide> <ide> def test_root <add> draw do <add> root :to => 'projects#index' <add> end <add> <ide> assert_equal '/', root_path <ide> get '/' <ide> assert_equal 'projects#index', @response.body <ide> end <ide> <add> def test_scoped_root <add> draw do <add> scope '(:locale)', :locale => /en|pl/ do <add> root :to => 'projects#index' <add> end <add> end <add> <add> assert_equal '/en', root_path(:locale => 'en') <add> get '/en' <add> assert_equal 'projects#index', @response.body <add> end <add> <ide> def test_index <add> draw do <add> get '/info' => 'projects#info', :as => 'info' <add> end <add> <ide> assert_equal '/info', info_path <ide> get '/info' <ide> assert_equal 'projects#info', @response.body <ide> end <ide> <ide> def test_match_shorthand_with_no_scope <add> draw do <add> get 'account/overview' <add> end <add> <ide> assert_equal '/account/overview', account_overview_path <ide> get '/account/overview' <ide> assert_equal 'account#overview', @response.body <ide> end <ide> <ide> def test_match_shorthand_inside_namespace <add> draw do <add> namespace :account do <add> get 'shorthand' <add> end <add> end <add> <ide> assert_equal '/account/shorthand', account_shorthand_path <ide> get '/account/shorthand' <ide> assert_equal 'account#shorthand', @response.body <ide> end <ide> <ide> def test_match_shorthand_inside_namespace_with_controller <add> draw do <add> namespace :api do <add> get "products/list" <add> end <add> end <add> <ide> assert_equal '/api/products/list', api_products_list_path <ide> get '/api/products/list' <ide> assert_equal 'api/products#list', @response.body <ide> end <ide> <ide> def test_dynamically_generated_helpers_on_collection_do_not_clobber_resources_url_helper <add> draw do <add> resources :replies do <add> collection do <add> get 'page/:page' => 'replies#index', :page => %r{\d+} <add> get ':page' => 'replies#index', :page => %r{\d+} <add> end <add> end <add> end <add> <ide> assert_equal '/replies', replies_path <ide> end <ide> <ide> def test_scoped_controller_with_namespace_and_action <add> draw do <add> namespace :account do <add> get ':action/callback', :action => /twitter|github/, :to => "callbacks", :as => :callback <add> end <add> end <add> <ide> assert_equal '/account/twitter/callback', account_callback_path("twitter") <ide> get '/account/twitter/callback' <ide> assert_equal 'account/callbacks#twitter', @response.body <ide> def test_scoped_controller_with_namespace_and_action <ide> end <ide> <ide> def test_convention_match_nested_and_with_leading_slash <add> draw do <add> get '/account/nested/overview' <add> end <add> <ide> assert_equal '/account/nested/overview', account_nested_overview_path <ide> get '/account/nested/overview' <ide> assert_equal 'account/nested#overview', @response.body <ide> end <ide> <ide> def test_convention_with_explicit_end <add> draw do <add> get 'sign_in' => "sessions#new" <add> end <add> <ide> get '/sign_in' <ide> assert_equal 'sessions#new', @response.body <ide> assert_equal '/sign_in', sign_in_path <ide> end <ide> <ide> def test_redirect_with_complete_url_and_status <add> draw do <add> get 'account/google' => redirect('http://www.google.com/', :status => 302) <add> end <add> <ide> get '/account/google' <ide> verify_redirect 'http://www.google.com/', 302 <ide> end <ide> <ide> def test_redirect_with_port <add> draw do <add> get 'account/login', :to => redirect("/login") <add> end <add> <ide> previous_host, self.host = self.host, 'www.example.com:3000' <ide> <ide> get '/account/login' <ide> def test_redirect_with_port <ide> end <ide> <ide> def test_normalize_namespaced_matches <add> draw do <add> namespace :account do <add> get 'description', :to => :description, :as => "description" <add> end <add> end <add> <ide> assert_equal '/account/description', account_description_path <ide> <ide> get '/account/description' <ide> assert_equal 'account#description', @response.body <ide> end <ide> <ide> def test_namespaced_roots <add> draw do <add> namespace :account do <add> root :to => "account#index" <add> end <add> end <add> <ide> assert_equal '/account', account_root_path <ide> get '/account' <ide> assert_equal 'account/account#index', @response.body <ide> end <ide> <ide> def test_optional_scoped_root <add> draw do <add> scope '(:locale)', :locale => /en|pl/ do <add> root :to => 'projects#index' <add> end <add> end <add> <ide> assert_equal '/en', root_path("en") <ide> get '/en' <ide> assert_equal 'projects#index', @response.body <ide> end <ide> <ide> def test_optional_scoped_path <add> draw do <add> scope '(:locale)', :locale => /en|pl/ do <add> resources :descriptions <add> end <add> end <add> <ide> assert_equal '/en/descriptions', descriptions_path("en") <ide> assert_equal '/descriptions', descriptions_path(nil) <ide> assert_equal '/en/descriptions/1', description_path("en", 1) <ide> def test_optional_scoped_path <ide> end <ide> <ide> def test_nested_optional_scoped_path <add> draw do <add> namespace :admin do <add> scope '(:locale)', :locale => /en|pl/ do <add> resources :descriptions <add> end <add> end <add> end <add> <ide> assert_equal '/admin/en/descriptions', admin_descriptions_path("en") <ide> assert_equal '/admin/descriptions', admin_descriptions_path(nil) <ide> assert_equal '/admin/en/descriptions/1', admin_description_path("en", 1) <ide> def test_nested_optional_scoped_path <ide> end <ide> <ide> def test_nested_optional_path_shorthand <add> draw do <add> scope '(:locale)', :locale => /en|pl/ do <add> get "registrations/new" <add> end <add> end <add> <ide> get '/registrations/new' <ide> assert_nil @request.params[:locale] <ide> <ide> def test_nested_optional_path_shorthand <ide> end <ide> <ide> def test_default_params <add> draw do <add> get 'inline_pages/(:id)', :to => 'pages#show', :id => 'home' <add> get 'default_pages/(:id)', :to => 'pages#show', :defaults => { :id => 'home' } <add> <add> defaults :id => 'home' do <add> get 'scoped_pages/(:id)', :to => 'pages#show' <add> end <add> end <add> <ide> get '/inline_pages' <ide> assert_equal 'home', @request.params[:id] <ide> <ide> def test_default_params <ide> end <ide> <ide> def test_resource_constraints <add> draw do <add> resources :products, :constraints => { :id => /\d{4}/ } do <add> root :to => "products#root" <add> get :favorite, :on => :collection <add> resources :images <add> end <add> <add> resource :dashboard, :constraints => { :ip => /192\.168\.1\.\d{1,3}/ } <add> end <add> <ide> get '/products/1' <ide> assert_equal 'pass', @response.headers['X-Cascade'] <ide> get '/products' <ide> def test_resource_constraints <ide> end <ide> <ide> def test_root_works_in_the_resources_scope <add> draw do <add> resources :products do <add> root :to => "products#root" <add> end <add> end <add> <ide> get '/products' <ide> assert_equal 'products#root', @response.body <ide> assert_equal '/products', products_root_path <ide> end <ide> <ide> def test_module_scope <add> draw do <add> resource :token, :module => :api <add> end <add> <ide> get '/token' <ide> assert_equal 'api/tokens#show', @response.body <ide> assert_equal '/token', token_path <ide> end <ide> <ide> def test_path_scope <add> draw do <add> scope :path => 'api' do <add> resource :me <add> get '/' => 'mes#index' <add> end <add> end <add> <ide> get '/api/me' <ide> assert_equal 'mes#show', @response.body <ide> assert_equal '/api/me', me_path <ide> def test_path_scope <ide> end <ide> <ide> def test_symbol_scope <add> draw do <add> scope :path => 'api' do <add> scope :v2 do <add> resource :me, as: 'v2_me' <add> get '/' => 'mes#index' <add> end <add> <add> scope :v3, :admin do <add> resource :me, as: 'v3_me' <add> end <add> end <add> end <add> <ide> get '/api/v2/me' <ide> assert_equal 'mes#show', @response.body <ide> assert_equal '/api/v2/me', v2_me_path <ide> def test_symbol_scope <ide> end <ide> <ide> def test_url_generator_for_generic_route <add> draw do <add> get "whatever/:controller(/:action(/:id))" <add> end <add> <ide> get 'whatever/foo/bar' <ide> assert_equal 'foo#bar', @response.body <ide> <ide> def test_url_generator_for_generic_route <ide> end <ide> <ide> def test_url_generator_for_namespaced_generic_route <add> draw do <add> get "whatever/:controller(/:action(/:id))", :id => /\d+/ <add> end <add> <ide> get 'whatever/foo/bar/show' <ide> assert_equal 'foo/bar#show', @response.body <ide> <ide> def test_url_generator_for_namespaced_generic_route <ide> url_for(:controller => "foo/bar", :action => "show", :id => '1') <ide> end <ide> <del> def test_assert_recognizes_account_overview <del> assert_recognizes({:controller => "account", :action => "overview"}, "/account/overview") <del> end <del> <ide> def test_resource_new_actions <add> draw do <add> resources :replies do <add> new do <add> post :preview <add> end <add> end <add> <add> scope 'pt', :as => 'pt' do <add> resources :projects, :path_names => { :new => 'novo' }, :path => 'projetos' do <add> post :preview, :on => :new <add> end <add> <add> resource :admin, :path_names => { :new => 'novo' }, :path => 'administrador' do <add> post :preview, :on => :new <add> end <add> <add> resources :products, :path_names => { :new => 'novo' } do <add> new do <add> post :preview <add> end <add> end <add> end <add> <add> resource :profile do <add> new do <add> post :preview <add> end <add> end <add> end <add> <ide> assert_equal '/replies/new/preview', preview_new_reply_path <ide> assert_equal '/pt/projetos/novo/preview', preview_new_pt_project_path <ide> assert_equal '/pt/administrador/novo/preview', preview_new_pt_admin_path <ide> def test_resource_new_actions <ide> end <ide> <ide> def test_resource_merges_options_from_scope <del> assert_raise(NameError) { new_account_path } <add> draw do <add> scope :only => :show do <add> resource :account <add> end <add> end <add> <add> assert_raise(NoMethodError) { new_account_path } <ide> <ide> get '/account/new' <ide> assert_equal 404, status <ide> end <ide> <ide> def test_resources_merges_options_from_scope <add> draw do <add> scope :only => [:index, :show] do <add> resources :products do <add> resources :images <add> end <add> end <add> end <add> <ide> assert_raise(NoMethodError) { edit_product_path('1') } <ide> <ide> get '/products/1/edit' <ide> def test_resources_merges_options_from_scope <ide> end <ide> <ide> def test_shallow_nested_resources <add> draw do <add> shallow do <add> namespace :api do <add> resources :teams do <add> resources :players <add> resource :captain <add> end <add> end <add> end <add> <add> resources :threads, :shallow => true do <add> resource :owner <add> resources :messages do <add> resources :comments do <add> member do <add> post :preview <add> end <add> end <add> end <add> end <add> end <add> <ide> get '/api/teams' <ide> assert_equal 'api/teams#index', @response.body <ide> assert_equal '/api/teams', api_teams_path <ide> def test_shallow_nested_resources <ide> end <ide> <ide> def test_shallow_nested_resources_within_scope <add> draw do <add> scope '/hello' do <add> shallow do <add> resources :notes do <add> resources :trackbacks <add> end <add> end <add> end <add> end <add> <ide> get '/hello/notes/1/trackbacks' <ide> assert_equal 'trackbacks#index', @response.body <ide> assert_equal '/hello/notes/1/trackbacks', note_trackbacks_path(:note_id => 1) <ide> def test_shallow_nested_resources_within_scope <ide> end <ide> <ide> def test_custom_resource_routes_are_scoped <add> draw do <add> resources :customers do <add> get :recent, :on => :collection <add> get "profile", :on => :member <add> get "secret/profile" => "customers#secret", :on => :member <add> post "preview" => "customers#preview", :as => :another_preview, :on => :new <add> resource :avatar do <add> get "thumbnail" => "avatars#thumbnail", :as => :thumbnail, :on => :member <add> end <add> resources :invoices do <add> get "outstanding" => "invoices#outstanding", :on => :collection <add> get "overdue", :to => :overdue, :on => :collection <add> get "print" => "invoices#print", :as => :print, :on => :member <add> post "preview" => "invoices#preview", :as => :preview, :on => :new <add> end <add> resources :notes, :shallow => true do <add> get "preview" => "notes#preview", :as => :preview, :on => :new <add> get "print" => "notes#print", :as => :print, :on => :member <add> end <add> end <add> <add> namespace :api do <add> resources :customers do <add> get "recent" => "customers#recent", :as => :recent, :on => :collection <add> get "profile" => "customers#profile", :as => :profile, :on => :member <add> post "preview" => "customers#preview", :as => :preview, :on => :new <add> end <add> end <add> end <add> <ide> assert_equal '/customers/recent', recent_customers_path <ide> assert_equal '/customers/1/profile', profile_customer_path(:id => '1') <ide> assert_equal '/customers/1/secret/profile', secret_profile_customer_path(:id => '1') <ide> def test_custom_resource_routes_are_scoped <ide> end <ide> <ide> def test_shallow_nested_routes_ignore_module <add> draw do <add> scope :module => :api do <add> resources :errors, :shallow => true do <add> resources :notices <add> end <add> end <add> end <add> <ide> get '/errors/1/notices' <ide> assert_equal 'api/notices#index', @response.body <ide> assert_equal '/errors/1/notices', error_notices_path(:error_id => '1') <ide> def test_shallow_nested_routes_ignore_module <ide> end <ide> <ide> def test_non_greedy_regexp <add> draw do <add> namespace :api do <add> scope(':version', :version => /.+/) do <add> resources :users, :id => /.+?/, :format => /json|xml/ <add> end <add> end <add> end <add> <ide> get '/api/1.0/users' <ide> assert_equal 'api/users#index', @response.body <ide> assert_equal '/api/1.0/users', api_users_path(:version => '1.0') <ide> def test_non_greedy_regexp <ide> end <ide> <ide> def test_glob_parameter_accepts_regexp <add> draw do <add> get '/:locale/*file.:format', :to => 'files#show', :file => /path\/to\/existing\/file/ <add> end <add> <ide> get '/en/path/to/existing/file.html' <ide> assert_equal 200, @response.status <ide> end <ide> <ide> def test_resources_controller_name_is_not_pluralized <add> draw do <add> resources :content <add> end <add> <ide> get '/content' <ide> assert_equal 'content#index', @response.body <ide> end <ide> <ide> def test_url_generator_for_optional_prefix_dynamic_segment <add> draw do <add> get "(/:username)/followers" => "followers#index" <add> end <add> <ide> get '/bob/followers' <ide> assert_equal 'followers#index', @response.body <ide> assert_equal 'http://www.example.com/bob/followers', <ide> def test_url_generator_for_optional_prefix_dynamic_segment <ide> end <ide> <ide> def test_url_generator_for_optional_suffix_static_and_dynamic_segment <add> draw do <add> get "/groups(/user/:username)" => "groups#index" <add> end <add> <ide> get '/groups/user/bob' <ide> assert_equal 'groups#index', @response.body <ide> assert_equal 'http://www.example.com/groups/user/bob', <ide> def test_url_generator_for_optional_suffix_static_and_dynamic_segment <ide> end <ide> <ide> def test_url_generator_for_optional_prefix_static_and_dynamic_segment <add> draw do <add> get "(/user/:username)/photos" => "photos#index" <add> end <add> <ide> get 'user/bob/photos' <ide> assert_equal 'photos#index', @response.body <ide> assert_equal 'http://www.example.com/user/bob/photos', <ide> def test_url_generator_for_optional_prefix_static_and_dynamic_segment <ide> end <ide> <ide> def test_url_recognition_for_optional_static_segments <add> draw do <add> scope '(groups)' do <add> scope '(discussions)' do <add> resources :messages <add> end <add> end <add> end <add> <ide> get '/groups/discussions/messages' <ide> assert_equal 'messages#index', @response.body <ide> <ide> def test_url_recognition_for_optional_static_segments <ide> end <ide> <ide> def test_router_removes_invalid_conditions <add> draw do <add> scope :constraints => { :id => /\d+/ } do <add> get '/tickets', :to => 'tickets#index', :as => :tickets <add> end <add> end <add> <ide> get '/tickets' <ide> assert_equal 'tickets#index', @response.body <ide> assert_equal '/tickets', tickets_path <ide> end <ide> <ide> def test_constraints_are_merged_from_scope <add> draw do <add> scope :constraints => { :id => /\d{4}/ } do <add> resources :movies do <add> resources :reviews <add> resource :trailer <add> end <add> end <add> end <add> <ide> get '/movies/0001' <ide> assert_equal 'movies#show', @response.body <ide> assert_equal '/movies/0001', movie_path(:id => '0001') <ide> def test_constraints_are_merged_from_scope <ide> end <ide> <ide> def test_only_should_be_read_from_scope <add> draw do <add> scope :only => [:index, :show] do <add> namespace :only do <add> resources :clubs do <add> resources :players <add> resource :chairman <add> end <add> end <add> end <add> end <add> <ide> get '/only/clubs' <ide> assert_equal 'only/clubs#index', @response.body <ide> assert_equal '/only/clubs', only_clubs_path <ide> def test_only_should_be_read_from_scope <ide> end <ide> <ide> def test_except_should_be_read_from_scope <add> draw do <add> scope :except => [:new, :create, :edit, :update, :destroy] do <add> namespace :except do <add> resources :clubs do <add> resources :players <add> resource :chairman <add> end <add> end <add> end <add> end <add> <ide> get '/except/clubs' <ide> assert_equal 'except/clubs#index', @response.body <ide> assert_equal '/except/clubs', except_clubs_path <ide> def test_except_should_be_read_from_scope <ide> end <ide> <ide> def test_only_option_should_override_scope <add> draw do <add> scope :only => :show do <add> namespace :only do <add> resources :sectors, :only => :index <add> end <add> end <add> end <add> <ide> get '/only/sectors' <ide> assert_equal 'only/sectors#index', @response.body <ide> assert_equal '/only/sectors', only_sectors_path <ide> def test_only_option_should_override_scope <ide> end <ide> <ide> def test_only_option_should_not_inherit <add> draw do <add> scope :only => :show do <add> namespace :only do <add> resources :sectors, :only => :index do <add> resources :companies <add> resource :leader <add> end <add> end <add> end <add> end <add> <ide> get '/only/sectors/1/companies/2' <ide> assert_equal 'only/companies#show', @response.body <ide> assert_equal '/only/sectors/1/companies/2', only_sector_company_path(:sector_id => '1', :id => '2') <ide> def test_only_option_should_not_inherit <ide> assert_equal '/only/sectors/1/leader', only_sector_leader_path(:sector_id => '1') <ide> end <ide> <del> def test_except_option_should_override_scope <add> def test_except_option_should_override_scope <add> draw do <add> scope :except => :index do <add> namespace :except do <add> resources :sectors, :except => [:show, :update, :destroy] <add> end <add> end <add> end <add> <ide> get '/except/sectors' <ide> assert_equal 'except/sectors#index', @response.body <ide> assert_equal '/except/sectors', except_sectors_path <ide> def test_except_option_should_override_scope <ide> end <ide> <ide> def test_except_option_should_not_inherit <add> draw do <add> scope :except => :index do <add> namespace :except do <add> resources :sectors, :except => [:show, :update, :destroy] do <add> resources :companies <add> resource :leader <add> end <add> end <add> end <add> end <add> <ide> get '/except/sectors/1/companies/2' <ide> assert_equal 'except/companies#show', @response.body <ide> assert_equal '/except/sectors/1/companies/2', except_sector_company_path(:sector_id => '1', :id => '2') <ide> def test_except_option_should_not_inherit <ide> end <ide> <ide> def test_except_option_should_override_scoped_only <add> draw do <add> scope :only => :show do <add> namespace :only do <add> resources :sectors, :only => :index do <add> resources :managers, :except => [:show, :update, :destroy] <add> end <add> end <add> end <add> end <add> <ide> get '/only/sectors/1/managers' <ide> assert_equal 'only/managers#index', @response.body <ide> assert_equal '/only/sectors/1/managers', only_sector_managers_path(:sector_id => '1') <ide> def test_except_option_should_override_scoped_only <ide> end <ide> <ide> def test_only_option_should_override_scoped_except <add> draw do <add> scope :except => :index do <add> namespace :except do <add> resources :sectors, :except => [:show, :update, :destroy] do <add> resources :managers, :only => :index <add> end <add> end <add> end <add> end <add> <ide> get '/except/sectors/1/managers' <ide> assert_equal 'except/managers#index', @response.body <ide> assert_equal '/except/sectors/1/managers', except_sector_managers_path(:sector_id => '1') <ide> def test_only_option_should_override_scoped_except <ide> end <ide> <ide> def test_only_scope_should_override_parent_scope <add> draw do <add> scope :only => :show do <add> namespace :only do <add> resources :sectors, :only => :index do <add> resources :companies do <add> scope :only => :index do <add> resources :divisions <add> end <add> end <add> end <add> end <add> end <add> end <add> <ide> get '/only/sectors/1/companies/2/divisions' <ide> assert_equal 'only/divisions#index', @response.body <ide> assert_equal '/only/sectors/1/companies/2/divisions', only_sector_company_divisions_path(:sector_id => '1', :company_id => '2') <ide> def test_only_scope_should_override_parent_scope <ide> end <ide> <ide> def test_except_scope_should_override_parent_scope <add> draw do <add> scope :except => :index do <add> namespace :except do <add> resources :sectors, :except => [:show, :update, :destroy] do <add> resources :companies do <add> scope :except => [:show, :update, :destroy] do <add> resources :divisions <add> end <add> end <add> end <add> end <add> end <add> end <add> <ide> get '/except/sectors/1/companies/2/divisions' <ide> assert_equal 'except/divisions#index', @response.body <ide> assert_equal '/except/sectors/1/companies/2/divisions', except_sector_company_divisions_path(:sector_id => '1', :company_id => '2') <ide> def test_except_scope_should_override_parent_scope <ide> end <ide> <ide> def test_except_scope_should_override_parent_only_scope <add> draw do <add> scope :only => :show do <add> namespace :only do <add> resources :sectors, :only => :index do <add> resources :companies do <add> scope :except => [:show, :update, :destroy] do <add> resources :departments <add> end <add> end <add> end <add> end <add> end <add> end <add> <ide> get '/only/sectors/1/companies/2/departments' <ide> assert_equal 'only/departments#index', @response.body <ide> assert_equal '/only/sectors/1/companies/2/departments', only_sector_company_departments_path(:sector_id => '1', :company_id => '2') <ide> def test_except_scope_should_override_parent_only_scope <ide> end <ide> <ide> def test_only_scope_should_override_parent_except_scope <add> draw do <add> scope :except => :index do <add> namespace :except do <add> resources :sectors, :except => [:show, :update, :destroy] do <add> resources :companies do <add> scope :only => :index do <add> resources :departments <add> end <add> end <add> end <add> end <add> end <add> end <add> <ide> get '/except/sectors/1/companies/2/departments' <ide> assert_equal 'except/departments#index', @response.body <ide> assert_equal '/except/sectors/1/companies/2/departments', except_sector_company_departments_path(:sector_id => '1', :company_id => '2') <ide> def test_only_scope_should_override_parent_except_scope <ide> end <ide> <ide> def test_resources_are_not_pluralized <add> draw do <add> namespace :transport do <add> resources :taxis <add> end <add> end <add> <ide> get '/transport/taxis' <ide> assert_equal 'transport/taxis#index', @response.body <ide> assert_equal '/transport/taxis', transport_taxis_path <ide> def test_resources_are_not_pluralized <ide> end <ide> <ide> def test_singleton_resources_are_not_singularized <add> draw do <add> namespace :medical do <add> resource :taxis <add> end <add> end <add> <ide> get '/medical/taxis/new' <ide> assert_equal 'medical/taxis#new', @response.body <ide> assert_equal '/medical/taxis/new', new_medical_taxis_path <ide> def test_singleton_resources_are_not_singularized <ide> end <ide> <ide> def test_greedy_resource_id_regexp_doesnt_match_edit_and_custom_action <add> draw do <add> resources :sections, :id => /.+/ do <add> get :preview, :on => :member <add> end <add> end <add> <ide> get '/sections/1/edit' <ide> assert_equal 'sections#edit', @response.body <ide> assert_equal '/sections/1/edit', edit_section_path(:id => '1') <ide> def test_greedy_resource_id_regexp_doesnt_match_edit_and_custom_action <ide> end <ide> <ide> def test_resource_constraints_are_pushed_to_scope <add> draw do <add> namespace :wiki do <add> resources :articles, :id => /[^\/]+/ do <add> resources :comments, :only => [:create, :new] <add> end <add> end <add> end <add> <ide> get '/wiki/articles/Ruby_on_Rails_3.0' <ide> assert_equal 'wiki/articles#show', @response.body <ide> assert_equal '/wiki/articles/Ruby_on_Rails_3.0', wiki_article_path(:id => 'Ruby_on_Rails_3.0') <ide> def test_resource_constraints_are_pushed_to_scope <ide> end <ide> <ide> def test_resources_path_can_be_a_symbol <add> draw do <add> resources :wiki_pages, :path => :pages <add> resource :wiki_account, :path => :my_account <add> end <add> <ide> get '/pages' <ide> assert_equal 'wiki_pages#index', @response.body <ide> assert_equal '/pages', wiki_pages_path <ide> def test_resources_path_can_be_a_symbol <ide> end <ide> <ide> def test_redirect_https <add> draw do <add> get 'secure', :to => redirect("/secure/login") <add> end <add> <ide> with_https do <ide> get '/secure' <ide> verify_redirect 'https://www.example.com/secure/login' <ide> end <ide> end <ide> <ide> def test_symbolized_path_parameters_is_not_stale <add> draw do <add> scope '/countries/:country', :constraints => lambda { |params, req| %w(all France).include?(params[:country]) } do <add> get '/', :to => 'countries#index' <add> get '/cities', :to => 'countries#cities' <add> end <add> <add> get '/countries/:country/(*other)', :to => redirect{ |params, req| params[:other] ? "/countries/all/#{params[:other]}" : '/countries/all' } <add> end <add> <ide> get '/countries/France' <ide> assert_equal 'countries#index', @response.body <ide> <ide> def test_symbolized_path_parameters_is_not_stale <ide> end <ide> <ide> def test_constraints_block_not_carried_to_following_routes <add> draw do <add> scope '/italians' do <add> get '/writers', :to => 'italians#writers', :constraints => ::TestRoutingMapper::IpRestrictor <add> get '/sculptors', :to => 'italians#sculptors' <add> get '/painters/:painter', :to => 'italians#painters', :constraints => {:painter => /michelangelo/} <add> end <add> end <add> <ide> get '/italians/writers' <ide> assert_equal 'Not Found', @response.body <ide> <ide> def test_constraints_block_not_carried_to_following_routes <ide> end <ide> <ide> def test_custom_resource_actions_defined_using_string <add> draw do <add> resources :customers do <add> resources :invoices do <add> get "aged/:months", :on => :collection, :action => :aged, :as => :aged <add> end <add> <add> get "inactive", :on => :collection <add> post "deactivate", :on => :member <add> get "old", :on => :collection, :as => :stale <add> end <add> end <add> <ide> get '/customers/inactive' <ide> assert_equal 'customers#inactive', @response.body <ide> assert_equal '/customers/inactive', inactive_customers_path <ide> def test_custom_resource_actions_defined_using_string <ide> end <ide> <ide> def test_route_defined_in_resources_scope_level <add> draw do <add> resources :customers do <add> get "export" <add> end <add> end <add> <ide> get '/customers/1/export' <ide> assert_equal 'customers#export', @response.body <ide> assert_equal '/customers/1/export', customer_export_path(:customer_id => '1') <ide> end <ide> <ide> def test_named_character_classes_in_regexp_constraints <add> draw do <add> get '/purchases/:token/:filename', <add> :to => 'purchases#fetch', <add> :token => /[[:alnum:]]{10}/, <add> :filename => /(.+)/, <add> :as => :purchase <add> end <add> <ide> get '/purchases/315004be7e/Ruby_on_Rails_3.pdf' <ide> assert_equal 'purchases#fetch', @response.body <ide> assert_equal '/purchases/315004be7e/Ruby_on_Rails_3.pdf', purchase_path(:token => '315004be7e', :filename => 'Ruby_on_Rails_3.pdf') <ide> end <ide> <ide> def test_nested_resource_constraints <add> draw do <add> resources :lists, :id => /([A-Za-z0-9]{25})|default/ do <add> resources :todos, :id => /\d+/ <add> end <add> end <add> <ide> get '/lists/01234012340123401234fffff' <ide> assert_equal 'lists#show', @response.body <ide> assert_equal '/lists/01234012340123401234fffff', list_path(:id => '01234012340123401234fffff') <ide> def test_nested_resource_constraints <ide> end <ide> <ide> def test_named_routes_collision_is_avoided_unless_explicitly_given_as <add> draw do <add> scope :as => "routes" do <add> get "/c/:id", :as => :collision, :to => "collision#show" <add> get "/collision", :to => "collision#show" <add> get "/no_collision", :to => "collision#show", :as => nil <add> <add> get "/fc/:id", :as => :forced_collision, :to => "forced_collision#show" <add> get "/forced_collision", :as => :forced_collision, :to => "forced_collision#show" <add> end <add> end <add> <ide> assert_equal "/c/1", routes_collision_path(1) <ide> assert_equal "/fc/1", routes_forced_collision_path(1) <ide> end <ide> def test_redirect_argument_error <ide> end <ide> <ide> def test_explicitly_avoiding_the_named_route <add> draw do <add> scope :as => "routes" do <add> get "/c/:id", :as => :collision, :to => "collision#show" <add> get "/collision", :to => "collision#show" <add> get "/no_collision", :to => "collision#show", :as => nil <add> <add> get "/fc/:id", :as => :forced_collision, :to => "forced_collision#show" <add> get "/forced_collision", :as => :forced_collision, :to => "forced_collision#show" <add> end <add> end <add> <ide> assert !respond_to?(:routes_no_collision_path) <ide> end <ide> <ide> def test_controller_name_with_leading_slash_raise_error <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/feeds/:service', :to => '/feeds#show' } <del> end <add> draw { get '/feeds/:service', :to => '/feeds#show' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/feeds/:service', :controller => '/feeds', :action => 'show' } <del> end <add> draw { get '/feeds/:service', :controller => '/feeds', :action => 'show' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/api/feeds/:service', :to => '/api/feeds#show' } <del> end <add> draw { get '/api/feeds/:service', :to => '/api/feeds#show' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { controller("/feeds") { get '/feeds/:service', :to => :show } } <del> end <add> draw { controller("/feeds") { get '/feeds/:service', :to => :show } } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { resources :feeds, :controller => '/feeds' } <del> end <add> draw { resources :feeds, :controller => '/feeds' } <ide> end <ide> end <ide> <ide> def test_invalid_route_name_raises_error <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/products', :to => 'products#index', :as => 'products ' } <del> end <add> draw { get '/products', :to => 'products#index', :as => 'products ' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/products', :to => 'products#index', :as => ' products' } <del> end <add> draw { get '/products', :to => 'products#index', :as => ' products' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/products', :to => 'products#index', :as => 'products!' } <del> end <add> draw { get '/products', :to => 'products#index', :as => 'products!' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/products', :to => 'products#index', :as => 'products index' } <del> end <add> draw { get '/products', :to => 'products#index', :as => 'products index' } <ide> end <ide> <ide> assert_raise(ArgumentError) do <del> self.class.stub_controllers do |routes| <del> routes.draw { get '/products', :to => 'products#index', :as => '1products' } <del> end <add> draw { get '/products', :to => 'products#index', :as => '1products' } <ide> end <ide> end <ide> <ide> def test_nested_route_in_nested_resource <add> draw do <add> resources :posts, :only => [:index, :show] do <add> resources :comments, :except => :destroy do <add> get "views" => "comments#views", :as => :views <add> end <add> end <add> end <add> <ide> get "/posts/1/comments/2/views" <ide> assert_equal "comments#views", @response.body <ide> assert_equal "/posts/1/comments/2/views", post_comment_views_path(:post_id => '1', :comment_id => '2') <ide> end <ide> <ide> def test_root_in_deeply_nested_scope <add> draw do <add> resources :posts, :only => [:index, :show] do <add> namespace :admin do <add> root :to => "index#index" <add> end <add> end <add> end <add> <ide> get "/posts/1/admin" <ide> assert_equal "admin/index#index", @response.body <ide> assert_equal "/posts/1/admin", post_admin_root_path(:post_id => '1') <ide> end <ide> <ide> def test_custom_param <add> draw do <add> resources :profiles, :param => :username do <add> get :details, :on => :member <add> resources :messages <add> end <add> end <add> <ide> get '/profiles/bob' <ide> assert_equal 'profiles#show', @response.body <ide> assert_equal 'bob', @request.params[:username] <ide> def test_custom_param <ide> end <ide> <ide> def test_custom_param_constraint <add> draw do <add> resources :profiles, :param => :username, :username => /[a-z]+/ do <add> get :details, :on => :member <add> resources :messages <add> end <add> end <add> <ide> get '/profiles/bob1' <ide> assert_equal 404, @response.status <ide> <ide> def test_custom_param_constraint <ide> end <ide> <ide> def test_shallow_custom_param <add> draw do <add> resources :orders do <add> constraints :download => /[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}/ do <add> resources :downloads, :param => :download, :shallow => true <add> end <add> end <add> end <add> <ide> get '/downloads/0c0c0b68-d24b-11e1-a861-001ff3fffe6f.zip' <ide> assert_equal 'downloads#show', @response.body <ide> assert_equal '0c0c0b68-d24b-11e1-a861-001ff3fffe6f', @request.params[:download] <ide> end <ide> <ide> private <add> <add> def draw(&block) <add> self.class.stub_controllers do |routes| <add> @app = routes <add> @app.default_url_options = { host: 'www.example.com' } <add> @app.draw(&block) <add> end <add> end <add> <add> def url_for(options = {}) <add> @app.url_helpers.url_for(options) <add> end <add> <add> def method_missing(method, *args, &block) <add> if method.to_s =~ /_(path|url)$/ <add> @app.url_helpers.send(method, *args, &block) <add> else <add> super <add> end <add> end <add> <ide> def with_https <ide> old_https = https? <ide> https! <ide> def expected_redirect_body(url) <ide> end <ide> end <ide> <add>class TestAltApp < ActionDispatch::IntegrationTest <add> class AltRequest <add> def initialize(env) <add> @env = env <add> end <add> <add> def path_info <add> "/" <add> end <add> <add> def request_method <add> "GET" <add> end <add> <add> def ip <add> "127.0.0.1" <add> end <add> <add> def x_header <add> @env["HTTP_X_HEADER"] || "" <add> end <add> end <add> <add> class XHeader <add> def call(env) <add> [200, {"Content-Type" => "text/html"}, ["XHeader"]] <add> end <add> end <add> <add> class AltApp <add> def call(env) <add> [200, {"Content-Type" => "text/html"}, ["Alternative App"]] <add> end <add> end <add> <add> AltRoutes = ActionDispatch::Routing::RouteSet.new(AltRequest) <add> AltRoutes.draw do <add> get "/" => TestAltApp::XHeader.new, :constraints => {:x_header => /HEADER/} <add> get "/" => TestAltApp::AltApp.new <add> end <add> <add> def app <add> AltRoutes <add> end <add> <add> def test_alt_request_without_header <add> get "/" <add> assert_equal "Alternative App", @response.body <add> end <add> <add> def test_alt_request_with_matched_header <add> get "/", {}, "HTTP_X_HEADER" => "HEADER" <add> assert_equal "XHeader", @response.body <add> end <add> <add> def test_alt_request_with_unmatched_header <add> get "/", {}, "HTTP_X_HEADER" => "NON_MATCH" <add> assert_equal "Alternative App", @response.body <add> end <add>end <add> <ide> class TestAppendingRoutes < ActionDispatch::IntegrationTest <ide> def simple_app(resp) <ide> lambda { |e| [ 200, { 'Content-Type' => 'text/plain' }, [resp] ] }
1
Text
Text
add audiomack to inthewild.md
6c0855d444defe5d0f7c30f4b9de9472564c6501
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Artelys](https://www.artelys.com/) [[@fortierq](https://github.com/fortierq)] <ide> 1. [Asana](https://asana.com/) [[@chang](https://github.com/chang), [@dima-asana](https://github.com/dima-asana), [@jdavidheiser](https://github.com/jdavidheiser), [@ricardoandresrojas](https://github.com/ricardoandresrojas)] <ide> 1. [Astronomer](https://www.astronomer.io) [[@schnie](https://github.com/schnie), [@ashb](https://github.com/ashb), [@kaxil](https://github.com/kaxil), [@dimberman](https://github.com/dimberman), [@andriisoldatenko](https://github.com/andriisoldatenko), [@ryw](https://github.com/ryw), [@ryanahamilton](https://github.com/ryanahamilton), [@jhtimmins](https://github.com/jhtimmins), [@vikramkoka](https://github.com/vikramkoka), [@jedcunningham](https://github.com/jedcunningham), [@BasPH](https://github.com/basph), [@ephraimbuddy](https://github.com/ephraimbuddy), [@feluelle](https://github.com/feluelle)] <add>1. [Audiomack](https://audiomack.com) [[@billcrook](https://github.com/billcrook)] <ide> 1. [Auth0](https://auth0.com) [[@scottypate](https://github.com/scottypate)], [[@dm03514](https://github.com/dm03514)], [[@karangale](https://github.com/karangale)] <ide> 1. [Automattic](https://automattic.com/) [[@anandnalya](https://github.com/anandnalya), [@bperson](https://github.com/bperson), [@khrol](https://github.com/Khrol), [@xyu](https://github.com/xyu)] <ide> 1. [Avesta Technologies](https://avestatechnologies.com) [[@TheRum](https://github.com/TheRum)]
1
Go
Go
skip some test under non-root
4aae77602a7540b4f977572f3fbdc0891ac57cab
<ide><path>pkg/mount/mount_unix_test.go <ide> func TestMountOptionsParsing(t *testing.T) { <ide> } <ide> <ide> func TestMounted(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> tmp := path.Join(os.TempDir(), "mount-tests") <ide> if err := os.MkdirAll(tmp, 0777); err != nil { <ide> t.Fatal(err) <ide> func TestMounted(t *testing.T) { <ide> } <ide> <ide> func TestMountReadonly(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> tmp := path.Join(os.TempDir(), "mount-tests") <ide> if err := os.MkdirAll(tmp, 0777); err != nil { <ide> t.Fatal(err) <ide><path>pkg/mount/mounter_linux_test.go <ide> import ( <ide> <ide> func TestMount(t *testing.T) { <ide> if os.Getuid() != 0 { <del> t.Skip("not root tests would fail") <add> t.Skip("root required") <ide> } <ide> <ide> source, err := ioutil.TempDir("", "mount-test-source-") <ide><path>pkg/mount/sharedsubtree_linux_test.go <ide> import ( <ide> <ide> // nothing is propagated in or out <ide> func TestSubtreePrivate(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> tmp := path.Join(os.TempDir(), "mount-tests") <ide> if err := os.MkdirAll(tmp, 0777); err != nil { <ide> t.Fatal(err) <ide> func TestSubtreePrivate(t *testing.T) { <ide> // Testing that when a target is a shared mount, <ide> // then child mounts propagate to the source <ide> func TestSubtreeShared(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> tmp := path.Join(os.TempDir(), "mount-tests") <ide> if err := os.MkdirAll(tmp, 0777); err != nil { <ide> t.Fatal(err) <ide> func TestSubtreeShared(t *testing.T) { <ide> // testing that mounts to a shared source show up in the slave target, <ide> // and that mounts into a slave target do _not_ show up in the shared source <ide> func TestSubtreeSharedSlave(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> tmp := path.Join(os.TempDir(), "mount-tests") <ide> if err := os.MkdirAll(tmp, 0777); err != nil { <ide> t.Fatal(err) <ide> func TestSubtreeSharedSlave(t *testing.T) { <ide> } <ide> <ide> func TestSubtreeUnbindable(t *testing.T) { <add> if os.Getuid() != 0 { <add> t.Skip("root required") <add> } <add> <ide> tmp := path.Join(os.TempDir(), "mount-tests") <ide> if err := os.MkdirAll(tmp, 0777); err != nil { <ide> t.Fatal(err)
3
Ruby
Ruby
fix failing test
8f8c3cc1b195b29551c10fea40889dae92ac3b55
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> class Testball < Formula <ide> ensure <ide> cmd("uninstall", "--force", "testball") <ide> cmd("cleanup", "--force", "--prune=all") <del> formula_file.unlink <add> formula_file.unlink unless formula_file.nil? <ide> end <ide> <ide> def test_uninstall
1
Go
Go
add unit test to check bind / server side
ab35aef6b5b15c7c2d7aff4315025563b93ee379
<ide><path>integration/api_test.go <ide> func TestPostContainersStart(t *testing.T) { <ide> containerKill(eng, containerID, t) <ide> } <ide> <add>// Expected behaviour: using / as a bind mount source should throw an error <add>func TestRunErrorBindMountRootSource(t *testing.T) { <add> eng := NewTestEngine(t) <add> defer mkRuntimeFromEngine(eng, t).Nuke() <add> srv := mkServerFromEngine(eng, t) <add> <add> containerID := createTestContainer( <add> eng, <add> &docker.Config{ <add> Image: unitTestImageID, <add> Cmd: []string{"/bin/cat"}, <add> OpenStdin: true, <add> }, <add> t, <add> ) <add> <add> hostConfigJSON, err := json.Marshal(&docker.HostConfig{ <add> Binds: []string{"/:/tmp"}, <add> }) <add> <add> req, err := http.NewRequest("POST", "/containers/"+containerID+"/start", bytes.NewReader(hostConfigJSON)) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> req.Header.Set("Content-Type", "application/json") <add> <add> r := httptest.NewRecorder() <add> if err := docker.ServeRequest(srv, docker.APIVERSION, r, req); err != nil { <add> t.Fatal(err) <add> } <add> if r.Code != http.StatusInternalServerError { <add> containerKill(eng, containerID, t) <add> t.Fatal("should have failed to run when using / as a source for the bind mount") <add> } <add>} <add> <ide> func TestPostContainersStop(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkRuntimeFromEngine(eng, t).Nuke()
1
Python
Python
detect iec 559 nextafter function
789ec8e18116c9f4fc8998c6ec0487ab275523c6
<ide><path>numpy/core/setup_common.py <ide> def check_api_version(apiversion, codegen_dir): <ide> # replacement implementation. Note that some of these are C99 functions. <ide> OPTIONAL_STDFUNCS = ["expm1", "log1p", "acosh", "asinh", "atanh", <ide> "rint", "trunc", "exp2", "log2", "hypot", "atan2", "pow", <del> "copysign"] <add> "copysign", "nextafter"] <ide> <ide> # Subset of OPTIONAL_STDFUNCS which may alreay have HAVE_* defined by Python.h <ide> OPTIONAL_STDFUNCS_MAYBE = ["expm1", "log1p", "acosh", "atanh", "asinh", "hypot", <ide> def check_api_version(apiversion, codegen_dir): <ide> "ceil", "rint", "trunc", "sqrt", "log10", "log", "log1p", "exp", <ide> "expm1", "asin", "acos", "atan", "asinh", "acosh", "atanh", <ide> "hypot", "atan2", "pow", "fmod", "modf", 'frexp', 'ldexp', <del> "exp2", "log2", "copysign"] <add> "exp2", "log2", "copysign", "nextafter"] <ide> <ide> C99_FUNCS_SINGLE = [f + 'f' for f in C99_FUNCS] <ide> C99_FUNCS_EXTENDED = [f + 'l' for f in C99_FUNCS]
1
Javascript
Javascript
improve touchable debugging
5c9b46c15e62d269d8eb6e9b3891f8626c51f1e5
<ide><path>Libraries/Components/Touchable/Touchable.js <ide> /** <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> * <ide> * @providesModule Touchable <ide> */ <ide> <ide> 'use strict'; <ide> <del>var BoundingDimensions = require('BoundingDimensions'); <del>var Position = require('Position'); <del>var TouchEventUtils = require('fbjs/lib/TouchEventUtils'); <add>const BoundingDimensions = require('BoundingDimensions'); <add>const Position = require('Position'); <add>const React = require('React'); // eslint-disable-line no-unused-vars <add>const TouchEventUtils = require('fbjs/lib/TouchEventUtils'); <add>const View = require('View'); <ide> <del>var keyMirror = require('fbjs/lib/keyMirror'); <del>var queryLayoutByID = require('queryLayoutByID'); <add>const keyMirror = require('fbjs/lib/keyMirror'); <add>const normalizeColor = require('normalizeColor'); <add>const queryLayoutByID = require('queryLayoutByID'); <ide> <ide> /** <ide> * `Touchable`: Taps done right. <ide> var TouchableMixin = { <ide> }; <ide> <ide> var Touchable = { <del> Mixin: TouchableMixin <add> Mixin: TouchableMixin, <add> TOUCH_TARGET_DEBUG: false, // Set this locally to help debug touch targets. <add> /** <add> * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). <add> */ <add> renderDebugView: ({color, hitSlop}) => { <add> if (!Touchable.TOUCH_TARGET_DEBUG) { <add> return null; <add> } <add> if (!__DEV__) { <add> throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!'); <add> } <add> const debugHitSlopStyle = {}; <add> hitSlop = hitSlop || {top: 0, bottom: 0, left: 0, right: 0}; <add> for (const key in hitSlop) { <add> debugHitSlopStyle[key] = -hitSlop[key]; <add> } <add> const hexColor = '#' + ('00000000' + normalizeColor(color).toString(16)).substr(-8); <add> return ( <add> <View <add> pointerEvents="none" <add> style={{ <add> position: 'absolute', <add> borderColor: hexColor.slice(0, -2) + '55', // More opaque <add> borderWidth: 1, <add> borderStyle: 'dashed', <add> backgroundColor: hexColor.slice(0, -2) + '0F', // Less opaque <add> ...debugHitSlopStyle <add> }} <add> /> <add> ); <add> } <ide> }; <add>if (Touchable.TOUCH_TARGET_DEBUG) { <add> console.warn('Touchable.TOUCH_TARGET_DEBUG is enabled'); <add>} <ide> <ide> module.exports = Touchable; <ide><path>Libraries/Components/Touchable/TouchableBounce.js <ide> var TouchableBounce = React.createClass({ <ide> onResponderRelease={this.touchableHandleResponderRelease} <ide> onResponderTerminate={this.touchableHandleResponderTerminate}> <ide> {this.props.children} <add> {Touchable.renderDebugView({color: 'orange', hitSlop: this.props.hitSlop})} <ide> </Animated.View> <ide> ); <ide> } <ide><path>Libraries/Components/Touchable/TouchableHighlight.js <ide> var TouchableHighlight = React.createClass({ <ide> ref: CHILD_REF, <ide> } <ide> )} <add> {Touchable.renderDebugView({color: 'green', hitSlop: this.props.hitSlop})} <ide> </View> <ide> ); <ide> } <ide><path>Libraries/Components/Touchable/TouchableNativeFeedback.android.js <ide> var PropTypes = require('ReactPropTypes'); <ide> var React = require('React'); <ide> var ReactNative = require('ReactNative'); <del>var ReactNativeViewAttributes = require('ReactNativeViewAttributes'); <ide> var Touchable = require('Touchable'); <ide> var TouchableWithoutFeedback = require('TouchableWithoutFeedback'); <ide> var UIManager = require('UIManager'); <ide> var TouchableNativeFeedback = React.createClass({ <ide> }, <ide> <ide> render: function() { <add> const child = onlyChild(this.props.children); <add> let children = child.props.children; <add> if (Touchable.TOUCH_TARGET_DEBUG && child.type.displayName === 'View') { <add> if (!Array.isArray(children)) { <add> children = [children]; <add> } <add> children.push(Touchable.renderDebugView({color: 'brown', hitSlop: this.props.hitSlop})); <add> } <ide> var childProps = { <del> ...onlyChild(this.props.children).props, <add> ...child.props, <ide> nativeBackgroundAndroid: this.props.background, <ide> accessible: this.props.accessible !== false, <ide> accessibilityLabel: this.props.accessibilityLabel, <ide> accessibilityComponentType: this.props.accessibilityComponentType, <ide> accessibilityTraits: this.props.accessibilityTraits, <add> children, <ide> testID: this.props.testID, <ide> onLayout: this.props.onLayout, <ide> hitSlop: this.props.hitSlop, <ide><path>Libraries/Components/Touchable/TouchableOpacity.js <ide> var TouchableOpacity = React.createClass({ <ide> onResponderRelease={this.touchableHandleResponderRelease} <ide> onResponderTerminate={this.touchableHandleResponderTerminate}> <ide> {this.props.children} <add> {Touchable.renderDebugView({color: 'cyan', hitSlop: this.props.hitSlop})} <ide> </Animated.View> <ide> ); <ide> }, <ide><path>Libraries/Components/Touchable/TouchableWithoutFeedback.js <ide> */ <ide> 'use strict'; <ide> <del>var EdgeInsetsPropType = require('EdgeInsetsPropType'); <del>var React = require('React'); <del>var TimerMixin = require('react-timer-mixin'); <del>var Touchable = require('Touchable'); <del>var View = require('View'); <del>var ensurePositiveDelayProps = require('ensurePositiveDelayProps'); <del>var invariant = require('fbjs/lib/invariant'); <del>var onlyChild = require('onlyChild'); <add>const EdgeInsetsPropType = require('EdgeInsetsPropType'); <add>const React = require('React'); <add>const TimerMixin = require('react-timer-mixin'); <add>const Touchable = require('Touchable'); <add>const View = require('View'); <add> <add>const ensurePositiveDelayProps = require('ensurePositiveDelayProps'); <add>const onlyChild = require('onlyChild'); <add>const warning = require('warning'); <ide> <ide> type Event = Object; <ide> <del>var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; <add>const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; <ide> <ide> /** <ide> * Do not use unless you have a very good reason. All the elements that <ide> var PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; <ide> * > <ide> * > If you wish to have several child components, wrap them in a View. <ide> */ <del>var TouchableWithoutFeedback = React.createClass({ <add>const TouchableWithoutFeedback = React.createClass({ <ide> mixins: [TimerMixin, Touchable.Mixin], <ide> <ide> propTypes: { <ide> var TouchableWithoutFeedback = React.createClass({ <ide> <ide> render: function(): ReactElement { <ide> // Note(avik): remove dynamic typecast once Flow has been upgraded <del> return (React: any).cloneElement(onlyChild(this.props.children), { <add> const child = onlyChild(this.props.children); <add> let children = child.props.children; <add> warning( <add> !child.type || child.type.displayName !== 'Text', <add> 'TouchableWithoutFeedback does not work well with Text children. Wrap children in a View instead. See ' + <add> child._owner.getName() <add> ); <add> if (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'View') { <add> if (!Array.isArray(children)) { <add> children = [children]; <add> } <add> children.push(Touchable.renderDebugView({color: 'red', hitSlop: this.props.hitSlop})); <add> } <add> const style = (Touchable.TOUCH_TARGET_DEBUG && child.type && child.type.displayName === 'Text') ? <add> [child.props.style, {color: 'red'}] : <add> child.props.style; <add> return (React: any).cloneElement(child, { <ide> accessible: this.props.accessible !== false, <ide> accessibilityLabel: this.props.accessibilityLabel, <ide> accessibilityComponentType: this.props.accessibilityComponentType, <ide> var TouchableWithoutFeedback = React.createClass({ <ide> onResponderGrant: this.touchableHandleResponderGrant, <ide> onResponderMove: this.touchableHandleResponderMove, <ide> onResponderRelease: this.touchableHandleResponderRelease, <del> onResponderTerminate: this.touchableHandleResponderTerminate <add> onResponderTerminate: this.touchableHandleResponderTerminate, <add> style, <add> children, <ide> }); <ide> } <ide> }); <ide><path>Libraries/Inspector/InspectorPanel.js <ide> var Text = require('Text'); <ide> var View = require('View'); <ide> var ElementProperties = require('ElementProperties'); <ide> var PerformanceOverlay = require('PerformanceOverlay'); <add>var Touchable = require('Touchable'); <ide> var TouchableHighlight = require('TouchableHighlight'); <ide> <ide> var PropTypes = React.PropTypes; <ide> class InspectorPanel extends React.Component { <ide> onClick={this.props.setPerfing} <ide> /> <ide> </View> <add> <Text style={styles.buttonText}> <add> {'Touchable.TOUCH_TARGET_DEBUG is ' + Touchable.TOUCH_TARGET_DEBUG} <add> </Text> <ide> </View> <ide> ); <ide> } <ide> var styles = StyleSheet.create({ <ide> fontSize: 20, <ide> textAlign: 'center', <ide> marginVertical: 20, <add> color: 'white', <ide> }, <ide> }); <ide> <ide><path>Libraries/Text/Text.js <ide> const NativeMethodsMixin = require('NativeMethodsMixin'); <ide> const Platform = require('Platform'); <ide> const React = require('React'); <del>const ReactInstanceMap = require('ReactInstanceMap'); <ide> const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); <ide> const StyleSheetPropType = require('StyleSheetPropType'); <ide> const TextStylePropTypes = require('TextStylePropTypes'); <ide> const Text = React.createClass({ <ide> if (setResponder && !this.touchableHandleActivePressIn) { <ide> // Attach and bind all the other handlers only the first time a touch <ide> // actually happens. <del> for (let key in Touchable.Mixin) { <add> for (const key in Touchable.Mixin) { <ide> if (typeof Touchable.Mixin[key] === 'function') { <ide> (this: any)[key] = Touchable.Mixin[key].bind(this); <ide> } <ide> const Text = React.createClass({ <ide> isHighlighted: this.state.isHighlighted, <ide> }; <ide> } <add> if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { <add> newProps = { <add> ...newProps, <add> style: [this.props.style, {color: 'magenta'}], <add> }; <add> } <ide> if (this.context.isInAParentText) { <ide> return <RCTVirtualText {...newProps} />; <ide> } else {
8
Java
Java
fix compiler warnings
1022683d1c122de07816346c980b25e174564c5a
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/codec/CodecException.java <ide> * <ide> * @author Sebastien Deleuze <ide> */ <add>@SuppressWarnings("serial") <ide> public class CodecException extends NestedRuntimeException { <ide> <ide> public CodecException(String msg, Throwable cause) { <ide><path>spring-web-reactive/src/main/java/org/springframework/core/convert/support/MonoToCompletableFutureConverter.java <ide> public class MonoToCompletableFutureConverter implements GenericConverter { <ide> <ide> @Override <del> public Set<ConvertiblePair> getConvertibleTypes() { <del> Set<GenericConverter.ConvertiblePair> pairs = new LinkedHashSet<>(); <add> public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() { <add> Set<GenericConverter.ConvertiblePair> pairs = new LinkedHashSet<>(2); <ide> pairs.add(new GenericConverter.ConvertiblePair(Mono.class, CompletableFuture.class)); <ide> pairs.add(new GenericConverter.ConvertiblePair(CompletableFuture.class, Mono.class)); <ide> return pairs; <ide> public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor t <ide> return null; <ide> } <ide> else if (CompletableFuture.class.isAssignableFrom(sourceType.getType())) { <del> return Mono.fromFuture((CompletableFuture) source); <add> return Mono.fromFuture((CompletableFuture<?>) source); <ide> } <ide> else if (CompletableFuture.class.isAssignableFrom(targetType.getType())) { <del> return Mono.from((Publisher) source).toFuture(); <add> return Mono.from((Publisher<?>) source).toFuture(); <ide> } <ide> return null; <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/core/convert/support/ReactorToRxJava1Converter.java <ide> public final class ReactorToRxJava1Converter implements GenericConverter { <ide> <ide> @Override <ide> public Set<GenericConverter.ConvertiblePair> getConvertibleTypes() { <del> Set<GenericConverter.ConvertiblePair> pairs = new LinkedHashSet<>(); <add> Set<GenericConverter.ConvertiblePair> pairs = new LinkedHashSet<>(6); <ide> pairs.add(new GenericConverter.ConvertiblePair(Flux.class, Observable.class)); <ide> pairs.add(new GenericConverter.ConvertiblePair(Observable.class, Flux.class)); <ide> pairs.add(new GenericConverter.ConvertiblePair(Mono.class, Single.class)); <ide> public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor t <ide> return null; <ide> } <ide> if (Observable.class.isAssignableFrom(sourceType.getType())) { <del> return RxJava1ObservableConverter.toPublisher((Observable) source); <add> return RxJava1ObservableConverter.toPublisher((Observable<?>) source); <ide> } <ide> else if (Observable.class.isAssignableFrom(targetType.getType())) { <del> return RxJava1ObservableConverter.fromPublisher((Publisher) source); <add> return RxJava1ObservableConverter.fromPublisher((Publisher<?>) source); <ide> } <ide> else if (Single.class.isAssignableFrom(sourceType.getType())) { <del> return RxJava1SingleConverter.toPublisher((Single) source); <add> return RxJava1SingleConverter.toPublisher((Single<?>) source); <ide> } <ide> else if (Single.class.isAssignableFrom(targetType.getType())) { <del> return RxJava1SingleConverter.fromPublisher((Publisher) source); <add> return RxJava1SingleConverter.fromPublisher((Publisher<?>) source); <ide> } <ide> else if (Completable.class.isAssignableFrom(sourceType.getType())) { <ide> return RxJava1CompletableConverter.toPublisher((Completable) source); <ide> } <ide> else if (Completable.class.isAssignableFrom(targetType.getType())) { <del> return RxJava1CompletableConverter.fromPublisher((Publisher) source); <add> return RxJava1CompletableConverter.fromPublisher((Publisher<?>) source); <ide> } <ide> return null; <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/http/codec/SseEventEncoder.java <ide> import reactor.core.publisher.Mono; <ide> <ide> import org.springframework.core.ResolvableType; <add>import org.springframework.core.codec.AbstractEncoder; <ide> import org.springframework.core.codec.CodecException; <ide> import org.springframework.core.codec.Encoder; <del>import org.springframework.core.codec.AbstractEncoder; <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.DataBufferFactory; <ide> import org.springframework.core.io.buffer.FlushingDataBuffer; <ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe <ide> sb.append(((String)data).replaceAll("\\n", "\ndata:")).append("\n"); <ide> } <ide> else { <del> Optional<Encoder<?>> encoder = dataEncoders <del> .stream() <del> .filter(e -> e.canEncode(ResolvableType.forClass(data.getClass()), mediaType)) <del> .findFirst(); <del> <del> if (encoder.isPresent()) { <del> dataBuffer = ((Encoder<Object>)encoder.get()) <del> .encode(Mono.just(data), bufferFactory, <del> ResolvableType.forClass(data.getClass()), mediaType) <del> .concatWith(encodeString("\n", bufferFactory)); <del> } <del> else { <del> throw new CodecException("No suitable encoder found!"); <del> } <add> dataBuffer = applyEncoder(data, mediaType, bufferFactory); <ide> } <ide> } <ide> <ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe <ide> <ide> } <ide> <add> @SuppressWarnings("unchecked") <add> private <T> Flux<DataBuffer> applyEncoder(Object data, MediaType mediaType, DataBufferFactory bufferFactory) { <add> ResolvableType elementType = ResolvableType.forClass(data.getClass()); <add> Optional<Encoder<?>> encoder = dataEncoders <add> .stream() <add> .filter(e -> e.canEncode(elementType, mediaType)) <add> .findFirst(); <add> if (!encoder.isPresent()) { <add> return Flux.error(new CodecException("No suitable encoder found!")); <add> } <add> return ((Encoder<T>) encoder.get()) <add> .encode(Mono.just((T) data), bufferFactory, elementType, mediaType) <add> .concatWith(encodeString("\n", bufferFactory)); <add> } <add> <ide> private Mono<DataBuffer> encodeString(String str, DataBufferFactory bufferFactory) { <ide> byte[] bytes = str.getBytes(StandardCharsets.UTF_8); <ide> DataBuffer buffer = bufferFactory.allocateBuffer(bytes.length).write(bytes); <ide><path>spring-web-reactive/src/main/java/org/springframework/http/codec/xml/XmlEventDecoder.java <ide> public XmlEventDecoder() { <ide> } <ide> <ide> @Override <add> @SuppressWarnings("unchecked") <ide> public Flux<XMLEvent> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType, <ide> MimeType mimeType, Object... hints) { <ide> Flux<DataBuffer> flux = Flux.from(inputStream); <ide> public Flux<XMLEvent> decode(Publisher<DataBuffer> inputStream, ResolvableType e <ide> flatMap(dataBuffer -> { <ide> try { <ide> InputStream is = dataBuffer.asInputStream(); <del> XMLEventReader eventReader = <del> inputFactory.createXMLEventReader(is); <del> return Flux <del> .fromIterable((Iterable<XMLEvent>) () -> eventReader); <add> XMLEventReader eventReader = inputFactory.createXMLEventReader(is); <add> return Flux.fromIterable((Iterable<XMLEvent>) () -> eventReader); <ide> } <ide> catch (XMLStreamException ex) { <ide> return Mono.error(ex); <ide><path>spring-web-reactive/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java <ide> * @author Rossen Stoyanchev <ide> */ <ide> @WebServlet(asyncSupported = true) <add>@SuppressWarnings("serial") <ide> public class ServletHttpHandlerAdapter extends HttpServlet { <ide> <ide> private static final int DEFAULT_BUFFER_SIZE = 8192; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/ClientWebRequest.java <ide> * <ide> * @author Brian Clozel <ide> */ <del>public class ClientWebRequest { <add>public class ClientWebRequest { <ide> <ide> protected final HttpMethod httpMethod; <ide> <ide> public class ClientWebRequest { <ide> <ide> private MultiValueMap<String, HttpCookie> cookies; <ide> <del> protected Publisher body; <add> protected Publisher<?> body; <ide> <ide> protected ResolvableType elementType; <ide> <ide> public void setCookies(MultiValueMap<String, HttpCookie> cookies) { <ide> this.cookies = cookies; <ide> } <ide> <del> public Publisher getBody() { <add> public Publisher<?> getBody() { <ide> return body; <ide> } <ide> <del> public void setBody(Publisher body) { <add> public void setBody(Publisher<?> body) { <ide> this.body = body; <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/DefaultClientWebRequestBuilder.java <ide> public class DefaultClientWebRequestBuilder implements ClientWebRequestBuilder { <ide> <ide> private final MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>(); <ide> <del> private Publisher body; <add> private Publisher<?> body; <ide> <ide> private ResolvableType elementType; <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/ResponseExtractors.java <ide> public class ResponseExtractors { <ide> * Extract the response body and decode it, returning it as a {@code Mono<T>} <ide> * @see ResolvableType#forClassWithGenerics(Class, Class[]) <ide> */ <add> @SuppressWarnings("unchecked") <ide> public static <T> ResponseExtractor<Mono<T>> body(ResolvableType bodyType) { <del> // noinspection unchecked <ide> return (clientResponse, messageConverters) -> (Mono<T>) clientResponse <ide> .flatMap(resp -> decodeResponseBody(resp, bodyType, <ide> messageConverters)) <ide> public static <T> ResponseExtractor<Flux<T>> bodyStream(Class<T> sourceClass) { <ide> * a single type {@code T} <ide> * @see ResolvableType#forClassWithGenerics(Class, Class[]) <ide> */ <add> @SuppressWarnings("unchecked") <ide> public static <T> ResponseExtractor<Mono<ResponseEntity<T>>> response( <ide> ResolvableType bodyType) { <ide> return (clientResponse, messageConverters) -> clientResponse.then(response -> { <ide> public static <T> ResponseExtractor<Mono<ResponseEntity<T>>> response( <ide> Mono.just(response.getStatusCode())); <ide> }).map(tuple -> { <ide> Object body = (tuple.getT1() != EMPTY_BODY ? tuple.getT1() : null); <del> // noinspection unchecked <ide> return new ResponseEntity<>((T) body, tuple.getT2(), tuple.getT3()); <ide> }); <ide> } <ide> public static ResponseExtractor<Mono<HttpHeaders>> headers() { <ide> return (clientResponse, messageConverters) -> clientResponse.map(resp -> resp.getHeaders()); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> protected static <T> Flux<T> decodeResponseBody(ClientHttpResponse response, <ide> ResolvableType responseType, <ide> List<HttpMessageConverter<?>> messageConverters) { <ide> protected static <T> Flux<T> decodeResponseBody(ClientHttpResponse response, <ide> "Could not decode response body of type '" + contentType <ide> + "' with target type '" + responseType.toString() + "'")); <ide> } <del> // noinspection unchecked <ide> return (Flux<T>) converter.get().read(responseType, response); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/WebClient.java <ide> public Mono<Void> apply(ClientHttpRequest clientHttpRequest) { <ide> } <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> protected Mono<Void> writeRequestBody(Publisher<?> content, <ide> ResolvableType requestType, ClientHttpRequest request, <ide> List<HttpMessageConverter<?>> messageConverters) { <ide> protected Mono<Void> writeRequestBody(Publisher<?> content, <ide> "Could not encode request body of type '" + contentType <ide> + "' with target type '" + requestType.toString() + "'")); <ide> } <del> // noinspection unchecked <ide> return converter.get().write((Publisher) content, requestType, contentType, request); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/WebClientException.java <ide> * <ide> * @author Brian Clozel <ide> */ <add>@SuppressWarnings("serial") <ide> public class WebClientException extends NestedRuntimeException { <ide> <ide> public WebClientException(String msg) { <ide><path>spring-web-reactive/src/main/java/org/springframework/web/client/reactive/support/RxJava1ResponseExtractors.java <ide> * <ide> * @author Brian Clozel <ide> */ <del>public class RxJava1ResponseExtractors { <add>public class RxJava1ResponseExtractors { <ide> <ide> /** <ide> * Extract the response body and decode it, returning it as a {@code Single<T>} <ide> */ <add> @SuppressWarnings("unchecked") <ide> public static <T> ResponseExtractor<Single<T>> body(Class<T> sourceClass) { <ide> <ide> ResolvableType resolvableType = ResolvableType.forClass(sourceClass); <del> //noinspection unchecked <ide> return (clientResponse, messageConverters) -> (Single<T>) RxJava1SingleConverter <ide> .fromPublisher(clientResponse <ide> .flatMap(resp -> decodeResponseBody(resp, resolvableType, messageConverters)).next()); <ide> public static <T> ResponseExtractor<Observable<T>> bodyStream(Class<T> sourceCla <ide> * Extract the full response body as a {@code ResponseEntity} <ide> * with its body decoded as a single type {@code T} <ide> */ <add> @SuppressWarnings("unchecked") <ide> public static <T> ResponseExtractor<Single<ResponseEntity<T>>> response(Class<T> sourceClass) { <ide> <ide> ResolvableType resolvableType = ResolvableType.forClass(sourceClass); <del> return (clientResponse, messageConverters) -> (Single<ResponseEntity<T>>) <add> return (clientResponse, messageConverters) -> <ide> RxJava1SingleConverter.fromPublisher(clientResponse <ide> .then(response -> <ide> Mono.when( <ide> decodeResponseBody(response, resolvableType, messageConverters).next(), <ide> Mono.just(response.getHeaders()), <ide> Mono.just(response.getStatusCode()))) <del> .map(tuple -> { <del> //noinspection unchecked <del> return new ResponseEntity<>((T) tuple.getT1(), tuple.getT2(), tuple.getT3()); <del> })); <add> .map(tuple -> <add> new ResponseEntity<>((T) tuple.getT1(), tuple.getT2(), tuple.getT3()))); <ide> } <ide> <ide> /** <ide> public static ResponseExtractor<Single<HttpHeaders>> headers() { <ide> .fromPublisher(clientResponse.map(resp -> resp.getHeaders())); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> protected static <T> Flux<T> decodeResponseBody(ClientHttpResponse response, ResolvableType responseType, <ide> List<HttpMessageConverter<?>> messageConverters) { <ide> <ide> protected static <T> Flux<T> decodeResponseBody(ClientHttpResponse response, Res <ide> return Flux.error(new IllegalStateException("Could not decode response body of type '" + contentType + <ide> "' with target type '" + responseType.toString() + "'")); <ide> } <del> //noinspection unchecked <ide> return (Flux<T>) converter.get().read(responseType, response); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/ContentNegotiatingResultHandlerSupport.java <ide> private List<MediaType> getAcceptableTypes(ServerWebExchange exchange) { <ide> return (mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> private List<MediaType> getProducibleTypes(ServerWebExchange exchange, List<MediaType> mediaTypes) { <del> Optional<?> optional = exchange.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); <add> Optional<Object> optional = exchange.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE); <ide> if (optional.isPresent()) { <ide> Set<MediaType> set = (Set<MediaType>) optional.get(); <ide> return new ArrayList<>(set); <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfoHandlerMapping.java <ide> public boolean hasParamsMismatch() { <ide> public Set<String> getAllowedMethods() { <ide> return this.partialMatches.stream(). <ide> flatMap(m -> m.getInfo().getMethodsCondition().getMethods().stream()). <del> map(Enum::name). <add> map(requestMethod -> requestMethod.name()). <ide> collect(Collectors.toCollection(LinkedHashSet::new)); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java <ide> protected String getDefaultViewName(HandlerResult result, ServerWebExchange exch <ide> return StringUtils.stripFilenameExtension(path); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> private Object updateModel(Object value, HandlerResult result) { <ide> if (value instanceof Model) { <ide> result.getModel().addAllAttributes(((Model) value).asMap()); <ide> } <ide> else if (value instanceof Map) { <del> //noinspection unchecked <ide> result.getModel().addAllAttributes((Map<String, ?>) value); <ide> } <ide> else { <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/MediaTypeNotSupportedStatusException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class MediaTypeNotSupportedStatusException extends ResponseStatusException { <ide> <ide> private final List<MediaType> supportedMediaTypes; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/MethodNotAllowedException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class MethodNotAllowedException extends ResponseStatusException { <ide> <ide> private String method; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/NotAcceptableStatusException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class NotAcceptableStatusException extends ResponseStatusException { <ide> <ide> private final List<MediaType> supportedMediaTypes; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/ResponseStatusException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class ResponseStatusException extends NestedRuntimeException { <ide> <ide> private final HttpStatus status; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/ServerErrorException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class ServerErrorException extends ResponseStatusException { <ide> <ide> private final MethodParameter parameter; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/ServerWebInputException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class ServerWebInputException extends ResponseStatusException { <ide> <ide> private final MethodParameter parameter; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/UnsupportedMediaTypeStatusException.java <ide> * <ide> * @author Rossen Stoyanchev <ide> */ <add>@SuppressWarnings("serial") <ide> public class UnsupportedMediaTypeStatusException extends ResponseStatusException { <ide> <ide> private final MediaType contentType; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/server/session/DefaultWebSession.java <ide> */ <ide> public class DefaultWebSession implements ConfigurableWebSession, Serializable { <ide> <add> private static final long serialVersionUID = -3567697426432961630L; <add> <add> <ide> private final String id; <ide> <ide> private final Map<String, Object> attributes; <ide><path>spring-web-reactive/src/test/java/org/springframework/http/codec/xml/Jaxb2DecoderTests.java <ide> public boolean equals(Object o) { <ide> return false; <ide> } <ide> <add> @Override <add> public int hashCode() { <add> int result = this.foo.hashCode(); <add> result = 31 * result + this.bar.hashCode(); <add> return result; <add> } <ide> } <ide> } <ide><path>spring-web-reactive/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java <ide> import org.junit.Test; <ide> <ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory; <del>import org.springframework.mock.web.MockHttpServletRequest; <add>import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.util.MultiValueMap; <ide> <ide> import static org.junit.Assert.assertEquals;
25
PHP
PHP
use a class constant for easier extandability
59fec3dfc6459dca28bc11d2543e23924186202b
<ide><path>src/Controller/Component/AuthComponent.php <ide> class AuthComponent extends Component <ide> <ide> use EventDispatcherTrait; <ide> <add> /** <add> * The query string key used for remembering the referrered page when getting <add> * redirected to login. <add> */ <add> const QUERY_STRING_REDIRECT = 'redirect'; <add> <ide> /** <ide> * Constant for 'all' <ide> * <ide> protected function _loginActionRedirectUrl() <ide> <ide> $loginAction = $this->_config['loginAction']; <ide> if (is_array($loginAction)) { <del> $loginAction['?']['redirect'] = $currentUrl; <add> $loginAction['?'][static::QUERY_STRING_REDIRECT] = $currentUrl; <ide> } else { <del> $loginAction .= '?redirect=' . rawurlencode($currentUrl); <add> $loginAction .= '?' . static::QUERY_STRING_REDIRECT . '=' . rawurlencode($currentUrl); <ide> } <ide> <ide> return $loginAction; <ide> protected function _getUser() <ide> */ <ide> public function redirectUrl($url = null) <ide> { <del> $redirectUrl = $this->request->query('redirect'); <add> $redirectUrl = $this->request->query(self::QUERY_STRING_REDIRECT); <ide> if ($redirectUrl && (substr($redirectUrl, 0, 1) !== '/')) { <ide> $redirectUrl = null; <ide> }
1
Text
Text
use es6 syntax and the object spread operator
9547056465d0758c8fb601699e5389a44d4dfc78
<ide><path>docs/recipes/ReducingBoilerplate.md <ide> The middleware that interprets such actions could look like this: <ide> <ide> ```js <ide> function callAPIMiddleware({ dispatch, getState }) { <del> return function (next) { <del> return function (action) { <del> const { <del> types, <del> callAPI, <del> shouldCallAPI = () => true, <del> payload = {} <del> } = action <del> <del> if (!types) { <del> // Normal action: pass it on <del> return next(action) <del> } <del> <del> if ( <del> !Array.isArray(types) || <del> types.length !== 3 || <del> !types.every(type => typeof type === 'string') <del> ) { <del> throw new Error('Expected an array of three string types.') <del> } <del> <del> if (typeof callAPI !== 'function') { <del> throw new Error('Expected fetch to be a function.') <del> } <del> <del> if (!shouldCallAPI(getState())) { <del> return <del> } <del> <del> const [ requestType, successType, failureType ] = types <del> <del> dispatch(Object.assign({}, payload, { <del> type: requestType <del> })) <del> <del> return callAPI().then( <del> response => dispatch(Object.assign({}, payload, { <del> response: response, <del> type: successType <del> })), <del> error => dispatch(Object.assign({}, payload, { <del> error: error, <del> type: failureType <del> })) <del> ) <add> return next => action => { <add> const { <add> types, <add> callAPI, <add> shouldCallAPI = () => true, <add> payload = {} <add> } = action <add> <add> if (!types) { <add> // Normal action: pass it on <add> return next(action) <ide> } <add> <add> if ( <add> !Array.isArray(types) || <add> types.length !== 3 || <add> !types.every(type => typeof type === 'string') <add> ) { <add> throw new Error('Expected an array of three string types.') <add> } <add> <add> if (typeof callAPI !== 'function') { <add> throw new Error('Expected fetch to be a function.') <add> } <add> <add> if (!shouldCallAPI(getState())) { <add> return <add> } <add> <add> const [ requestType, successType, failureType ] = types <add> <add> dispatch({ <add> ...payload, <add> type: requestType <add> }) <add> <add> return callAPI().then( <add> response => dispatch({ <add> ...payload, <add> response, <add> type: successType <add> }), <add> error => dispatch({ <add> ...payload, <add> error, <add> type: failureType <add> }) <add> ) <ide> } <ide> } <ide> ```
1
Text
Text
use un-minified three.js in fiddles
d5e3cb3fab32b07d7f369e80fe67c4019b1ea4d3
<ide><path>.github/CONTRIBUTING.md <ide> 1. Specify the revision number of the three.js library where the bug occurred. <ide> 2. Specify your browser version, operating system, and graphics card. (for example, Chrome 23.0.1271.95, Windows 7, Nvidia Quadro 2000M) <ide> 3. Describe the problem in detail. Explain what happened, and what you expected would happen. <del>4. Provide a small test-case (http://jsfiddle.net). [Here is a fiddle](http://jsfiddle.net/akmcv7Lh/) you can edit that runs the current version. [And here is a fiddle](http://jsfiddle.net/hw9rcLL8/) that uses the dev branch. If a test-case is not possible, provide a link to a live version of your application. <add>4. Provide a small test-case (http://jsfiddle.net). [Here is a fiddle](https://jsfiddle.net/3foLr7sn/) you can edit that runs the current version. [And here is a fiddle](https://jsfiddle.net/qgu17w5o/) that uses the dev branch. If a test-case is not possible, provide a link to a live version of your application. <ide> 5. If helpful, include a screenshot. Annotate the screenshot for clarity. <ide> <ide> --- <ide><path>.github/ISSUE_TEMPLATE.md <ide> Always include a code snippet, screenshots, and any relevant models or textures <ide> <ide> Please also include a live example if possible. You can start from these templates: <ide> <del>* [jsfiddle](https://jsfiddle.net/s3rjfcc3/) (latest release branch) <del>* [jsfiddle](https://jsfiddle.net/ptgwhemb/) (dev branch) <add>* [jsfiddle](https://jsfiddle.net/3foLr7sn/) (latest release branch) <add>* [jsfiddle](https://jsfiddle.net/qgu17w5o/) (dev branch) <ide> * [codepen](https://codepen.io/anon/pen/aEBKxR) (latest release branch) <ide> * [codepen](https://codepen.io/anon/pen/BJWzaN) (dev branch) <ide>
2
Javascript
Javascript
add tests for ternary operator in class bindings
a75451c878d3cda382da583118e8c021366ee82f
<ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> test("{{view}} should evaluate class bindings set to global paths", function() { <ide> window.App = Ember.Application.create({ <ide> isApp: true, <ide> isGreat: true, <del> directClass: "app-direct" <add> directClass: "app-direct", <add> isEnabled: true <ide> }); <ide> }); <ide> <ide> view = Ember.View.create({ <del> template: Ember.Handlebars.compile('{{view Ember.TextField class="unbound" classBinding="App.isGreat:great App.directClass App.isApp"}}') <add> template: Ember.Handlebars.compile('{{view Ember.TextField class="unbound" classBinding="App.isGreat:great App.directClass App.isApp App.isEnabled?enabled:disabled"}}') <ide> }); <ide> <ide> appendView(); <ide> test("{{view}} should evaluate class bindings set to global paths", function() { <ide> ok(view.$('input').hasClass('great'), "evaluates classes bound to global paths"); <ide> ok(view.$('input').hasClass('app-direct'), "evaluates classes bound directly to global paths"); <ide> ok(view.$('input').hasClass('is-app'), "evaluates classes bound directly to booleans in global paths - dasherizes and sets class when true"); <add> ok(view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings"); <add> ok(!view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings"); <ide> <ide> Ember.run(function() { <ide> App.set('isApp', false); <add> App.set('isEnabled', false); <ide> }); <ide> <ide> ok(!view.$('input').hasClass('is-app'), "evaluates classes bound directly to booleans in global paths - removes class when false"); <add> ok(!view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings"); <add> ok(view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings"); <ide> <ide> Ember.run(function() { <ide> window.App.destroy(); <ide> test("{{view}} should evaluate class bindings set in the current context", funct <ide> isView: true, <ide> isEditable: true, <ide> directClass: "view-direct", <del> template: Ember.Handlebars.compile('{{view Ember.TextField class="unbound" classBinding="isEditable:editable directClass isView"}}') <add> isEnabled: true, <add> template: Ember.Handlebars.compile('{{view Ember.TextField class="unbound" classBinding="isEditable:editable directClass isView isEnabled?enabled:disabled"}}') <ide> }); <ide> <ide> appendView(); <ide> test("{{view}} should evaluate class bindings set in the current context", funct <ide> ok(view.$('input').hasClass('editable'), "evaluates classes bound in the current context"); <ide> ok(view.$('input').hasClass('view-direct'), "evaluates classes bound directly in the current context"); <ide> ok(view.$('input').hasClass('is-view'), "evaluates classes bound directly to booleans in the current context - dasherizes and sets class when true"); <add> ok(view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings"); <add> ok(!view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings"); <ide> <ide> Ember.run(function() { <ide> view.set('isView', false); <add> view.set('isEnabled', false); <ide> }); <ide> <ide> ok(!view.$('input').hasClass('is-view'), "evaluates classes bound directly to booleans in the current context - removes class when false"); <add> ok(!view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings"); <add> ok(view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings"); <ide> }); <ide> <ide> test("{{view}} should evaluate class bindings set with either classBinding or classNameBindings", function() { <ide> Ember.run(function() { <ide> window.App = Ember.Application.create({ <del> isGreat: true <add> isGreat: true, <add> isEnabled: true <ide> }); <ide> }); <ide> <ide> view = Ember.View.create({ <del> template: Ember.Handlebars.compile('{{view Ember.TextField class="unbound" classBinding="App.isGreat:great" classNameBindings="App.isGreat:really-great"}}') <add> template: Ember.Handlebars.compile('{{view Ember.TextField class="unbound" classBinding="App.isGreat:great App.isEnabled?enabled:disabled" classNameBindings="App.isGreat:really-great App.isEnabled?really-enabled:really-disabled"}}') <ide> }); <ide> <ide> appendView(); <ide> <del> ok(view.$('input').hasClass('unbound'), "sets unbound classes directly"); <del> ok(view.$('input').hasClass('great'), "evaluates classBinding"); <del> ok(view.$('input').hasClass('really-great'), "evaluates classNameBinding"); <add> ok(view.$('input').hasClass('unbound'), "sets unbound classes directly"); <add> ok(view.$('input').hasClass('great'), "evaluates classBinding"); <add> ok(view.$('input').hasClass('really-great'), "evaluates classNameBinding"); <add> ok(view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings"); <add> ok(view.$('input').hasClass('really-enabled'), "evaluates ternary operator in classBindings"); <add> ok(!view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings"); <add> ok(!view.$('input').hasClass('really-disabled'), "evaluates ternary operator in classBindings"); <add> <add> Ember.run(function() { <add> App.set('isEnabled', false); <add> }); <add> <add> ok(!view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings"); <add> ok(!view.$('input').hasClass('really-enabled'), "evaluates ternary operator in classBindings"); <add> ok(view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings"); <add> ok(view.$('input').hasClass('really-disabled'), "evaluates ternary operator in classBindings"); <ide> <ide> Ember.run(function() { <ide> window.App.destroy(); <ide> test("should not allow XSS injection via {{bindAttr}} with class", function() { <ide> equal(view.$('img').attr('class'), '" onmouseover="alert(\'I am in your classes hacking your app\');'); <ide> }); <ide> <del>test("should be able to bind boolean element attributes using {{bindAttr}}", function() { <del> var template = Ember.Handlebars.compile('<input type="checkbox" {{bindAttr disabled="content.isDisabled" checked="content.isChecked"}} />'); <add>test("should be able to bind class attribute using ternary operator in {{bindAttr}}", function() { <add> var template = Ember.Handlebars.compile('<img {{bindAttr class="content.isDisabled?disabled:enabled"}} />'); <ide> var content = Ember.Object.create({ <del> isDisabled: false, <del> isChecked: true <add> isDisabled: true <ide> }); <ide> <ide> view = Ember.View.create({ <ide> test("should be able to bind boolean element attributes using {{bindAttr}}", fun <ide> <ide> appendView(); <ide> <del> ok(!view.$('input').attr('disabled'), 'attribute does not exist upon initial render'); <del> ok(view.$('input').attr('checked'), 'attribute is present upon initial render'); <add> ok(view.$('img').hasClass('disabled'), 'disabled class is rendered'); <add> ok(!view.$('img').hasClass('enabled'), 'enabled class is not rendered'); <ide> <ide> Ember.run(function() { <del> set(content, 'isDisabled', true); <del> set(content, 'isChecked', false); <add> set(content, 'isDisabled', false); <ide> }); <ide> <del> ok(view.$('input').attr('disabled'), 'attribute exists after update'); <del> ok(!view.$('input').attr('checked'), 'attribute is not present after update'); <add> ok(!view.$('img').hasClass('disabled'), 'disabled class is not rendered'); <add> ok(view.$('img').hasClass('enabled'), 'enabled class is rendered'); <ide> }); <ide> <ide> test("should be able to add multiple classes using {{bindAttr class}}", function() { <del> var template = Ember.Handlebars.compile('<div {{bindAttr class="content.isAwesomeSauce content.isAlsoCool content.isAmazing:amazing :is-super-duper"}}></div>'); <add> var template = Ember.Handlebars.compile('<div {{bindAttr class="content.isAwesomeSauce content.isAlsoCool content.isAmazing:amazing :is-super-duper content.isEnabled?enabled:disabled"}}></div>'); <ide> var content = Ember.Object.create({ <ide> isAwesomeSauce: true, <ide> isAlsoCool: true, <del> isAmazing: true <add> isAmazing: true, <add> isEnabled: true <ide> }); <ide> <ide> view = Ember.View.create({ <ide> test("should be able to add multiple classes using {{bindAttr class}}", function <ide> ok(view.$('div').hasClass('is-also-cool'), "dasherizes second property and sets classname"); <ide> ok(view.$('div').hasClass('amazing'), "uses alias for third property and sets classname"); <ide> ok(view.$('div').hasClass('is-super-duper'), "static class is present"); <add> ok(view.$('div').hasClass('enabled'), "truthy class in ternary classname definition is rendered"); <add> ok(!view.$('div').hasClass('disabled'), "falsy class in ternary classname definition is not rendered"); <ide> <ide> Ember.run(function() { <ide> set(content, 'isAwesomeSauce', false); <ide> set(content, 'isAmazing', false); <add> set(content, 'isEnabled', false); <ide> }); <ide> <ide> ok(!view.$('div').hasClass('is-awesome-sauce'), "removes dasherized class when property is set to false"); <ide> ok(!view.$('div').hasClass('amazing'), "removes aliased class when property is set to false"); <ide> ok(view.$('div').hasClass('is-super-duper'), "static class is still present"); <add> ok(!view.$('div').hasClass('enabled'), "truthy class in ternary classname definition is not rendered"); <add> ok(view.$('div').hasClass('disabled'), "falsy class in ternary classname definition is rendered"); <ide> }); <ide> <ide> test("should be able to bind classes to globals with {{bindAttr class}}", function() { <ide><path>packages/ember-views/tests/views/view/class_name_bindings_test.js <ide> module("Ember.View - Class Name Bindings"); <ide> test("should apply bound class names to the element", function() { <ide> var view = Ember.View.create({ <ide> classNameBindings: ['priority', 'isUrgent', 'isClassified:classified', <del> 'canIgnore', 'messages.count', 'messages.resent:is-resent', 'isNumber:is-number'], <add> 'canIgnore', 'messages.count', 'messages.resent:is-resent', 'isNumber:is-number', <add> 'isEnabled?enabled:disabled'], <ide> <ide> priority: 'high', <ide> isUrgent: true, <ide> isClassified: true, <ide> canIgnore: false, <del> isNumber: 5, <add> isNumber: 5, <add> isEnabled: true, <ide> <ide> messages: { <ide> count: 'five-messages', <ide> test("should apply bound class names to the element", function() { <ide> ok(view.$().hasClass('is-resent'), "supports customing class name for paths"); <ide> ok(view.$().hasClass('is-number'), "supports colon syntax with truthy properties"); <ide> ok(!view.$().hasClass('can-ignore'), "does not add false Boolean values as class"); <add> ok(view.$().hasClass('enabled'), "supports customizing class name for Boolean values with negation"); <add> ok(!view.$().hasClass('disabled'), "does not add class name for negated binding"); <ide> }); <ide> <ide> test("should add, remove, or change class names if changed after element is created", function() { <ide> var view = Ember.View.create({ <ide> classNameBindings: ['priority', 'isUrgent', 'isClassified:classified', <del> 'canIgnore', 'messages.count', 'messages.resent:is-resent'], <add> 'canIgnore', 'messages.count', 'messages.resent:is-resent', <add> 'isEnabled?enabled:disabled'], <ide> <ide> priority: 'high', <ide> isUrgent: true, <ide> isClassified: true, <ide> canIgnore: false, <add> isEnabled: true, <ide> <ide> messages: Ember.Object.create({ <ide> count: 'five-messages', <ide> test("should add, remove, or change class names if changed after element is crea <ide> set(view, 'priority', 'orange'); <ide> set(view, 'isUrgent', false); <ide> set(view, 'canIgnore', true); <add> set(view, 'isEnabled', false); <ide> setPath(view, 'messages.count', 'six-messages'); <ide> setPath(view, 'messages.resent', true ); <ide> }); <ide> test("should add, remove, or change class names if changed after element is crea <ide> ok(!view.$().hasClass('five-messages'), "removes old value when path changes"); <ide> <ide> ok(view.$().hasClass('is-resent'), "adds customized class name when path changes"); <add> <add> ok(!view.$().hasClass('enabled'), "updates class name for negated binding"); <add> ok(view.$().hasClass('disabled'), "adds negated class name for negated binding"); <ide> }); <ide> <ide> test("classNames should not be duplicated on rerender", function(){
2
Ruby
Ruby
restore env setting for global options
5e98d4df088128d32036bc2518db754714aa6f81
<ide><path>Library/Homebrew/cli/parser.rb <ide> def initialize(&block) <ide> @formula_options = false <ide> <ide> self.class.global_options.each do |short, long, desc| <del> switch short, long, description: desc <add> switch short, long, description: desc, env: option_to_name(long) <ide> end <ide> <ide> instance_eval(&block) if block_given?
1
Python
Python
remove tabs and unnecessary whitespace
37abe7a2f64dbd5dffee0d5abd5784b15191d9a5
<ide><path>numpy/core/setup.py <ide> def generate_umath_c(ext,build_dir): <ide> # (don't ask). Because clib are generated before extensions, we have to <ide> # explicitly add an extension which has generate_config_h and <ide> # generate_numpyconfig_h as sources *before* adding npymath. <del> config.add_library('npymath', <add> config.add_library('npymath', <ide> sources=[join('src', 'npy_math.c.src')], <ide> depends=[]) <ide> <ide> def get_dotblas_sources(ext, build_dir): <ide> extra_info = blas_info <ide> ) <ide> <del> config.add_extension('umath_tests', <del> sources = [join('src','umath_tests.c.src')]) <add> config.add_extension('umath_tests', <add> sources = [join('src','umath_tests.c.src')]) <ide> <ide> config.add_data_dir('tests') <ide> config.add_data_dir('tests/data') <ide><path>numpy/core/tests/test_scalarmath.py <ide> def _test_type_repr(self, t): <ide> assert_equal(val, val2) <ide> <ide> def test_float_repr(self): <del> # long double test cannot work, because eval goes through a python <del> # float <add> # long double test cannot work, because eval goes through a python <add> # float <ide> for t in [np.float32, np.float64]: <del> yield test_float_repr, t <add> yield test_float_repr, t <ide> <ide> if __name__ == "__main__": <ide> run_module_suite() <ide><path>numpy/distutils/command/build_ext.py <ide> def build_extension(self, ext): <ide> build_temp=self.build_temp,**kws) <ide> <ide> def _add_dummy_mingwex_sym(self, c_sources): <del> build_src = self.get_finalized_command("build_src").build_src <del> build_clib = self.get_finalized_command("build_clib").build_clib <del> objects = self.compiler.compile([os.path.join(build_src, <del> "gfortran_vs2003_hack.c")], <add> build_src = self.get_finalized_command("build_src").build_src <add> build_clib = self.get_finalized_command("build_clib").build_clib <add> objects = self.compiler.compile([os.path.join(build_src, <add> "gfortran_vs2003_hack.c")], <ide> output_dir=self.build_temp) <ide> self.compiler.create_static_lib(objects, "_gfortran_workaround", output_dir=build_clib, debug=self.debug) <ide> <ide><path>numpy/distutils/fcompiler/compaq.py <ide> class CompaqVisualFCompiler(FCompiler): <ide> m.initialize() <ide> ar_exe = m.lib <ide> except DistutilsPlatformError, msg: <del> pass <add> pass <ide> except AttributeError, msg: <ide> if '_MSVCCompiler__root' in str(msg): <ide> print 'Ignoring "%s" (I think it is msvccompiler.py bug)' % (msg) <ide> class CompaqVisualFCompiler(FCompiler): <ide> print "Unexpected IOError in", __file__ <ide> raise e <ide> except ValueError, e: <del> if not "path']" in str(e): <add> if not "path']" in str(e): <ide> print "Unexpected ValueError in", __file__ <ide> raise e <ide> <ide><path>numpy/distutils/misc_util.py <ide> def msvc_version(compiler): <ide> """Return version major and minor of compiler instance if it is <ide> MSVC, raise an exception otherwise.""" <ide> if not compiler.compiler_type == "msvc": <del> raise ValueError("Compiler instance is not msvc (%s)"\ <del> % compiler.compiler_type) <add> raise ValueError("Compiler instance is not msvc (%s)"\ <add> % compiler.compiler_type) <ide> return compiler._MSVCCompiler__version <ide> <ide> if sys.version[:3] >= '2.5':
5
Text
Text
update coverage badge and link to coveralls
e510ace5a7874daa9c49b5767ebf60ee48de1586
<ide><path>README.md <ide> <a href="https://travis-ci.org/cakephp/cakephp" target="_blank"> <ide> <img alt="Build Status" src="https://img.shields.io/travis/cakephp/cakephp/master.svg?style=flat-square"> <ide> </a> <del> <a href="https://codecov.io/github/cakephp/cakephp" target="_blank"> <del> <img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/cakephp/cakephp.svg?style=flat-square"> <add> <a href="https://coveralls.io/r/cakephp/cakephp?branch=master" target="_blank"> <add> <img alt="Coverage Status" src="https://img.shields.io/coveralls/cakephp/cakephp/master.svg?style=flat-square"> <ide> </a> <ide> <a href="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/" target="_blank"> <ide> <img alt="Code Consistency" src="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/grade.svg">
1