I am new to django and I misunderstand how to use templates.

I have a a file called base.html which I see as a parent to hello.html.

In hello.html I have this syntax:

{% extends "base.html" %}
{% block hello %}

hello

I should see this template. This is the hello.html template. {% endblock %}

In base.html I have this syntax:

{% block hello %}{% endblock %}

It is my understanding that django should render hello.html inside of base.html

When I deploy my two html files, django ignores my syntax.

Question: How to render hello.html in base.html?

The files are visible inside of github:

https://github.com/danbikle/sof1231/blob/master/hello/templates/base.html

https://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html

Also I deployed them to heroku with these commands:

heroku create sof1231
git push heroku master

You can see base.html deployed to https://sof1231.herokuapp.com

Again, How to render hello.html in base.html?

user3676943

Ответов: 2

Ответы (2)

To render a template in another template, you use include:

base.html

{% include 'hello.html' %}

Your templates are designed to work with inheritance, and there is nothing wrong with the simplified templates that you show in your question (I didn't check those on github).

I think that your problem might be caused by your view rendering the base.html template, when it should instead be rendering the hello.html template. You should add your view code to your question so that this can be verified. Your view code should be something like this, which renders the child template hello.html:

def hello(request):
    template_variables = {'a': 1, 'b': 2}
    return render(request, 'hello.html', template_variables)

Another answer (which you have accepted) recommends using include. I don't think that include is the correct approach.

There is a difference between inheriting from a base template and simple inclusion of content from another file. One important benefit of template inheritance is that you can add common content (e.g. menu, side bars, footers, etc.) to a "base" template and then inherit from that base in child templates without duplicating the common content for each page. Another benefit is that the child templates can override content in the base templates, e.g. </code>. This allows you to markup areas of your layout in the base template (using <code>block</code>) and then override the content of the block with other content. This is not possible with a simple <code>include</code>.</p> </div></div><div class="flex justify-between items-center"><div class="flex justify-start items-center"><div class="mr-2 p-1.5 rounded bg-purple-200 text-center w-10 h-10 text-xl font-bold text-purple-500" itemscope="" itemType="http://schema.org/Person" itemProp="author creator"><meta itemProp="name" content="mhawke"/><a target="_blank" rel="nofollow noopener noreferrer" itemProp="url" href="https://stackoverflow.com/users/21945/mhawke">m</a></div><div><p class="mb-0.5"><a class="text-sm font-bold text-gray-900 hover:text-purple-500 transition-all" target="_blank" rel="nofollow noopener noreferrer" href="https://stackoverflow.com/users/21945/mhawke">mhawke</a></p><p class="mb-0 text-sm font-normal text-gray-500"><a itemProp="url" href="/q/618-in-django-how-to-render-hellohtml-in-basehtml#answer_1924"><time itemProp="dateCreated" dateTime="2016-01-01 11:44:25" title="Дата публикации: 01.01.2016, в 11:44">6 лет назад</time></a></p></div></div></div></div></div></div></div><footer class="mt-6 py-6 border-t border-gray-200"><p class="mb-0 text-center font-semibold text-base text-gray-900">2022<!-- --> WebDevInsider</p></footer></main><aside class="hidden lg:block col-span-1"><div class="p-4 mb-4 rounded bg-purple-50 whitespace-pre-wrap"><h4 class="mt-0 mb-4 font-bold text-xl text-gray-900">Популярные</h4><div class="overflow-hidden"><ul><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/2178-kak-ya-mogu-sohranit-imya-polzovatelya-i-parol-v-git"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Как я могу сохранить имя пользователя и пароль в G</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/2209-na-zaproshennom-resurse-otsutstvuet-zagolovok-access-control-allow-origin-pri-popytke-poluchit-dannye-iz-rest-api"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">На запрошенном ресурсе отсутствует заголовок Acces</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/2173-git-otkazyvaetsya-obuedinyat-nesvyazannye-istorii-pri-perebazirovanii"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Git отказывается объединять несвязанные истории пр</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/2202-kak-mne-ubit-process-kotoryj-v-nastoyashee-vremya-ispolzuet-port-na-lokalnom-hoste-v-windows"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Как мне убить процесс, который в настоящее время и</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/2322-otvet-na-predpoletnyj-zapros-ne-prohodit-proverku-kontrolya-dostupa"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Ответ на предполетный запрос не проходит проверку </div></div></a></li></ul></div></div><div class="p-4 mb-4 rounded bg-purple-50 whitespace-pre-wrap"><h4 class="mt-0 mb-4 font-bold text-xl text-gray-900">Недавно добавленные</h4><div class="overflow-hidden"><ul><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/5821-proizvoditelnost-bolshogo-spiska-s-react"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Производительность большого списка с React</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/5857-kakovy-argumenty-urovni-klyuchi-i-imena-dlya-funkcii-concat-pandas"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Каковы аргументы «уровни», «ключи» и имена для фун</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/5823-sostoyanie-kak-massiv-obuektov-i-obuekt-s-klyuchom-po-identifikatoru"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Состояние как массив объектов и объект с ключом по</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/6845-stil-react-native-button-ne-rabotaet"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Стиль React-Native Button не работает</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/6836-oshibka-kompilyacii-sborki-maven-ne-udalos-vypolnit-cel-orgapachemavenpluginsmaven-compiler-plugin31compile-kompilyaciya-po-umolchaniyu-v-proekte-maven"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Ошибка компиляции сборки Maven: не удалось выполни</div></div></a></li></ul></div></div><div class="p-4 mb-4 rounded bg-purple-50 whitespace-pre-wrap"><h4 class="mt-0 mb-4 font-bold text-xl text-gray-900">Интересные</h4><div class="overflow-hidden"><ul><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/3207-make-axios-send-cookies-in-its-requests-automatically"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Make Axios send cookies in its requests automatica</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/3214-intellij-errorjava-error-release-version-5-not-supported"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">IntelliJ: Error:java: error: release version 5 not</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/3218-git-says-remote-ref-does-not-exist-when-i-delete-remote-branch"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Git says remote ref does not exist when I delete r</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/3184-how-to-manage-angular2-expression-has-changed-after-it-was-checked-exception-when-a-component-property-depends-on-current-datetime"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">How to manage Angular2 "expression has changed aft</div></div></a></li><li class="mb-4 last:mb-0"><a class="block break-words text-gray-900 hover:text-purple-500 transition-all" href="/q/3077-enabling-cors-in-cloud-functions-for-firebase"><div class="flex justify-start items-start"><div class="w-1/6"><div class="w-5 h-5 p-1 bg-purple-100 rounded"><svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg></div></div><div class="w-5/6 text-base -mt-1.5">Enabling CORS in Cloud Functions for Firebase</div></div></a></li></ul></div></div></aside></div></div></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"pageProps":{},"question":{"id":1359,"addedBy":null,"slug":"618-in-django-how-to-render-hellohtml-in-basehtml","title":"In Django how to render hello.html in base.html?","body":"I am new to django and I misunderstand how to use templates.\n\nI have a a file called base.html which I see as a parent to hello.html.\n\nIn hello.html I have this syntax:\n\n```\n{% extends \"base.html\" %}\n{% block hello %}\n\u003ch1\u003ehello\u003c/h1\u003e\nI should see this template. This is the hello.html template.\n{% endblock %}\n```\n\nIn base.html I have this syntax:\n\n```\n{% block hello %}{% endblock %}\n```\n\nIt is my understanding that django should render hello.html inside of base.html\n\nWhen I deploy my two html files, django ignores my syntax.\n\nQuestion: How to render hello.html in base.html?\n\nThe files are visible inside of github:\n\n[https://github.com/danbikle/sof1231/blob/master/hello/templates/base.html](\u003chttps://github.com/danbikle/sof1231/blob/master/hello/templates/base.html\u003e)\n\n[https://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html](\u003chttps://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html\u003e)\n\nAlso I deployed them to heroku with these commands:\n\n```\nheroku create sof1231\ngit push heroku master\n```\n\nYou can see base.html deployed to [https://sof1231.herokuapp.com](\u003chttps://sof1231.herokuapp.com\u003e)\n\nAgain, How to render hello.html in base.html?\n\n","htmlBody":"\u003cp\u003eI am new to django and I misunderstand how to use templates.\u003c/p\u003e\n\n\u003cp\u003eI have a a file called base.html which I see as a parent to hello.html.\u003c/p\u003e\n\n\u003cp\u003eIn hello.html I have this syntax:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e{% extends \"base.html\" %}\n{% block hello %}\n\u0026lt;h1\u0026gt;hello\u0026lt;/h1\u0026gt;\nI should see this template. This is the hello.html template.\n{% endblock %}\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eIn base.html I have this syntax:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e{% block hello %}{% endblock %}\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eIt is my understanding that django should render hello.html inside of base.html\u003c/p\u003e\n\n\u003cp\u003eWhen I deploy my two html files, django ignores my syntax.\u003c/p\u003e\n\n\u003cp\u003eQuestion: How to render hello.html in base.html?\u003c/p\u003e\n\n\u003cp\u003eThe files are visible inside of github:\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://github.com/danbikle/sof1231/blob/master/hello/templates/base.html\" rel=\"nofollow\"\u003ehttps://github.com/danbikle/sof1231/blob/master/hello/templates/base.html\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html\" rel=\"nofollow\"\u003ehttps://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eAlso I deployed them to heroku with these commands:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eheroku create sof1231\ngit push heroku master\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eYou can see base.html deployed to \u003ca href=\"https://sof1231.herokuapp.com\" rel=\"nofollow\"\u003ehttps://sof1231.herokuapp.com\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eAgain,\nHow to render hello.html in base.html?\u003c/p\u003e\n","originalBody":null,"likes":0,"pageViews":578,"author":"user3676943","authorProfile":"https://stackoverflow.com/users/3676943/user3676943","sourceLink":"https://stackoverflow.com/questions/34553049/in-django-how-to-render-hello-html-in-base-html","sourceId":34553049,"isActive":true,"isTranslated":false,"createdAt":"2016-01-01T02:08:12.000Z","updatedAt":"2021-12-15T22:14:08.625Z","tags":[{"id":4138,"questionId":1359,"tagId":318,"tag":{"id":318,"slug":"heroku","title":"heroku","description":null,"totalQuestions":8,"isActive":true,"createdAt":"2021-12-01T19:36:15.687Z","updatedAt":"2022-01-17T08:43:34.938Z"}},{"id":4136,"questionId":1359,"tagId":46,"tag":{"id":46,"slug":"python","title":"python","description":null,"totalQuestions":743,"isActive":true,"createdAt":"2021-12-01T19:35:07.579Z","updatedAt":"2022-01-17T08:47:45.240Z"}},{"id":4137,"questionId":1359,"tagId":48,"tag":{"id":48,"slug":"django","title":"django","description":null,"totalQuestions":68,"isActive":true,"createdAt":"2021-12-01T19:35:07.582Z","updatedAt":"2022-01-17T08:47:18.745Z"}}],"comments":[{"id":4722,"questionId":1359,"answerId":null,"comment":"@user3676943: I'm not sure that \u003ccode\u003einclude\u003c/code\u003e is the way to go. There's nothing wrong with the templates that you show, so there might be a problem with the way that you are rendering them. For that reason you should add your view code (as already suggested by Shang Wang) so this can be checked.","author":"mhawke","authorProfile":"https://stackoverflow.com/users/21945/mhawke","sourceId":56854381,"createdAt":"2016-01-01T11:46:51.000Z","updatedAt":"2016-01-01T11:46:51.000Z"},{"id":4721,"questionId":1359,"answerId":null,"comment":"I was following this doc: \u003ca href=\"https://docs.djangoproject.com/en/1.7/topics/templates/#templates\" rel=\"nofollow noreferrer\"\u003edocs.djangoproject.com/en/1.7/topics/templates/#templates\u003c/a\u003e which I think has wrong syntax in it. The answer below works well for me.","author":"user3676943","authorProfile":"https://stackoverflow.com/users/3676943/user3676943","sourceId":56849048,"createdAt":"2016-01-01T02:33:26.000Z","updatedAt":"2016-01-01T02:33:26.000Z"},{"id":4720,"questionId":1359,"answerId":null,"comment":"Show us your views code on how do you render the template?","author":"Shang Wang","authorProfile":"https://stackoverflow.com/users/636625/shang-wang","sourceId":56848909,"createdAt":"2016-01-01T02:15:40.000Z","updatedAt":"2016-01-01T02:15:40.000Z"}],"answers":[{"id":1923,"questionId":1359,"body":"To render a template in another template, you use [`include`](\u003chttps://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include\u003e):\n\n**base.html**\n\n```\n{% include 'hello.html' %}\n```\n\n","htmlBody":"\u003cp\u003eTo render a template in another template, you use \u003ca href=\"https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include\" rel=\"nofollow\"\u003e\u003ccode\u003einclude\u003c/code\u003e\u003c/a\u003e:\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003ebase.html\u003c/strong\u003e\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e{% include 'hello.html' %}\n\u003c/code\u003e\u003c/pre\u003e\n","originalBody":null,"author":"Leistungsabfall","authorProfile":"https://stackoverflow.com/users/3224008/leistungsabfall","sourceId":34553091,"isSolution":true,"isTranslated":false,"likes":0,"createdAt":"2016-01-01T02:23:04.000Z","updatedAt":"2016-01-01T02:23:04.000Z","comments":[]},{"id":1924,"questionId":1359,"body":"Your templates are designed to work with inheritance, and there is nothing wrong with the simplified templates that you show in your question (I didn't check those on github).\n\nI think that your problem *might* be caused by your view rendering the `base.html` template, when it should instead be rendering the `hello.html` template. You should add your view code to your question so that this can be verified. Your view code should be something like this, which renders the child template `hello.html`:\n\n```\ndef hello(request):\n template_variables = {'a': 1, 'b': 2}\n return render(request, 'hello.html', template_variables)\n```\n\n---\n\nAnother answer (which you have accepted) recommends using `include`. I don't think that `include` is the correct approach.\n\nThere is a difference between inheriting from a base template and simple inclusion of content from another file. One important benefit of template inheritance is that you can add common content (e.g. menu, side bars, footers, etc.) to a \"base\" template and then inherit from that base in child templates without duplicating the common content for each page. Another benefit is that the child templates can override content in the base templates, e.g. `\u0026lt;title\u0026gt;`. This allows you to markup areas of your layout in the base template (using `block`) and then override the content of the block with other content. This is not possible with a simple `include`.\n\n","htmlBody":"\u003cp\u003eYour templates are designed to work with inheritance, and there is nothing wrong with the simplified templates that you show in your question (I didn't check those on github).\u003c/p\u003e\n\n\u003cp\u003eI think that your problem \u003cem\u003emight\u003c/em\u003e be caused by your view rendering the \u003ccode\u003ebase.html\u003c/code\u003e template, when it should instead be rendering the \u003ccode\u003ehello.html\u003c/code\u003e template. You should add your view code to your question so that this can be verified. Your view code should be something like this, which renders the child template \u003ccode\u003ehello.html\u003c/code\u003e:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003edef hello(request):\n template_variables = {'a': 1, 'b': 2}\n return render(request, 'hello.html', template_variables)\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003chr\u003e\n\n\u003cp\u003eAnother answer (which you have accepted) recommends using \u003ccode\u003einclude\u003c/code\u003e. I don't think that \u003ccode\u003einclude\u003c/code\u003e is the correct approach.\u003c/p\u003e\n\n\u003cp\u003eThere is a difference between inheriting from a base template and simple inclusion of content from another file. One important benefit of template inheritance is that you can add common content (e.g. menu, side bars, footers, etc.) to a \"base\" template and then inherit from that base in child templates without duplicating the common content for each page. Another benefit is that the child templates can override content in the base templates, e.g. \u003ccode\u003e\u0026lt;title\u0026gt;\u003c/code\u003e. This allows you to markup areas of your layout in the base template (using \u003ccode\u003eblock\u003c/code\u003e) and then override the content of the block with other content. This is not possible with a simple \u003ccode\u003einclude\u003c/code\u003e.\u003c/p\u003e\n","originalBody":null,"author":"mhawke","authorProfile":"https://stackoverflow.com/users/21945/mhawke","sourceId":34555822,"isSolution":false,"isTranslated":false,"likes":0,"createdAt":"2016-01-01T11:44:25.000Z","updatedAt":"2016-01-01T11:44:25.000Z","comments":[]}]}},"initialData":{"popularQuestions":[{"id":2178,"addedBy":null,"slug":"2178-kak-ya-mogu-sohranit-imya-polzovatelya-i-parol-v-git","title":"Как я могу сохранить имя пользователя и пароль в Git?","body":"Я хочу использовать автоматическое нажатие и вытягивание в *[Git Extensions](\u003chttp://gitextensions.github.io/\u003e)*, *[Sourcetree](\u003chttps://en.wikipedia.org/wiki/Atlassian#Acquisitions_and_product_announcements\u003e)* или любом другом графическом интерфейсе Git без ввода моего имени пользователя и пароль в подсказке каждый раз.\n\nИтак, как я могу сохранить свои учетные данные в Git?\n\n","htmlBody":"\u003cp\u003eЯ хочу использовать автоматическое нажатие и вытягивание в \u003cem\u003e\u003ca href=\"http://gitextensions.github.io/\" rel=\"noreferrer\"\u003eGit Extensions\u003c/a\u003e\u003c/em\u003e, \u003cem\u003e\u003ca href=\"https://en.wikipedia.org/wiki/Atlassian#Acquisitions_and_product_announcements\" rel=\"noreferrer\"\u003eSourcetree\u003c/a\u003e\u003c/em\u003e или любом другом графическом интерфейсе Git без ввода моего имени пользователя и пароль в подсказке каждый раз.\u003c/p\u003e\u003cp\u003eИтак, как я могу сохранить свои учетные данные в Git?\u003c/p\u003e","originalBody":"\u003cp\u003eI want to use a push and pull automatically in \u003cem\u003e\u003ca href=\"http://gitextensions.github.io/\" rel=\"noreferrer\"\u003eGit Extensions\u003c/a\u003e\u003c/em\u003e, \u003cem\u003e\u003ca href=\"https://en.wikipedia.org/wiki/Atlassian#Acquisitions_and_product_announcements\" rel=\"noreferrer\"\u003eSourcetree\u003c/a\u003e\u003c/em\u003e or any other Git GUI without entering my username and password in a prompt, every time.\u003c/p\u003e\n\u003cp\u003eSo how can I save my credentials in Git?\u003c/p\u003e\n","likes":0,"pageViews":2283166,"author":"Edson Cezar","authorProfile":"https://stackoverflow.com/users/3511668/edson-cezar","sourceLink":"https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git","sourceId":35942754,"isActive":true,"isTranslated":false,"createdAt":"2016-03-11T14:29:37.000Z","updatedAt":"2021-12-15T21:32:00.655Z","tags":[{"id":6716,"questionId":2178,"tagId":1974,"tag":{"id":1974,"slug":"git-extensions","title":"git-extensions","description":null,"totalQuestions":2,"isActive":true,"createdAt":"2021-12-12T22:51:45.739Z","updatedAt":"2021-12-20T12:31:45.774Z"}},{"id":6714,"questionId":2178,"tagId":1972,"tag":{"id":1972,"slug":"git-config","title":"git-config","description":null,"totalQuestions":1,"isActive":true,"createdAt":"2021-12-12T22:51:45.739Z","updatedAt":"2021-12-12T22:51:49.439Z"}},{"id":6496,"questionId":2178,"tagId":320,"tag":{"id":320,"slug":"git","title":"git","description":null,"totalQuestions":142,"isActive":true,"createdAt":"2021-12-01T19:36:15.699Z","updatedAt":"2022-01-17T08:47:45.276Z"}},{"id":6715,"questionId":2178,"tagId":1973,"tag":{"id":1973,"slug":"credentials","title":"credentials","description":null,"totalQuestions":1,"isActive":true,"createdAt":"2021-12-12T22:51:45.736Z","updatedAt":"2021-12-12T22:51:49.444Z"}}],"_count":{"answers":26}},{"id":2209,"addedBy":null,"slug":"2209-na-zaproshennom-resurse-otsutstvuet-zagolovok-access-control-allow-origin-pri-popytke-poluchit-dannye-iz-rest-api","title":"На запрошенном ресурсе отсутствует заголовок Access-Control-Allow-Origin - при попытке получить данные из REST API.","body":"Я пытаюсь получить данные из REST API HP Alm. Он неплохо работает с небольшим скриптом curl - я получаю свои данные.\n\nТеперь сделать это с помощью JavaScript, fetch и ES6 (более или менее) кажется более серьезной проблемой. Я все время получаю это сообщение об ошибке:\n\n\u003e Не удается загрузить API-интерфейс Fetch. Ответ на предполетный запрос не пройти проверку контроля доступа: заголовок 'Access-Control-Allow-Origin' не присутствует на запрошенном ресурсе. Origin '[http://127.0.0.1: 3000](\u003chttp://127.0.0.1:3000\u003e)' равно поэтому не разрешен доступ. Ответ имел код состояния HTTP 501. Если непрозрачный ответ соответствует вашим потребностям, установите режим запроса на 'no-cors' для выборки ресурса с отключенным CORS.\n\nЯ понимаю, что это связано с тем, что я пытаюсь получить эти данные из своего локального хоста, и решение должно использовать CORS. Теперь я думал, что действительно это сделал, но почему-то он либо игнорирует то, что я пишу в заголовке, либо проблема в другом?\n\nИтак, есть проблема с реализацией? Я что делаю неправильно? К сожалению, я не могу проверить логи сервера. Я действительно немного застрял здесь.\n\n```\nfunction performSignIn() {\n\n let headers = new Headers();\n\n headers.append('Content-Type', 'application/json');\n headers.append('Accept', 'application/json');\n\n headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');\n headers.append('Access-Control-Allow-Credentials', 'true');\n\n headers.append('GET', 'POST', 'OPTIONS');\n\n headers.append('Authorization', 'Basic ' + base64.encode(username + \":\" + password));\n\n fetch(sign_in, {\n //mode: 'no-cors',\n credentials: 'include',\n method: 'POST',\n headers: headers\n })\n .then(response =\u003e response.json())\n .then(json =\u003e console.log(json))\n .catch(error =\u003e console.log('Authorization failed : ' + error.message));\n}\n```\n\nЯ использую Chrome. Я также пробовал использовать этот плагин Chrome CORS, но затем получаю другое сообщение об ошибке:\n\n\u003e Значение заголовка Access-Control-Allow-Origin в ответе не должен быть подстановочным знаком '\\*', когда режим учетных данных запроса 'включают'. Следовательно, источник '[http://127.0.0.1: 3000](\u003chttp://127.0.0.1:3000\u003e)' не допускается. доступ. Режим учетных данных запросов, инициированных XMLHttpRequest управляется атрибутом withCredentials.\n\n","htmlBody":"\u003cp\u003eЯ пытаюсь получить данные из REST API HP Alm. Он неплохо работает с небольшим скриптом curl - я получаю свои данные.\u003c/p\u003e\u003cp\u003eТеперь сделать это с помощью JavaScript, fetch и ES6 (более или менее) кажется более серьезной проблемой. Я все время получаю это сообщение об ошибке:\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003eНе удается загрузить API-интерфейс Fetch. Ответ на предполетный запрос не\n пройти проверку контроля доступа: заголовок 'Access-Control-Allow-Origin' не\n присутствует на запрошенном ресурсе. Origin '\u003ca href=\"http://127.0.0.1:3000\" rel=\"noreferrer\"\u003ehttp://127.0.0.1: 3000\u003c/a\u003e' равно\n поэтому не разрешен доступ. Ответ имел код состояния HTTP 501.\n Если непрозрачный ответ соответствует вашим потребностям, установите режим запроса на\n 'no-cors' для выборки ресурса с отключенным CORS.\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eЯ понимаю, что это связано с тем, что я пытаюсь получить эти данные из своего локального хоста, и решение должно использовать CORS. Теперь я думал, что действительно это сделал, но почему-то он либо игнорирует то, что я пишу в заголовке, либо проблема в другом?\u003c/p\u003e\u003cp\u003eИтак, есть проблема с реализацией? Я что делаю неправильно? К сожалению, я не могу проверить логи сервера. Я действительно немного застрял здесь.\u003c/p\u003e\u003cpre\u003e\u003ccode\u003efunction performSignIn() {\n\n let headers = new Headers();\n\n headers.append('Content-Type', 'application/json');\n headers.append('Accept', 'application/json');\n\n headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');\n headers.append('Access-Control-Allow-Credentials', 'true');\n\n headers.append('GET', 'POST', 'OPTIONS');\n\n headers.append('Authorization', 'Basic ' + base64.encode(username + \":\" + password));\n\n fetch(sign_in, {\n //mode: 'no-cors',\n credentials: 'include',\n method: 'POST',\n headers: headers\n })\n .then(response =\u0026gt; response.json())\n .then(json =\u0026gt; console.log(json))\n .catch(error =\u0026gt; console.log('Authorization failed : ' + error.message));\n}\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eЯ использую Chrome. Я также пробовал использовать этот плагин Chrome CORS, но затем получаю другое сообщение об ошибке:\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003eЗначение заголовка Access-Control-Allow-Origin в ответе\n не должен быть подстановочным знаком '*', когда режим учетных данных запроса\n 'включают'. Следовательно, источник '\u003ca href=\"http://127.0.0.1:3000\" rel=\"noreferrer\"\u003ehttp://127.0.0.1: 3000\u003c/a\u003e' не допускается.\n доступ. Режим учетных данных запросов, инициированных\n XMLHttpRequest управляется атрибутом withCredentials.\u003c/p\u003e\n\u003c/blockquote\u003e","originalBody":"\u003cp\u003eI'm trying to fetch some data from the REST API of HP Alm. It works pretty well with a small curl script - I get my data.\u003c/p\u003e\n\n\u003cp\u003eNow doing that with JavaScript, fetch and ES6 (more or less) seems to be a bigger issue. I keep getting this error message:\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003eFetch API cannot load . Response to preflight request doesn't\n pass access control check: No 'Access-Control-Allow-Origin' header is\n present on the requested resource. Origin '\u003ca href=\"http://127.0.0.1:3000\" rel=\"noreferrer\"\u003ehttp://127.0.0.1:3000\u003c/a\u003e' is\n therefore not allowed access. The response had HTTP status code 501.\n If an opaque response serves your needs, set the request's mode to\n 'no-cors' to fetch the resource with CORS disabled.\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eI understand that this is because I am trying to fetch that data from within my localhost and the solution should be using CORS. Now I thought I actually did that, but somehow it either ignores what I write in the header or the problem is something else? \u003c/p\u003e\n\n\u003cp\u003eSo, is there an implementation issue? Am I doing it wrong? I can't check the server logs unfortunately. I'm really a bit stuck here.\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003efunction performSignIn() {\n\n let headers = new Headers();\n\n headers.append('Content-Type', 'application/json');\n headers.append('Accept', 'application/json');\n\n headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');\n headers.append('Access-Control-Allow-Credentials', 'true');\n\n headers.append('GET', 'POST', 'OPTIONS');\n\n headers.append('Authorization', 'Basic ' + base64.encode(username + \":\" + password));\n\n fetch(sign_in, {\n //mode: 'no-cors',\n credentials: 'include',\n method: 'POST',\n headers: headers\n })\n .then(response =\u0026gt; response.json())\n .then(json =\u0026gt; console.log(json))\n .catch(error =\u0026gt; console.log('Authorization failed : ' + error.message));\n}\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI am using Chrome. I also tried using that Chrome CORS Plugin, but then I am getting another error message:\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003eThe value of the 'Access-Control-Allow-Origin' header in the response\n must not be the wildcard '*' when the request's credentials mode is\n 'include'. Origin '\u003ca href=\"http://127.0.0.1:3000\" rel=\"noreferrer\"\u003ehttp://127.0.0.1:3000\u003c/a\u003e' is therefore not allowed\n access. The credentials mode of requests initiated by the\n XMLHttpRequest is controlled by the withCredentials attribute.\u003c/p\u003e\n\u003c/blockquote\u003e\n","likes":0,"pageViews":2246005,"author":"daniel.lozynski","authorProfile":"https://stackoverflow.com/users/1331465/daniel-lozynski","sourceLink":"https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe","sourceId":43871637,"isActive":true,"isTranslated":false,"createdAt":"2017-05-09T13:47:47.000Z","updatedAt":"2021-12-15T21:31:46.092Z","tags":[{"id":6568,"questionId":2209,"tagId":5,"tag":{"id":5,"slug":"javascript","title":"javascript","description":null,"totalQuestions":956,"isActive":true,"createdAt":"2021-12-01T19:35:07.552Z","updatedAt":"2022-01-17T08:47:45.275Z"}},{"id":6570,"questionId":2209,"tagId":759,"tag":{"id":759,"slug":"fetch-api","title":"fetch-api","description":null,"totalQuestions":19,"isActive":true,"createdAt":"2021-12-01T19:37:26.360Z","updatedAt":"2022-01-17T08:46:59.319Z"}},{"id":6755,"questionId":2209,"tagId":2013,"tag":{"id":2013,"slug":"preflight","title":"preflight","description":null,"totalQuestions":2,"isActive":true,"createdAt":"2021-12-12T22:51:45.881Z","updatedAt":"2022-01-17T08:35:31.615Z"}},{"id":6569,"questionId":2209,"tagId":577,"tag":{"id":577,"slug":"cors","title":"cors","description":null,"totalQuestions":16,"isActive":true,"createdAt":"2021-12-01T19:36:57.071Z","updatedAt":"2022-01-17T08:46:11.988Z"}}],"_count":{"answers":21}},{"id":2173,"addedBy":null,"slug":"2173-git-otkazyvaetsya-obuedinyat-nesvyazannye-istorii-pri-perebazirovanii","title":"Git отказывается объединять несвязанные истории при перебазировании","body":"Во время `git rebase origin / development` из Git отображается следующее сообщение об ошибке:\n\n```\nfatal: refusing to merge unrelated histories\nError redoing merge 1234deadbeef1234deadbeef\n```\n\nМоя версия Git - 2.9.0. В предыдущей версии он работал нормально.\n\nКак я могу продолжить эту перебазировку, разрешив несвязанные истории с флагом принудительного действия, введенным в новом выпуске?\n\n","htmlBody":"\u003cp\u003eВо время \u003ccode\u003egit rebase origin / development\u003c/code\u003e из Git отображается следующее сообщение об ошибке:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003efatal: refusing to merge unrelated histories\nError redoing merge 1234deadbeef1234deadbeef\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eМоя версия Git - 2.9.0. В предыдущей версии он работал нормально.\u003c/p\u003e\u003cp\u003eКак я могу продолжить эту перебазировку, разрешив несвязанные истории с флагом принудительного действия, введенным в новом выпуске?\u003c/p\u003e","originalBody":"\u003cp\u003eDuring \u003ccode\u003egit rebase origin/development\u003c/code\u003e the following error message is shown from Git:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003efatal: refusing to merge unrelated histories\nError redoing merge 1234deadbeef1234deadbeef\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eMy Git version is 2.9.0. It used to work fine in the previous version. \u003c/p\u003e\n\n\u003cp\u003eHow can I continue this rebase allowing unrelated histories with the forced flag introduced in the new release?\u003c/p\u003e\n","likes":0,"pageViews":1988529,"author":"Shubham Chaudhary","authorProfile":"https://stackoverflow.com/users/2670370/shubham-chaudhary","sourceLink":"https://stackoverflow.com/questions/37937984/git-refusing-to-merge-unrelated-histories-on-rebase","sourceId":37937984,"isActive":true,"isTranslated":false,"createdAt":"2016-06-21T07:23:00.000Z","updatedAt":"2021-12-15T22:18:07.535Z","tags":[{"id":6479,"questionId":2173,"tagId":320,"tag":{"id":320,"slug":"git","title":"git","description":null,"totalQuestions":142,"isActive":true,"createdAt":"2021-12-01T19:36:15.699Z","updatedAt":"2022-01-17T08:47:45.276Z"}},{"id":6480,"questionId":2173,"tagId":1426,"tag":{"id":1426,"slug":"rebase","title":"rebase","description":null,"totalQuestions":3,"isActive":true,"createdAt":"2021-12-11T07:41:32.717Z","updatedAt":"2021-12-16T13:37:21.262Z"}}],"_count":{"answers":25}},{"id":2202,"addedBy":null,"slug":"2202-kak-mne-ubit-process-kotoryj-v-nastoyashee-vremya-ispolzuet-port-na-lokalnom-hoste-v-windows","title":"Как мне убить процесс, который в настоящее время использует порт на локальном хосте в Windows?","body":"Как я могу удалить текущий процесс / приложение, которое уже назначено на порт?\n\nНапример: `localhost: 8080`\n\n","htmlBody":"\u003cp\u003eКак я могу удалить текущий процесс / приложение, которое уже назначено на порт?\u003c/p\u003e\u003cp\u003eНапример: \u003ccode\u003elocalhost: 8080\u003c/code\u003e\u003c/p\u003e","originalBody":"\u003cp\u003eHow can I remove the current process/application which is already assigned to a port?\u003c/p\u003e\n\n\u003cp\u003eFor example: \u003ccode\u003elocalhost:8080\u003c/code\u003e\u003c/p\u003e\n","likes":0,"pageViews":1843311,"author":"KavinduWije","authorProfile":"https://stackoverflow.com/users/3626371/kavinduwije","sourceLink":"https://stackoverflow.com/questions/39632667/how-do-i-kill-the-process-currently-using-a-port-on-localhost-in-windows","sourceId":39632667,"isActive":true,"isTranslated":false,"createdAt":"2016-09-22T07:19:51.000Z","updatedAt":"2021-12-15T21:29:19.097Z","tags":[{"id":6551,"questionId":2202,"tagId":1703,"tag":{"id":1703,"slug":"localhost","title":"localhost","description":null,"totalQuestions":6,"isActive":true,"createdAt":"2021-12-12T22:08:18.812Z","updatedAt":"2022-01-17T08:45:09.975Z"}},{"id":6748,"questionId":2202,"tagId":2006,"tag":{"id":2006,"slug":"port","title":"port","description":null,"totalQuestions":5,"isActive":true,"createdAt":"2021-12-12T22:51:45.847Z","updatedAt":"2021-12-20T16:51:33.026Z"}},{"id":6550,"questionId":2202,"tagId":871,"tag":{"id":871,"slug":"cmd","title":"cmd","description":null,"totalQuestions":10,"isActive":true,"createdAt":"2021-12-03T12:35:55.978Z","updatedAt":"2022-01-17T08:46:29.499Z"}},{"id":6552,"questionId":2202,"tagId":1427,"tag":{"id":1427,"slug":"command-prompt","title":"command-prompt","description":null,"totalQuestions":2,"isActive":true,"createdAt":"2021-12-11T07:41:32.731Z","updatedAt":"2021-12-12T22:51:48.479Z"}},{"id":6549,"questionId":2202,"tagId":51,"tag":{"id":51,"slug":"windows","title":"windows","description":null,"totalQuestions":44,"isActive":true,"createdAt":"2021-12-01T19:35:07.583Z","updatedAt":"2022-01-17T08:47:18.478Z"}}],"_count":{"answers":27}},{"id":2322,"addedBy":null,"slug":"2322-otvet-na-predpoletnyj-zapros-ne-prohodit-proverku-kontrolya-dostupa","title":"Ответ на предполетный запрос не проходит проверку контроля доступа","body":"Я получаю эту ошибку, используя ngResource для вызова REST API в Amazon Web Services:\n\n\u003e XMLHttpRequest не загружается [http://server.apiurl.com: 8000 / с / логин? Login = facebook](\u003chttp://server.apiurl.com:8000/s/login?login=facebook\u003e). Ответ на предполетный запрос не проходит проверку контроля доступа: Нет Заголовок Access-Control-Allow-Origin присутствует в запрошенном ресурс. Следовательно, к источнику 'http://localhost' доступ не разрешен. *Ошибка 405*\n\nСервис:\n\n```\nsocialMarkt.factory('loginService', ['$resource', function ($resource) {\n var apiAddress = \"http://server.apiurl.com:8000/s/login/\";\n return $resource(apiAddress, {\n login: \"facebook\",\n access_token: \"@access_token\",\n facebook_id: \"@facebook_id\"\n }, {\n getUser: {\n method: 'POST'\n }\n });\n}]);\n```\n\nКонтроллер:\n\n```\n[...]\nloginService.getUser(JSON.stringify(fbObj)),\n function (data) {\n console.log(data);\n },\n function (result) {\n console.error('Error', result.status);\n }\n[...]\n```\n\nЯ использую Chrome и не знаю, что еще делать, чтобы решить эту проблему. Я даже настроил сервер для приема заголовков от источника `localhost`.\n\n","htmlBody":"\u003cp\u003eЯ получаю эту ошибку, используя ngResource для вызова REST API в Amazon Web Services:\u003c/p\u003e\u003cblockquote\u003e\n\u003cp\u003eXMLHttpRequest не загружается\n\u003ca href=\"http://server.apiurl.com:8000/s/login?login=facebook\" rel=\"noreferrer\"\u003ehttp://server.apiurl.com: 8000 / с / логин? Login = facebook\u003c/a\u003e. Ответ на\nпредполетный запрос не проходит проверку контроля доступа: Нет\nЗаголовок Access-Control-Allow-Origin присутствует в запрошенном\nресурс. Следовательно, к источнику 'http://localhost' доступ не разрешен.\n\u003cem\u003eОшибка 405\u003c/em\u003e\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eСервис:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003esocialMarkt.factory('loginService', ['$resource', function ($resource) {\n var apiAddress = \"http://server.apiurl.com:8000/s/login/\";\n return $resource(apiAddress, {\n login: \"facebook\",\n access_token: \"@access_token\",\n facebook_id: \"@facebook_id\"\n }, {\n getUser: {\n method: 'POST'\n }\n });\n}]);\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eКонтроллер:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e[...]\nloginService.getUser(JSON.stringify(fbObj)),\n function (data) {\n console.log(data);\n },\n function (result) {\n console.error('Error', result.status);\n }\n[...]\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eЯ использую Chrome и не знаю, что еще делать, чтобы решить эту проблему. Я даже настроил сервер для приема заголовков от источника \u003ccode\u003elocalhost\u003c/code\u003e.\u003c/p\u003e","originalBody":"\u003cp\u003eI'm getting this error using ngResource to call a REST API on Amazon Web Services:\u003c/p\u003e\n\u003cblockquote\u003e\n\u003cp\u003eXMLHttpRequest cannot load\n\u003ca href=\"http://server.apiurl.com:8000/s/login?login=facebook\" rel=\"noreferrer\"\u003ehttp://server.apiurl.com:8000/s/login?login=facebook\u003c/a\u003e. Response to\npreflight request doesn't pass access control check: No\n'Access-Control-Allow-Origin' header is present on the requested\nresource. Origin 'http://localhost' is therefore not allowed access.\n\u003cem\u003eError 405\u003c/em\u003e\u003c/p\u003e\n\u003c/blockquote\u003e\n\u003cp\u003eService:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003esocialMarkt.factory('loginService', ['$resource', function ($resource) {\n var apiAddress = \u0026quot;http://server.apiurl.com:8000/s/login/\u0026quot;;\n return $resource(apiAddress, {\n login: \u0026quot;facebook\u0026quot;,\n access_token: \u0026quot;@access_token\u0026quot;,\n facebook_id: \u0026quot;@facebook_id\u0026quot;\n }, {\n getUser: {\n method: 'POST'\n }\n });\n}]);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eController:\u003c/p\u003e\n\u003cpre\u003e\u003ccode\u003e[...]\nloginService.getUser(JSON.stringify(fbObj)),\n function (data) {\n console.log(data);\n },\n function (result) {\n console.error('Error', result.status);\n }\n[...]\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eI'm using Chrome, and I dont know what else to do in order to fix this problem. I've even configured the server to accept headers from origin \u003ccode\u003elocalhost\u003c/code\u003e.\u003c/p\u003e\n","likes":0,"pageViews":1754370,"author":"Andre Mendes","authorProfile":"https://stackoverflow.com/users/2896963/andre-mendes","sourceLink":"https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check","sourceId":35588699,"isActive":true,"isTranslated":false,"createdAt":"2016-02-23T21:37:06.000Z","updatedAt":"2021-12-15T21:47:34.401Z","tags":[{"id":6932,"questionId":2322,"tagId":5,"tag":{"id":5,"slug":"javascript","title":"javascript","description":null,"totalQuestions":956,"isActive":true,"createdAt":"2021-12-01T19:35:07.552Z","updatedAt":"2022-01-17T08:47:45.275Z"}},{"id":6935,"questionId":2322,"tagId":577,"tag":{"id":577,"slug":"cors","title":"cors","description":null,"totalQuestions":16,"isActive":true,"createdAt":"2021-12-01T19:36:57.071Z","updatedAt":"2022-01-17T08:46:11.988Z"}},{"id":6934,"questionId":2322,"tagId":1045,"tag":{"id":1045,"slug":"http","title":"http","description":null,"totalQuestions":21,"isActive":true,"createdAt":"2021-12-03T12:36:25.133Z","updatedAt":"2022-01-17T08:46:58.938Z"}},{"id":6933,"questionId":2322,"tagId":50,"tag":{"id":50,"slug":"ajax","title":"ajax","description":null,"totalQuestions":35,"isActive":true,"createdAt":"2021-12-01T19:35:07.583Z","updatedAt":"2021-12-20T12:30:23.069Z"}},{"id":6967,"questionId":2322,"tagId":2107,"tag":{"id":2107,"slug":"http-status-code-405","title":"http-status-code-405","description":null,"totalQuestions":1,"isActive":true,"createdAt":"2021-12-12T22:57:06.448Z","updatedAt":"2021-12-12T22:57:09.531Z"}}],"_count":{"answers":24}}],"latestQuestions":[{"id":5821,"addedBy":null,"slug":"5821-proizvoditelnost-bolshogo-spiska-s-react","title":"Производительность большого списка с React","body":"Я создаю фильтруемый список с помощью React. Структура списка показана на изображении ниже.\n\n[![enter image description here](\u003chttps://i.stack.imgur.com/lTcZm.png\u003e)](\u003chttps://i.stack.imgur.com/lTcZm.png\u003e)\n\n**ПОМЕЩЕНИЕ**\n\nВот описание того, как это должно работать:\n\n- Состояние находится в компоненте самого высокого уровня, компоненте `Поиск`.\n- Состояние описывается следующим образом:\n\n\u003c!-- --\u003e\n\n\u003cpre\u003e{\n visible : boolean,\n files : array,\n filtered : array,\n query : string,\n currentlySelectedIndex : integer\n}\n\u003c/pre\u003e\n\n- `files` — потенциально очень большой массив, содержащий пути к файлам (10000 записей — правдоподобное число).\n- `filtered` — это отфильтрованный массив после того, как пользователь введет не менее 2 символов. Я знаю, что это производные данные, и поэтому можно привести аргумент о сохранении их в состоянии, но это необходимо для\n- `currentlySelectedIndex` который является индексом текущего выбранного элемента из отфильтрованного списка.\n\n- Пользователь вводит более 2 букв в компонент `Input`, массив фильтруется и для каждой записи в отфильтрованном массиве отображается компонент `Result`\n\n\\* 100023\\* \n- Каждый компонент `Результат` отображает полный путь, который частично соответствует запросу, а часть пути с частичным совпадением выделена. Например, DOM компонента Result, если пользователь ввел «le», будет выглядеть примерно так:\n\n ``\n\n- `это/является/файлом\u003cstrong\u003eфайл\u003c/strong\u003e/путь`\n- Если пользователь нажимает клавиши вверх или вниз, когда компонент `Input` сфокусирован, `currentlySelectedIndex` изменяется на основе массива `filtered`. Это приводит к тому, что компонент `Result`, соответствующий индексу, помечается как выбранный, вызывая повторный рендеринг\n\n\u003c!-- --\u003e\n\n**ПРОБЛЕМА**\n\nПервоначально я протестировал это с достаточно небольшим массивом из `файлов`, используя разрабатываемую версию React, и все работало нормально.\n\nПроблема возникла, когда мне пришлось иметь дело с массивом `files` размером до 10000 записей. Ввод 2 букв в поле ввода привел бы к созданию большого списка, и когда я нажимал клавиши вверх и вниз для навигации по нему, он сильно тормозил.\n\nСначала у меня не было определенного компонента для элементов `Result`, и я просто составлял список на лету, при каждом рендеринге компонента `Search`, как таковой:\n\n```\nresults = this.state.filtered.map(function(file, index) {\n var start, end, matchIndex, match = this.state.query;\n\n matchIndex = file.indexOf(match);\n start = file.slice(0, matchIndex);\n end = file.slice(matchIndex + match.length);\n\n return (\n \u003cli onClick={this.handleListClick}\n data-path={file}\n className={(index === this.state.currentlySelected) ? \"valid selected\" : \"valid\"}\n key={file} \u003e\n {start}\n \u003cspan className=\"marked\"\u003e{match}\u003c/span\u003e\n {end}\n \u003c/li\u003e\n );\n}.bind(this));\n```\n\nКак вы понимаете, каждый раз, когда `currentlySelectedIndex` изменялся, это вызывало повторную визуализацию, и список каждый раз создавался заново. Я думал, что, поскольку я установил значение `key` для каждого элемента `li`, React избежит повторного рендеринга каждого другого элемента `li`, у которого нет его `className` измениться, но видимо это было не так.\n\nВ итоге я определил класс для элементов `Result`, где он явно проверяет, должен ли каждый элемент `Result` повторно отображаться на основе того, был ли он выбран ранее и на основе текущего пользовательский ввод:\n\n```\nvar ResultItem = React.createClass({\n shouldComponentUpdate : function(nextProps) {\n if (nextProps.match !== this.props.match) {\n return true;\n } else {\n return (nextProps.selected !== this.props.selected);\n }\n },\n render : function() {\n return (\n \u003cli onClick={this.props.handleListClick}\n data-path={this.props.file}\n className={\n (this.props.selected) ? \"valid selected\" : \"valid\"\n }\n key={this.props.file} \u003e\n {this.props.children}\n \u003c/li\u003e\n );\n }\n});\n```\n\nИ список теперь создан как таковой:\n\n```\nresults = this.state.filtered.map(function(file, index) {\n var start, end, matchIndex, match = this.state.query, selected;\n\n matchIndex = file.indexOf(match);\n start = file.slice(0, matchIndex);\n end = file.slice(matchIndex + match.length);\n selected = (index === this.state.currentlySelected) ? true : false\n\n return (\n \u003cResultItem handleClick={this.handleListClick}\n data-path={file}\n selected={selected}\n key={file}\n match={match} \u003e\n {start}\n \u003cspan className=\"marked\"\u003e{match}\u003c/span\u003e\n {end}\n \u003c/ResultItem\u003e\n );\n}.bind(this));\n}\n```\n\nЭто улучшило производительность *немного*, но все равно недостаточно. Дело в том, что когда я тестировал производственную версию React, все работало плавно, без задержек.\n\n**НИЖНЯЯ ЛИНИЯ**\n\n**Такое заметное расхождение между разрабатываемой и производственной версиями React нормально?**\n\n**Я понимаю/делаю что-то не так, когда думаю о том, как React управляет списком?**\n\n**ОБНОВЛЕНИЕ 14-11-2016**\n\nЯ нашел эту презентацию Майкла Джексона, где он решает проблему, очень похожую на эту: [https://youtu.be/7S8v8jfLb1Q?t=26m2s](\u003chttps://youtu.be/7S8v8jfLb1Q?t=26m2s\u003e)\n\nРешение очень похоже на решение, предложенное Аскаровым Бекнаром [ответ](\u003chttps://stackoverflow.com/a/38193164/4651083\u003e), ниже\n\n**ОБНОВЛЕНИЕ 14-4-2018**\n\nПоскольку это, по-видимому, популярный вопрос, и с тех пор, как был задан первоначальный вопрос, дела пошли дальше, хотя я рекомендую вам посмотреть видео по ссылке выше, чтобы получить представление о виртуальном макете, я также рекомендую вам использовать библиотеку [React Virtualized](\u003chttps://github.com/bvaughn/react-virtualized\u003e), если вы не хотите заново изобретать велосипед.\n\n","htmlBody":"\u003cp\u003eЯ создаю фильтруемый список с помощью React. Структура списка показана на изображении ниже.\u003c/p\u003e\u003cp\u003e\u003ca href=\"https://i.stack.imgur.com/lTcZm.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/lTcZm.png\" alt=\"enter image description here\"\u003e\u003c/a\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003eПОМЕЩЕНИЕ\u003c/strong\u003e\u003c/p\u003e\u003cp\u003eВот описание того, как это должно работать:\u003c/p\u003e\u003cul\u003e\n\u003cli\u003eСостояние находится в компоненте самого высокого уровня, компоненте \u003ccode\u003eПоиск\u003c/code\u003e.\u003c/li\u003e\n\u003cli\u003eСостояние описывается следующим образом:\u003c/li\u003e\n\u003c/ul\u003e\u003cpre\u003e{\n visible : boolean,\n files : array,\n filtered : array,\n query : string,\n currentlySelectedIndex : integer\n}\n\u003c/pre\u003e\u003cul\u003e\n\u003cli\u003e\u003ccode\u003efiles\u003c/code\u003e — потенциально очень большой массив, содержащий пути к файлам (10000 записей — правдоподобное число).\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003efiltered\u003c/code\u003e — это отфильтрованный массив после того, как пользователь введет не менее 2 символов. Я знаю, что это производные данные, и поэтому можно привести аргумент о сохранении их в состоянии, но это необходимо для\u003c/li\u003e\n\u003cli\u003e\u003cp\u003e\u003ccode\u003ecurrentlySelectedIndex\u003c/code\u003e который является индексом текущего выбранного элемента из отфильтрованного списка.\u003c/p\u003e\u003c/li\u003e\n\u003cli\u003e\u003cp\u003eПользователь вводит более 2 букв в компонент \u003ccode\u003eInput\u003c/code\u003e, массив фильтруется и для каждой записи в отфильтрованном массиве отображается компонент \u003ccode\u003eResult\u003c/code\u003e\u003c/p\u003e* 100023*\n\u003cli\u003e\u003cp\u003eКаждый компонент \u003ccode\u003eРезультат\u003c/code\u003e отображает полный путь, который частично соответствует запросу, а часть пути с частичным совпадением выделена. Например, DOM компонента Result, если пользователь ввел «le», будет выглядеть примерно так:\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003e\u003cli\u003eэто/является/файлом\u003cstrong\u003eфайл\u003c/strong\u003e/путь\u003c/li\u003e\u003c/code\u003e\u003c/p\u003e\u003c/li\u003e\n\u003cli\u003eЕсли пользователь нажимает клавиши вверх или вниз, когда компонент \u003ccode\u003eInput\u003c/code\u003e сфокусирован, \u003ccode\u003ecurrentlySelectedIndex\u003c/code\u003e изменяется на основе массива \u003ccode\u003efiltered\u003c/code\u003e. Это приводит к тому, что компонент \u003ccode\u003eResult\u003c/code\u003e, соответствующий индексу, помечается как выбранный, вызывая повторный рендеринг\u003c/li\u003e\n\u003c/ul\u003e\u003cp\u003e\u003cstrong\u003eПРОБЛЕМА\u003c/strong\u003e\u003c/p\u003e\u003cp\u003eПервоначально я протестировал это с достаточно небольшим массивом из \u003ccode\u003eфайлов\u003c/code\u003e, используя разрабатываемую версию React, и все работало нормально.\u003c/p\u003e\u003cp\u003eПроблема возникла, когда мне пришлось иметь дело с массивом \u003ccode\u003efiles\u003c/code\u003e размером до 10000 записей. Ввод 2 букв в поле ввода привел бы к созданию большого списка, и когда я нажимал клавиши вверх и вниз для навигации по нему, он сильно тормозил.\u003c/p\u003e\u003cp\u003eСначала у меня не было определенного компонента для элементов \u003ccode\u003eResult\u003c/code\u003e, и я просто составлял список на лету, при каждом рендеринге компонента \u003ccode\u003eSearch\u003c/code\u003e, как таковой:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eresults = this.state.filtered.map(function(file, index) {\n var start, end, matchIndex, match = this.state.query;\n\n matchIndex = file.indexOf(match);\n start = file.slice(0, matchIndex);\n end = file.slice(matchIndex + match.length);\n\n return (\n \u0026lt;li onClick={this.handleListClick}\n data-path={file}\n className={(index === this.state.currentlySelected) ? \"valid selected\" : \"valid\"}\n key={file} \u0026gt;\n {start}\n \u0026lt;span className=\"marked\"\u0026gt;{match}\u0026lt;/span\u0026gt;\n {end}\n \u0026lt;/li\u0026gt;\n );\n}.bind(this));\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eКак вы понимаете, каждый раз, когда \u003ccode\u003ecurrentlySelectedIndex\u003c/code\u003e изменялся, это вызывало повторную визуализацию, и список каждый раз создавался заново. Я думал, что, поскольку я установил значение \u003ccode\u003ekey\u003c/code\u003e для каждого элемента \u003ccode\u003eli\u003c/code\u003e, React избежит повторного рендеринга каждого другого элемента \u003ccode\u003eli\u003c/code\u003e, у которого нет его \u003ccode\u003eclassName\u003c/code\u003e измениться, но видимо это было не так.\u003c/p\u003e\u003cp\u003eВ итоге я определил класс для элементов \u003ccode\u003eResult\u003c/code\u003e, где он явно проверяет, должен ли каждый элемент \u003ccode\u003eResult\u003c/code\u003e повторно отображаться на основе того, был ли он выбран ранее и на основе текущего пользовательский ввод:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003evar ResultItem = React.createClass({\n shouldComponentUpdate : function(nextProps) {\n if (nextProps.match !== this.props.match) {\n return true;\n } else {\n return (nextProps.selected !== this.props.selected);\n }\n },\n render : function() {\n return (\n \u0026lt;li onClick={this.props.handleListClick}\n data-path={this.props.file}\n className={\n (this.props.selected) ? \"valid selected\" : \"valid\"\n }\n key={this.props.file} \u0026gt;\n {this.props.children}\n \u0026lt;/li\u0026gt;\n );\n }\n});\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eИ список теперь создан как таковой: \u003c/p\u003e\u003cpre\u003e\u003ccode\u003eresults = this.state.filtered.map(function(file, index) {\n var start, end, matchIndex, match = this.state.query, selected;\n\n matchIndex = file.indexOf(match);\n start = file.slice(0, matchIndex);\n end = file.slice(matchIndex + match.length);\n selected = (index === this.state.currentlySelected) ? true : false\n\n return (\n \u0026lt;ResultItem handleClick={this.handleListClick}\n data-path={file}\n selected={selected}\n key={file}\n match={match} \u0026gt;\n {start}\n \u0026lt;span className=\"marked\"\u0026gt;{match}\u0026lt;/span\u0026gt;\n {end}\n \u0026lt;/ResultItem\u0026gt;\n );\n}.bind(this));\n}\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eЭто улучшило производительность \u003cem\u003eнемного\u003c/em\u003e, но все равно недостаточно. Дело в том, что когда я тестировал производственную версию React, все работало плавно, без задержек.\u003c/p\u003e\u003cp\u003e\u003cstrong\u003eНИЖНЯЯ ЛИНИЯ\u003c/strong\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003eТакое заметное расхождение между разрабатываемой и производственной версиями React нормально?\u003c/strong\u003e\u003c/p\u003e\u003cp\u003e\u003cstrong\u003eЯ понимаю/делаю что-то не так, когда думаю о том, как React управляет списком?\u003c/strong\u003e \u003c/p\u003e\u003cp\u003e\u003cstrong\u003eОБНОВЛЕНИЕ 14-11-2016\u003c/strong\u003e\u003c/p\u003e\u003cp\u003eЯ нашел эту презентацию Майкла Джексона, где он решает проблему, очень похожую на эту: \u003ca href=\"https://youtu.be/7S8v8jfLb1Q?t=26m2s\" rel=\"noreferrer\"\u003ehttps://youtu.be/7S8v8jfLb1Q?t=26m2s\u003c/a\u003e\u003c/p\u003e\u003cp\u003eРешение очень похоже на решение, предложенное Аскаровым Бекнаром \u003ca href=\"https://stackoverflow.com/a/38193164/4651083\"\u003eответ\u003c/a\u003e, ниже\u003c/p\u003e\u003cp\u003e\u003cstrong\u003eОБНОВЛЕНИЕ 14-4-2018\u003c/strong\u003e\u003c/p\u003e\u003cp\u003eПоскольку это, по-видимому, популярный вопрос, и с тех пор, как был задан первоначальный вопрос, дела пошли дальше, хотя я рекомендую вам посмотреть видео по ссылке выше, чтобы получить представление о виртуальном макете, я также рекомендую вам использовать библиотеку \u003ca href=\"https://github.com/bvaughn/react-virtualized\" rel=\"noreferrer\"\u003eReact Virtualized\u003c/a\u003e, если вы не хотите заново изобретать велосипед.\u003c/p\u003e","originalBody":"\u003cp\u003eI am in the process of implementing a filterable list with React. The structure of the list is as shown in the image below.\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://i.stack.imgur.com/lTcZm.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/lTcZm.png\" alt=\"enter image description here\"\u003e\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003ePREMISE\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003eHere's a description of how it is supposed to work:\u003c/p\u003e\n\n\u003cul\u003e\n\u003cli\u003eThe state resides in the highest level component, the \u003ccode\u003eSearch\u003c/code\u003e component.\u003c/li\u003e\n\u003cli\u003eThe state is described as follows:\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cpre\u003e\n{\n visible : boolean,\n files : array,\n filtered : array,\n query : string,\n currentlySelectedIndex : integer\n}\n\u003c/pre\u003e\n\n\u003cul\u003e\n\u003cli\u003e\u003ccode\u003efiles\u003c/code\u003e is a potentially very large, array containing file paths (10000 entries is a plausible number).\u003c/li\u003e\n\u003cli\u003e\u003ccode\u003efiltered\u003c/code\u003e is the filtered array after the user types at least 2 characters. I know it's derivative data and as such an argument could be made about storing it in the state but it is needed for\u003c/li\u003e\n\u003cli\u003e\u003cp\u003e\u003ccode\u003ecurrentlySelectedIndex\u003c/code\u003e which is the index of the currently selected element from the filtered list.\u003c/p\u003e\u003c/li\u003e\n\u003cli\u003e\u003cp\u003eUser types more than 2 letters into the \u003ccode\u003eInput\u003c/code\u003e component, the array is filtered and for each entry in the filtered array a \u003ccode\u003eResult\u003c/code\u003e component is rendered\u003c/p\u003e\u003c/li\u003e\n\u003cli\u003e\u003cp\u003eEach \u003ccode\u003eResult\u003c/code\u003e component is displaying the full path that partially matched the query, and the partial match part of the path is highlighted. For example the DOM of a Result component, if the user had typed 'le' would be something like this :\u003c/p\u003e\n\n\u003cp\u003e\u003ccode\u003e\u0026lt;li\u0026gt;this/is/a/fi\u0026lt;strong\u0026gt;le\u0026lt;/strong\u0026gt;/path\u0026lt;/li\u0026gt;\u003c/code\u003e\u003c/p\u003e\u003c/li\u003e\n\u003cli\u003eIf the user presses the up or down keys while the \u003ccode\u003eInput\u003c/code\u003e component is focused the \u003ccode\u003ecurrentlySelectedIndex\u003c/code\u003e changes based on the \u003ccode\u003efiltered\u003c/code\u003e array. This causes the \u003ccode\u003eResult\u003c/code\u003e component that matches the index to be marked as selected causing a re-render\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cp\u003e\u003cstrong\u003ePROBLEM\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003eInitially I tested this with a small enough array of \u003ccode\u003efiles\u003c/code\u003e, using the development version of React, and all worked fine. \u003c/p\u003e\n\n\u003cp\u003eThe problem appeared when I had to deal with a \u003ccode\u003efiles\u003c/code\u003e array as big as 10000 entries. Typing 2 letters in the Input would generate a big list and when I pressed the up and down keys to navigate it it would be very laggy.\u003c/p\u003e\n\n\u003cp\u003eAt first I did not have a defined component for the \u003ccode\u003eResult\u003c/code\u003e elements and I was merely making the list on the fly, on each render of the \u003ccode\u003eSearch\u003c/code\u003e component, as such:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eresults = this.state.filtered.map(function(file, index) {\n var start, end, matchIndex, match = this.state.query;\n\n matchIndex = file.indexOf(match);\n start = file.slice(0, matchIndex);\n end = file.slice(matchIndex + match.length);\n\n return (\n \u0026lt;li onClick={this.handleListClick}\n data-path={file}\n className={(index === this.state.currentlySelected) ? \"valid selected\" : \"valid\"}\n key={file} \u0026gt;\n {start}\n \u0026lt;span className=\"marked\"\u0026gt;{match}\u0026lt;/span\u0026gt;\n {end}\n \u0026lt;/li\u0026gt;\n );\n}.bind(this));\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eAs you can tell, every time the \u003ccode\u003ecurrentlySelectedIndex\u003c/code\u003e changed, it would cause a re-render and the list would be re-created each time. I thought that since I had set a \u003ccode\u003ekey\u003c/code\u003e value on each \u003ccode\u003eli\u003c/code\u003e element React would avoid re-rendering every other \u003ccode\u003eli\u003c/code\u003e element that did not have its \u003ccode\u003eclassName\u003c/code\u003e change, but apparently it wasn't so.\u003c/p\u003e\n\n\u003cp\u003eI ended up defining a class for the \u003ccode\u003eResult\u003c/code\u003e elements, where it explicitly checks whether each \u003ccode\u003eResult\u003c/code\u003e element should re-render based on whether it was previously selected and based on the current user input :\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003evar ResultItem = React.createClass({\n shouldComponentUpdate : function(nextProps) {\n if (nextProps.match !== this.props.match) {\n return true;\n } else {\n return (nextProps.selected !== this.props.selected);\n }\n },\n render : function() {\n return (\n \u0026lt;li onClick={this.props.handleListClick}\n data-path={this.props.file}\n className={\n (this.props.selected) ? \"valid selected\" : \"valid\"\n }\n key={this.props.file} \u0026gt;\n {this.props.children}\n \u0026lt;/li\u0026gt;\n );\n }\n});\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eAnd the list is now created as such: \u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eresults = this.state.filtered.map(function(file, index) {\n var start, end, matchIndex, match = this.state.query, selected;\n\n matchIndex = file.indexOf(match);\n start = file.slice(0, matchIndex);\n end = file.slice(matchIndex + match.length);\n selected = (index === this.state.currentlySelected) ? true : false\n\n return (\n \u0026lt;ResultItem handleClick={this.handleListClick}\n data-path={file}\n selected={selected}\n key={file}\n match={match} \u0026gt;\n {start}\n \u0026lt;span className=\"marked\"\u0026gt;{match}\u0026lt;/span\u0026gt;\n {end}\n \u0026lt;/ResultItem\u0026gt;\n );\n}.bind(this));\n}\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eThis made performance \u003cem\u003eslightly\u003c/em\u003e better, but it's still not good enough. Thing is when I tested on the production version of React things worked buttery smooth, no lag at all. \u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eBOTTOMLINE\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eIs such a noticeable discrepancy between development and production versions of React normal?\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eAm I understanding/doing something wrong when I think about how React manages the list?\u003c/strong\u003e \u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eUPDATE 14-11-2016\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003eI have found this presentation of Michael Jackson, where he tackles an issue very similar to this one: \u003ca href=\"https://youtu.be/7S8v8jfLb1Q?t=26m2s\" rel=\"noreferrer\"\u003ehttps://youtu.be/7S8v8jfLb1Q?t=26m2s\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eThe solution is very similar to the one proposed by AskarovBeknar's \u003ca href=\"https://stackoverflow.com/a/38193164/4651083\"\u003eanswer\u003c/a\u003e, below\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eUPDATE 14-4-2018\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003eSince this is apparently a popular question and things have progressed since the original question was asked, while I do encourage you to watch the video linked above, in order to get a grasp of a virtual layout, I also encourage you to use the \u003ca href=\"https://github.com/bvaughn/react-virtualized\" rel=\"noreferrer\"\u003eReact Virtualized\u003c/a\u003e library if you do not want to re-invent the wheel. \u003c/p\u003e\n","likes":0,"pageViews":82261,"author":"Dimitris Karagiannis","authorProfile":"https://stackoverflow.com/users/4651083/dimitris-karagiannis","sourceLink":"https://stackoverflow.com/questions/38033442/big-list-performance-with-react","sourceId":38033442,"isActive":true,"isTranslated":true,"createdAt":"2016-06-25T22:18:01.000Z","updatedAt":"2022-01-17T10:15:43.227Z","tags":[{"id":17573,"questionId":5821,"tagId":5,"tag":{"id":5,"slug":"javascript","title":"javascript","description":null,"totalQuestions":956,"isActive":true,"createdAt":"2021-12-01T19:35:07.552Z","updatedAt":"2022-01-17T08:47:45.275Z"}},{"id":17575,"questionId":5821,"tagId":22,"tag":{"id":22,"slug":"reactjs","title":"reactjs","description":null,"totalQuestions":424,"isActive":true,"createdAt":"2021-12-01T19:35:07.562Z","updatedAt":"2022-01-17T08:47:45.269Z"}},{"id":17572,"questionId":5821,"tagId":343,"tag":{"id":343,"slug":"list","title":"list","description":null,"totalQuestions":28,"isActive":true,"createdAt":"2021-12-01T19:36:25.778Z","updatedAt":"2022-01-17T08:40:21.905Z"}}],"_count":{"answers":9}},{"id":5857,"addedBy":null,"slug":"5857-kakovy-argumenty-urovni-klyuchi-i-imena-dlya-funkcii-concat-pandas","title":"Каковы аргументы «уровни», «ключи» и имена для функции concat Pandas?","body":"### Вопросы\n\n- Как использовать `pd.concat`?\n- Для чего нужен аргумент `levels`?\n- Для чего нужен аргумент `keys`?\n- Есть ли куча примеров, которые помогут объяснить, как использовать все аргументы?\n\n\u003c!-- --\u003e\n\nФункцияPandas `concat` является [швейцарским армейским ножом](\u003chttps://en.wikipedia.org/wiki/Swiss_Army_knife\u003e) объединенных утилит. Разнообразие ситуаций, в которых это полезно, многочисленно. Существующая документация упускает некоторые подробности о некоторых необязательных аргументах. Среди них аргументы `levels` и `keys`. Я решил выяснить, что делают эти аргументы.\n\nЯ задам вопрос, который послужит воротами во многие аспекты `pd.concat`.\n\nРассмотрите кадры данных `d1`, `d2`и `d3`:\n\n```\nimport pandas as pd\n\nd1 = pd.DataFrame(dict(A=.1, B=.2, C=.3), [2, 3])\nd2 = pd.DataFrame(dict(B=.4, C=.5, D=.6), [1, 2])\nd3 = pd.DataFrame(dict(A=.7, B=.8, D=.9), [1, 3])\n```\n\nЕсли бы я объединил их вместе с\n\n```\npd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'])\n```\n\nЯ получаю ожидаемый результат с `pandas.MultiIndex` для моего объекта `columns`:\n\n```\nA B C D\nd1 2 0.1 0.2 0.3 NaN\n 3 0.1 0.2 0.3 NaN\nd2 1 NaN 0.4 0.5 0.6\n 2 NaN 0.4 0.5 0.6\nd3 1 0.7 0.8 NaN 0.9\n 3 0.7 0.8 NaN 0.9\n```\n\nОднако я хотел использовать [`уровни` документацию по аргументам](\u003chttps://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas-concat\u003e):\n\n\u003e **levels**: список последовательностей, по умолчанию нет. Конкретные уровни (уникальные значения), используемые для построения MultiIndex. В противном случае они будут выводиться из ключей.\n\nТак я прошел\n\n```\npd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2']])\n```\n\nИ получите `KeyError`\n\n\u003e `ValueError: ключ d3 не находится на уровне Index(['d1', 'd2'], dtype='object')`\n\nЭто имело смысл. Уровни, которые я прошел, были недостаточны для описания необходимых уровней, обозначенных клавишами. Если бы я ничего не прошел, как я сделал выше, уровни выводятся (как указано в документации). Но как еще я могу использовать этот аргумент для большего эффекта?\n\nЕсли бы я попробовал это вместо этого:\n\n```\npd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2', 'd3']])\n```\n\nI и получил те же результаты, что и выше. Но когда я добавляю еще одно значение к уровням,\n\n```\ndf = pd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2', 'd3', 'd4']])\n```\n\nВ итоге я получаю такой же фрейм данных, но результирующий `MultiIndex` имеет неиспользуемый уровень.\n\n```\ndf.index.levels[0]\n\nIndex(['d1', 'd2', 'd3', 'd4'], dtype='object')\n```\n\nТак в чем смысл аргумента `уровень` и должен ли я использовать `ключи` по-другому?\n\nЯ использую Python 3.6 и Pandas 0.22.\n\n","htmlBody":"\u003ch3\u003eВопросы\u003c/h3\u003e\u003cul\u003e\n\u003cli\u003eКак использовать \u003ccode\u003epd.concat\u003c/code\u003e?\u003c/li\u003e\n\u003cli\u003eДля чего нужен аргумент \u003ccode\u003elevels\u003c/code\u003e?\u003c/li\u003e\n\u003cli\u003eДля чего нужен аргумент \u003ccode\u003ekeys\u003c/code\u003e?\u003c/li\u003e\n\u003cli\u003eЕсть ли куча примеров, которые помогут объяснить, как использовать все аргументы?\u003c/li\u003e\n\u003c/ul\u003eФункция\u003cp\u003ePandas \u003ccode\u003econcat\u003c/code\u003e является \u003ca href=\"https://en.wikipedia.org/wiki/Swiss_Army_knife\" rel=\"noreferrer\"\u003eшвейцарским армейским ножом\u003c/a\u003e объединенных утилит. Разнообразие ситуаций, в которых это полезно, многочисленно. Существующая документация упускает некоторые подробности о некоторых необязательных аргументах. Среди них аргументы \u003ccode\u003elevels\u003c/code\u003e и \u003ccode\u003ekeys\u003c/code\u003e. Я решил выяснить, что делают эти аргументы.\u003c/p\u003e\u003cp\u003eЯ задам вопрос, который послужит воротами во многие аспекты \u003ccode\u003epd.concat\u003c/code\u003e.\u003c/p\u003e\u003cp\u003eРассмотрите кадры данных \u003ccode\u003ed1\u003c/code\u003e, \u003ccode\u003ed2\u003c/code\u003eи \u003ccode\u003ed3\u003c/code\u003e:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eimport pandas as pd\n\nd1 = pd.DataFrame(dict(A=.1, B=.2, C=.3), [2, 3])\nd2 = pd.DataFrame(dict(B=.4, C=.5, D=.6), [1, 2])\nd3 = pd.DataFrame(dict(A=.7, B=.8, D=.9), [1, 3])\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eЕсли бы я объединил их вместе с\u003c/p\u003e\u003cpre\u003e\u003ccode\u003epd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'])\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eЯ получаю ожидаемый результат с \u003ccode\u003epandas.MultiIndex\u003c/code\u003e для моего объекта \u003ccode\u003ecolumns\u003c/code\u003e:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e A B C D\nd1 2 0.1 0.2 0.3 NaN\n 3 0.1 0.2 0.3 NaN\nd2 1 NaN 0.4 0.5 0.6\n 2 NaN 0.4 0.5 0.6\nd3 1 0.7 0.8 NaN 0.9\n 3 0.7 0.8 NaN 0.9\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eОднако я хотел использовать \u003ca href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas-concat\" rel=\"noreferrer\"\u003e\u003ccode\u003eуровни\u003c/code\u003e документацию по аргументам\u003c/a\u003e:\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003e\u003cstrong\u003elevels\u003c/strong\u003e: список последовательностей, по умолчанию нет.\n Конкретные уровни (уникальные значения), используемые для построения MultiIndex. В противном случае они будут выводиться из ключей.\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eТак я прошел\u003c/p\u003e\u003cpre\u003e\u003ccode\u003epd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2']])\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eИ получите \u003ccode\u003eKeyError\u003c/code\u003e\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003e\u003ccode\u003eValueError: ключ d3 не находится на уровне Index(['d1', 'd2'], dtype='object')\u003c/code\u003e\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eЭто имело смысл. Уровни, которые я прошел, были недостаточны для описания необходимых уровней, обозначенных клавишами. Если бы я ничего не прошел, как я сделал выше, уровни выводятся (как указано в документации). Но как еще я могу использовать этот аргумент для большего эффекта?\u003c/p\u003e\u003cp\u003eЕсли бы я попробовал это вместо этого:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003epd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2', 'd3']])\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eI и получил те же результаты, что и выше. Но когда я добавляю еще одно значение к уровням,\u003c/p\u003e\u003cpre\u003e\u003ccode\u003edf = pd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2', 'd3', 'd4']])\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eВ итоге я получаю такой же фрейм данных, но результирующий \u003ccode\u003eMultiIndex\u003c/code\u003e имеет неиспользуемый уровень.\u003c/p\u003e\u003cpre\u003e\u003ccode\u003edf.index.levels[0]\n\nIndex(['d1', 'd2', 'd3', 'd4'], dtype='object')\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eТак в чем смысл аргумента \u003ccode\u003eуровень\u003c/code\u003e и должен ли я использовать \u003ccode\u003eключи\u003c/code\u003e по-другому?\u003c/p\u003e\u003cp\u003eЯ использую Python 3.6 и Pandas 0.22.\u003c/p\u003e","originalBody":"\u003ch3\u003eQuestions\u003c/h3\u003e\n\n\u003cul\u003e\n\u003cli\u003eHow do I use \u003ccode\u003epd.concat\u003c/code\u003e?\u003c/li\u003e\n\u003cli\u003eWhat is the \u003ccode\u003elevels\u003c/code\u003e argument for?\u003c/li\u003e\n\u003cli\u003eWhat is the \u003ccode\u003ekeys\u003c/code\u003e argument for?\u003c/li\u003e\n\u003cli\u003eAre there a bunch of examples to help explain how to use all the arguments?\u003c/li\u003e\n\u003c/ul\u003e\n\n\u003cp\u003ePandas' \u003ccode\u003econcat\u003c/code\u003e function is the \u003ca href=\"https://en.wikipedia.org/wiki/Swiss_Army_knife\" rel=\"noreferrer\"\u003eSwiss Army knife\u003c/a\u003e of the merging utilities. The variety of situations in which it is useful are numerous. The existing documentation leaves out a few details on some of the optional arguments. Among them are the \u003ccode\u003elevels\u003c/code\u003e and \u003ccode\u003ekeys\u003c/code\u003e arguments. I set out to figure out what those arguments do.\u003c/p\u003e\n\n\u003cp\u003eI'll pose a question that will act as a gateway into many aspects of \u003ccode\u003epd.concat\u003c/code\u003e.\u003c/p\u003e\n\n\u003cp\u003eConsider the data frames \u003ccode\u003ed1\u003c/code\u003e, \u003ccode\u003ed2\u003c/code\u003e, and \u003ccode\u003ed3\u003c/code\u003e:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport pandas as pd\n\nd1 = pd.DataFrame(dict(A=.1, B=.2, C=.3), [2, 3])\nd2 = pd.DataFrame(dict(B=.4, C=.5, D=.6), [1, 2])\nd3 = pd.DataFrame(dict(A=.7, B=.8, D=.9), [1, 3])\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eIf I were to concatenate these together with\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003epd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'])\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI get the expected result with a \u003ccode\u003epandas.MultiIndex\u003c/code\u003e for my \u003ccode\u003ecolumns\u003c/code\u003e object:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e A B C D\nd1 2 0.1 0.2 0.3 NaN\n 3 0.1 0.2 0.3 NaN\nd2 1 NaN 0.4 0.5 0.6\n 2 NaN 0.4 0.5 0.6\nd3 1 0.7 0.8 NaN 0.9\n 3 0.7 0.8 NaN 0.9\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eHowever, I wanted to use the \u003ca href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html#pandas-concat\" rel=\"noreferrer\"\u003e\u003ccode\u003elevels\u003c/code\u003e argument documentation\u003c/a\u003e:\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003e\u003cstrong\u003elevels\u003c/strong\u003e: list of sequences, default None.\n Specific levels (unique values) to use for constructing a MultiIndex. Otherwise, they will be inferred from the keys.\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eSo I passed\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003epd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2']])\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eAnd get a \u003ccode\u003eKeyError\u003c/code\u003e\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003e\u003ccode\u003eValueError: Key d3 not in level Index(['d1', 'd2'], dtype='object')\u003c/code\u003e\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eThis made sense. The levels I passed were inadequate to describe the necessary levels indicated by the keys. Had I not passed anything, as I did above, the levels are inferred (as stated in the documentation). But how else can I use this argument to better effect?\u003c/p\u003e\n\n\u003cp\u003eIf I tried this instead:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003epd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2', 'd3']])\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI and got the same results as above. But when I add one more value to the levels,\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003edf = pd.concat([d1, d2, d3], keys=['d1', 'd2', 'd3'], levels=[['d1', 'd2', 'd3', 'd4']])\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI end up with the same looking data frame, but the resulting \u003ccode\u003eMultiIndex\u003c/code\u003e has an unused level.\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003edf.index.levels[0]\n\nIndex(['d1', 'd2', 'd3', 'd4'], dtype='object')\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eSo what is the point of the \u003ccode\u003elevel\u003c/code\u003e argument and should I be using \u003ccode\u003ekeys\u003c/code\u003e differently?\u003c/p\u003e\n\n\u003cp\u003eI'm using Python 3.6 and Pandas 0.22.\u003c/p\u003e\n","likes":0,"pageViews":19508,"author":"piRSquared","authorProfile":"https://stackoverflow.com/users/2336654/pirsquared","sourceLink":"https://stackoverflow.com/questions/49620538/what-are-the-levels-keys-and-names-arguments-for-in-pandas-concat-functio","sourceId":49620538,"isActive":true,"isTranslated":true,"createdAt":"2018-04-03T00:25:14.000Z","updatedAt":"2022-01-17T10:15:35.952Z","tags":[{"id":17697,"questionId":5857,"tagId":46,"tag":{"id":46,"slug":"python","title":"python","description":null,"totalQuestions":743,"isActive":true,"createdAt":"2021-12-01T19:35:07.579Z","updatedAt":"2022-01-17T08:47:45.240Z"}},{"id":17699,"questionId":5857,"tagId":86,"tag":{"id":86,"slug":"pandas","title":"pandas","description":null,"totalQuestions":104,"isActive":true,"createdAt":"2021-12-01T19:35:07.637Z","updatedAt":"2022-01-17T08:47:45.218Z"}}],"_count":{"answers":1}},{"id":5823,"addedBy":null,"slug":"5823-sostoyanie-kak-massiv-obuektov-i-obuekt-s-klyuchom-po-identifikatoru","title":"Состояние как массив объектов и объект с ключом по идентификатору","body":"В главе [Проектирование формы состояния](\u003chttp://redux.js.org/docs/basics/Reducers.html\u003e)документация предлагает хранить ваше состояние в объекте с ID:\n\n\u003e Сохраняйте каждую сущность в объекте с идентификатором в качестве ключа и используйте идентификаторы для ссылки на нее из других сущностей или списков.\n\nОни продолжают говорить\n\n\u003e Подумайте о состоянии приложения как о базе данных.\n\nЯ работаю над формой состояния для списка фильтров, некоторые из которых будут открыты (они отображаются во всплывающем окне) или имеют выбранные параметры. Когда я прочитал «Думайте о состоянии приложения как о базе данных», я подумал о том, чтобы думать о них как об ответе JSON, поскольку он будет возвращен из API (который сам поддерживается базой данных).\n\nЯ думал об этом как\n\n```\n[{\n id: '1',\n name: 'View',\n open: false,\n options: ['10', '11', '12', '13'],\n selectedOption: ['10'],\n parent: null,\n },\n {\n id: '10',\n name: 'Time \u0026 Fees',\n open: false,\n options: ['20', '21', '22', '23', '24'],\n selectedOption: null,\n parent: '1',\n }]\n```\n\nОднако в документации предлагается формат, больше похожий на\n\n```\n{\n 1: { \n name: 'View',\n open: false,\n options: ['10', '11', '12', '13'],\n selectedOption: ['10'],\n parent: null,\n },\n 10: {\n name: 'Time \u0026 Fees',\n open: false,\n options: ['20', '21', '22', '23', '24'],\n selectedOption: null,\n parent: '1',\n }\n}\n```\n\nТеоретически это не имеет значения, если [данные сериализуемы (под заголовком \"Состояние\")](\u003chttp://redux.js.org/docs/Glossary.html\u003e).\n\nПоэтому я с удовольствием использовал подход с массивом объектов, пока не написал свой редьюсер.\n\nПри подходе с ключом объекта по идентификатору (и свободном использовании синтаксиса распространения) часть редуктора `OPEN_FILTER` становится\n\n```\nswitch (action.type) {\n case OPEN_FILTER: {\n return { ...state, { ...state[action.id], open: true } }\n }\n```\n\nВ то время как подход с массивом объектов более подробный (и зависит от вспомогательной функции)\n\n```\nswitch (action.type) {\n case OPEN_FILTER: {\n // relies on getFilterById helper function\n const filter = getFilterById(state, action.id);\n const index = state.indexOf(filter);\n return state\n .slice(0, index)\n .concat([{ ...filter, open: true }])\n .concat(state.slice(index + 1));\n }\n ...\n```\n\n## Итак, у меня три вопроса:\n\n1) Является ли простота редуктора мотивацией для использования подхода с ключом объекта по идентификатору? Есть ли другие преимущества в этой форме состояния?\n\nи\n\n2) Похоже, что подход с ключом объекта по идентификатору усложняет работу со стандартным вводом/выводом JSON для API. (Вот почему я в первую очередь выбрал массив объектов.) Итак, если вы выберете этот подход, вы просто используете функцию для преобразования его туда и обратно между форматом JSON и форматом формы состояния? Это кажется неуклюжим. (Хотя, если вы поддерживаете этот подход, является ли частью ваших рассуждений то, что он менее неуклюж, чем редуктор массива объектов выше?)\n\nи\n\n3) Я знаю, что Дэн Абрамов разработал редукцию, чтобы теоретически быть независимым от структуры данных и состояния (как было предложено [«По соглашению, состояние верхнего уровня является объектом или какой-либо другой коллекцией ключ-значение, такой как Карта, но *технически это может быть любой тип*, \"](\u003chttp://redux.js.org/docs/Glossary.html\u003e) подчеркнуто мной). Но, учитывая вышеизложенное, просто «рекомендуется» сохранить его как объект с ключом по идентификатору, или есть другие непредвиденные болевые точки, с которыми я столкнусь, используя массив объектов, которые делают его таким, что я должен просто прервать это спланировать и попытаться придерживаться объекта с ID?\n\n","htmlBody":"\u003cp\u003eВ главе \u003ca href=\"http://redux.js.org/docs/basics/Reducers.html\" rel=\"noreferrer\"\u003eПроектирование формы состояния\u003c/a\u003eдокументация предлагает хранить ваше состояние в объекте с ID:\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003eСохраняйте каждую сущность в объекте с идентификатором в качестве ключа и используйте идентификаторы для ссылки на нее из других сущностей или списков.\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eОни продолжают говорить\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003eПодумайте о состоянии приложения как о базе данных.\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eЯ работаю над формой состояния для списка фильтров, некоторые из которых будут открыты (они отображаются во всплывающем окне) или имеют выбранные параметры. Когда я прочитал «Думайте о состоянии приложения как о базе данных», я подумал о том, чтобы думать о них как об ответе JSON, поскольку он будет возвращен из API (который сам поддерживается базой данных).\u003c/p\u003e\u003cp\u003eЯ думал об этом как\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e[{\n id: '1',\n name: 'View',\n open: false,\n options: ['10', '11', '12', '13'],\n selectedOption: ['10'],\n parent: null,\n },\n {\n id: '10',\n name: 'Time \u0026amp; Fees',\n open: false,\n options: ['20', '21', '22', '23', '24'],\n selectedOption: null,\n parent: '1',\n }]\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eОднако в документации предлагается формат, больше похожий на\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e{\n 1: { \n name: 'View',\n open: false,\n options: ['10', '11', '12', '13'],\n selectedOption: ['10'],\n parent: null,\n },\n 10: {\n name: 'Time \u0026amp; Fees',\n open: false,\n options: ['20', '21', '22', '23', '24'],\n selectedOption: null,\n parent: '1',\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eТеоретически это не имеет значения, если \u003ca href=\"http://redux.js.org/docs/Glossary.html\" rel=\"noreferrer\"\u003eданные сериализуемы (под заголовком \"Состояние\")\u003c/a\u003e.\u003c/p\u003e\u003cp\u003eПоэтому я с удовольствием использовал подход с массивом объектов, пока не написал свой редьюсер.\u003c/p\u003e\u003cp\u003eПри подходе с ключом объекта по идентификатору (и свободном использовании синтаксиса распространения) часть редуктора \u003ccode\u003eOPEN_FILTER\u003c/code\u003e становится\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eswitch (action.type) {\n case OPEN_FILTER: {\n return { ...state, { ...state[action.id], open: true } }\n }\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eВ то время как подход с массивом объектов более подробный (и зависит от вспомогательной функции)\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eswitch (action.type) {\n case OPEN_FILTER: {\n // relies on getFilterById helper function\n const filter = getFilterById(state, action.id);\n const index = state.indexOf(filter);\n return state\n .slice(0, index)\n .concat([{ ...filter, open: true }])\n .concat(state.slice(index + 1));\n }\n ...\n\u003c/code\u003e\u003c/pre\u003e\u003ch2\u003eИтак, у меня три вопроса:\u003c/h2\u003e\u003cp\u003e1) Является ли простота редуктора мотивацией для использования подхода с ключом объекта по идентификатору? Есть ли другие преимущества в этой форме состояния?\u003c/p\u003e\u003cp\u003eи\u003c/p\u003e\u003cp\u003e2) Похоже, что подход с ключом объекта по идентификатору усложняет работу со стандартным вводом/выводом JSON для API. (Вот почему я в первую очередь выбрал массив объектов.) Итак, если вы выберете этот подход, вы просто используете функцию для преобразования его туда и обратно между форматом JSON и форматом формы состояния? Это кажется неуклюжим. (Хотя, если вы поддерживаете этот подход, является ли частью ваших рассуждений то, что он менее неуклюж, чем редуктор массива объектов выше?)\u003c/p\u003e\u003cp\u003eи\u003c/p\u003e\u003cp\u003e3) Я знаю, что Дэн Абрамов разработал редукцию, чтобы теоретически быть независимым от структуры данных и состояния (как было предложено \u003ca href=\"http://redux.js.org/docs/Glossary.html\" rel=\"noreferrer\"\u003e«По соглашению, состояние верхнего уровня является объектом или какой-либо другой коллекцией ключ-значение, такой как Карта, но \u003cem\u003eтехнически это может быть любой тип\u003c/em\u003e, \"\u003c/a\u003e подчеркнуто мной). Но, учитывая вышеизложенное, просто «рекомендуется» сохранить его как объект с ключом по идентификатору, или есть другие непредвиденные болевые точки, с которыми я столкнусь, используя массив объектов, которые делают его таким, что я должен просто прервать это спланировать и попытаться придерживаться объекта с ID?\u003c/p\u003e","originalBody":"\u003cp\u003eIn the chapter on \u003ca href=\"http://redux.js.org/docs/basics/Reducers.html\" rel=\"noreferrer\"\u003eDesigning the State Shape\u003c/a\u003e, the docs suggest to keep your state in an object keyed by ID:\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003eKeep every entity in an object stored with an ID as a key, and use IDs to reference it from other entities, or lists.\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eThey go on to state\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003eThink of the app’s state as a database.\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eI'm working on the state shape for a list of filters, some of which will be open (they're displayed in a popup), or have selected options. When I read \"Think of the app’s state as a database,\" I thought about thinking of them as a JSON response as it would be returned from an API (itself backed by a database). \u003c/p\u003e\n\n\u003cp\u003eSo I was thinking of it as\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e[{\n id: '1',\n name: 'View',\n open: false,\n options: ['10', '11', '12', '13'],\n selectedOption: ['10'],\n parent: null,\n },\n {\n id: '10',\n name: 'Time \u0026amp; Fees',\n open: false,\n options: ['20', '21', '22', '23', '24'],\n selectedOption: null,\n parent: '1',\n }]\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eHowever, the docs suggest a format more like\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e{\n 1: { \n name: 'View',\n open: false,\n options: ['10', '11', '12', '13'],\n selectedOption: ['10'],\n parent: null,\n },\n 10: {\n name: 'Time \u0026amp; Fees',\n open: false,\n options: ['20', '21', '22', '23', '24'],\n selectedOption: null,\n parent: '1',\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eIn theory, it shouldn't matter as long as the \u003ca href=\"http://redux.js.org/docs/Glossary.html\" rel=\"noreferrer\"\u003edata is serializable (under the heading \"State\")\u003c/a\u003e.\u003c/p\u003e\n\n\u003cp\u003eSo I went with the array-of-objects approach happily, until I was writing my reducer.\u003c/p\u003e\n\n\u003cp\u003eWith the object-keyed-by-id approach (and liberal use of the spread syntax), the \u003ccode\u003eOPEN_FILTER\u003c/code\u003e part of the reducer becomes\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eswitch (action.type) {\n case OPEN_FILTER: {\n return { ...state, { ...state[action.id], open: true } }\n }\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eWhereas with the array-of-objects approach, it's the more verbose (and helper function reliant)\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eswitch (action.type) {\n case OPEN_FILTER: {\n // relies on getFilterById helper function\n const filter = getFilterById(state, action.id);\n const index = state.indexOf(filter);\n return state\n .slice(0, index)\n .concat([{ ...filter, open: true }])\n .concat(state.slice(index + 1));\n }\n ...\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003ch2\u003eSo my questions are threefold:\u003c/h2\u003e\n\n\u003cp\u003e1) Is the simplicity of the reducer the motivation for going with the object-keyed-by-id approach? Are there other advantages to that state shape?\u003c/p\u003e\n\n\u003cp\u003eand\u003c/p\u003e\n\n\u003cp\u003e2) It seems like the object-keyed-by-id approach makes it harder to deal with standard JSON in/out for an API. (That's why I went with the array of objects in the first place.) So if you go with that approach, do you just use a function to transform it back and forth between JSON format and state shape format? That seems clunky. (Though if you advocate that approach, is part of your reasoning that that's less clunky than the array-of-objects reducer above?)\u003c/p\u003e\n\n\u003cp\u003eand\u003c/p\u003e\n\n\u003cp\u003e3) I know Dan Abramov designed redux to theoretically be state-data-structure agnostic (as suggested by \u003ca href=\"http://redux.js.org/docs/Glossary.html\" rel=\"noreferrer\"\u003e\"By convention, the top-level state is an object or some other key-value collection like a Map, but \u003cem\u003etechnically it can be any type\u003c/em\u003e,\"\u003c/a\u003e emphasis mine). But given the above, is it just \"recommended\" to keep it an object keyed by ID, or are there other unforeseen pain points I'm going to run into by using an array of objects that make it such that I should just abort that plan and try to stick with an object keyed by ID?\u003c/p\u003e\n","likes":0,"pageViews":29422,"author":"nickcoxdotme","authorProfile":"https://stackoverflow.com/users/931934/nickcoxdotme","sourceLink":"https://stackoverflow.com/questions/38445006/state-as-array-of-objects-vs-object-keyed-by-id","sourceId":38445006,"isActive":true,"isTranslated":true,"createdAt":"2016-07-18T19:57:13.000Z","updatedAt":"2022-01-17T10:15:21.244Z","tags":[{"id":17620,"questionId":5823,"tagId":3423,"tag":{"id":3423,"slug":"spread-syntax","title":"spread-syntax","description":null,"totalQuestions":1,"isActive":true,"createdAt":"2022-01-17T08:34:11.419Z","updatedAt":"2022-01-17T08:34:14.745Z"}},{"id":17571,"questionId":5823,"tagId":5,"tag":{"id":5,"slug":"javascript","title":"javascript","description":null,"totalQuestions":956,"isActive":true,"createdAt":"2021-12-01T19:35:07.552Z","updatedAt":"2022-01-17T08:47:45.275Z"}},{"id":17570,"questionId":5823,"tagId":881,"tag":{"id":881,"slug":"redux","title":"redux","description":null,"totalQuestions":55,"isActive":true,"createdAt":"2021-12-03T12:36:06.097Z","updatedAt":"2022-01-17T08:47:45.189Z"}}],"_count":{"answers":3}},{"id":6845,"addedBy":null,"slug":"6845-stil-react-native-button-ne-rabotaet","title":"Стиль React-Native Button не работает","body":"# Импортировать\\_это\n\n```\nимпорт {AppRegistry, Text, View, Button, StyleSheet} из 'React-Native';\n```\n\nЭто мой код кнопки React, но стиль не работает Заяц...\n\n```\n\u003cКнопка\n onPress={это.onPress.bind(это)}\n title={\"Вернуться\"}\n style={{color: 'red', marginTop: 10, padding: 10}}\n/\u003e\n```\n\nТакже пробовал по этому коду\n\n```\n\u003cКнопка\n containerStyle={{padding:10, height:45, overflow:'hidden',\n borderRadius:4, backgroundColor: 'белый'}}\n style={{fontSize: 20, цвет: \"зеленый\"}}\n onPress={this.onPress.bind(this)} title={\"Вернуться\"}\n \u003e Нажмите на меня!\n\u003c!--кнопка--\u003e\n```\n\n# Обновить вопрос:\n\nТакже я пробовал вот так..\n\n```\n\u003cКнопка\n onPress={это.onPress.bind(это)}\n title={\"Вернуться\"}\n стиль = {стили.buttonStyle}\n\u003eку ка\n```\n\n# Стиль\n\n```\nпостоянные стили = StyleSheet.create({\n стиль кнопки: {\n красный цвет',\n полеВерх: 20,\n набивка: 20,\n backgroundColor: зеленый\n }\n});\n```\n\nНо нет вывода: Скриншот моего телефона: - [![Screenshot of my phone:-](\u003chttps://i.stack.imgur.com/vaNeD.png\u003e)](\u003chttps://i.stack.imgur.com/vaNeD.png\u003e)\n\n","htmlBody":"\u003cdiv\u003e\u003ch1\u003eИмпортировать_это\u003c/h1\u003e\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003eимпорт {AppRegistry, Text, View, Button, StyleSheet} из 'React-Native';\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eЭто мой код кнопки React, но стиль не работает Заяц...\u003c/p\u003e\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003e\u003cКнопка\n onPress={это.onPress.bind(this)}\n title={\"Вернуться\"}\n style={{color: 'red', marginTop: 10, padding: 10}}\n/\u003e\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eТакже пробовал по этому коду \u003c/p\u003e\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003e\u003cКнопка\n containerStyle={{padding:10, height:45, overflow:'hidden',\n borderRadius:4, backgroundColor: 'белый'}}\n style={{fontSize: 20, цвет: \"зеленый\"}}\n onPress={this.onPress.bind(this)} title={\"Вернуться\"}\n \u003e Нажмите на меня!\n\u003c/кнопка\u003e\n\u003c/code\u003e\u003c/pre\u003e\u003ch1\u003eОбновить вопрос:\u003c/h1\u003e\u003cp\u003eТакже я пробовал вот так..\u003c/p\u003e\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003e\u003cКнопка\n onPress={это.onPress.bind(это)}\n title={\"Вернуться\"}\n стиль = {стили.buttonStyle}\n\u003eку ка\u003c/Button\u003e\n\u003c/code\u003e\u003c/pre\u003e\u003ch1\u003eСтиль\u003c/h1\u003e\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003eпостоянные стили = StyleSheet.create({\n стиль кнопки: {\n красный цвет',\n полеВерх: 20,\n набивка: 20,\n backgroundColor: зеленый\n }\n});\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eНо нет вывода:\nСкриншот моего телефона: -\n\u003ca href=\"https://i.stack.imgur.com/vaNeD.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/vaNeD.png\" alt=\"Screenshot of my phone:-\"\u003e\u003c/a\u003e\u003c/p\u003e\u003c/div\u003e","originalBody":"\u003ch1\u003eImport_this\u003c/h1\u003e\n\n\n\n\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003eimport {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eThis my React Button code But style not working Hare ...\u003c/p\u003e\n\n\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003e\u0026lt;Button\n onPress={this.onPress.bind(this)} \n title={\"Go Back\"}\n style={{color: 'red', marginTop: 10, padding: 10}}\n/\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eAlso I was try by this code \u003c/p\u003e\n\n\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003e\u0026lt;Button \n containerStyle={{padding:10, height:45, overflow:'hidden', \n borderRadius:4, backgroundColor: 'white'}}\n style={{fontSize: 20, color: 'green'}} \n onPress={this.onPress.bind(this)} title={\"Go Back\"}\n \u0026gt; Press me!\n\u0026lt;/Button\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003ch1\u003eUpdate Question:\u003c/h1\u003e\n\n\u003cp\u003eAlso I was try by This way..\u003c/p\u003e\n\n\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003e\u0026lt;Button\n onPress={this.onPress.bind(this)}\n title={\"Go Back\"}\n style={styles.buttonStyle}\n\u0026gt;ku ka\u0026lt;/Button\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003ch1\u003eStyle\u003c/h1\u003e\n\n\u003cpre class=\"lang-jsx prettyprint-override\"\u003e\u003ccode\u003econst styles = StyleSheet.create({\n buttonStyle: {\n color: 'red',\n marginTop: 20,\n padding: 20,\n backgroundColor: 'green'\n }\n});\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eBut No out put: \nScreenshot of my phone:-\n\u003ca href=\"https://i.stack.imgur.com/vaNeD.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/vaNeD.png\" alt=\"Screenshot of my phone:-\"\u003e\u003c/a\u003e\u003c/p\u003e\n","likes":0,"pageViews":158692,"author":"MD Ashik","authorProfile":"https://stackoverflow.com/users/5404861/md-ashik","sourceLink":"https://stackoverflow.com/questions/43585297/react-native-button-style-not-work","sourceId":43585297,"isActive":true,"isTranslated":true,"createdAt":"2017-04-24T10:08:25.000Z","updatedAt":"2022-01-17T10:14:19.498Z","tags":[{"id":20656,"questionId":6845,"tagId":21,"tag":{"id":21,"slug":"react-native","title":"react-native","description":null,"totalQuestions":112,"isActive":true,"createdAt":"2021-12-01T19:35:07.562Z","updatedAt":"2022-01-17T08:47:45.038Z"}},{"id":20657,"questionId":6845,"tagId":472,"tag":{"id":472,"slug":"jsx","title":"jsx","description":null,"totalQuestions":17,"isActive":true,"createdAt":"2021-12-01T19:36:35.879Z","updatedAt":"2022-01-17T08:46:59.308Z"}},{"id":20743,"questionId":6845,"tagId":3691,"tag":{"id":3691,"slug":"react-native-button","title":"react-native-button","description":null,"totalQuestions":1,"isActive":true,"createdAt":"2022-01-17T08:46:57.727Z","updatedAt":"2022-01-17T08:47:00.934Z"}},{"id":20655,"questionId":6845,"tagId":22,"tag":{"id":22,"slug":"reactjs","title":"reactjs","description":null,"totalQuestions":424,"isActive":true,"createdAt":"2021-12-01T19:35:07.562Z","updatedAt":"2022-01-17T08:47:45.269Z"}}],"_count":{"answers":14}},{"id":6836,"addedBy":null,"slug":"6836-oshibka-kompilyacii-sborki-maven-ne-udalos-vypolnit-cel-orgapachemavenpluginsmaven-compiler-plugin31compile-kompilyaciya-po-umolchaniyu-v-proekte-maven","title":"Ошибка компиляции сборки Maven: не удалось выполнить цель org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (компиляция по умолчанию) в проекте Maven","body":"У меня есть проект maven, разветвленный и клонированный из репозитория git на мое затмение. Он построен на Java 8. Первое, что я делаю, это выполняю\n\n```\nmvn clean install\n```\n\nНо я получаю следующее сообщение об ошибке:\n\n```\n[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] Building Maven 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO] \n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---\n[INFO] Deleting /Users/vshukla/git/Prism/target\n[INFO] \n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources\n[INFO] \n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!\n[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes\n[INFO] -------------------------------------------------------------\n[ERROR] COMPILATION ERROR : \n[INFO] -------------------------------------------------------------\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[INFO] 3 errors \n[INFO] -------------------------------------------------------------\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 1.266 s\n[INFO] Finished at: 2017-03-01T12:11:27+05:30\n[INFO] Final Memory: 13M/309M\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] -\u003e [Help 1]\n[ERROR] \n[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.\n[ERROR] Re-run Maven using the -X switch to enable full debug logging.\n[ERROR] \n[ERROR] For more information about the errors and possible solutions, please read the following articles:\n[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException\n```\n\nОднако ниже приведены сведения о пути сборки проекта, в котором явно настроена JRE-8: [![build path](\u003chttps://i.stack.imgur.com/kz3U7.png\u003e)](\u003chttps://i.stack.imgur.com/kz3U7.png\u003e)\n\nи настройка компиляции:\n\n[![Compliance level](\u003chttps://i.stack.imgur.com/kkZmb.png\u003e)](\u003chttps://i.stack.imgur.com/kkZmb.png\u003e)\n\nНезависимо от того, сколько раз я собираю проект, я получаю ту же ошибку. Даже после очистки проекта и его обновления из eclipse не помогает. Пожалуйста, помогите.\n\n**ОБНОВЛЕНИЕ:**\n\nПосле добавления свойств для установки плагина компилятора maven\n\n```\n\u003cproperties\u003e\n \u003cmaven.compiler.source\u003e1.8\u003c/maven.compiler.source\u003e\n \u003cmaven.compiler.target\u003e1.8\u003c/maven.compiler.target\u003e\n\u003c/properties\u003e\n```\n\n,\n\nполучаю следующую ошибку:\n\n```\n[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] Building Maven 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO] \n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---\n[INFO] Deleting /Users/vshukla/git/Prism/target\n[INFO] \n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources\n[INFO] \n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!\n[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes\n[INFO] -------------------------------------------------------------\n[WARNING] COMPILATION WARNING : \n[INFO] -------------------------------------------------------------\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java uses or overrides a deprecated API.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:deprecation for details.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Some input files use unchecked or unsafe operations.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:unchecked for details.\n[INFO] 4 warnings \n[INFO] -------------------------------------------------------------\n[INFO] -------------------------------------------------------------\n[ERROR] COMPILATION ERROR : \n[INFO] -------------------------------------------------------------\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol\n symbol: class Application\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol\n symbol: variable Application\n[INFO] 3 errors \n[INFO] -------------------------------------------------------------\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.591 s\n[INFO] Finished at: 2017-03-01T13:09:47+05:30\n[INFO] Final Memory: 21M/347M\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol\n[ERROR] symbol: class Application\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol\n[ERROR] symbol: variable Application\n[ERROR] -\u003e [Help 1]\n[ERROR] \n[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.\n[ERROR] Re-run Maven using the -X switch to enable full debug logging.\n[ERROR] \n[ERROR] For more information about the errors and possible solutions, please read the following articles:\n[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException\n```\n\nА вот фрагмент кода, выдающий ошибку компиляции из класса MainUITabbed:\n\n```\nimport com.apple.eawt.Application;\npublic static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n\n\n Application application = Application.getApplication(); // line 93\n\n ImageIcon imgicon = new ImageIcon(getClass().getResource(\n \"ICON.jpg\"));\n Image img = imgicon.getImage();\n\n\n application.setDockIconImage(img);\n\n MainUITabbed frame = new MainUITabbed();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n\n }\n }\n });\n}\n```\n\n","htmlBody":"\u003cp\u003eУ меня есть проект maven, разветвленный и клонированный из репозитория git на мое затмение. Он построен на Java 8. Первое, что я делаю, это выполняю \u003c/p\u003e\u003cpre\u003e\u003ccode\u003emvn clean install\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eНо я получаю следующее сообщение об ошибке:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] Building Maven 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO] \n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---\n[INFO] Deleting /Users/vshukla/git/Prism/target\n[INFO] \n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources\n[INFO] \n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!\n[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes\n[INFO] -------------------------------------------------------------\n[ERROR] COMPILATION ERROR : \n[INFO] -------------------------------------------------------------\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[INFO] 3 errors \n[INFO] -------------------------------------------------------------\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 1.266 s\n[INFO] Finished at: 2017-03-01T12:11:27+05:30\n[INFO] Final Memory: 13M/309M\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] -\u0026gt; [Help 1]\n[ERROR] \n[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.\n[ERROR] Re-run Maven using the -X switch to enable full debug logging.\n[ERROR] \n[ERROR] For more information about the errors and possible solutions, please read the following articles:\n[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eОднако ниже приведены сведения о пути сборки проекта, в котором явно настроена JRE-8:\n\u003ca href=\"https://i.stack.imgur.com/kz3U7.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/kz3U7.png\" alt=\"build path\"\u003e\u003c/a\u003e\u003c/p\u003e\u003cp\u003eи настройка компиляции:\u003c/p\u003e\u003cp\u003e\u003ca href=\"https://i.stack.imgur.com/kkZmb.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/kkZmb.png\" alt=\"Compliance level\"\u003e\u003c/a\u003e\u003c/p\u003e\u003cp\u003eНезависимо от того, сколько раз я собираю проект, я получаю ту же ошибку. Даже после очистки проекта и его обновления из eclipse не помогает. Пожалуйста, помогите.\u003c/p\u003e\u003cp\u003e\u003cstrong\u003eОБНОВЛЕНИЕ:\u003c/strong\u003e\u003c/p\u003e\u003cp\u003eПосле добавления свойств для установки плагина компилятора maven\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e\u0026lt;properties\u0026gt;\n \u0026lt;maven.compiler.source\u0026gt;1.8\u0026lt;/maven.compiler.source\u0026gt;\n \u0026lt;maven.compiler.target\u0026gt;1.8\u0026lt;/maven.compiler.target\u0026gt;\n\u0026lt;/properties\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003e, \u003c/p\u003e\u003cp\u003eполучаю следующую ошибку:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] Building Maven 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO] \n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---\n[INFO] Deleting /Users/vshukla/git/Prism/target\n[INFO] \n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources\n[INFO] \n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!\n[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes\n[INFO] -------------------------------------------------------------\n[WARNING] COMPILATION WARNING : \n[INFO] -------------------------------------------------------------\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java uses or overrides a deprecated API.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:deprecation for details.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Some input files use unchecked or unsafe operations.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:unchecked for details.\n[INFO] 4 warnings \n[INFO] -------------------------------------------------------------\n[INFO] -------------------------------------------------------------\n[ERROR] COMPILATION ERROR : \n[INFO] -------------------------------------------------------------\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol\n symbol: class Application\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol\n symbol: variable Application\n[INFO] 3 errors \n[INFO] -------------------------------------------------------------\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.591 s\n[INFO] Finished at: 2017-03-01T13:09:47+05:30\n[INFO] Final Memory: 21M/347M\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol\n[ERROR] symbol: class Application\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol\n[ERROR] symbol: variable Application\n[ERROR] -\u0026gt; [Help 1]\n[ERROR] \n[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.\n[ERROR] Re-run Maven using the -X switch to enable full debug logging.\n[ERROR] \n[ERROR] For more information about the errors and possible solutions, please read the following articles:\n[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eА вот фрагмент кода, выдающий ошибку компиляции из класса MainUITabbed:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eimport com.apple.eawt.Application;\npublic static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n\n\n Application application = Application.getApplication(); // line 93\n\n ImageIcon imgicon = new ImageIcon(getClass().getResource(\n \"ICON.jpg\"));\n Image img = imgicon.getImage();\n\n\n application.setDockIconImage(img);\n\n MainUITabbed frame = new MainUITabbed();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n\n }\n }\n });\n}\n\u003c/code\u003e\u003c/pre\u003e","originalBody":"\u003cp\u003eI have a maven project forked and cloned from a git repo onto my eclipse. It is build on Java 8. The first thing i do is perform a \u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003emvn clean install\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eBut I get following failure message:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] Building Maven 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO] \n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---\n[INFO] Deleting /Users/vshukla/git/Prism/target\n[INFO] \n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources\n[INFO] \n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!\n[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes\n[INFO] -------------------------------------------------------------\n[ERROR] COMPILATION ERROR : \n[INFO] -------------------------------------------------------------\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5\n (use -source 7 or higher to enable diamond operator)\n[INFO] 3 errors \n[INFO] -------------------------------------------------------------\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 1.266 s\n[INFO] Finished at: 2017-03-01T12:11:27+05:30\n[INFO] Final Memory: 13M/309M\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/scanUtility.java:[54,52] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/AppUtility.java:[87,86] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] /Users/vshukla/git/Prism/src/main/java/PrenPost/ComparisionUtility.java:[58,52] diamond operator is not supported in -source 1.5\n[ERROR] (use -source 7 or higher to enable diamond operator)\n[ERROR] -\u0026gt; [Help 1]\n[ERROR] \n[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.\n[ERROR] Re-run Maven using the -X switch to enable full debug logging.\n[ERROR] \n[ERROR] For more information about the errors and possible solutions, please read the following articles:\n[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eHowever, below is the build path details of the project which clearly has JRE - 8 set up:\n\u003ca href=\"https://i.stack.imgur.com/kz3U7.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/kz3U7.png\" alt=\"build path\"\u003e\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eand the compilation set up:\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://i.stack.imgur.com/kkZmb.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/kkZmb.png\" alt=\"Compliance level\"\u003e\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eNo matter how many times I build the project, i get the same error. Even after cleaning the project and refreshing it from eclipse doesn't help. Please guide.\u003c/p\u003e\n\n\u003cp\u003e\u003cstrong\u003eUPDATE:\u003c/strong\u003e\u003c/p\u003e\n\n\u003cp\u003eAfter adding the properties to set maven compiler plugin\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e\u0026lt;properties\u0026gt;\n \u0026lt;maven.compiler.source\u0026gt;1.8\u0026lt;/maven.compiler.source\u0026gt;\n \u0026lt;maven.compiler.target\u0026gt;1.8\u0026lt;/maven.compiler.target\u0026gt;\n\u0026lt;/properties\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e, \u003c/p\u003e\n\n\u003cp\u003eam getting the below error:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e[INFO] Scanning for projects...\n[INFO] \n[INFO] ------------------------------------------------------------------------\n[INFO] Building Maven 0.0.1-SNAPSHOT\n[INFO] ------------------------------------------------------------------------\n[INFO] \n[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ Maven ---\n[INFO] Deleting /Users/vshukla/git/Prism/target\n[INFO] \n[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ Maven ---\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /Users/vshukla/git/Prism/src/main/resources\n[INFO] \n[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ Maven ---\n[INFO] Changes detected - recompiling the module!\n[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!\n[INFO] Compiling 66 source files to /Users/vshukla/git/Prism/target/classes\n[INFO] -------------------------------------------------------------\n[WARNING] COMPILATION WARNING : \n[INFO] -------------------------------------------------------------\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java uses or overrides a deprecated API.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:deprecation for details.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Some input files use unchecked or unsafe operations.\n[WARNING] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java: Recompile with -Xlint:unchecked for details.\n[INFO] 4 warnings \n[INFO] -------------------------------------------------------------\n[INFO] -------------------------------------------------------------\n[ERROR] COMPILATION ERROR : \n[INFO] -------------------------------------------------------------\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol\n symbol: class Application\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol\n symbol: variable Application\n[INFO] 3 errors \n[INFO] -------------------------------------------------------------\n[INFO] ------------------------------------------------------------------------\n[INFO] BUILD FAILURE\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 2.591 s\n[INFO] Finished at: 2017-03-01T13:09:47+05:30\n[INFO] Final Memory: 21M/347M\n[INFO] ------------------------------------------------------------------------\n[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven: Compilation failure: Compilation failure:\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[26,22] package com.apple.eawt does not exist\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,41] cannot find symbol\n[ERROR] symbol: class Application\n[ERROR] /Users/vshukla/git/Prism/src/main/java/main/MainUITabbed.java:[93,67] cannot find symbol\n[ERROR] symbol: variable Application\n[ERROR] -\u0026gt; [Help 1]\n[ERROR] \n[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.\n[ERROR] Re-run Maven using the -X switch to enable full debug logging.\n[ERROR] \n[ERROR] For more information about the errors and possible solutions, please read the following articles:\n[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eAnd here is the code snippet giving the compilation error from MainUITabbed class:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport com.apple.eawt.Application;\npublic static void main(String[] args) {\n EventQueue.invokeLater(new Runnable() {\n public void run() {\n try {\n\n\n Application application = Application.getApplication(); // line 93\n\n ImageIcon imgicon = new ImageIcon(getClass().getResource(\n \"ICON.jpg\"));\n Image img = imgicon.getImage();\n\n\n application.setDockIconImage(img);\n\n MainUITabbed frame = new MainUITabbed();\n frame.setVisible(true);\n } catch (Exception e) {\n e.printStackTrace();\n\n }\n }\n });\n}\n\u003c/code\u003e\u003c/pre\u003e\n","likes":0,"pageViews":708378,"author":"roger_that","authorProfile":"https://stackoverflow.com/users/1471314/roger-that","sourceLink":"https://stackoverflow.com/questions/42525139/maven-build-compilation-error-failed-to-execute-goal-org-apache-maven-plugins","sourceId":42525139,"isActive":true,"isTranslated":true,"createdAt":"2017-03-01T06:56:18.000Z","updatedAt":"2022-01-17T10:14:03.377Z","tags":[{"id":20628,"questionId":6836,"tagId":2242,"tag":{"id":2242,"slug":"build","title":"build","description":null,"totalQuestions":15,"isActive":true,"createdAt":"2021-12-13T09:01:27.630Z","updatedAt":"2022-01-17T08:47:44.950Z"}},{"id":20626,"questionId":6836,"tagId":33,"tag":{"id":33,"slug":"java","title":"java","description":null,"totalQuestions":339,"isActive":true,"createdAt":"2021-12-01T19:35:07.573Z","updatedAt":"2022-01-17T08:47:45.058Z"}},{"id":20629,"questionId":6836,"tagId":2438,"tag":{"id":2438,"slug":"maven-compiler-plugin","title":"maven-compiler-plugin","description":null,"totalQuestions":2,"isActive":true,"createdAt":"2021-12-16T10:37:00.747Z","updatedAt":"2022-01-17T08:46:59.241Z"}},{"id":20627,"questionId":6836,"tagId":54,"tag":{"id":54,"slug":"maven","title":"maven","description":null,"totalQuestions":25,"isActive":true,"createdAt":"2021-12-01T19:35:07.585Z","updatedAt":"2022-01-17T08:46:59.234Z"}}],"_count":{"answers":25}}],"randomQuestions":[{"id":3207,"addedBy":null,"slug":"3207-make-axios-send-cookies-in-its-requests-automatically","title":"Make Axios send cookies in its requests automatically","body":"I am sending requests from the client to my Express.js server using Axios.\n\nI set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.\n\nThis is my clientside request example:\n\n```\naxios.get(`some api url`).then(response =\u003e ...\n```\n\nI tried to access headers or cookies by using these properties in my Express.js server:\n\n```\nreq.headers\nreq.cookies\n```\n\nNeither of them contained any cookies. I am using cookie parser middleware:\n\n```\napp.use(cookieParser())\n```\n\nHow do I make Axios send cookies in requests automatically?\n\nEdit:\n\nI set cookie on the client like this:\n\n```\nimport cookieClient from 'react-cookie'\n\n...\nlet cookie = cookieClient.load('cookie-name')\nif(cookie === undefined){\n axios.get('path/to/my/cookie/api').then(response =\u003e {\n if(response.status == 200){\n cookieClient.save('cookie-name', response.data, {path:'/'})\n }\n })\n }\n...\n```\n\nWhile it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.\n\n","htmlBody":"\u003cp\u003eI am sending requests from the client to my Express.js server using Axios. \u003c/p\u003e\u003cp\u003eI set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand. \u003c/p\u003e\u003cp\u003eThis is my clientside request example:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eaxios.get(`some api url`).then(response =\u0026gt; ...\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eI tried to access headers or cookies by using these properties in my Express.js server:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003ereq.headers\nreq.cookies\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eNeither of them contained any cookies. I am using cookie parser middleware:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eapp.use(cookieParser())\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eHow do I make Axios send cookies in requests automatically? \u003c/p\u003e\u003cp\u003eEdit:\u003c/p\u003e\u003cp\u003eI set cookie on the client like this:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eimport cookieClient from 'react-cookie'\n\n...\nlet cookie = cookieClient.load('cookie-name')\nif(cookie === undefined){\n axios.get('path/to/my/cookie/api').then(response =\u0026gt; {\n if(response.status == 200){\n cookieClient.save('cookie-name', response.data, {path:'/'})\n }\n })\n }\n...\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eWhile it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set. \u003c/p\u003e","originalBody":"\u003cp\u003eI am sending requests from the client to my Express.js server using Axios. \u003c/p\u003e\n\n\u003cp\u003eI set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand. \u003c/p\u003e\n\n\u003cp\u003eThis is my clientside request example:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eaxios.get(`some api url`).then(response =\u0026gt; ...\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI tried to access headers or cookies by using these properties in my Express.js server:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003ereq.headers\nreq.cookies\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eNeither of them contained any cookies. I am using cookie parser middleware:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eapp.use(cookieParser())\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eHow do I make Axios send cookies in requests automatically? \u003c/p\u003e\n\n\u003cp\u003eEdit:\u003c/p\u003e\n\n\u003cp\u003eI set cookie on the client like this:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport cookieClient from 'react-cookie'\n\n...\nlet cookie = cookieClient.load('cookie-name')\nif(cookie === undefined){\n axios.get('path/to/my/cookie/api').then(response =\u0026gt; {\n if(response.status == 200){\n cookieClient.save('cookie-name', response.data, {path:'/'})\n }\n })\n }\n...\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eWhile it's also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set. \u003c/p\u003e\n","likes":0,"pageViews":329650,"author":"Kunok","authorProfile":"https://stackoverflow.com/users/5426743/kunok","sourceLink":"https://stackoverflow.com/questions/43002444/make-axios-send-cookies-in-its-requests-automatically","sourceId":43002444,"isActive":true,"isTranslated":true,"createdAt":"2017-03-24T14:44:09.000Z","updatedAt":"2021-12-26T20:39:38.595Z","tags":[{"id":9676,"questionId":3207,"tagId":5,"tag":{"id":5,"slug":"javascript","title":"javascript","description":null,"totalQuestions":956,"isActive":true,"createdAt":"2021-12-01T19:35:07.552Z","updatedAt":"2022-01-17T08:47:45.275Z"}},{"id":9679,"questionId":3207,"tagId":1433,"tag":{"id":1433,"slug":"cookies","title":"cookies","description":null,"totalQuestions":8,"isActive":true,"createdAt":"2021-12-11T07:41:32.771Z","updatedAt":"2022-01-17T08:35:32.058Z"}},{"id":9678,"questionId":3207,"tagId":6,"tag":{"id":6,"slug":"nodejs","title":"node.js","description":null,"totalQuestions":243,"isActive":true,"createdAt":"2021-12-01T19:35:07.553Z","updatedAt":"2022-01-17T08:47:45.254Z"}},{"id":9677,"questionId":3207,"tagId":9,"tag":{"id":9,"slug":"express","title":"express","description":null,"totalQuestions":18,"isActive":true,"createdAt":"2021-12-01T19:35:07.559Z","updatedAt":"2022-01-17T08:47:45.248Z"}},{"id":9681,"questionId":3207,"tagId":562,"tag":{"id":562,"slug":"axios","title":"axios","description":null,"totalQuestions":23,"isActive":true,"createdAt":"2021-12-01T19:36:57.023Z","updatedAt":"2022-01-17T08:47:18.783Z"}}],"_count":{"answers":14}},{"id":3214,"addedBy":null,"slug":"3214-intellij-errorjava-error-release-version-5-not-supported","title":"IntelliJ: Error:java: error: release version 5 not supported","body":"I'm using **IntelliJ IDEA Ultimate 2019.3.1**. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:\n\n```\nError:java: error: release version 5 not supported\n```\n\nRunning `java --version` by terminal I get the following output:\n\n```\nopenjdk 11.0.5 2019-10-15\nOpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)\nOpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)\n```\n\nRunning `javac --version` by terminal I get the following output:\n\n```\njavac 11.0.5\n```\n\nGoing to the Settings of the Java Compiler ( as suggested [here](\u003chttps://stackoverflow.com/questions/52788743/intellij-error-java-release-version-10-not-supported\u003e) ) I see this:\n\n[![Java Compiler Settings](\u003chttps://i.stack.imgur.com/WJdHN.png\u003e)](\u003chttps://i.stack.imgur.com/WJdHN.png\u003e)\n\nI tried editing the \"**Target bytecode version**\" to **1\\.8** but I get the following errors:\n\n```\nError:(1, 26) java: package javafx.application does not exist\nError:(2, 20) java: package javafx.stage does not exist\nError:(4, 27) java: cannot find symbol\n symbol: class Application\nError:(12, 23) java: cannot find symbol\n symbol: class Stage\n location: class Main\nError:(7, 9) java: cannot find symbol\n symbol: method launch(java.lang.String[])\n location: class Main\nError:(11, 5) java: method does not override or implement a method from a supertype\n```\n\nChanging it to version **1\\.11** I get this error instead:\n\n```\nError:java: Source option 5 is no longer supported. Use 6 or later.\n```\n\nWhat do you think is the problem? How may I solve it?\n\n","htmlBody":"\u003cp\u003eI'm using \u003cstrong\u003eIntelliJ IDEA Ultimate 2019.3.1\u003c/strong\u003e. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eError:java: error: release version 5 not supported\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eRunning \u003ccode\u003ejava --version\u003c/code\u003e by terminal I get the following output:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eopenjdk 11.0.5 2019-10-15\nOpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)\nOpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eRunning \u003ccode\u003ejavac --version\u003c/code\u003e by terminal I get the following output:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003ejavac 11.0.5\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eGoing to the Settings of the Java Compiler ( as suggested \u003ca href=\"https://stackoverflow.com/questions/52788743/intellij-error-java-release-version-10-not-supported\"\u003ehere\u003c/a\u003e ) I see this:\u003c/p\u003e\u003cp\u003e\u003ca href=\"https://i.stack.imgur.com/WJdHN.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/WJdHN.png\" alt=\"Java Compiler Settings\"\u003e\u003c/a\u003e\u003c/p\u003e\u003cp\u003eI tried editing the \"\u003cstrong\u003eTarget bytecode version\u003c/strong\u003e\" to \u003cstrong\u003e1.8\u003c/strong\u003e but I get the following errors:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eError:(1, 26) java: package javafx.application does not exist\nError:(2, 20) java: package javafx.stage does not exist\nError:(4, 27) java: cannot find symbol\n symbol: class Application\nError:(12, 23) java: cannot find symbol\n symbol: class Stage\n location: class Main\nError:(7, 9) java: cannot find symbol\n symbol: method launch(java.lang.String[])\n location: class Main\nError:(11, 5) java: method does not override or implement a method from a supertype\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eChanging it to version \u003cstrong\u003e1.11\u003c/strong\u003e I get this error instead:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eError:java: Source option 5 is no longer supported. Use 6 or later.\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eWhat do you think is the problem? How may I solve it?\u003c/p\u003e","originalBody":"\u003cp\u003eI'm using \u003cstrong\u003eIntelliJ IDEA Ultimate 2019.3.1\u003c/strong\u003e. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eError:java: error: release version 5 not supported\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eRunning \u003ccode\u003ejava --version\u003c/code\u003e by terminal I get the following output:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eopenjdk 11.0.5 2019-10-15\nOpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)\nOpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eRunning \u003ccode\u003ejavac --version\u003c/code\u003e by terminal I get the following output:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003ejavac 11.0.5\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eGoing to the Settings of the Java Compiler ( as suggested \u003ca href=\"https://stackoverflow.com/questions/52788743/intellij-error-java-release-version-10-not-supported\"\u003ehere\u003c/a\u003e ) I see this:\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://i.stack.imgur.com/WJdHN.png\" rel=\"noreferrer\"\u003e\u003cimg src=\"https://i.stack.imgur.com/WJdHN.png\" alt=\"Java Compiler Settings\"\u003e\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eI tried editing the \"\u003cstrong\u003eTarget bytecode version\u003c/strong\u003e\" to \u003cstrong\u003e1.8\u003c/strong\u003e but I get the following errors:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eError:(1, 26) java: package javafx.application does not exist\nError:(2, 20) java: package javafx.stage does not exist\nError:(4, 27) java: cannot find symbol\n symbol: class Application\nError:(12, 23) java: cannot find symbol\n symbol: class Stage\n location: class Main\nError:(7, 9) java: cannot find symbol\n symbol: method launch(java.lang.String[])\n location: class Main\nError:(11, 5) java: method does not override or implement a method from a supertype\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eChanging it to version \u003cstrong\u003e1.11\u003c/strong\u003e I get this error instead:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eError:java: Source option 5 is no longer supported. Use 6 or later.\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eWhat do you think is the problem? How may I solve it?\u003c/p\u003e\n","likes":0,"pageViews":263782,"author":"Robb1","authorProfile":"https://stackoverflow.com/users/5559342/robb1","sourceLink":"https://stackoverflow.com/questions/59601077/intellij-errorjava-error-release-version-5-not-supported","sourceId":59601077,"isActive":true,"isTranslated":true,"createdAt":"2020-01-05T14:54:15.000Z","updatedAt":"2021-12-26T20:39:23.426Z","tags":[{"id":9708,"questionId":3214,"tagId":33,"tag":{"id":33,"slug":"java","title":"java","description":null,"totalQuestions":339,"isActive":true,"createdAt":"2021-12-01T19:35:07.573Z","updatedAt":"2022-01-17T08:47:45.058Z"}},{"id":9709,"questionId":3214,"tagId":739,"tag":{"id":739,"slug":"intellij-idea","title":"intellij-idea","description":null,"totalQuestions":39,"isActive":true,"createdAt":"2021-12-01T19:37:17.157Z","updatedAt":"2022-01-17T08:47:44.993Z"}}],"_count":{"answers":20}},{"id":3218,"addedBy":null,"slug":"3218-git-says-remote-ref-does-not-exist-when-i-delete-remote-branch","title":"Git says remote ref does not exist when I delete remote branch","body":"I ran `git branch -a`\n\n```\n* master\n remotes/origin/test\n remotes/origin/master\n```\n\nI want to delete my remote branch\n\nI've tried\n\n```\ngit push origin --delete remotes/origin/test\n```\n\nI got\n\n\u003e error: unable to delete 'remotes/origin/test': remote ref does not exist\n\nHow is it not exist ?\n\nI did a `git branch -a`, and I saw it listed.\n\nDid I miss anything ?\n\n","htmlBody":"\u003cp\u003eI ran \u003ccode\u003egit branch -a\u003c/code\u003e \u003c/p\u003e\u003cpre\u003e\u003ccode\u003e* master\n remotes/origin/test\n remotes/origin/master\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eI want to delete my remote branch \u003c/p\u003e\u003cp\u003eI've tried \u003c/p\u003e\u003cpre\u003e\u003ccode\u003egit push origin --delete remotes/origin/test\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eI got \u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003eerror: unable to delete 'remotes/origin/test': remote ref does not\n exist\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eHow is it not exist ? \u003c/p\u003e\u003cp\u003eI did a \u003ccode\u003egit branch -a\u003c/code\u003e, and I saw it listed. \u003c/p\u003e\u003cp\u003eDid I miss anything ? \u003c/p\u003e","originalBody":"\u003cp\u003eI ran \u003ccode\u003egit branch -a\u003c/code\u003e \u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e* master\n remotes/origin/test\n remotes/origin/master\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI want to delete my remote branch \u003c/p\u003e\n\n\u003cp\u003eI've tried \u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003egit push origin --delete remotes/origin/test\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eI got \u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003eerror: unable to delete 'remotes/origin/test': remote ref does not\n exist\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eHow is it not exist ? \u003c/p\u003e\n\n\u003cp\u003eI did a \u003ccode\u003egit branch -a\u003c/code\u003e, and I saw it listed. \u003c/p\u003e\n\n\u003cp\u003eDid I miss anything ? \u003c/p\u003e\n","likes":0,"pageViews":119755,"author":"code8888","authorProfile":"https://stackoverflow.com/users/4480164/code8888","sourceLink":"https://stackoverflow.com/questions/35941566/git-says-remote-ref-does-not-exist-when-i-delete-remote-branch","sourceId":35941566,"isActive":true,"isTranslated":true,"createdAt":"2016-03-11T13:31:09.000Z","updatedAt":"2021-12-26T20:39:18.374Z","tags":[{"id":9720,"questionId":3218,"tagId":320,"tag":{"id":320,"slug":"git","title":"git","description":null,"totalQuestions":142,"isActive":true,"createdAt":"2021-12-01T19:36:15.699Z","updatedAt":"2022-01-17T08:47:45.276Z"}}],"_count":{"answers":13}},{"id":3184,"addedBy":null,"slug":"3184-how-to-manage-angular2-expression-has-changed-after-it-was-checked-exception-when-a-component-property-depends-on-current-datetime","title":"How to manage Angular2 \"expression has changed after it was checked\" exception when a component property depends on current datetime","body":"My component has styles that depend on current datetime. In my component I've got the following function.\n\n```\nprivate fontColor( dto : Dto ) : string {\n // date d'exécution du dto\n let dtoDate : Date = new Date( dto.LastExecution );\n\n (...)\n\n let color = \"hsl( \" + hue + \", 80%, \" + (maxLigness - lightnessAmp) + \"%)\";\n\n return color;\n }\n```\n\n`lightnessAmp` is calculated from the current datetime. The color changes if `dtoDate` is in the last 24 hours.\n\nThe exact error is the following:\n\n\u003e Expression has changed after it was checked. Previous value: 'hsl( 123, 80%, 49%)'. Current value: 'hsl( 123, 80%, 48%)'\n\nI know the exception appear in development mode only at the moment the value is checked. If the checked value is different of the updated value, the exception is thrown.\n\nSo I tried to update the current datetime at each lifecycle in the following hook method to prevent the exception:\n\n```\nngAfterViewChecked()\n {\n console.log( \"! changement de la date du composant !\" );\n this.dateNow = new Date();\n }\n```\n\n...but without success.\n\n","htmlBody":"\u003cp\u003eMy component has styles that depend on current datetime. In my component I've got the following function.\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e private fontColor( dto : Dto ) : string {\n // date d'exécution du dto\n let dtoDate : Date = new Date( dto.LastExecution );\n\n (...)\n\n let color = \"hsl( \" + hue + \", 80%, \" + (maxLigness - lightnessAmp) + \"%)\";\n\n return color;\n }\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003e\u003ccode\u003elightnessAmp\u003c/code\u003e is calculated from the current datetime. The color changes if \u003ccode\u003edtoDate\u003c/code\u003e is in the last 24 hours.\u003c/p\u003e\u003cp\u003eThe exact error is the following:\u003c/p\u003e\u003cblockquote\u003e\n \u003cp\u003eExpression has changed after it was checked. Previous value: 'hsl( 123, 80%, 49%)'. Current value: 'hsl( 123, 80%, 48%)'\u003c/p\u003e\n\u003c/blockquote\u003e\u003cp\u003eI know the exception appear in development mode only at the moment the value is checked. If the checked value is different of the updated value, the exception is thrown.\u003c/p\u003e\u003cp\u003eSo I tried to update the current datetime at each lifecycle in the following hook method to prevent the exception:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003e ngAfterViewChecked()\n {\n console.log( \"! changement de la date du composant !\" );\n this.dateNow = new Date();\n }\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003e...but without success.\u003c/p\u003e","originalBody":"\u003cp\u003eMy component has styles that depend on current datetime. In my component I've got the following function.\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e private fontColor( dto : Dto ) : string {\n // date d'exécution du dto\n let dtoDate : Date = new Date( dto.LastExecution );\n\n (...)\n\n let color = \"hsl( \" + hue + \", 80%, \" + (maxLigness - lightnessAmp) + \"%)\";\n\n return color;\n }\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e\u003ccode\u003elightnessAmp\u003c/code\u003e is calculated from the current datetime. The color changes if \u003ccode\u003edtoDate\u003c/code\u003e is in the last 24 hours.\u003c/p\u003e\n\n\u003cp\u003eThe exact error is the following:\u003c/p\u003e\n\n\u003cblockquote\u003e\n \u003cp\u003eExpression has changed after it was checked. Previous value: 'hsl( 123, 80%, 49%)'. Current value: 'hsl( 123, 80%, 48%)'\u003c/p\u003e\n\u003c/blockquote\u003e\n\n\u003cp\u003eI know the exception appear in development mode only at the moment the value is checked. If the checked value is different of the updated value, the exception is thrown.\u003c/p\u003e\n\n\u003cp\u003eSo I tried to update the current datetime at each lifecycle in the following hook method to prevent the exception:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e ngAfterViewChecked()\n {\n console.log( \"! changement de la date du composant !\" );\n this.dateNow = new Date();\n }\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003e...but without success.\u003c/p\u003e\n","likes":0,"pageViews":214484,"author":"Anthony Breneli\u0026#232;re","authorProfile":"https://stackoverflow.com/users/3433751/anthony-breneli%c3%a8re","sourceLink":"https://stackoverflow.com/questions/39787038/how-to-manage-angular2-expression-has-changed-after-it-was-checked-exception-w","sourceId":39787038,"isActive":true,"isTranslated":true,"createdAt":"2016-09-30T08:31:52.000Z","updatedAt":"2021-12-26T20:37:52.880Z","tags":[{"id":9619,"questionId":3184,"tagId":8,"tag":{"id":8,"slug":"angular","title":"angular","description":null,"totalQuestions":441,"isActive":true,"createdAt":"2021-12-01T19:35:07.560Z","updatedAt":"2022-01-17T08:47:45.261Z"}},{"id":9620,"questionId":3184,"tagId":272,"tag":{"id":272,"slug":"typescript","title":"typescript","description":null,"totalQuestions":333,"isActive":true,"createdAt":"2021-12-01T19:36:15.604Z","updatedAt":"2022-01-17T08:47:45.253Z"}},{"id":9622,"questionId":3184,"tagId":2353,"tag":{"id":2353,"slug":"components","title":"components","description":null,"totalQuestions":6,"isActive":true,"createdAt":"2021-12-14T21:28:52.307Z","updatedAt":"2022-01-17T08:42:09.302Z"}},{"id":9621,"questionId":3184,"tagId":723,"tag":{"id":723,"slug":"time","title":"time","description":null,"totalQuestions":4,"isActive":true,"createdAt":"2021-12-01T19:37:17.120Z","updatedAt":"2021-12-20T12:30:23.207Z"}},{"id":9763,"questionId":3184,"tagId":2545,"tag":{"id":2545,"slug":"styles","title":"styles","description":null,"totalQuestions":1,"isActive":true,"createdAt":"2021-12-16T10:38:10.680Z","updatedAt":"2021-12-16T10:38:13.309Z"}}],"_count":{"answers":11}},{"id":3077,"addedBy":null,"slug":"3077-enabling-cors-in-cloud-functions-for-firebase","title":"Enabling CORS in Cloud Functions for Firebase","body":"I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the \"No 'Access-Control-Allow-Origin'\" error. Here's an example of the function I wrote:\n\n```\nexports.test = functions.https.onRequest((request, response) =\u003e {\n response.status(500).send({test: 'Testing functions'});\n})\n```\n\nThe function sits in this url: [https://us-central1-fba-shipper-140ae.cloudfunctions.net/test](\u003chttps://us-central1-fba-shipper-140ae.cloudfunctions.net/test\u003e)\n\nFirebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: [https://firebase.google.com/docs/functions/http-events](\u003chttps://firebase.google.com/docs/functions/http-events\u003e)\n\nThis is how I did it:\n\n```\nvar cors = require('cors'); \n\nexports.test = functions.https.onRequest((request, response) =\u003e {\n cors(request, response, () =\u003e {\n response.status(500).send({test: 'Testing functions'});\n })\n})\n```\n\nWhat am I doing wrong? I would appreciate any help with this.\n\nUPDATE:\n\n[Doug Stevenson](\u003chttps://stackoverflow.com/users/807126/doug-stevenson\u003e)'s answer helped. Adding ({origin: true}) fixed the issue, I also had to change `response.status(500)` to `response.status(200)` which I completely missed at first.\n\n","htmlBody":"\u003cp\u003eI'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the \"No 'Access-Control-Allow-Origin'\" error. Here's an example of the function I wrote:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003eexports.test = functions.https.onRequest((request, response) =\u0026gt; {\n response.status(500).send({test: 'Testing functions'});\n})\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eThe function sits in this url:\n\u003ca href=\"https://us-central1-fba-shipper-140ae.cloudfunctions.net/test\" rel=\"noreferrer\"\u003ehttps://us-central1-fba-shipper-140ae.cloudfunctions.net/test\u003c/a\u003e\u003c/p\u003e\u003cp\u003eFirebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: \u003ca href=\"https://firebase.google.com/docs/functions/http-events\" rel=\"noreferrer\"\u003ehttps://firebase.google.com/docs/functions/http-events\u003c/a\u003e\u003c/p\u003e\u003cp\u003eThis is how I did it:\u003c/p\u003e\u003cpre\u003e\u003ccode\u003evar cors = require('cors'); \n\nexports.test = functions.https.onRequest((request, response) =\u0026gt; {\n cors(request, response, () =\u0026gt; {\n response.status(500).send({test: 'Testing functions'});\n })\n})\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eWhat am I doing wrong? I would appreciate any help with this.\u003c/p\u003e\u003cp\u003eUPDATE:\u003c/p\u003e\u003cp\u003e\u003ca href=\"https://stackoverflow.com/users/807126/doug-stevenson\"\u003eDoug Stevenson\u003c/a\u003e's answer helped. Adding ({origin: true}) fixed the issue, I also had to change \u003ccode\u003eresponse.status(500)\u003c/code\u003e to \u003ccode\u003eresponse.status(200)\u003c/code\u003e which I completely missed at first.\u003c/p\u003e","originalBody":"\u003cp\u003eI'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the \"No 'Access-Control-Allow-Origin'\" error. Here's an example of the function I wrote:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eexports.test = functions.https.onRequest((request, response) =\u0026gt; {\n response.status(500).send({test: 'Testing functions'});\n})\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eThe function sits in this url:\n\u003ca href=\"https://us-central1-fba-shipper-140ae.cloudfunctions.net/test\" rel=\"noreferrer\"\u003ehttps://us-central1-fba-shipper-140ae.cloudfunctions.net/test\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eFirebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: \u003ca href=\"https://firebase.google.com/docs/functions/http-events\" rel=\"noreferrer\"\u003ehttps://firebase.google.com/docs/functions/http-events\u003c/a\u003e\u003c/p\u003e\n\n\u003cp\u003eThis is how I did it:\u003c/p\u003e\n\n\u003cpre\u003e\u003ccode\u003evar cors = require('cors'); \n\nexports.test = functions.https.onRequest((request, response) =\u0026gt; {\n cors(request, response, () =\u0026gt; {\n response.status(500).send({test: 'Testing functions'});\n })\n})\n\u003c/code\u003e\u003c/pre\u003e\n\n\u003cp\u003eWhat am I doing wrong? I would appreciate any help with this.\u003c/p\u003e\n\n\u003cp\u003eUPDATE:\u003c/p\u003e\n\n\u003cp\u003e\u003ca href=\"https://stackoverflow.com/users/807126/doug-stevenson\"\u003eDoug Stevenson\u003c/a\u003e's answer helped. Adding ({origin: true}) fixed the issue, I also had to change \u003ccode\u003eresponse.status(500)\u003c/code\u003e to \u003ccode\u003eresponse.status(200)\u003c/code\u003e which I completely missed at first.\u003c/p\u003e\n","likes":0,"pageViews":163911,"author":"Andrey Pokrovskiy","authorProfile":"https://stackoverflow.com/users/5003986/andrey-pokrovskiy","sourceLink":"https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase","sourceId":42755131,"isActive":true,"isTranslated":true,"createdAt":"2017-03-13T01:01:10.000Z","updatedAt":"2021-12-26T20:37:42.767Z","tags":[{"id":9279,"questionId":3077,"tagId":185,"tag":{"id":185,"slug":"firebase","title":"firebase","description":null,"totalQuestions":84,"isActive":true,"createdAt":"2021-12-01T19:35:16.781Z","updatedAt":"2022-01-17T08:47:44.766Z"}},{"id":9278,"questionId":3077,"tagId":5,"tag":{"id":5,"slug":"javascript","title":"javascript","description":null,"totalQuestions":956,"isActive":true,"createdAt":"2021-12-01T19:35:07.552Z","updatedAt":"2022-01-17T08:47:45.275Z"}},{"id":9281,"questionId":3077,"tagId":600,"tag":{"id":600,"slug":"google-cloud-platform","title":"google-cloud-platform","description":null,"totalQuestions":15,"isActive":true,"createdAt":"2021-12-01T19:36:57.165Z","updatedAt":"2022-01-17T08:45:55.501Z"}},{"id":9280,"questionId":3077,"tagId":577,"tag":{"id":577,"slug":"cors","title":"cors","description":null,"totalQuestions":16,"isActive":true,"createdAt":"2021-12-01T19:36:57.071Z","updatedAt":"2022-01-17T08:46:11.988Z"}},{"id":9282,"questionId":3077,"tagId":270,"tag":{"id":270,"slug":"google-cloud-functions","title":"google-cloud-functions","description":null,"totalQuestions":15,"isActive":true,"createdAt":"2021-12-01T19:36:15.598Z","updatedAt":"2022-01-17T08:46:59.261Z"}}],"_count":{"answers":29}}]},"__N_SSP":true},"page":"/q/[slug]","query":{"slug":"618-in-django-how-to-render-hellohtml-in-basehtml"},"buildId":"_nTUMzeVdUwsvauKBwjDQ","isFallback":false,"gssp":true,"appGip":true,"scriptLoader":[]}</script></body></html>