qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Если **этруски** и русские - родственные народы, то это должно наблюдаться в языке. А этого как раз нет (кроме созвучия названий). Родственные связи этрусского языка являются дискуссионными. Составление словаря этрусского языка и расшифровка текстов продвигаются медленно и по сей день далеки от завершения. Этрусский язык считается языком-изолятом и не имеет признанных наукой родственников. Одной из гипотез о возможном родстве этрусского является версия Старостина и Дьяконова о родстве этрусского языка с вымершими хурритским и урартским. Другие исследователи продолжают настаивать о родстве этрусского с анатолийской (хетто-лувийской) ветвью индоевропейских языков. Учитывая **немногочисленность известных этрусских слов** и лишь *ограниченное знание этрусской грамматики*, все эти предположения в очень большой степени **спекулятивны**. Главное, чтó при наивном, любительском отношении к делу остается незамеченным и чем грешат многочисленные псевдонаучные сочинения, — это непонимание того, что никакие языки не остаются в ходе времени неизменными. Никто не будет отрицать, что этруски жили примерно 25 веков назад. Так что даже если предположить, что это русские, то они говорили на русском языке двадцатипятивековой давности, а не на современном языке. А разница между нынешним языком и языком, который был двадцать пять веков назад, колоссальная! Что касается **пруссов**, то о происхождении их этнического самоназвания prūss, prūsai («прусс», «пруссы») и регионима Prūsa («Пруссия») среди исследователей нет единого мнения. По замечанию некоторых исследователей романтиков, самоназвание страны пруссов (Prūsa — произн. как «Пруса») созвучно древнему имени страны фризов (Frusa — «Фруза»); вероятно, как раз не пожелавшие отступиться от язычества фризы, будучи главными союзниками «мятежных» саксов, и принесли на территорию Погезании, Помезании и Вармии прототип самоназвания древних пруссов. По другой версии, название «Пруссия» возникло из гидронима Русс или Русне, то есть названия правого рукава дельты Немана, или же из «Руссна» — прежнего названия Куршского залива, которое можно прочесть на карте Пруссии, составленной в 1576 г. немецким историком и картографом Каспаром Генненбергером (англ.)русск. (1529—1600). Третья версия самоназвание древних пруссов выводит из коневодства, которым славились древние пруссы. *Прус* означает 'конь' в готском языке, а также 'кобыла' в старославянском. Как видите, схожесть названий может натолкнуть на ложный след и совершенно не означает, что народы, носящие эти названия, родственны. К тому же специалисты сами подчеркивают, что не обладают достаточным объемом информации, чтобы делать такие "сенсационные" выводы. Нужны доказательства, а их-то у историков-любителей и нет.
Задорнов тоже не с потолка взял, а от других теоретиков. Этрусский язык, который "не читается", был прочитан одним из ученых изучавших древнерусское письмо. Этрусский язык является более древним, чем сейчас преподаваемая староверами "буквица"(если не изменяет память) из 49 букв.
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Если **этруски** и русские - родственные народы, то это должно наблюдаться в языке. А этого как раз нет (кроме созвучия названий). Родственные связи этрусского языка являются дискуссионными. Составление словаря этрусского языка и расшифровка текстов продвигаются медленно и по сей день далеки от завершения. Этрусский язык считается языком-изолятом и не имеет признанных наукой родственников. Одной из гипотез о возможном родстве этрусского является версия Старостина и Дьяконова о родстве этрусского языка с вымершими хурритским и урартским. Другие исследователи продолжают настаивать о родстве этрусского с анатолийской (хетто-лувийской) ветвью индоевропейских языков. Учитывая **немногочисленность известных этрусских слов** и лишь *ограниченное знание этрусской грамматики*, все эти предположения в очень большой степени **спекулятивны**. Главное, чтó при наивном, любительском отношении к делу остается незамеченным и чем грешат многочисленные псевдонаучные сочинения, — это непонимание того, что никакие языки не остаются в ходе времени неизменными. Никто не будет отрицать, что этруски жили примерно 25 веков назад. Так что даже если предположить, что это русские, то они говорили на русском языке двадцатипятивековой давности, а не на современном языке. А разница между нынешним языком и языком, который был двадцать пять веков назад, колоссальная! Что касается **пруссов**, то о происхождении их этнического самоназвания prūss, prūsai («прусс», «пруссы») и регионима Prūsa («Пруссия») среди исследователей нет единого мнения. По замечанию некоторых исследователей романтиков, самоназвание страны пруссов (Prūsa — произн. как «Пруса») созвучно древнему имени страны фризов (Frusa — «Фруза»); вероятно, как раз не пожелавшие отступиться от язычества фризы, будучи главными союзниками «мятежных» саксов, и принесли на территорию Погезании, Помезании и Вармии прототип самоназвания древних пруссов. По другой версии, название «Пруссия» возникло из гидронима Русс или Русне, то есть названия правого рукава дельты Немана, или же из «Руссна» — прежнего названия Куршского залива, которое можно прочесть на карте Пруссии, составленной в 1576 г. немецким историком и картографом Каспаром Генненбергером (англ.)русск. (1529—1600). Третья версия самоназвание древних пруссов выводит из коневодства, которым славились древние пруссы. *Прус* означает 'конь' в готском языке, а также 'кобыла' в старославянском. Как видите, схожесть названий может натолкнуть на ложный след и совершенно не означает, что народы, носящие эти названия, родственны. К тому же специалисты сами подчеркивают, что не обладают достаточным объемом информации, чтобы делать такие "сенсационные" выводы. Нужны доказательства, а их-то у историков-любителей и нет.
> > Вот спасибо, порадовали. Я-то дкмал, что он, типа, шутит, а он оказыввается с титиретиками общается. Не иначе как на спиритическом сеансе. Или это у него диагноз такой "теоретик"? > > > --- Нормальные живые теоретики ("мертвые" - это которым сказать нечего. От них один мало чем подкрепленный сарказм). Я видел видео об одном таком теоретике + есть книжечка (ну официально 100% достоверность ей конечно никто не даст) где выложен этрусский алфавит и значения букавок. Было бы желание и не было бы лени можно было и проверить. :)
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Если **этруски** и русские - родственные народы, то это должно наблюдаться в языке. А этого как раз нет (кроме созвучия названий). Родственные связи этрусского языка являются дискуссионными. Составление словаря этрусского языка и расшифровка текстов продвигаются медленно и по сей день далеки от завершения. Этрусский язык считается языком-изолятом и не имеет признанных наукой родственников. Одной из гипотез о возможном родстве этрусского является версия Старостина и Дьяконова о родстве этрусского языка с вымершими хурритским и урартским. Другие исследователи продолжают настаивать о родстве этрусского с анатолийской (хетто-лувийской) ветвью индоевропейских языков. Учитывая **немногочисленность известных этрусских слов** и лишь *ограниченное знание этрусской грамматики*, все эти предположения в очень большой степени **спекулятивны**. Главное, чтó при наивном, любительском отношении к делу остается незамеченным и чем грешат многочисленные псевдонаучные сочинения, — это непонимание того, что никакие языки не остаются в ходе времени неизменными. Никто не будет отрицать, что этруски жили примерно 25 веков назад. Так что даже если предположить, что это русские, то они говорили на русском языке двадцатипятивековой давности, а не на современном языке. А разница между нынешним языком и языком, который был двадцать пять веков назад, колоссальная! Что касается **пруссов**, то о происхождении их этнического самоназвания prūss, prūsai («прусс», «пруссы») и регионима Prūsa («Пруссия») среди исследователей нет единого мнения. По замечанию некоторых исследователей романтиков, самоназвание страны пруссов (Prūsa — произн. как «Пруса») созвучно древнему имени страны фризов (Frusa — «Фруза»); вероятно, как раз не пожелавшие отступиться от язычества фризы, будучи главными союзниками «мятежных» саксов, и принесли на территорию Погезании, Помезании и Вармии прототип самоназвания древних пруссов. По другой версии, название «Пруссия» возникло из гидронима Русс или Русне, то есть названия правого рукава дельты Немана, или же из «Руссна» — прежнего названия Куршского залива, которое можно прочесть на карте Пруссии, составленной в 1576 г. немецким историком и картографом Каспаром Генненбергером (англ.)русск. (1529—1600). Третья версия самоназвание древних пруссов выводит из коневодства, которым славились древние пруссы. *Прус* означает 'конь' в готском языке, а также 'кобыла' в старославянском. Как видите, схожесть названий может натолкнуть на ложный след и совершенно не означает, что народы, носящие эти названия, родственны. К тому же специалисты сами подчеркивают, что не обладают достаточным объемом информации, чтобы делать такие "сенсационные" выводы. Нужны доказательства, а их-то у историков-любителей и нет.
Задорнова люблю давно (лет 30 уже). И сейчас иногда его слушаю, хотя, честно говоря, примелькался. Его лингвистические изыскания никогда всерьёз не воспринимала. Это просто юмор. Не думаю, что он родоначальник т. н. "народной этимологии". Думается, дилетанство у нас в крови. Все знают, как правильно лечить, учить, судить и т. п. А вот и новая мода: все "умеют" находить "скрытое значение" слов и объяснять их происхождение. Так что притензии к Задорнову считаю необоснованными.
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Этру**сс**ки - это очередной шедевр от Задорнова. Этим всё сказано. Честно говоря, не заслуживает оно развернутых комментариев. А вот насчет пруссов... Начнем от печки. Поскольку этнохороним "русские" не имеет ясной этимологии (посмотрите в Интренете, столько всего понаписано) и версии строятся в ориентации на разные языки-источники (от скифских до норманских), то и разговоры о родстве его с ещё менее понятным самоназванием далёкого от всех народа ещё менее состоятельны. Вообще пруссы - исчезнувший народ балтийской группы, родственен литовскому. Таким образом сторонникам родства пруссов и русских надо копать в сторону балто-славянских корней топонима Русь или этнохоронима руссы. Но такие версии сейчас непопулярны. Хотя можно порыскать, глядишь что-то и найдётся. Касательно же самого происхождения названия пруссы я повторяться не буду. **Olsa** даёт всё более чем исчерпывающе.
Задорнов тоже не с потолка взял, а от других теоретиков. Этрусский язык, который "не читается", был прочитан одним из ученых изучавших древнерусское письмо. Этрусский язык является более древним, чем сейчас преподаваемая староверами "буквица"(если не изменяет память) из 49 букв.
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Этру**сс**ки - это очередной шедевр от Задорнова. Этим всё сказано. Честно говоря, не заслуживает оно развернутых комментариев. А вот насчет пруссов... Начнем от печки. Поскольку этнохороним "русские" не имеет ясной этимологии (посмотрите в Интренете, столько всего понаписано) и версии строятся в ориентации на разные языки-источники (от скифских до норманских), то и разговоры о родстве его с ещё менее понятным самоназванием далёкого от всех народа ещё менее состоятельны. Вообще пруссы - исчезнувший народ балтийской группы, родственен литовскому. Таким образом сторонникам родства пруссов и русских надо копать в сторону балто-славянских корней топонима Русь или этнохоронима руссы. Но такие версии сейчас непопулярны. Хотя можно порыскать, глядишь что-то и найдётся. Касательно же самого происхождения названия пруссы я повторяться не буду. **Olsa** даёт всё более чем исчерпывающе.
> > Вот спасибо, порадовали. Я-то дкмал, что он, типа, шутит, а он оказыввается с титиретиками общается. Не иначе как на спиритическом сеансе. Или это у него диагноз такой "теоретик"? > > > --- Нормальные живые теоретики ("мертвые" - это которым сказать нечего. От них один мало чем подкрепленный сарказм). Я видел видео об одном таком теоретике + есть книжечка (ну официально 100% достоверность ей конечно никто не даст) где выложен этрусский алфавит и значения букавок. Было бы желание и не было бы лени можно было и проверить. :)
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Этру**сс**ки - это очередной шедевр от Задорнова. Этим всё сказано. Честно говоря, не заслуживает оно развернутых комментариев. А вот насчет пруссов... Начнем от печки. Поскольку этнохороним "русские" не имеет ясной этимологии (посмотрите в Интренете, столько всего понаписано) и версии строятся в ориентации на разные языки-источники (от скифских до норманских), то и разговоры о родстве его с ещё менее понятным самоназванием далёкого от всех народа ещё менее состоятельны. Вообще пруссы - исчезнувший народ балтийской группы, родственен литовскому. Таким образом сторонникам родства пруссов и русских надо копать в сторону балто-славянских корней топонима Русь или этнохоронима руссы. Но такие версии сейчас непопулярны. Хотя можно порыскать, глядишь что-то и найдётся. Касательно же самого происхождения названия пруссы я повторяться не буду. **Olsa** даёт всё более чем исчерпывающе.
Задорнова люблю давно (лет 30 уже). И сейчас иногда его слушаю, хотя, честно говоря, примелькался. Его лингвистические изыскания никогда всерьёз не воспринимала. Это просто юмор. Не думаю, что он родоначальник т. н. "народной этимологии". Думается, дилетанство у нас в крови. Все знают, как правильно лечить, учить, судить и т. п. А вот и новая мода: все "умеют" находить "скрытое значение" слов и объяснять их происхождение. Так что притензии к Задорнову считаю необоснованными.
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
> > Вот спасибо, порадовали. Я-то дкмал, что он, типа, шутит, а он оказыввается с титиретиками общается. Не иначе как на спиритическом сеансе. Или это у него диагноз такой "теоретик"? > > > --- Нормальные живые теоретики ("мертвые" - это которым сказать нечего. От них один мало чем подкрепленный сарказм). Я видел видео об одном таком теоретике + есть книжечка (ну официально 100% достоверность ей конечно никто не даст) где выложен этрусский алфавит и значения букавок. Было бы желание и не было бы лени можно было и проверить. :)
Задорнов тоже не с потолка взял, а от других теоретиков. Этрусский язык, который "не читается", был прочитан одним из ученых изучавших древнерусское письмо. Этрусский язык является более древним, чем сейчас преподаваемая староверами "буквица"(если не изменяет память) из 49 букв.
4,649
Есть некоторые научные, а скорее, псевдонаучные теории о том, что якобы русские и этруски - это родственные народы. В качестве доказательства приводят схожесть названий. Действительно ли в названии этих народов есть общий корень "-рус-", или это случайность? А также меня интересуют пруссы. Спасибо.
2012/05/15
[ "https://rus.stackexchange.com/questions/4649", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/3/" ]
Задорнова люблю давно (лет 30 уже). И сейчас иногда его слушаю, хотя, честно говоря, примелькался. Его лингвистические изыскания никогда всерьёз не воспринимала. Это просто юмор. Не думаю, что он родоначальник т. н. "народной этимологии". Думается, дилетанство у нас в крови. Все знают, как правильно лечить, учить, судить и т. п. А вот и новая мода: все "умеют" находить "скрытое значение" слов и объяснять их происхождение. Так что притензии к Задорнову считаю необоснованными.
Задорнов тоже не с потолка взял, а от других теоретиков. Этрусский язык, который "не читается", был прочитан одним из ученых изучавших древнерусское письмо. Этрусский язык является более древним, чем сейчас преподаваемая староверами "буквица"(если не изменяет память) из 49 букв.
29,278,651
Is the port for "Resource­Manager Web UI" for a yarn machine always set to 8088 or is it possible to change it? I see here in the [documentation of hortonworks](http://docs.hortonworks.com/HDP2Alpha/index.htm#Appendix/Ports_Appendix/YARN_Ports.htm) that the default value is 8088, but it is not written whether it could have different values. Thanks!
2015/03/26
[ "https://Stackoverflow.com/questions/29278651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3518314/" ]
You can setup the WebUI address in `yarn-default.xml` file. Set property `yarn.resourcemanager.webapp.address` to another port. For more detailed information refer to the documentation <http://docs.hortonworks.com/Hadoop2.0/hadoop-yarn/hadoop-yarn-common/yarn-default.xml>
With last version of YARN as of now (Oct 2018), default port is 8088: <https://hadoop.apache.org/docs/r2.4.1/hadoop-yarn/hadoop-yarn-common/yarn-default.xml>
36,319,083
I'm trying to coordinate data between two separate sheets using the following formula: ``` =LOOKUP(A3,Housed!A:A,Housed!B:B) ``` However, when that formula is applied to destination cells for which "`search_key`" is not found among "`search_range`", the output of "`result_range`" for the previous cell in the destination column is repeated, as described in Google Docs Editors Help: > > If search\_key is not found, the item used in the lookup will be the value that’s immediately smaller in the range provided. For example, if the data set contains the numbers 1, 3, 5 and search\_key is 2, then 1 will be used for the lookup. > > > This is a problem for me, because data is placed in cells where it doesn't apply, and I would like these cells, for which "`search_key`" is not found in "`search_range`" to remain blank. I've tried incorporating `VLOOKUP` instead, but get a `#REF` error, it seems due to evaluating data on a separate sheet, or otherwise outside the stated range. And I can't seem to wrap my head around incorporating an `IF` formula into the array in a way that gives me the desired outcome. The original spreadsheet contains confidential information, so I cannot share that link here; however, I've duplicated the necessary components [here:](https://docs.google.com/spreadsheets/d/1eZS3q7_PaAOwwHMKmPEfLLzizFJn3FsuEyQytNKlggg/edit?usp=sharing) Does anyone have ideas or fixes for this? Is there something I need to add? Am I using the wrong formula?
2016/03/30
[ "https://Stackoverflow.com/questions/36319083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6136794/" ]
You need `vlookup`, not `lookup` (suggestion: never use `lookup`). The following function achieves your objective: ``` =IFERROR(VLOOKUP(A2, Sheet2!A:B, 2, False)) ``` Explanation: * Second parameter of vlookup is the range that includes both the column to search (must be the first one), and the column from which result is to be taken. * Third parameter specifies that the result is taken from 2nd column * `False` indicates that exact match is required * `iferror` wrapper suppresses error messages, replacing them with blanks.
Try this `=IF(isna(MATCH(A2,Sheet2!A:A,0))=false,VLOOKUP(A2,Sheet2!A:B,2),"")`
36,319,083
I'm trying to coordinate data between two separate sheets using the following formula: ``` =LOOKUP(A3,Housed!A:A,Housed!B:B) ``` However, when that formula is applied to destination cells for which "`search_key`" is not found among "`search_range`", the output of "`result_range`" for the previous cell in the destination column is repeated, as described in Google Docs Editors Help: > > If search\_key is not found, the item used in the lookup will be the value that’s immediately smaller in the range provided. For example, if the data set contains the numbers 1, 3, 5 and search\_key is 2, then 1 will be used for the lookup. > > > This is a problem for me, because data is placed in cells where it doesn't apply, and I would like these cells, for which "`search_key`" is not found in "`search_range`" to remain blank. I've tried incorporating `VLOOKUP` instead, but get a `#REF` error, it seems due to evaluating data on a separate sheet, or otherwise outside the stated range. And I can't seem to wrap my head around incorporating an `IF` formula into the array in a way that gives me the desired outcome. The original spreadsheet contains confidential information, so I cannot share that link here; however, I've duplicated the necessary components [here:](https://docs.google.com/spreadsheets/d/1eZS3q7_PaAOwwHMKmPEfLLzizFJn3FsuEyQytNKlggg/edit?usp=sharing) Does anyone have ideas or fixes for this? Is there something I need to add? Am I using the wrong formula?
2016/03/30
[ "https://Stackoverflow.com/questions/36319083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6136794/" ]
`VLOOKUP` with the last parameter (`IsSorted`) set FALSE can get very slow. ``` =IF(VLOOKUP(A2, other!A:A, 1) = A2, VLOOKUP(A2, other!A:B, 2), "") ```
Try this `=IF(isna(MATCH(A2,Sheet2!A:A,0))=false,VLOOKUP(A2,Sheet2!A:B,2),"")`
36,319,083
I'm trying to coordinate data between two separate sheets using the following formula: ``` =LOOKUP(A3,Housed!A:A,Housed!B:B) ``` However, when that formula is applied to destination cells for which "`search_key`" is not found among "`search_range`", the output of "`result_range`" for the previous cell in the destination column is repeated, as described in Google Docs Editors Help: > > If search\_key is not found, the item used in the lookup will be the value that’s immediately smaller in the range provided. For example, if the data set contains the numbers 1, 3, 5 and search\_key is 2, then 1 will be used for the lookup. > > > This is a problem for me, because data is placed in cells where it doesn't apply, and I would like these cells, for which "`search_key`" is not found in "`search_range`" to remain blank. I've tried incorporating `VLOOKUP` instead, but get a `#REF` error, it seems due to evaluating data on a separate sheet, or otherwise outside the stated range. And I can't seem to wrap my head around incorporating an `IF` formula into the array in a way that gives me the desired outcome. The original spreadsheet contains confidential information, so I cannot share that link here; however, I've duplicated the necessary components [here:](https://docs.google.com/spreadsheets/d/1eZS3q7_PaAOwwHMKmPEfLLzizFJn3FsuEyQytNKlggg/edit?usp=sharing) Does anyone have ideas or fixes for this? Is there something I need to add? Am I using the wrong formula?
2016/03/30
[ "https://Stackoverflow.com/questions/36319083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6136794/" ]
You need `vlookup`, not `lookup` (suggestion: never use `lookup`). The following function achieves your objective: ``` =IFERROR(VLOOKUP(A2, Sheet2!A:B, 2, False)) ``` Explanation: * Second parameter of vlookup is the range that includes both the column to search (must be the first one), and the column from which result is to be taken. * Third parameter specifies that the result is taken from 2nd column * `False` indicates that exact match is required * `iferror` wrapper suppresses error messages, replacing them with blanks.
`VLOOKUP` with the last parameter (`IsSorted`) set FALSE can get very slow. ``` =IF(VLOOKUP(A2, other!A:A, 1) = A2, VLOOKUP(A2, other!A:B, 2), "") ```
23,420,057
I'm using Zurb Foundation, and I would like to create a navigation bar fixed to the bottom of the window. I've positioned it properly, but the dropdown menus can't be seen because they are appearing below the bottom of the window. How can I make the menus drop up from the nav rather than drop down? Here is a codepen which shows the hidden menus: <http://cdpn.io/lnqFL> ``` <div class="fixed-bottom"> <nav class="top-bar" id="menu" data-topbar> <ul class="title-area"> <li class="name"></li> <li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li> </ul> <section class="top-bar-section"> <ul class="right"> <li class="has-dropdown"> <a href="#">Right Button Dropdown</a> <ul class="dropdown"> <li><a href="#">First link in dropdown</a></li> </ul> </li> </ul> </section> </nav> </div> ``` Here's the menu class I'm using to position the nav: ``` #menu { margin-bottom: 0; bottom: 0; position: fixed; width: 100%; } ```
2014/05/02
[ "https://Stackoverflow.com/questions/23420057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2877587/" ]
@bigfish66 got me half way there, but on small screens the data-options value was being ignored. To get the menu to always drop up, I took the css from the drop up at the larger screen, and applied it with !important to overwrite the element styles from placing the menu back underneath the button on the smaller screens. ``` <button data-dropdown="drop1" aria-controls="drop1" data-options="align:top" aria-expanded="false">Has Dropdown</button> <ul id="drop1" class="f-dropdown" data-dropdown-content aria-hidden="true" tabindex="-1"> <li><a href="#">This is a link</a></li> <li><a href="#">This is another</a></li> <li><a href="#">Yet another</a></li> </ul> #drop1:before { bottom: -14px !important; top: auto !important; content: ""; display: block; width: 0; height: 0; border: inset 6px; border-top-style: solid; position: absolute; left: 10px; right: auto; z-index: 89; border-color: white transparent transparent transparent; } #drop1:after { bottom: -14px !important; top: auto !important; content: ""; display: block; width: 0; height: 0; border: inset 7px; border-color: #cccccc transparent transparent transparent; border-top-style: solid; position: absolute; left: 9px; right: auto; z-index: 88; } #drop1 { top: 227px !important; } ```
You can align them with a data-options attribute...so for you align to the top : ``` <section class="top-bar-section"> <ul class="right"> <li class="has-dropdown"> <a href="#" data-options = "align:top" >Right Button Dropdown</a> <ul class="dropdown"> <li><a href="#">First link in dropdown</a></li> </ul> </li> </ul> </section> ``` Documentation here : [Dropdowns](http://foundation.zurb.com/docs/components/dropdown.html)
63,747,598
I have created a SQL Server trigger as below. ``` create trigger testtrigger on testdb for insert as declare @sql varchar(8000) SELECT @sql = 'bcp "select * from testdb" queryout c:/test.txt -c -t -T -S localhost' exec xp_cmdshell @sql go ``` But when a row inserted in the testdb, the text file is created, but there is no content. Can someone please help me to resolve this.
2020/09/04
[ "https://Stackoverflow.com/questions/63747598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12340627/" ]
Beyond the recommendations regarding not using that approach, I'd ask you if you are sure that the insert is completed. The most probable situation is that you're facing a deadlock, and a kind of deadlock that SQL is not able to handle because of the fact that one of the resources involved is out of SQL scope (command line). The thing is that when you finished the insert, the trigger is activated without releasing the exclusive locks that were taken in `testtrigger`. Then the select over `testtrigger` is tried but since there still locks the select needs to wait for those locks to be released, something that will never happen because you don't close the transaction as it's waiting for the select. So the file is created, but the insert and the select are never completed due to the deadlock. You'll see it work by adding updating the command to: ``` 'bcp "select * from inserted with(nolock)" queryout c:/test.txt -c -t -T -S localhost' ``` Of course the whole approach is not recommended but I wish it helps you understand the situation.
Try making the trigger AFTER INSERT and then export from the 'inserted' psuedo-table instead of the actual table 'testdb'. The newly inserted rows will be exported. ``` create trigger testtrigger on testdb after insert as if exists (select * from inserted) begin declare @sql varchar(8000), @guidName char(36)=newid(); SELECT @sql = concat('bcp "select * from inserted" queryout c:/', @guidName, '.txt -c -t -T -S localhost'); exec xp_cmdshell @sql end go ```
41,357,330
I have null values in database specifically for Good Expiry Date, which is the field is:`good_expiryDate`. What i want is to handle it in this way: If `good_expiryDate` is null i want to present it as "" or "-", if it has value it will show the value retrieved from database? the LINQ query i write is like this, but it return `MinValue` if `good_expiryDate` is `null`(this is what i tried to do). ``` var query = (from cd in db.CDIndexes join gds in db.Goods on cd.cdin_CDIndexID equals gds.good_CDIndexId join itms in db.Items on gds.good_ItemsID equals itms.item_ItemsID where cd.cdin_CompanyId==c.Comp_CompanyId&& ( gds.good_RemainCBM > 0 || gds.good_RemainWT > 0 || gds.good_RemainPackages > 0 || gds.good_RemainVolumeWT > 0 ) && itms.item_ItemsID==customerId select new DataItem { depNumber=(int)cd.cdin_Serial, ItemDesc=gds.good_Name, gdExpiryDate =(DateTime) gds.good_expiryDate==null?DateTime.MinValue: (DateTime)gds.good_expiryDate, InvoicBalanceUnits = (decimal) gds.good_RemainPackages, WTBal=(decimal)gds.good_RemainWT, VolWT=(decimal)gds.good_RemainVolumeWT } ); return query.ToList(); ``` > > Update: good\_expiryDate is type of Datetime, nullable in database > > >
2016/12/28
[ "https://Stackoverflow.com/questions/41357330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7279958/" ]
Ensure that `gdExpiryDate` is of type `string`. Then change this line ``` gdExpiryDate =(DateTime) gds.good_expiryDate==null?DateTime.MinValue: (DateTime)gds.good_expiryDate, ``` to ``` gdExpiryDate = gds.good_expiryDate==null? "-" : ((DateTime)gds.good_expiryDate).ToString(), ```
Change `gdExpiryDate` type to `string` type and write like this: ``` select new DataItem { depNumber=(int)cd.cdin_Serial, ItemDesc=gds.good_Name, gdExpiryDate = gds.good_expiryDate == null ? "" : gds.good_expiryDate.Value.ToString("dd.mm.yyyy"), InvoicBalanceUnits = (decimal) gds.good_RemainPackages, WTBal=(decimal)gds.good_RemainWT, VolWT=(decimal)gds.good_RemainVolumeWT } ```
20,398,773
Following code read a piece data from given `DataRow`(modelValue) and parse it to a `nullable` `DateTime` instance. **Question**: Please see the code sections under `L1 & L2` where both are technically equal (If i am not making any schoolboy error). However, `L1` works as expected but not `L2`. I am getting > > there is no implicit conversion between null and datetime > > > when I execute the code under `L2`. Can someone advise me ? ``` DateTime? CallBack; var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString(); //Parsing DateTime cdate; if (!DateTime.TryParse(callBackDate, out cdate)) cdate = DateTime.MinValue; //L1 if (cdate==DateTime.MinValue) CallBack = null; else CallBack = cdate.Date; //L2 CallBack = cdate == DateTime.MinValue?null:cdate.Date; ```
2013/12/05
[ "https://Stackoverflow.com/questions/20398773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346961/" ]
You need to tell the compiler that the null should be treated as `DateTime?`. Otherwise the compiler doesn't know what type `null` is. `CallBack = cdate == DateTime.MinValue ? (DateTime?)null : cdate.Date;`
Why don't you use the [`DataRow.Field`](http://msdn.microsoft.com/en-us/library/bb360891%28v=vs.100%29.aspx) extension method which supports nullable types in the first place? ``` DateTime? CallBack = modelValue.Field<DateTime?>("CallBack"); ``` But since you actually have a `string` column you need to parse it first: ``` DateTime? CallBack = null; string callBackDate = modelValue.Field<string>("CallBack"); if(!string.IsNullOrWhiteSpace(callBackDate)) { DateTime cdate; if(DateTime.TryParse(callBackDate, out cdate)) CallBack = cdate; } ``` That's all.
20,398,773
Following code read a piece data from given `DataRow`(modelValue) and parse it to a `nullable` `DateTime` instance. **Question**: Please see the code sections under `L1 & L2` where both are technically equal (If i am not making any schoolboy error). However, `L1` works as expected but not `L2`. I am getting > > there is no implicit conversion between null and datetime > > > when I execute the code under `L2`. Can someone advise me ? ``` DateTime? CallBack; var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString(); //Parsing DateTime cdate; if (!DateTime.TryParse(callBackDate, out cdate)) cdate = DateTime.MinValue; //L1 if (cdate==DateTime.MinValue) CallBack = null; else CallBack = cdate.Date; //L2 CallBack = cdate == DateTime.MinValue?null:cdate.Date; ```
2013/12/05
[ "https://Stackoverflow.com/questions/20398773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346961/" ]
``` (Z) ? X : Y ``` The ternary operator requires that an implicit conversion exists from the second operand (X) to the third operand (Y), or from Y to X. Since `null` cannot be implicitly converted to `DateTime`, nor `DateTime` to `null`, the expression cannot be evaluated. More on this: [Type inference woes by Eric Lippert](http://blogs.msdn.com/b/ericlippert/archive/2006/05/24/type-inference-woes-part-one.aspx). You have to cast `null` to `DateTime?`. By doing so, X will be of type `DateTime?` and Y will be of type `DateTime`. Since there is an implicit conversion from `DateTime` to `DateTime?`, the expression can be evaluated, and it will return a value of type `DateTime?`. Alternatively, and following the same logic, you could also cast the third operand Y to `DateTime?`.
You need to tell the compiler that the null should be treated as `DateTime?`. Otherwise the compiler doesn't know what type `null` is. `CallBack = cdate == DateTime.MinValue ? (DateTime?)null : cdate.Date;`
20,398,773
Following code read a piece data from given `DataRow`(modelValue) and parse it to a `nullable` `DateTime` instance. **Question**: Please see the code sections under `L1 & L2` where both are technically equal (If i am not making any schoolboy error). However, `L1` works as expected but not `L2`. I am getting > > there is no implicit conversion between null and datetime > > > when I execute the code under `L2`. Can someone advise me ? ``` DateTime? CallBack; var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString(); //Parsing DateTime cdate; if (!DateTime.TryParse(callBackDate, out cdate)) cdate = DateTime.MinValue; //L1 if (cdate==DateTime.MinValue) CallBack = null; else CallBack = cdate.Date; //L2 CallBack = cdate == DateTime.MinValue?null:cdate.Date; ```
2013/12/05
[ "https://Stackoverflow.com/questions/20398773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346961/" ]
You need to tell the compiler that the null should be treated as `DateTime?`. Otherwise the compiler doesn't know what type `null` is. `CallBack = cdate == DateTime.MinValue ? (DateTime?)null : cdate.Date;`
You could do the following: ``` DateTime aDateTime = DateTime.MinValue; DateTime? aNullableDateTime = aDateTime == DateTime.MinValue ? null : new DateTime?(aDateTime.Date); ``` which uses the Nullable(Of T) structure.
20,398,773
Following code read a piece data from given `DataRow`(modelValue) and parse it to a `nullable` `DateTime` instance. **Question**: Please see the code sections under `L1 & L2` where both are technically equal (If i am not making any schoolboy error). However, `L1` works as expected but not `L2`. I am getting > > there is no implicit conversion between null and datetime > > > when I execute the code under `L2`. Can someone advise me ? ``` DateTime? CallBack; var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString(); //Parsing DateTime cdate; if (!DateTime.TryParse(callBackDate, out cdate)) cdate = DateTime.MinValue; //L1 if (cdate==DateTime.MinValue) CallBack = null; else CallBack = cdate.Date; //L2 CallBack = cdate == DateTime.MinValue?null:cdate.Date; ```
2013/12/05
[ "https://Stackoverflow.com/questions/20398773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346961/" ]
``` (Z) ? X : Y ``` The ternary operator requires that an implicit conversion exists from the second operand (X) to the third operand (Y), or from Y to X. Since `null` cannot be implicitly converted to `DateTime`, nor `DateTime` to `null`, the expression cannot be evaluated. More on this: [Type inference woes by Eric Lippert](http://blogs.msdn.com/b/ericlippert/archive/2006/05/24/type-inference-woes-part-one.aspx). You have to cast `null` to `DateTime?`. By doing so, X will be of type `DateTime?` and Y will be of type `DateTime`. Since there is an implicit conversion from `DateTime` to `DateTime?`, the expression can be evaluated, and it will return a value of type `DateTime?`. Alternatively, and following the same logic, you could also cast the third operand Y to `DateTime?`.
Why don't you use the [`DataRow.Field`](http://msdn.microsoft.com/en-us/library/bb360891%28v=vs.100%29.aspx) extension method which supports nullable types in the first place? ``` DateTime? CallBack = modelValue.Field<DateTime?>("CallBack"); ``` But since you actually have a `string` column you need to parse it first: ``` DateTime? CallBack = null; string callBackDate = modelValue.Field<string>("CallBack"); if(!string.IsNullOrWhiteSpace(callBackDate)) { DateTime cdate; if(DateTime.TryParse(callBackDate, out cdate)) CallBack = cdate; } ``` That's all.
20,398,773
Following code read a piece data from given `DataRow`(modelValue) and parse it to a `nullable` `DateTime` instance. **Question**: Please see the code sections under `L1 & L2` where both are technically equal (If i am not making any schoolboy error). However, `L1` works as expected but not `L2`. I am getting > > there is no implicit conversion between null and datetime > > > when I execute the code under `L2`. Can someone advise me ? ``` DateTime? CallBack; var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString(); //Parsing DateTime cdate; if (!DateTime.TryParse(callBackDate, out cdate)) cdate = DateTime.MinValue; //L1 if (cdate==DateTime.MinValue) CallBack = null; else CallBack = cdate.Date; //L2 CallBack = cdate == DateTime.MinValue?null:cdate.Date; ```
2013/12/05
[ "https://Stackoverflow.com/questions/20398773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346961/" ]
Why don't you use the [`DataRow.Field`](http://msdn.microsoft.com/en-us/library/bb360891%28v=vs.100%29.aspx) extension method which supports nullable types in the first place? ``` DateTime? CallBack = modelValue.Field<DateTime?>("CallBack"); ``` But since you actually have a `string` column you need to parse it first: ``` DateTime? CallBack = null; string callBackDate = modelValue.Field<string>("CallBack"); if(!string.IsNullOrWhiteSpace(callBackDate)) { DateTime cdate; if(DateTime.TryParse(callBackDate, out cdate)) CallBack = cdate; } ``` That's all.
You could do the following: ``` DateTime aDateTime = DateTime.MinValue; DateTime? aNullableDateTime = aDateTime == DateTime.MinValue ? null : new DateTime?(aDateTime.Date); ``` which uses the Nullable(Of T) structure.
20,398,773
Following code read a piece data from given `DataRow`(modelValue) and parse it to a `nullable` `DateTime` instance. **Question**: Please see the code sections under `L1 & L2` where both are technically equal (If i am not making any schoolboy error). However, `L1` works as expected but not `L2`. I am getting > > there is no implicit conversion between null and datetime > > > when I execute the code under `L2`. Can someone advise me ? ``` DateTime? CallBack; var callBackDate = modelValue["CallBack"] == DBNull.Value ? null : modelValue["CallBack"].ToString(); //Parsing DateTime cdate; if (!DateTime.TryParse(callBackDate, out cdate)) cdate = DateTime.MinValue; //L1 if (cdate==DateTime.MinValue) CallBack = null; else CallBack = cdate.Date; //L2 CallBack = cdate == DateTime.MinValue?null:cdate.Date; ```
2013/12/05
[ "https://Stackoverflow.com/questions/20398773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2346961/" ]
``` (Z) ? X : Y ``` The ternary operator requires that an implicit conversion exists from the second operand (X) to the third operand (Y), or from Y to X. Since `null` cannot be implicitly converted to `DateTime`, nor `DateTime` to `null`, the expression cannot be evaluated. More on this: [Type inference woes by Eric Lippert](http://blogs.msdn.com/b/ericlippert/archive/2006/05/24/type-inference-woes-part-one.aspx). You have to cast `null` to `DateTime?`. By doing so, X will be of type `DateTime?` and Y will be of type `DateTime`. Since there is an implicit conversion from `DateTime` to `DateTime?`, the expression can be evaluated, and it will return a value of type `DateTime?`. Alternatively, and following the same logic, you could also cast the third operand Y to `DateTime?`.
You could do the following: ``` DateTime aDateTime = DateTime.MinValue; DateTime? aNullableDateTime = aDateTime == DateTime.MinValue ? null : new DateTime?(aDateTime.Date); ``` which uses the Nullable(Of T) structure.
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
For all versions: ``` Replace[a2, Append[Thread[a -> b], _ -> 0], 1] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > If you need speed look at [`Dispatch`](http://reference.wolfram.com/language/ref/Dispatch.html). For versions 10.0 or later Association functionality is fast and concise: ``` Lookup[AssociationThread[a, b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > Tersely `Thread` works in place of `AssociationThread` but it causes a redundant evaluation: ``` Lookup[Thread[a -> b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > >
``` Fold[Insert[#1, 0, #2] &, b, Position[Map[Position[a, #] &, a2], {}]] ``` > > {10, 20, 0, 50, 80, 0} > > > Probably faster with large lists: ``` Fold[Insert[#1, 0, #2] &, b, Position[a2, Alternatives @@ Complement[a2, a]]] ```
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
For all versions: ``` Replace[a2, Append[Thread[a -> b], _ -> 0], 1] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > If you need speed look at [`Dispatch`](http://reference.wolfram.com/language/ref/Dispatch.html). For versions 10.0 or later Association functionality is fast and concise: ``` Lookup[AssociationThread[a, b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > Tersely `Thread` works in place of `AssociationThread` but it causes a redundant evaluation: ``` Lookup[Thread[a -> b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > >
``` b2 = Sort[Join[{#, 0} & /@ Complement[a2, a], Join[Partition[Riffle[a, b], 2]]]][[All, 2]] ``` > > {10, 20, 0, 50, 80, 0} > > >
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
The most obvious : ``` If[MemberQ[a, #], b[[Position[a, #][[1, 1]]]], 0] & /@ a2 ``` > > {10, 20, 0, 50, 80, 0} > > >
``` b2 = Sort[Join[{#, 0} & /@ Complement[a2, a], Join[Partition[Riffle[a, b], 2]]]][[All, 2]] ``` > > {10, 20, 0, 50, 80, 0} > > >
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
Some pure "mathematical" ad hoc: ``` a2 /. Thread[a -> b] /. Thread[Complement[a2, a] -> 0] ``` > > {10, 20, 0, 50, 80, 0} > > >
``` mia = MapIndexed[Rule[#2, t[#1]] &, a]; mib = MapIndexed[Rule[#2, #1] &, b]; mic = MapIndexed[Rule[t[#1], #2] &, a2]; Normal@SparseArray[mib /. (mia /. mic), Length[a2]] (*{10, 20, 0, 50, 80, 0}*) ```
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
``` mia = MapIndexed[Rule[#2, t[#1]] &, a]; mib = MapIndexed[Rule[#2, #1] &, b]; mic = MapIndexed[Rule[t[#1], #2] &, a2]; Normal@SparseArray[mib /. (mia /. mic), Length[a2]] (*{10, 20, 0, 50, 80, 0}*) ```
``` b2 = Sort[Join[{#, 0} & /@ Complement[a2, a], Join[Partition[Riffle[a, b], 2]]]][[All, 2]] ``` > > {10, 20, 0, 50, 80, 0} > > >
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
``` Fold[Insert[#1, 0, #2] &, b, Position[Map[Position[a, #] &, a2], {}]] ``` > > {10, 20, 0, 50, 80, 0} > > > Probably faster with large lists: ``` Fold[Insert[#1, 0, #2] &, b, Position[a2, Alternatives @@ Complement[a2, a]]] ```
``` b2 = Sort[Join[{#, 0} & /@ Complement[a2, a], Join[Partition[Riffle[a, b], 2]]]][[All, 2]] ``` > > {10, 20, 0, 50, 80, 0} > > >
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
For all versions: ``` Replace[a2, Append[Thread[a -> b], _ -> 0], 1] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > If you need speed look at [`Dispatch`](http://reference.wolfram.com/language/ref/Dispatch.html). For versions 10.0 or later Association functionality is fast and concise: ``` Lookup[AssociationThread[a, b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > Tersely `Thread` works in place of `AssociationThread` but it causes a redundant evaluation: ``` Lookup[Thread[a -> b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > >
Some pure "mathematical" ad hoc: ``` a2 /. Thread[a -> b] /. Thread[Complement[a2, a] -> 0] ``` > > {10, 20, 0, 50, 80, 0} > > >
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
For all versions: ``` Replace[a2, Append[Thread[a -> b], _ -> 0], 1] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > If you need speed look at [`Dispatch`](http://reference.wolfram.com/language/ref/Dispatch.html). For versions 10.0 or later Association functionality is fast and concise: ``` Lookup[AssociationThread[a, b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > > Tersely `Thread` works in place of `AssociationThread` but it causes a redundant evaluation: ``` Lookup[Thread[a -> b], a2, 0] ``` > > > ``` > {10, 20, 0, 50, 80, 0} > > ``` > >
``` mia = MapIndexed[Rule[#2, t[#1]] &, a]; mib = MapIndexed[Rule[#2, #1] &, b]; mic = MapIndexed[Rule[t[#1], #2] &, a2]; Normal@SparseArray[mib /. (mia /. mic), Length[a2]] (*{10, 20, 0, 50, 80, 0}*) ```
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
``` Fold[Insert[#1, 0, #2] &, b, Position[Map[Position[a, #] &, a2], {}]] ``` > > {10, 20, 0, 50, 80, 0} > > > Probably faster with large lists: ``` Fold[Insert[#1, 0, #2] &, b, Position[a2, Alternatives @@ Complement[a2, a]]] ```
``` mia = MapIndexed[Rule[#2, t[#1]] &, a]; mib = MapIndexed[Rule[#2, #1] &, b]; mic = MapIndexed[Rule[t[#1], #2] &, a2]; Normal@SparseArray[mib /. (mia /. mic), Length[a2]] (*{10, 20, 0, 50, 80, 0}*) ```
104,085
I have two lists `a` and `b` of the same length. And another list `a2` which contains all elements from `a` and some others. Now I want to construct a list `b2` so that for the shared elements between `a2` and `a`, the corresponding elements in `b2` and `b` are the same, and for those elements in `a2` but not `a`, the values in `b2` should be placeholder `0`. Example: ``` a = {1, 2, 5, 8}; b = {10, 20, 50, 80}; a2 = {1, 2, 4, 5, 8, 9}; (*Output b2={10,20,0,50,80,0}*) ``` I know how to achieve this in C-like languages, so I'm wondering if there is a better way of doing this in Mathematica. Thanks! P.S. `a` and `a2` are both ordered. And no duplicate exsists in either list, if it helps.
2016/01/14
[ "https://mathematica.stackexchange.com/questions/104085", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/7959/" ]
Some pure "mathematical" ad hoc: ``` a2 /. Thread[a -> b] /. Thread[Complement[a2, a] -> 0] ``` > > {10, 20, 0, 50, 80, 0} > > >
``` b2 = Sort[Join[{#, 0} & /@ Complement[a2, a], Join[Partition[Riffle[a, b], 2]]]][[All, 2]] ``` > > {10, 20, 0, 50, 80, 0} > > >
73,896,431
It's possible to use for loop with double indices in Java, e.g: ```java for (int j = 0, k = myArray.length - 1; j < myArray.length; j++, k--) ``` To iterate myArray elements from the first element using j and from the last element using k simultaneously without using inner loop. How can we do this in Kotlin without using inner loop.
2022/09/29
[ "https://Stackoverflow.com/questions/73896431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17574835/" ]
You don't need an inner loop. Just create an additional variable inside for loop. ```kotlin for(j in myArray.indices) { val k = myArray.size - 1 - j // Use j and k here } ``` Or alternatively, ```kotlin var k = myArray.size - 1 for(j in myArray.indices) { // Use j and k here k-- } ```
`generateSequence()` is powerful alternative for complex loops. Not so fast as pure for/while loop but very flexible and easy. ```kotlin generateSequence( 0 to myArray.size - 1 // initial values ) { it.first + 1 to it.second - 1 // new values after each iteration }.takeWhile { it.first < myArray.size // limit }.forEach { (j, k) -> println("$j $k") } ``` And yes, it's good idea to not iterate second variable but calculate it from first (if applicable), as suggested in other answers.
73,896,431
It's possible to use for loop with double indices in Java, e.g: ```java for (int j = 0, k = myArray.length - 1; j < myArray.length; j++, k--) ``` To iterate myArray elements from the first element using j and from the last element using k simultaneously without using inner loop. How can we do this in Kotlin without using inner loop.
2022/09/29
[ "https://Stackoverflow.com/questions/73896431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17574835/" ]
**Kotlin doesn't provide a way to permit what you attempt to do.** Because I imagine your case is purely for exemple, I purpose you two solutions: 1. The good old way ------------------- The most optimized for the exemple you give. ``` for (i in a.indices) { val j = a.size - 1 - i println("($i, $j)") } ``` > > (0, 3)(1, 2)(2, 1)(3, 0) > > > [See code snippet on play.kotlinlang.org](https://pl.kotl.in/BLqOOsc4m) 2. The .zip() way ----------------- Can be usefull on some contexts, the zip method combine two lists of the same size on one list of Tuples which can be used after directly. ``` val indices = a.indices; for (i in indices.zip(indices.reversed())) { println(i) } ``` > > (0, 3)(1, 2)(2, 1)(3, 0) > > > [See code snippet on play.kotlinlang.org](https://pl.kotl.in/gFFeB9Z-N)
`generateSequence()` is powerful alternative for complex loops. Not so fast as pure for/while loop but very flexible and easy. ```kotlin generateSequence( 0 to myArray.size - 1 // initial values ) { it.first + 1 to it.second - 1 // new values after each iteration }.takeWhile { it.first < myArray.size // limit }.forEach { (j, k) -> println("$j $k") } ``` And yes, it's good idea to not iterate second variable but calculate it from first (if applicable), as suggested in other answers.
9,135
[Here is a video of Miami reliever Carter Capps pitching.](http://m.mlb.com/video/v73287783/miaatl-capps-hopstep-delivery-analyzed) As you can see, he basically jumps off the rubber, and delivers from the front of the mound. [Apparently](http://m.mlb.com/news/article/118060152/marlins-reliever-carter-capps-clears-up-confusion-on-illegal-pitches), MLB gave their approval to Capps's pitching style -- but with a caveat: > > "They just said they wanted me to make sure I dragged my foot and not get too elevated in the air, and make sure it's more on a lateral plane," Capps said. "As long as I do that, they have no problem with it. But it was very strange." > > > However, as a [Bleacher Report article](http://bleacherreport.com/articles/2430372-marlins-pitcher-carter-capps-has-a-bizarre-leaping-pitch-delivery) notes: > > Not to be a foot in Capps’ punch bowl, but his pitching on Monday didn’t exactly feature extensive toe-dragging. There didn't appear to be any toe-dragging, actually. And by launching down the mound, he does chop off a not-immeasurable distance between him and the plate. In a game where batters have fractions of a second to react to the ball, this difference can be significant. > > > **Was Capps's pitching in the MIA@ATL game legal?** If not, why didn't the umpires disqualify him?
2015/04/17
[ "https://sports.stackexchange.com/questions/9135", "https://sports.stackexchange.com", "https://sports.stackexchange.com/users/6240/" ]
There are other relievers that "jump" off the rubber in their delivery. One I recall in particular is an 8th inning set up guy for Atlanta. He was traded in the off season to St. Louis. I believe his name is Jordan Walden. I never saw umpires call a balk on him or other such deliveries
Yes, It should be legal as multiple pitchers have been doing similar things. The reason Capps is not being busted is because of a possible bending of the balk rules - saying that he is not *really* attempting to bait anyone off base, so his other foot can come off the bag in one clear sweeping motion.
9,135
[Here is a video of Miami reliever Carter Capps pitching.](http://m.mlb.com/video/v73287783/miaatl-capps-hopstep-delivery-analyzed) As you can see, he basically jumps off the rubber, and delivers from the front of the mound. [Apparently](http://m.mlb.com/news/article/118060152/marlins-reliever-carter-capps-clears-up-confusion-on-illegal-pitches), MLB gave their approval to Capps's pitching style -- but with a caveat: > > "They just said they wanted me to make sure I dragged my foot and not get too elevated in the air, and make sure it's more on a lateral plane," Capps said. "As long as I do that, they have no problem with it. But it was very strange." > > > However, as a [Bleacher Report article](http://bleacherreport.com/articles/2430372-marlins-pitcher-carter-capps-has-a-bizarre-leaping-pitch-delivery) notes: > > Not to be a foot in Capps’ punch bowl, but his pitching on Monday didn’t exactly feature extensive toe-dragging. There didn't appear to be any toe-dragging, actually. And by launching down the mound, he does chop off a not-immeasurable distance between him and the plate. In a game where batters have fractions of a second to react to the ball, this difference can be significant. > > > **Was Capps's pitching in the MIA@ATL game legal?** If not, why didn't the umpires disqualify him?
2015/04/17
[ "https://sports.stackexchange.com/questions/9135", "https://sports.stackexchange.com", "https://sports.stackexchange.com/users/6240/" ]
The baseball rulebook is rather ambiguous when it comes to launch points for pitchers. I have a strong feeling that within the next few years we see pitchers try to take advantage of whatever they can will happen and then eventually we might see actual rules that define exact things that need to happen. Right now umpires get a situation book that gives examples - we used to receive these every spring. It would go over trendy things and tell whether each was acceptable or not. To answer your question there really isn't legal/illegal in baseball. If a pitch doesn't follow the rules is a balk. A pitcher has unlimited balks. Each balk without a runner on base is a ball. With runners it is a base and a ball.
Yes, It should be legal as multiple pitchers have been doing similar things. The reason Capps is not being busted is because of a possible bending of the balk rules - saying that he is not *really* attempting to bait anyone off base, so his other foot can come off the bag in one clear sweeping motion.
9,135
[Here is a video of Miami reliever Carter Capps pitching.](http://m.mlb.com/video/v73287783/miaatl-capps-hopstep-delivery-analyzed) As you can see, he basically jumps off the rubber, and delivers from the front of the mound. [Apparently](http://m.mlb.com/news/article/118060152/marlins-reliever-carter-capps-clears-up-confusion-on-illegal-pitches), MLB gave their approval to Capps's pitching style -- but with a caveat: > > "They just said they wanted me to make sure I dragged my foot and not get too elevated in the air, and make sure it's more on a lateral plane," Capps said. "As long as I do that, they have no problem with it. But it was very strange." > > > However, as a [Bleacher Report article](http://bleacherreport.com/articles/2430372-marlins-pitcher-carter-capps-has-a-bizarre-leaping-pitch-delivery) notes: > > Not to be a foot in Capps’ punch bowl, but his pitching on Monday didn’t exactly feature extensive toe-dragging. There didn't appear to be any toe-dragging, actually. And by launching down the mound, he does chop off a not-immeasurable distance between him and the plate. In a game where batters have fractions of a second to react to the ball, this difference can be significant. > > > **Was Capps's pitching in the MIA@ATL game legal?** If not, why didn't the umpires disqualify him?
2015/04/17
[ "https://sports.stackexchange.com/questions/9135", "https://sports.stackexchange.com", "https://sports.stackexchange.com/users/6240/" ]
The baseball rulebook is rather ambiguous when it comes to launch points for pitchers. I have a strong feeling that within the next few years we see pitchers try to take advantage of whatever they can will happen and then eventually we might see actual rules that define exact things that need to happen. Right now umpires get a situation book that gives examples - we used to receive these every spring. It would go over trendy things and tell whether each was acceptable or not. To answer your question there really isn't legal/illegal in baseball. If a pitch doesn't follow the rules is a balk. A pitcher has unlimited balks. Each balk without a runner on base is a ball. With runners it is a base and a ball.
There are other relievers that "jump" off the rubber in their delivery. One I recall in particular is an 8th inning set up guy for Atlanta. He was traded in the off season to St. Louis. I believe his name is Jordan Walden. I never saw umpires call a balk on him or other such deliveries
220,020
Is there a difference between wubi install and doing an install of Ubuntu alongside windows7? I ask because I used wubi, but I'm having trouble with certain things like being unable to change my brightness settings and I'm wondering if installing from a usb drive would change anything. Also, I've tried to do a usb drive install, but it doesn't give me the option to install alongside, it only shows the "Replace Windows 7" and "something else" options. Is this because I already did a wubi install?
2012/11/21
[ "https://askubuntu.com/questions/220020", "https://askubuntu.com", "https://askubuntu.com/users/109616/" ]
**Format and enable LZO** I would avoid using any GUI to format;-) `mkfs.btrfs device` is good enough, depending on how you would like to make use of Btrfs features: 1. use the external USB HDD as 1 single partition/block device 2. create 2 partitions (2 block devices) and form a raid1 or raid0 for data (-d), metadata is replicated on all devices by default, unless you manually specify to change You can make use of the compression by adding the option when mounting, for example: ``` sudo mount -o compress=lzo /dev/sdd /mnt/btrfs ``` The good thing about Btrfs is that LZO compression can also be enabled on a `subvol` basis, very flexible;-) For example ``` /* Create a subvolume named subvol1 */ # btrfs subvolume create /mnt/btrfs/subvol1 /* Mount the subvolume and enable compression */ # mount -o compress=lzo,subvol=subvol1 /dev/sdd /mnt/subvol1 ``` **NOTE: You can add compression to existing Btrfs file systems at any time, just add the option when mounting and do a `defragment` to apply compression to existing data.** BTW: 2 best Btrfs docs out there: <http://www.funtoo.org/wiki/BTRFS_Fun> <http://docs.oracle.com/cd/E37670_01/E37355/html/ol_btrfs.html> Make use of LZO compression: <http://www.oracle.com/technetwork/articles/servers-storage-admin/advanced-btrfs-1734952.html> **USB Auto Mount** I am not too sure about this, will let other blokes answer it;-) I'd prefer to write a simple shell script to do the mount because I won't attach the USB HDD to the computer all the time.
As the formatting and enabling LZO compression question is answered already, here is the answer to the Question how to automatically set the compression mount option on automount. This solution also works if you have btrfs on a LUKS-encrypted disk. **USB Automount** 1. Connect the disk and let your automounter mount the filesystem 2. Use `lsblk -o UUID,MOUNTPOINT` to find the UUID of the block device the filesystem is on, e.g. `6e642696-3cb4-4d4e-86a6-2fae2b9295cc` 3. Add a line to your /etc/fstab referencing the UUID and specifying the additional mount option: ``` UUID=6e642696-3cb4-4d4e-86a6-2fae2b9295cc /media/user/backupdrive btrfs noauto,subvol=/,compress=zstd ``` 4. Unmount and re-mount the drive and check that the options were set using `mount`
1,211,937
I am quite new to SSH and Ubuntu. I am trying to connect to a server (e.g. `server1.com`) via SOCKS5 proxy host (e.g. `proxy1.com`) for which username and password is already given. I am including the jump host directives and path to proxy username and password in the SSH config file but no luck until now as I am always getting an error: > > unable to resolve proxy hostname > > > My `.ssh/config` file format is as below: ``` Host host1 HostName server1.com Port 22 ProxyCommand ssh username:password@proxy.com portnum %h %p ``` And then I am using `ssh host1` to initiate the session. Can anyone give me the possible solutions?
2017/05/23
[ "https://superuser.com/questions/1211937", "https://superuser.com", "https://superuser.com/users/731129/" ]
Any large-sector disks, such as 4K native, 512E, or any non-512 native disks, are **not supported** on any Windows XP version. However, WD quick format can fix this: Please check the [WD official documentation](https://support.wdc.com/knowledgebase/answer.aspx?ID=3868) Just follow the guide and select Window XP compatibility when formatting the drive. It should then work.
I disagree slightly with @Overmind. While Microsoft may not officially support large sectors on XP, that doesn't mean it won't work. I can successfully use a Seagate 8TB drive on Windows XP SP3 *because* it has 4K Native sectors. In other words, because it identifies as having 4K sectors, Windows XP is able to use it normally. Based on your description, the issue I believe you're running into is that the drive is formatted with GPT. That would explain why it works on Windows 7 but not XP. If you want it to work on XP *and* be able to access the full 3 TB, then you need to verify the sector size in msinfo32. Just run msinfo32 and navigate to Components->Storage->Disks, then find your external drive in the list. If it says, "Bytes/Sector 4096" then it is XP-compatible and just needs to be reformatted with the WD Quick Formatter as Overmind suggested. If it says, "Bytes/Sector 512", then Windows XP will not be able to access more than the first ~2 TB or so.
12,011,926
I have this perl script ``` #!/usr/bin/perl use lib "/home/gdanko/test/perl"; use Main; Plugins::Plug1::devices; ``` The module Main looks like this ``` package Main; use lib "/home/gdanko/test/perl"; use Plugins::Plug1; use DBI; @ISA = ('Exporter'); @EXPORT = qw(); @EXPORT_OK = qw($dbh &load_devices); our $dbh = DBI->connect("dbi:SQLite:dbname=/home/gdanko/test/mydb.db", "", ""); sub load_devices { my $sth = $dbh->prepare("SELECT * FROM devices"); $sth->execute; my $devices = $dbh->selectall_hashref($sth, "id"); return $devices; } 1; ``` The module Plug1 looks like this ``` package Plug1; use lib "/home/gdanko/test/perl"; use Data::Dumper; use Main qw(&load_devices); @ISA = ('Exporter'); @EXPORT = (); @EXPORT_OK = qw(&devices); sub devices { print "module plug1\n"; my $devices = Main::load_devices; print Dumper(\$devices->{maguro}); } 1; ``` When I execute Plugins::Plug::devices from the main script I get this in return: gdanko@apollo:~/test$ ./script.pl module plug1 $VAR1 = \undef; How can I make the methods and variables in Main available to Plug1?
2012/08/17
[ "https://Stackoverflow.com/questions/12011926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/589254/" ]
You describe your module variously as `Plugins::Plug1`, `Plugins::Plug`, `Plug1` and `plug1`. You must be clear which it is, and a module `Plugins::Plug1` must be in a file named `Plugins/Plug1.pm` starting with the statement `package Plugins::Plug1` It is unclear from your question what is going wrong. What should happen is that Perl will tell you `Plugins::Plug1::devices` doesn't exist, because your `package` statement doesn't match. But it looks like you are saying that `Main::load_devices` is returning `undef` instead of a hash reference. It looks like the subroutines are probably being called, and you need to debug them. Put some `print` statements in your code to see what is being called, but most of all you must `use strict` and `use warnings` at the top of every file. That will reveal many simple mistakes. Also note that `Exporter` exports symbols from a module into the calling package, and is unnecessary if you intend always to call the subroutines with their fully-qualified names. If you use `Exporter` you can omit the package names from the calls
`Plugins::Plug1` must declare that it "is a" `Main` (hint: Just like they both declare that they have an "is a" relationship to `Exporter`.) . Then the methods will be immediately available. However, you should read the perldoc on objects (start with [perlobj](http://perldoc.perl.org/perlobj.html)) if you're asking how to make variables "visible" to subclasses. You can't and you *shouldn't*. I take it you're thinking standard OO and the variables in the package represent members of the object. The most common implementation is a blessed hash, where the members are named values in the hash.
7,037,875
I have a short code to get the results of a db\_query into an array: ``` $r = db_query('SELECT vid FROM {node_revisions} WHERE nid = %d', $node->nid); while ($vids[] = db_result($r)); ``` The only problem is, that I get an empty array value: ``` Array( [] => 105 [] => 409 [] => ) ``` How can I prevent the empty array value?
2011/08/12
[ "https://Stackoverflow.com/questions/7037875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488794/" ]
I found the shortest code to get all results from db\_query in an array: ``` for ($vid; $vid = db_result($r); $vids[] = $vid); ``` The resulted array looks now like this: ``` Array( [0] => 105 [1] => 409 ) ```
Perhaps something like. ``` $next_result = db_result($r); while ($next_result) { $vids[] = $next_result; $next_result = db_result($r); } ``` Edit: Single line using short-circuit syntax. ``` while ($next = db_result($r) && $vids[] = $next); ```
28,122,856
i have xml file like this ``` > <?xml version='1.0' ?> <config> <app> <app version="1.1.0" /> > </app> </config> ``` and i want to read attribute version from node app without any loop like this while(reader.read()) or foreach etc. Thanks
2015/01/24
[ "https://Stackoverflow.com/questions/28122856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4487740/" ]
You can do it this way. ``` XmlDocument doc = new XmlDocument(); string str = "<config><app><app version=" + "\"1.1.0\"" + "/></app></config>"; doc.LoadXml(str); var nodes = doc.GetElementsByTagName("app"); foreach (XmlNode node in nodes) { if (node.Attributes["version"] != null) { string version = node.Attributes["version"].Value; } } ``` And you need to this for loop cause you got two nodes with same name App. If you have a single node with name App, ``` XmlDocument doc = new XmlDocument(); string str = "<config><app version=" + "\"1.1.0\"" + "/></config>"; doc.LoadXml(str); var node = doc.SelectSingleNode("//app"); if (node.Attributes["version"] != null) { string version = node.Attributes["version"].Value; Console.WriteLine(version); } ```
You can use linq to do ``` string stringXml= "yourXml Here"; XElement xdoc = XElement.Parse(stringXml); var result= xdoc.Descendants("app").FirstOrDefault(x=> x.Attribute("version") != null).attribute("version").Value; ``` or: ``` var result = xdoc.Descendants("app").Where(x => x.Attribute("version") != null) .Select(x => new { Version = x.Value }); ```
28,122,856
i have xml file like this ``` > <?xml version='1.0' ?> <config> <app> <app version="1.1.0" /> > </app> </config> ``` and i want to read attribute version from node app without any loop like this while(reader.read()) or foreach etc. Thanks
2015/01/24
[ "https://Stackoverflow.com/questions/28122856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4487740/" ]
``` XmlDocument document = new XmlDocument(); document.Load("D:/source.xml"); XmlNode appVersion1 = document.SelectSingleNode("//app[@version]/@version"); XmlNode appVersion2 = document["config"]["app"]["app"].Attributes["version"]; Console.WriteLine("{0}, {1}", appVersion1.Value, appVersion2.Value); ```
You can use linq to do ``` string stringXml= "yourXml Here"; XElement xdoc = XElement.Parse(stringXml); var result= xdoc.Descendants("app").FirstOrDefault(x=> x.Attribute("version") != null).attribute("version").Value; ``` or: ``` var result = xdoc.Descendants("app").Where(x => x.Attribute("version") != null) .Select(x => new { Version = x.Value }); ```
69,219
I have a Web App that i have developed I am looking to develop a plugin for this app so that i can pull information from the users accounts package such as sage or quickbooks(offline version). Ideally I would like to do this without them having to have a static ip etc. Unfortunately this is way over my head I currently have no idea on how to do this. Please can some one guide me in the right direction I will probably use json data between the webapp and the client service that I will make and im fine with that part its just the initial connection that I am confused about. Any help would be really really appreciated I hope this makes sense. Thanks Ash
2011/04/18
[ "https://softwareengineering.stackexchange.com/questions/69219", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/23282/" ]
Bottom line: you need to write some`thing` that the user installs on his computer (either write a Browser plug in or an active x control.) That `Thing` will get data from the local comp and push it to you.. (This can be trigged by your web app.)
Could you get the users to upload a file? In other words they need to save the data locally from their application, then in your web application they can upload it to you. If this would work there is more info on SO: <https://stackoverflow.com/questions/116353/uploading-files-in-ruby-on-rails>
69,219
I have a Web App that i have developed I am looking to develop a plugin for this app so that i can pull information from the users accounts package such as sage or quickbooks(offline version). Ideally I would like to do this without them having to have a static ip etc. Unfortunately this is way over my head I currently have no idea on how to do this. Please can some one guide me in the right direction I will probably use json data between the webapp and the client service that I will make and im fine with that part its just the initial connection that I am confused about. Any help would be really really appreciated I hope this makes sense. Thanks Ash
2011/04/18
[ "https://softwareengineering.stackexchange.com/questions/69219", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/23282/" ]
Bottom line: you need to write some`thing` that the user installs on his computer (either write a Browser plug in or an active x control.) That `Thing` will get data from the local comp and push it to you.. (This can be trigged by your web app.)
Have you consider using the WebSockets in order to allows users to send information to the server? I know, it needs HTML 5 ready browsers, but its a small price to pay. Here is an interesting link [HTML5 - Web Sockets](http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/)
726,117
I want to print the first and the last non-empty or non-whitespace-only line in a file, idally using `sed` or `awk`. * Input File: ``` 123 345 456 087 er 56 32 78 ``` Note that there is a blank line after `32 78`. * Desired output: ``` 123 345 32 78 ```
2022/11/24
[ "https://unix.stackexchange.com/questions/726117", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/431343/" ]
Note that I'm answering two questions here as the text in the question was modified: 1. How may we output the first and the penultimate lines from a file (the initial question contained the wording "second last line")? 2. How may we output the first line, and the last non-empty, non-blank line? --- Using the `ed` editor, which is slightly more flexible with its addressing of lines than `sed`, mostly due to reading all of the data into memory rather than a line at a time: ```bash $ printf '%s\n' 1p '$-1p' Q | ed -s file 123 345 32 78 ``` This prints the first and penultimate line from the input file before quitting. The penultimate line is addressed using `$-1`, which could be shortened to just `$-`. If we don't know that there's exactly one blank line at the end, we may instead search backwards from line 1 for a line that contains something and print that: ```bash $ printf '%s\n' 1p '?[[:graph:]]?p' Q | ed -s file 123 345 32 78 ``` --- Using `sed`: ```bash $ sed -n -e 1p -e '${ g; p; }' -e h file 123 345 32 78 ``` This first turns off the default outputting of each line with `-n`. It then prints the first line. All lines are saved to the hold space using `h`, and on the last line, we fetch the hold space with `g` and print it. Due to the ordering of the last two expressions, this will print the penultimate line. With a small modification, we can change this to output the last non-blank line, no matter if it's the penultimate one or not: ```bash $ sed -n -e 1p -e '/[[:graph:]]/h' -e '${ g; p; }' file 123 345 32 78 ``` --- With a combination of `grep` and `sed`, we may first filter out all empty or empty-looking lines, and then just output the first and last lines: ```bash $ grep '[[:graph:]]' file | sed -n -e 1p -e '$p' 123 345 32 78 ``` Note that this will also output the first non-empty line, even if this is not the first line in the original data.
The following `awk` program will do this: ``` awk 'NF{last=$0; if (!c++) print;} END {if (c>1) print last}' file.txt ``` * `awk` by default splits input lines into fields at "whitespace", i.e. contiguous runs of space and tabs. The number of fields is stored in `NF`. If a line is completely empty, or only consists of whitespace, `NF` will be zero. * If the program encounters a truly and visually non-empty line, i.e. `NF` is non-zero and evaluates to `true`, it stores the line content in a buffer `last`. If this is the first such line (the counter variable `c` will be unset and evaluate to `false`), it prints the current line. In any case, it increases `c` so that this condition can only occur once, for the first non-empty line. * At the end, if prints `last`, the content of the last non-empty line, *but only if `c>1`*, so that if only a single line is non-empty, that line will just be printed once. If all lines were empty, `c` will evaluate to 0, and nothing will be printed even in the `END` clause.
726,117
I want to print the first and the last non-empty or non-whitespace-only line in a file, idally using `sed` or `awk`. * Input File: ``` 123 345 456 087 er 56 32 78 ``` Note that there is a blank line after `32 78`. * Desired output: ``` 123 345 32 78 ```
2022/11/24
[ "https://unix.stackexchange.com/questions/726117", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/431343/" ]
Note that I'm answering two questions here as the text in the question was modified: 1. How may we output the first and the penultimate lines from a file (the initial question contained the wording "second last line")? 2. How may we output the first line, and the last non-empty, non-blank line? --- Using the `ed` editor, which is slightly more flexible with its addressing of lines than `sed`, mostly due to reading all of the data into memory rather than a line at a time: ```bash $ printf '%s\n' 1p '$-1p' Q | ed -s file 123 345 32 78 ``` This prints the first and penultimate line from the input file before quitting. The penultimate line is addressed using `$-1`, which could be shortened to just `$-`. If we don't know that there's exactly one blank line at the end, we may instead search backwards from line 1 for a line that contains something and print that: ```bash $ printf '%s\n' 1p '?[[:graph:]]?p' Q | ed -s file 123 345 32 78 ``` --- Using `sed`: ```bash $ sed -n -e 1p -e '${ g; p; }' -e h file 123 345 32 78 ``` This first turns off the default outputting of each line with `-n`. It then prints the first line. All lines are saved to the hold space using `h`, and on the last line, we fetch the hold space with `g` and print it. Due to the ordering of the last two expressions, this will print the penultimate line. With a small modification, we can change this to output the last non-blank line, no matter if it's the penultimate one or not: ```bash $ sed -n -e 1p -e '/[[:graph:]]/h' -e '${ g; p; }' file 123 345 32 78 ``` --- With a combination of `grep` and `sed`, we may first filter out all empty or empty-looking lines, and then just output the first and last lines: ```bash $ grep '[[:graph:]]' file | sed -n -e 1p -e '$p' 123 345 32 78 ``` Note that this will also output the first non-empty line, even if this is not the first line in the original data.
``` sed -n '/^$/d; p; :a; n; /^$/!h; $!ba; g; /^$/!p' file.txt ``` **Test files content:** ``` ==> file_1.txt <== 123 345 456 087 er 56 32 78 ==> file_2.txt <== 123 345 456 087 er 56 32 78 ==> file_3.txt <== 123 345 456 087 er 56 32 78 ==> file_4.txt <== 123 345 456 087 er 56 32 78 ==> file_5.txt <== 123 345 ``` **Testing** ``` for f in file_{1..5}.txt; do echo "==> $f <==" sed -n '/^$/d; p; :a; n; /^$/!h; $!ba; g; /^$/!p' "$f" done ``` **Output:** ``` ==> file_1.txt <== 123 345 32 78 ==> file_2.txt <== 123 345 32 78 ==> file_3.txt <== 123 345 32 78 ==> file_4.txt <== 123 345 32 78 ==> file_5.txt <== 123 345 ```
726,117
I want to print the first and the last non-empty or non-whitespace-only line in a file, idally using `sed` or `awk`. * Input File: ``` 123 345 456 087 er 56 32 78 ``` Note that there is a blank line after `32 78`. * Desired output: ``` 123 345 32 78 ```
2022/11/24
[ "https://unix.stackexchange.com/questions/726117", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/431343/" ]
The following `awk` program will do this: ``` awk 'NF{last=$0; if (!c++) print;} END {if (c>1) print last}' file.txt ``` * `awk` by default splits input lines into fields at "whitespace", i.e. contiguous runs of space and tabs. The number of fields is stored in `NF`. If a line is completely empty, or only consists of whitespace, `NF` will be zero. * If the program encounters a truly and visually non-empty line, i.e. `NF` is non-zero and evaluates to `true`, it stores the line content in a buffer `last`. If this is the first such line (the counter variable `c` will be unset and evaluate to `false`), it prints the current line. In any case, it increases `c` so that this condition can only occur once, for the first non-empty line. * At the end, if prints `last`, the content of the last non-empty line, *but only if `c>1`*, so that if only a single line is non-empty, that line will just be printed once. If all lines were empty, `c` will evaluate to 0, and nothing will be printed even in the `END` clause.
``` sed -n '/^$/d; p; :a; n; /^$/!h; $!ba; g; /^$/!p' file.txt ``` **Test files content:** ``` ==> file_1.txt <== 123 345 456 087 er 56 32 78 ==> file_2.txt <== 123 345 456 087 er 56 32 78 ==> file_3.txt <== 123 345 456 087 er 56 32 78 ==> file_4.txt <== 123 345 456 087 er 56 32 78 ==> file_5.txt <== 123 345 ``` **Testing** ``` for f in file_{1..5}.txt; do echo "==> $f <==" sed -n '/^$/d; p; :a; n; /^$/!h; $!ba; g; /^$/!p' "$f" done ``` **Output:** ``` ==> file_1.txt <== 123 345 32 78 ==> file_2.txt <== 123 345 32 78 ==> file_3.txt <== 123 345 32 78 ==> file_4.txt <== 123 345 32 78 ==> file_5.txt <== 123 345 ```
2,529,663
Lets say I have the following: ``` data Greek = Alpha | Beta | Gamma | Phi deriving Show ``` I want to use the default showing of all items except Beta, which I want to say "two". Can I do this?
2010/03/27
[ "https://Stackoverflow.com/questions/2529663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169404/" ]
`deriving Show` uses the standard instantiation mechanism (simply returning the definition). If you want any special things, you will have to instantiate it manually: ``` data Greek = Alpha | Beta | Gamma | Phi instance Show Greek where show Alpha = "Alpha" show Beta = "2" show Gamma = "Gamma" show Phi = "Phi" ```
As far as I know, you can't. The deriving mechanism doesn't support anyway to alter or extend the derived instances.
2,529,663
Lets say I have the following: ``` data Greek = Alpha | Beta | Gamma | Phi deriving Show ``` I want to use the default showing of all items except Beta, which I want to say "two". Can I do this?
2010/03/27
[ "https://Stackoverflow.com/questions/2529663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169404/" ]
Not that this is entirely satisfactory, but you could do: ``` data Greek = Alpha | Beta | Gamma | Phi deriving (Show) showGreek Beta = "2" showGreek x = show x ``` And use showGreek instead of show. If you needed a real show instance (in my code I find that I need this less than beginners tend to think), you could do the rather cumbersome: ``` newtype Greek' = Greek' Greek instance Show Greek' where show (Greek' g) = showGreek g ``` If it were my code, I'd just stick with `showGreek`. A nice rule of thumb I use is that the Show and Read instances are Haskell-generated only. If show doesn't produce valid Haskell code, it shouldn't be in a Show instance.
As far as I know, you can't. The deriving mechanism doesn't support anyway to alter or extend the derived instances.
2,529,663
Lets say I have the following: ``` data Greek = Alpha | Beta | Gamma | Phi deriving Show ``` I want to use the default showing of all items except Beta, which I want to say "two". Can I do this?
2010/03/27
[ "https://Stackoverflow.com/questions/2529663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169404/" ]
`deriving Show` uses the standard instantiation mechanism (simply returning the definition). If you want any special things, you will have to instantiate it manually: ``` data Greek = Alpha | Beta | Gamma | Phi instance Show Greek where show Alpha = "Alpha" show Beta = "2" show Gamma = "Gamma" show Phi = "Phi" ```
Not that this is entirely satisfactory, but you could do: ``` data Greek = Alpha | Beta | Gamma | Phi deriving (Show) showGreek Beta = "2" showGreek x = show x ``` And use showGreek instead of show. If you needed a real show instance (in my code I find that I need this less than beginners tend to think), you could do the rather cumbersome: ``` newtype Greek' = Greek' Greek instance Show Greek' where show (Greek' g) = showGreek g ``` If it were my code, I'd just stick with `showGreek`. A nice rule of thumb I use is that the Show and Read instances are Haskell-generated only. If show doesn't produce valid Haskell code, it shouldn't be in a Show instance.
2,529,663
Lets say I have the following: ``` data Greek = Alpha | Beta | Gamma | Phi deriving Show ``` I want to use the default showing of all items except Beta, which I want to say "two". Can I do this?
2010/03/27
[ "https://Stackoverflow.com/questions/2529663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169404/" ]
`deriving Show` uses the standard instantiation mechanism (simply returning the definition). If you want any special things, you will have to instantiate it manually: ``` data Greek = Alpha | Beta | Gamma | Phi instance Show Greek where show Alpha = "Alpha" show Beta = "2" show Gamma = "Gamma" show Phi = "Phi" ```
Some of the other suggestions work great in your particular example, and I would suggest to use those. But in a more general case you might want to use [datatype-generic programming](http://www.haskell.org/haskellwiki/Research_papers/Generics). Using generic programming, you can write functions that work on multiple data types, i.e. functions that do the same for every data type. Examples of such functions are `show` and `==` (this is the reason those can be derived in GHC). This is an example using the [regular](http://hackage.haskell.org/package/regular) library: ``` {-# LANGUAGE TemplateHaskell, EmptyDataDecls, TypeFamilies #-} import Generics.Regular import qualified Generics.Regular.Functions.Show as G data Greek = Alpha | Beta | Gamma | Phi -- These two lines are all that is needed to use -- Regulars generic functions on the 'Greek' data type. $(deriveAll ''Greek "PFGreek") type instance PF Greek = PFGreek -- Manual written instance for 'Show' instance Show Greek where show Beta = "Two" show x = G.show x -- Use Regulars 'show' for the boring parts ``` To be honest, I don't really like the output from Regulars [`show`](http://hackage.haskell.org/packages/archive/regular/0.2.3/doc/html/Generics-Regular-Functions-Show.html#v%3Ashow) function (it throws in an extra set of parentheses). But this might be a good starting point for writing your own generic functions.
2,529,663
Lets say I have the following: ``` data Greek = Alpha | Beta | Gamma | Phi deriving Show ``` I want to use the default showing of all items except Beta, which I want to say "two". Can I do this?
2010/03/27
[ "https://Stackoverflow.com/questions/2529663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169404/" ]
Not that this is entirely satisfactory, but you could do: ``` data Greek = Alpha | Beta | Gamma | Phi deriving (Show) showGreek Beta = "2" showGreek x = show x ``` And use showGreek instead of show. If you needed a real show instance (in my code I find that I need this less than beginners tend to think), you could do the rather cumbersome: ``` newtype Greek' = Greek' Greek instance Show Greek' where show (Greek' g) = showGreek g ``` If it were my code, I'd just stick with `showGreek`. A nice rule of thumb I use is that the Show and Read instances are Haskell-generated only. If show doesn't produce valid Haskell code, it shouldn't be in a Show instance.
Some of the other suggestions work great in your particular example, and I would suggest to use those. But in a more general case you might want to use [datatype-generic programming](http://www.haskell.org/haskellwiki/Research_papers/Generics). Using generic programming, you can write functions that work on multiple data types, i.e. functions that do the same for every data type. Examples of such functions are `show` and `==` (this is the reason those can be derived in GHC). This is an example using the [regular](http://hackage.haskell.org/package/regular) library: ``` {-# LANGUAGE TemplateHaskell, EmptyDataDecls, TypeFamilies #-} import Generics.Regular import qualified Generics.Regular.Functions.Show as G data Greek = Alpha | Beta | Gamma | Phi -- These two lines are all that is needed to use -- Regulars generic functions on the 'Greek' data type. $(deriveAll ''Greek "PFGreek") type instance PF Greek = PFGreek -- Manual written instance for 'Show' instance Show Greek where show Beta = "Two" show x = G.show x -- Use Regulars 'show' for the boring parts ``` To be honest, I don't really like the output from Regulars [`show`](http://hackage.haskell.org/packages/archive/regular/0.2.3/doc/html/Generics-Regular-Functions-Show.html#v%3Ashow) function (it throws in an extra set of parentheses). But this might be a good starting point for writing your own generic functions.
20,740,442
I've come across a useful repo, but it's unmaintained and there are some good pull requests with bug fixes etc. that haven't been implemented. Is there anyway I can fork the repo and implement the pull requests into my forked repo?
2013/12/23
[ "https://Stackoverflow.com/questions/20740442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1437296/" ]
By using service you can achieve this.. ``` public void checkActivity() { handler = new Handler(); activityRunnable = new ActivityRunnable(); handler.postDelayed(activityRunnable, 500); } private class ActivityRunnable implements Runnable { @Override public void run() { ActivityManager manager = (ActivityManager) getApplicationContext() .getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1); if (runningTasks != null && runningTasks.size() > 0) { ComponentName topActivity = runningTasks.get(0).topActivity; // Here you can get the TopActivity for every 500ms if(!topActivity.getPackageName().equals(getPackageName())){ // Other Application is opened } handler.postDelayed(this, 500); } } } ``` Call the `checkActivity()` in onCreate of `service` and dont forgot to remove the `handler.removeCallbacks(activityRunnable);` callbacks in `onDestroy` start the service in LauncherActivity `onCreate` and stop the service in LauncherActivity `onDestroy` **Note**: Dont forgot to add the permission in your manifest ``` <uses-permission android:name="android.permission.GET_TASKS" /> ```
You should use Service for this. Then only you can achieve the background process..Please Go through about Services <http://developer.android.com/guide/components/services.html> and you can see this also <http://www.vogella.com/articles/AndroidServices/article.html> both URLs will help you
20,740,442
I've come across a useful repo, but it's unmaintained and there are some good pull requests with bug fixes etc. that haven't been implemented. Is there anyway I can fork the repo and implement the pull requests into my forked repo?
2013/12/23
[ "https://Stackoverflow.com/questions/20740442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1437296/" ]
By using service you can achieve this.. ``` public void checkActivity() { handler = new Handler(); activityRunnable = new ActivityRunnable(); handler.postDelayed(activityRunnable, 500); } private class ActivityRunnable implements Runnable { @Override public void run() { ActivityManager manager = (ActivityManager) getApplicationContext() .getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1); if (runningTasks != null && runningTasks.size() > 0) { ComponentName topActivity = runningTasks.get(0).topActivity; // Here you can get the TopActivity for every 500ms if(!topActivity.getPackageName().equals(getPackageName())){ // Other Application is opened } handler.postDelayed(this, 500); } } } ``` Call the `checkActivity()` in onCreate of `service` and dont forgot to remove the `handler.removeCallbacks(activityRunnable);` callbacks in `onDestroy` start the service in LauncherActivity `onCreate` and stop the service in LauncherActivity `onDestroy` **Note**: Dont forgot to add the permission in your manifest ``` <uses-permission android:name="android.permission.GET_TASKS" /> ```
The approach you are taking is wrong and prone to have your app rejected from the Google Play Store (plus it may stop working). Check [this thread](https://stackoverflow.com/questions/4414171/how-to-detect-when-an-android-app-goes-to-the-background-and-come-back-to-the-fo) to see possible ways to detect wether your app went to the background or not.
20,740,442
I've come across a useful repo, but it's unmaintained and there are some good pull requests with bug fixes etc. that haven't been implemented. Is there anyway I can fork the repo and implement the pull requests into my forked repo?
2013/12/23
[ "https://Stackoverflow.com/questions/20740442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1437296/" ]
By using service you can achieve this.. ``` public void checkActivity() { handler = new Handler(); activityRunnable = new ActivityRunnable(); handler.postDelayed(activityRunnable, 500); } private class ActivityRunnable implements Runnable { @Override public void run() { ActivityManager manager = (ActivityManager) getApplicationContext() .getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1); if (runningTasks != null && runningTasks.size() > 0) { ComponentName topActivity = runningTasks.get(0).topActivity; // Here you can get the TopActivity for every 500ms if(!topActivity.getPackageName().equals(getPackageName())){ // Other Application is opened } handler.postDelayed(this, 500); } } } ``` Call the `checkActivity()` in onCreate of `service` and dont forgot to remove the `handler.removeCallbacks(activityRunnable);` callbacks in `onDestroy` start the service in LauncherActivity `onCreate` and stop the service in LauncherActivity `onDestroy` **Note**: Dont forgot to add the permission in your manifest ``` <uses-permission android:name="android.permission.GET_TASKS" /> ```
instead of service Use receiver to receive the launch event and there you can implement this code.
70,610,424
This works: ``` mtcars[, c("mpg"), drop = F] mpg Mazda RX4 21.0 Mazda RX4 Wag 21.0 Datsun 710 22.8 Hornet 4 Drive 21.4 Hornet Sportabout 18.7 Valiant 18.1 Duster 360 14.3 Merc 240D 24.4 Merc 230 22.8 Merc 280 19.2 Merc 280C 17.8 Merc 450SE 16.4 Merc 450SL 17.3 Merc 450SLC 15.2 Cadillac Fleetwood 10.4 Lincoln Continental 10.4 Chrysler Imperial 14.7 Fiat 128 32.4 Honda Civic 30.4 Toyota Corolla 33.9 Toyota Corona 21.5 Dodge Challenger 15.5 AMC Javelin 15.2 Camaro Z28 13.3 Pontiac Firebird 19.2 Fiat X1-9 27.3 Porsche 914-2 26.0 Lotus Europa 30.4 Ford Pantera L 15.8 Ferrari Dino 19.7 Maserati Bora 15.0 Volvo 142E 21.4 ``` But this does not: ``` mtcars[, -c("mpg"), drop = F] Error in -c("mpg") : invalid argument to unary operator ```
2022/01/06
[ "https://Stackoverflow.com/questions/70610424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14802285/" ]
You can't make a string negative. `-"mpg"` causes an error. (`-` is a *unary operator*, as it only takes one argument. `-x` tries to make `x` negative, but `x` must be numeric or you will get this error. There are a handful of functions that allow you to use `-` on a column name like `base::subset` and `dplyr::select`, but they only work because of special handling under the hood.) If you want to remove the column from the original data, assigning `NULL` works well: ``` mtcars[["mpg"]] <- NULL ``` To make a copy of the data without a column, `setdiff` suggestion is good: ``` mtcars[, setdiff(names(mtcars), "mpg"), drop = FALSE] ```
Another suggestion: ``` names = names(mtcars) mtcars[, !names %in% names[1]] ``` **Output:** ``` cyl disp hp drat wt qsec vs am gear carb Mazda RX4 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 230 4 140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 280 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SL 8 275.8 180 3.07 3.730 17.60 0 0 3 3 Merc 450SLC 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Cadillac Fleetwood 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Chrysler Imperial 8 440.0 230 3.23 5.345 17.42 0 0 3 4 Fiat 128 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Honda Civic 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Toyota Corolla 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Dodge Challenger 8 318.0 150 2.76 3.520 16.87 0 0 3 2 AMC Javelin 8 304.0 150 3.15 3.435 17.30 0 0 3 2 Camaro Z28 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Pontiac Firebird 8 400.0 175 3.08 3.845 17.05 0 0 3 2 Fiat X1-9 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Porsche 914-2 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Lotus Europa 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ford Pantera L 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Ferrari Dino 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Maserati Bora 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Volvo 142E 4 121.0 109 4.11 2.780 18.60 1 1 4 2 ```
229,818
I am trying to chunk the results of a query of mine, but I am noticing the batches stop after 50,000 records (25 batches of 2000 records). I read iterable has a limit of 50,000 but I thought that was 50,000 records per batch. What are my options for being able to query and process all of my case records when recordtype 000 has over 50,000 records and record type 111 has over 50,000 records? **Execute Anonymous:** ``` Database.executeBatch(new batchClassExample(), 2000); ``` --- **Batch Class:** ``` global class batchClassExample implements Database.Batchable < Case > { List < string > exampleRecordTypeIds = new List < string > (); global batchClassExample() { string exampleRecordTypeIdString = '000XXX000XXX, 111XXX111XXX'; exampleRecordTypeIdString = exampleRecordTypeIdString.deleteWhitespace(); exampleRecordTypeIds = exampleRecordTypeIdString.split(','); } global Iterable < Case > start(Database.BatchableContext BC) { Integer count = Limits.getLimitQueryRows() - Limits.getQueryRows(); return [select Id, Owner.Id from case where RecordType.Id = :exampleRecordTypeIds LIMIT: count ]; } global void execute(Database.BatchableContext BC, List < Case > scope) { for (integer s = 0; s < scope.size(); s++) { system.debug(scope[s]); } } global void finish(Database.BatchableContext BC) { } } ```
2018/08/22
[ "https://salesforce.stackexchange.com/questions/229818", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/51210/" ]
Your start method is limited to 50,000 SOQL rows, except for your Database.QueryLocator, if you choose to use one. To get past this limit, use a Database.QueryLocator: ``` return (Iterable<Case>)Database.getQueryLocator([ select Id, Owner.Id from case where RecordType.Id = :exampleRecordTypeIds ]); ```
A batch can process up to 50 million records. Based on [documentation](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm) , I think you may want to change your code in the following ways: 1. Create a global string variable, call it "queryString" for example - which holds the query for both recordtypes (I.E 'Where RecordTypeId IN: recordTypeIds') 2. Change the start() method to return type DataBase.queryLocator, and within the start method call Database.queryLocator(queryString).
4,432
I have several lines, and each line has 2 quoted string, and I want to replace all space with "\_" for the first quoted string. How to do that? Could I use macro? ``` select 'a b c','a b c' union all select 'a e1 c d','a e1 c d' union all select 'a f11 c','a f11 c' union all select 'a g1 c','a g1 c' union ``` result: ``` select 'a_b_c','a b c' union all select 'a_e1_c_d','a e1 c d' union all select 'a_f11_c','a f11 c' union all select 'a_g1_c','a g1 c' union ```
2015/08/21
[ "https://vi.stackexchange.com/questions/4432", "https://vi.stackexchange.com", "https://vi.stackexchange.com/users/3262/" ]
You can create a new empty buffer in a new tab and then populate it with the result of a grep search on the previous file: ``` :tabnew|0r!grep -n pattern # ``` In a mapping: ``` nnoremap <key> :tabnew\|0r!grep -n #<Left><Left> ``` Which works like this: [![enter image description here](https://i.stack.imgur.com/bsoAY.gif)](https://i.stack.imgur.com/bsoAY.gif) --- edit --- Here is an alternative command that works with the current buffer instead of the current file: ``` :%y z|tabnew|0put=@z|%!grep -n pattern ``` Explanation: ``` :%y z " yank the whole buffer in register z :tabnew " edit a new buffer in a new tab :0put=@z " put the yanked text in that new buffer :%!grep -n pattern " do your filtering ``` As a command: ``` :command! -nargs=1 -range=% Filter <line1>,<line2>y z|tabnew|0put=@z|%!grep -n '<q-args>' ``` Usage: ``` :Filter pattern " works on the whole buffer by default :5,20Filter pattern " works on the supplied range ```
First clear an register: `qaq` second, append all matching lines using the `:g` command: ``` :g/pattern/y A ``` Third, put all matches on a new page ``` :tabnew +$put\ A ``` If you want to be able to make changes on those filtered mached, have a look at my [NrrwRgn Plugin](https://github.com/chrisbra/NrrwRgn). The advantage is, once you save the narrowed buffer, the changes will be taken back into the original buffer.
12,769,823
I'm re-implementing an app to support a national engineering contest, moving it from a local server to the cloud. In order to tell a team where they stand at the moment, the query has the form ``` select 1 + count(*) from team where where score < ? ``` Teams scores change very dynamically. There may be up to 2 million teams and I need to handle at least 10 of these queries per second. The original gets the needed performance (actually it already did with 1999 harware) by using a separate Berkeley DB of team/scores records. There is a "record number" feature in Berkeley DB that provides exactly the right functionality, and it's very fast. Heroku apparently has no way to support Berkeley DB. PostgreSQL, their standard DB, does `select count(*)` with a full table or index scan, which is way too slow. Any ideas on how to proceed? I am not wedded to Heroku, but must move to a cloud solution of some kind.
2012/10/07
[ "https://Stackoverflow.com/questions/12769823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161878/" ]
Create a rank table and update as frequently as adequate. Include the category (open or official) and score so you don't have to join it to the team table at query time: ``` create table "rank" ( team integer primary key, category integer, score integer, rank_consolidated integer, rank_category integer ); begin; truncate table "rank" ; insert into "rank" (team, category, score, rank_consolidated, rank_category) select team, category, score, rank() over(order by score desc) rank_consolidated, rank() over(partition by category order by score desc) rank_category from team ; commit ; select * from "rank" where team = 11; ``` As for the exact ranking behavior look into [window functions](http://www.postgresql.org/docs/9.2/interactive/functions-window.html)
Putting an index on score should avoid the full table scan.
12,769,823
I'm re-implementing an app to support a national engineering contest, moving it from a local server to the cloud. In order to tell a team where they stand at the moment, the query has the form ``` select 1 + count(*) from team where where score < ? ``` Teams scores change very dynamically. There may be up to 2 million teams and I need to handle at least 10 of these queries per second. The original gets the needed performance (actually it already did with 1999 harware) by using a separate Berkeley DB of team/scores records. There is a "record number" feature in Berkeley DB that provides exactly the right functionality, and it's very fast. Heroku apparently has no way to support Berkeley DB. PostgreSQL, their standard DB, does `select count(*)` with a full table or index scan, which is way too slow. Any ideas on how to proceed? I am not wedded to Heroku, but must move to a cloud solution of some kind.
2012/10/07
[ "https://Stackoverflow.com/questions/12769823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161878/" ]
Use [redis](http://redis.io) to store your team data in a `sorted set`. Then the [`ZRANK`](http://redis.io/commands/zrank) function will return the count you need. Redis is very fast in general, and the `ZRANK` function is O(log N) expected. It is implemented with skip lists.
Putting an index on score should avoid the full table scan.
12,769,823
I'm re-implementing an app to support a national engineering contest, moving it from a local server to the cloud. In order to tell a team where they stand at the moment, the query has the form ``` select 1 + count(*) from team where where score < ? ``` Teams scores change very dynamically. There may be up to 2 million teams and I need to handle at least 10 of these queries per second. The original gets the needed performance (actually it already did with 1999 harware) by using a separate Berkeley DB of team/scores records. There is a "record number" feature in Berkeley DB that provides exactly the right functionality, and it's very fast. Heroku apparently has no way to support Berkeley DB. PostgreSQL, their standard DB, does `select count(*)` with a full table or index scan, which is way too slow. Any ideas on how to proceed? I am not wedded to Heroku, but must move to a cloud solution of some kind.
2012/10/07
[ "https://Stackoverflow.com/questions/12769823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161878/" ]
Create a rank table and update as frequently as adequate. Include the category (open or official) and score so you don't have to join it to the team table at query time: ``` create table "rank" ( team integer primary key, category integer, score integer, rank_consolidated integer, rank_category integer ); begin; truncate table "rank" ; insert into "rank" (team, category, score, rank_consolidated, rank_category) select team, category, score, rank() over(order by score desc) rank_consolidated, rank() over(partition by category order by score desc) rank_category from team ; commit ; select * from "rank" where team = 11; ``` As for the exact ranking behavior look into [window functions](http://www.postgresql.org/docs/9.2/interactive/functions-window.html)
If it's read from a lot more heavily than it's written to and it always has to be up to date, then this is an ideal job for a trigger-maintained summary table (sort of a materialized view). Have a trigger on the `team` table that, `AFTER EACH INSERT OR UPDATE OR DELETE FOR EACH ROW` executes a trigger function that updates the `team_summary` table entry for that team with the new score. The `team_summary` table can be accessed via a simple, direct index lookup by equality so it'll be crazy fast. Since Pg supports simultaneous readers and writers the `team_summary` table will remain responsive even if it's being updated very frequently. The only thing you really need to do for best results is set `FILLFACTOR` to something like 50 in the `team_summary` table so that HOT can work well, and make sure autovacuum is set to run quite often to spread the load of the vacuum I/O churn. Writing the trigger should be pretty trivial. You just have to be careful to write a concurrency-safe trigger that won't break when you have concurrent updates to the same team by multiple concurrent connections. Something like: ``` UPDATE team_summary SET score = score + 1 WHERE team_id = NEW.team_id; ``` should be fine under both `SERIALIZABLE` and `READ COMMITTED` isolation. See [Concurrency control](http://www.postgresql.org/docs/current/static/mvcc.html). The only hard bit is that you must make sure to insert a new row into `team_summary` before inserting the first row for a new team into `team` so your trigger doesn't have to handle the surprisingly tricky case where the `team_summary` row might not yet exist in the `team` table. Getting the upsert/merge right for that is kind of tricky. If the write rate is also very high and you can get away with the results being updated only every few seconds/minutes, use Clodoaldo's approach instead.
12,769,823
I'm re-implementing an app to support a national engineering contest, moving it from a local server to the cloud. In order to tell a team where they stand at the moment, the query has the form ``` select 1 + count(*) from team where where score < ? ``` Teams scores change very dynamically. There may be up to 2 million teams and I need to handle at least 10 of these queries per second. The original gets the needed performance (actually it already did with 1999 harware) by using a separate Berkeley DB of team/scores records. There is a "record number" feature in Berkeley DB that provides exactly the right functionality, and it's very fast. Heroku apparently has no way to support Berkeley DB. PostgreSQL, their standard DB, does `select count(*)` with a full table or index scan, which is way too slow. Any ideas on how to proceed? I am not wedded to Heroku, but must move to a cloud solution of some kind.
2012/10/07
[ "https://Stackoverflow.com/questions/12769823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161878/" ]
Use [redis](http://redis.io) to store your team data in a `sorted set`. Then the [`ZRANK`](http://redis.io/commands/zrank) function will return the count you need. Redis is very fast in general, and the `ZRANK` function is O(log N) expected. It is implemented with skip lists.
Create a rank table and update as frequently as adequate. Include the category (open or official) and score so you don't have to join it to the team table at query time: ``` create table "rank" ( team integer primary key, category integer, score integer, rank_consolidated integer, rank_category integer ); begin; truncate table "rank" ; insert into "rank" (team, category, score, rank_consolidated, rank_category) select team, category, score, rank() over(order by score desc) rank_consolidated, rank() over(partition by category order by score desc) rank_category from team ; commit ; select * from "rank" where team = 11; ``` As for the exact ranking behavior look into [window functions](http://www.postgresql.org/docs/9.2/interactive/functions-window.html)
12,769,823
I'm re-implementing an app to support a national engineering contest, moving it from a local server to the cloud. In order to tell a team where they stand at the moment, the query has the form ``` select 1 + count(*) from team where where score < ? ``` Teams scores change very dynamically. There may be up to 2 million teams and I need to handle at least 10 of these queries per second. The original gets the needed performance (actually it already did with 1999 harware) by using a separate Berkeley DB of team/scores records. There is a "record number" feature in Berkeley DB that provides exactly the right functionality, and it's very fast. Heroku apparently has no way to support Berkeley DB. PostgreSQL, their standard DB, does `select count(*)` with a full table or index scan, which is way too slow. Any ideas on how to proceed? I am not wedded to Heroku, but must move to a cloud solution of some kind.
2012/10/07
[ "https://Stackoverflow.com/questions/12769823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161878/" ]
Use [redis](http://redis.io) to store your team data in a `sorted set`. Then the [`ZRANK`](http://redis.io/commands/zrank) function will return the count you need. Redis is very fast in general, and the `ZRANK` function is O(log N) expected. It is implemented with skip lists.
If it's read from a lot more heavily than it's written to and it always has to be up to date, then this is an ideal job for a trigger-maintained summary table (sort of a materialized view). Have a trigger on the `team` table that, `AFTER EACH INSERT OR UPDATE OR DELETE FOR EACH ROW` executes a trigger function that updates the `team_summary` table entry for that team with the new score. The `team_summary` table can be accessed via a simple, direct index lookup by equality so it'll be crazy fast. Since Pg supports simultaneous readers and writers the `team_summary` table will remain responsive even if it's being updated very frequently. The only thing you really need to do for best results is set `FILLFACTOR` to something like 50 in the `team_summary` table so that HOT can work well, and make sure autovacuum is set to run quite often to spread the load of the vacuum I/O churn. Writing the trigger should be pretty trivial. You just have to be careful to write a concurrency-safe trigger that won't break when you have concurrent updates to the same team by multiple concurrent connections. Something like: ``` UPDATE team_summary SET score = score + 1 WHERE team_id = NEW.team_id; ``` should be fine under both `SERIALIZABLE` and `READ COMMITTED` isolation. See [Concurrency control](http://www.postgresql.org/docs/current/static/mvcc.html). The only hard bit is that you must make sure to insert a new row into `team_summary` before inserting the first row for a new team into `team` so your trigger doesn't have to handle the surprisingly tricky case where the `team_summary` row might not yet exist in the `team` table. Getting the upsert/merge right for that is kind of tricky. If the write rate is also very high and you can get away with the results being updated only every few seconds/minutes, use Clodoaldo's approach instead.
56,318,103
I have a React-TypeScript SSR app where I used SCSS files for my styling. I need to write a rule in Webpack to load the SCSS and I haven't been able to do it. I found various solutions online, all of which are extremely complex and use things like mini-css-extract-plugin. I couldn't get any of them to work. I currently have two webpack config files, one for the client (web) and one for the server (node), both of which load the SCSS as such: ``` { test: /\.scss$/, use: ["css-loader", "sass-loader"] } ``` I also encountered another issue in that I can't use style-loader as it throws an error about the window object. Does anyone have a working example (simple preferably) of loading SCSS in Webpack?
2019/05/26
[ "https://Stackoverflow.com/questions/56318103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9448339/" ]
You are on right track with 2 web config file you can use <https://gist.github.com/mburakerman/629783c16acf5e5f03de60528d3139af> But don't set any other config file like babel.rc .yaml etc or other definition in project.json **try this** ``` test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader' ] ``` //.. ``` plugins: [ new MiniCssExtractPlugin({ filename: 'assets/css/bundle-[contenthash].css', chunkFilename: 'assets/css/bundle-[contenthash].css' }) ], ``` Look full example <https://github.com/dewelloper/pzone/blob/master/webpack.config.store.js>
A boilerplate for server-side rendering using `react`, `webpack`, `Sass` (for both css-modules and pure sass) webpack.config.js ``` const path = require('path'); const isDevelopment = true; module.exports = [ { name: 'client', target: 'web', entry: './client.jsx', output: { path: path.join(__dirname, 'static'), filename: 'client.js', publicPath: '/static/', }, resolve: { extensions: ['.js', '.jsx'] }, devtool: 'source-map', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /(node_modules\/)/, use: [ { loader: 'babel-loader', } ] }, { test: /\.scss$/, use: [ { loader: 'style-loader', }, { loader: "css-loader", options: { modules: { localIdentName: "[name]__[local]___[hash:base64:5]", }, sourceMap: isDevelopment, } }, { loader: 'sass-loader' } ] } ], }, }, { name: 'server', target: 'node', entry: './server.jsx', output: { path: path.join(__dirname, 'static'), filename: 'server.js', libraryTarget: 'commonjs2', publicPath: '/static/', }, devtool: 'source-map', resolve: { extensions: ['.js', '.jsx'] }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /(node_modules\/)/, use: [ { loader: 'babel-loader', } ] }, { test: /\.scss$/, use: [ { loader: 'isomorphic-style-loader', }, { loader: "css-loader", options: { modules: { localIdentName: "[name]__[local]___[hash:base64:5]", }, sourceMap: isDevelopment, } }, { loader: 'sass-loader' } ] } ], }, } ]; ``` dev dependencies: ``` npm i -D @babel/cli @babel/preset-es2015 @babel/core @babel/plugin-proposal-class-properties @babel/preset-env @babel/preset-react babel-core babel-loader babel-plugin-lodash babel-plugin-react-transform babel-preset-env babel-preset-es2015 babel-preset-react babel-preset-stage-0 css-loader express isomorphic-style-loader node-sass sass-loader style-loader webpack webpack-dev-middleware webpack-hot-middleware webpack-hot-server-middleware ``` and dependencies: ``` npm i react react-dom react-helmet react-router-dom ``` sever.jsx: ``` import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { StaticRouter } from 'react-router-dom'; import {Helmet} from "react-helmet"; import Template from './template'; import App from './App'; export default function serverRenderer({ clientStats, serverStats }) { return (req, res, next) => { const context = {}; const markup = ReactDOMServer.renderToString( <StaticRouter location={ req.url } context={ context }> <App /> </StaticRouter> ); const helmet = Helmet.renderStatic(); res.status(200).send(Template({ markup: markup, helmet: helmet, })); }; } ``` App.jsx: ``` import React, { Component } from 'react'; import { Switch, Route } from 'react-router-dom'; import Menu from './Menu' import Helmet from "react-helmet"; import homepageStyles from './homepage.scss'; class Homepage extends Component { render() { return ( <div className={ homepageStyles.component }> <Helmet title="Welcome to our Homepage" /> <Menu /> <h1>Homepage</h1> </div> ); } } class About extends Component { render() { return ( <div> <h1>About</h1> </div> ); } } class Contact extends Component { render() { return ( <div> <h1>Contact</h1> </div> ); } } export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <Helmet htmlAttributes={{lang: "en", amp: undefined}} // amp takes no value titleTemplate="%s | React App" titleAttributes={{itemprop: "name", lang: "en"}} meta={[ {name: "description", content: "Server side rendering example"}, {name: "viewport", content: "width=device-width, initial-scale=1"}, ]} /> <Switch> <Route exact path='/' component={ Homepage } /> <Route path="/about" component={ About } /> <Route path="/contact" component={ Contact } /> </Switch> </div> ); } } ``` template.jsx ``` export default ({ markup, helmet }) => { return `<!doctype html> <html ${helmet.htmlAttributes.toString()}> <head> ${helmet.title.toString()} ${helmet.meta.toString()} ${helmet.link.toString()} </head> <body ${helmet.bodyAttributes.toString()}> <div id="root">${markup}</div> <div>Heeeeeeeeeeeeeeeeeeeelmet</div> <script src="/static/client.js" async></script> </body> </html>`; }; ``` menu.jsx: ``` import { Link } from 'react-router-dom'; import React, { Component } from 'react'; import './menu.scss'; class Menu extends Component { render() { return ( <div> <ul> <li> <Link to={'/'}>Homepage</Link> </li> <li> <Link to={'/about'}>About</Link> </li> <li> <Link to={'/contact'}>Contact</Link> </li> </ul> </div> ); } } export default Menu; ``` .babelrc: ``` { "presets": [ "@babel/react", "@babel/preset-env" ], "plugins": [ "@babel/proposal-class-properties" ] } ``` homepage.sccs ``` .component { color: blue; } ``` menu.scss: ``` li { background-color: yellow; } ``` I used this article: <https://blog.digitalkwarts.com/server-side-rendering-with-reactjs-react-router-v4-react-helmet-and-css-modules/>
56,318,103
I have a React-TypeScript SSR app where I used SCSS files for my styling. I need to write a rule in Webpack to load the SCSS and I haven't been able to do it. I found various solutions online, all of which are extremely complex and use things like mini-css-extract-plugin. I couldn't get any of them to work. I currently have two webpack config files, one for the client (web) and one for the server (node), both of which load the SCSS as such: ``` { test: /\.scss$/, use: ["css-loader", "sass-loader"] } ``` I also encountered another issue in that I can't use style-loader as it throws an error about the window object. Does anyone have a working example (simple preferably) of loading SCSS in Webpack?
2019/05/26
[ "https://Stackoverflow.com/questions/56318103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9448339/" ]
You are on right track with 2 web config file you can use <https://gist.github.com/mburakerman/629783c16acf5e5f03de60528d3139af> But don't set any other config file like babel.rc .yaml etc or other definition in project.json **try this** ``` test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader' ] ``` //.. ``` plugins: [ new MiniCssExtractPlugin({ filename: 'assets/css/bundle-[contenthash].css', chunkFilename: 'assets/css/bundle-[contenthash].css' }) ], ``` Look full example <https://github.com/dewelloper/pzone/blob/master/webpack.config.store.js>
Webpack Community now details an approach for SSR sass compiled via webpack in [mini-css-extract-plugin/#recommend](https://webpack.js.org/plugins/mini-css-extract-plugin/#recommend) ``` const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const devMode = process.env.NODE_ENV !== "production"; module.exports = { module: { rules: [ { test: /\.(sa|sc|c)ss$/, use: [ devMode ? "style-loader" : MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader", ], }, ], }, plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]), }; ``` Note that `style-loader` should not be used in an SSR app or in a webpack production build because injects CSS into the DOM. MiniCSSExtractPlugin is recommended for SSR production builds and should not be used with `style-loader` (window will not be defined in webpack's node-based prod build).
11,409,201
I'm writing an application in Java/Android.In my application I consume a wcf web service using KSOAP2.My problem is that there are times that instead of a single string I could receive an object (or arrays of objects) which are defined in the c# web services.Is there any way I can process these objects?If it helps I can tell you that I know how the classes of these objects are defined in the c#.
2012/07/10
[ "https://Stackoverflow.com/questions/11409201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514105/" ]
Okay I figured this out in fact I found out 2 articles about it with really explicit tutorials I will just post them here in case anyone stumbles upon this post [link](http://seesharpgears.blogspot.gr/2010/10/ksoap-android-web-service-tutorial-with.html?commentPage=2) and [link](http://seesharpgears.blogspot.gr/2010/10/web-service-that-returns-array-of.html)
> > Is there any way I can process these objects? > > > Define "process". Using webservices, you transmit serialized objects, which are (usually) an XML representation of the objects in the language at either end (service or client). If you define a class `Person` with a property `Name`, you can return an object of this class from a service. The client consuming this service will have to use a framework or built-in mechanism to deserialize the service classes to objects. You'll probably have to generate classes for those objects in Java, using the WSDL the C# service generates.
2,377,602
I am asked if the ideal $I = \left \{ \left ( x,7y \right ): x,y \in \mathbb{Z} \right \}$ of a ring R= $\mathbb{Z}\oplus \mathbb{Z}$ is a prime ideal. Looking at the factor ring, $\mathbb{Z}\oplus \mathbb{Z} / I $, there exists zero-divisors; in particular $\left ( x\_{1},0 \right ) and \left ( 0,y\_{2} \right ) \in \mathbb{Z}\bigoplus \mathbb{Z} \forall$ $x\_{1}, y\_{2}$ non-zero. Hence, there exists a zero-divisor and hence the factor ring is not an integral domain and so the ideal $I$ is not prime. However, my solution says the factor ring is an integral domain. Am I wrong or is my solution wrong?
2017/07/31
[ "https://math.stackexchange.com/questions/2377602", "https://math.stackexchange.com", "https://math.stackexchange.com/users/227967/" ]
Note that the zero element of $\mathbb{Z}\oplus \mathbb{Z} / I $ is $I=0+I.$ Let $$((x\_1,y\_1)+I)((x\_2,y\_2)+I)=0+I$$ Then $$(x\_1x\_2,y\_1y\_2)\in I$$ Thus $$7\mid y\_1y\_2$$ As $7$ is prime, therefore $7 \mid y\_1$ or $7 \mid y\_2$. Hence, $(x\_1,y\_1) \in I$ or $(x\_2,y\_2)\in I$. So, $(x\_1,y\_1)+I = 0 + I$ or $(x\_2,y\_2)+I=0+I$. So, $\mathbb{Z}\oplus \mathbb{Z} / I $ is an integral domain.
It would be a good exercise to prove the following results. > > **Result-1:** In $\Bbb Z \times \Bbb Z$ the prime ideals are of the form, $\Bbb Z/p\Bbb Z\times \Bbb Z$ or $\Bbb Z\times\Bbb Z/p\Bbb Z $ where $p$ is prime. > > > In fact you can generalize the above result as follows. > > **Result-2:** Let $R\_i$ be a comutative ring with unity for each $i=1,...,n$. The prime ideals of $R\_1\times ...\times R\_n$ are of the form $P\_1\times...\times P\_n$ where for some $j$, $P\_j$ is a prime ideal of $R\_j$ and $ P\_i=R\_i$ for $i\not=j$. > > > In your case, $I=\Bbb Z \times \Bbb Z/7\Bbb Z$. Hence it follows that $I$ is a prime ideal.
50,906,497
Since the update from 4.2.0 to 4.3.0, publishing the sonar qube results fail with this error for my react application: ``` 2018-06-18T07:35:56.8644128Z ##[section]Starting: Publish Quality Gate Result 2018-06-18T07:35:56.8648466Z ============================================================================== 2018-06-18T07:35:56.8648887Z Task : Publish Quality Gate Result 2018-06-18T07:35:56.8649287Z Description : Publish SonarQube's Quality Gate result on the VSTS/TFS build result, to be used after the actual analysis. 2018-06-18T07:35:56.8649650Z Version : 4.3.0 2018-06-18T07:35:56.8649925Z Author : sonarsource 2018-06-18T07:35:56.8650254Z Help : [More Information](http://redirect.sonarsource.com/doc/install-configure-scanner-tfs-ts.html) 2018-06-18T07:35:56.8650681Z ============================================================================== 2018-06-18T07:36:05.4520694Z ##[error][SQ] API GET '/api/ce/task' failed, status code was: 404 2018-06-18T07:36:05.4531287Z ##[error][SQ] Could not fetch task for ID 'AV6EiGo9XAfivOz6jp5l' 2018-06-18T07:36:05.4532808Z ##[error][SQ] API GET '/api/ce/task' failed, status code was: 404 2018-06-18T07:36:05.4534300Z ##[error][SQ] API GET '/api/ce/task' failed, status code was: 404 2018-06-18T07:36:05.5248790Z ##[section]Finishing: Publish Quality Gate Result ``` Found some similar errors on StackOverflow, but they seems to be more related to authentication. Is it a bug in the VSTS task or is there a workaround? **UPDATE: Some more detailed logs** ``` serverVersion=6.7.3.38370 dashboardUrl=https://XXXXXX/dashboard/index/XXXXXXcmp-ui-dev ceTaskId=AWQXyd5mNr8GlRD53mvW ceTaskUrl=https://XXXXXX/api/ce/task?id=AWQXyd5mNr8GlRD53mvW 2018-06-19T11:24:35.6562477Z ##[debug][SQ] Parse Task report file: projectKey=sonarqube-scanner serverUrl=http://localhost:9000 serverVersion=6.5.0.27846 dashboardUrl=http://localhost:9000/dashboard/index/sonarqube-scanner ceTaskId=AV6EiGo9XAfivOz6jp5l ceTaskUrl=http://localhost:9000/api/ce/task?id=AV6EiGo9XAfivOz6jp5l 2018-06-19T11:24:35.6564194Z ##[debug][SQ] Parse Task report file: projectKey=sonarqube-scanner serverUrl=http://localhost:9000 dashboardUrl=http://localhost:9000/dashboard/index/sonarqube-scanner ceTaskId=AViCXLBOyOPDYliRRPPD ceTaskUrl=http://localhost:9000/api/ce/task?id=AViCXLBOyOPDYliRRPPD 2018-06-19T11:24:35.6579126Z ##[debug][SQ] Parse Task report file: projectKey=dist serverUrl=http://localhost:9000 serverVersion=6.5.0.27846 dashboardUrl=http://localhost:9000/dashboard/index/dist ceTaskId=AV2jO_7EtQnci7vN0TrW ceTaskUrl=http://localhost:9000/api/ce/task?id=AV2jO_7EtQnci7vN0TrW ##[debug][SQ] Waiting for task 'AWQXyd5mNr8GlRD53mvW' to complete. ##[debug][SQ] API GET: '/api/ce/task' with query "{"id":"AWQXyd5mNr8GlRD53mvW"}" ##[debug][SQ] Waiting for task 'AV6EiGo9XAfivOz6jp5l' to complete. ##[debug][SQ] API GET: '/api/ce/task' with query "{"id":"AV6EiGo9XAfivOz6jp5l"}" ##[debug][SQ] Waiting for task 'AViCXLBOyOPDYliRRPPD' to complete. ##[debug][SQ] API GET: '/api/ce/task' with query "{"id":"AViCXLBOyOPDYliRRPPD"}" ##[debug][SQ] Waiting for task 'AV2jO_7EtQnci7vN0TrW' to complete. ##[debug][SQ] API GET: '/api/ce/task' with query "{"id":"AV2jO_7EtQnci7vN0TrW"}" ##[debug]Response: 404 Body: "{"errors":[{"msg":"No activity found for task 'AV6EiGo9XAfivOz6jp5l'"}]}" ##[debug][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[error][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[debug]Processed: ##vso[task.issue type=error;][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[debug][SQ] Publish task error: [SQ] Could not fetch task for ID 'AV6EiGo9XAfivOz6jp5l' ##[debug]task result: Failed ##[error][SQ] Could not fetch task for ID 'AV6EiGo9XAfivOz6jp5l' ##[debug]Processed: ##vso[task.issue type=error;][SQ] Could not fetch task for ID 'AV6EiGo9XAfivOz6jp5l' ##[debug]Processed: ##vso[task.complete result=Failed;][SQ] Could not fetch task for ID 'AV6EiGo9XAfivOz6jp5l' ##[debug]Response: 200 Body: "{"task":{"id":"AWQXyd5mNr8GlRD53mvW","type":"REPORT","componentId":"AWPvWj0KNr8GlRD53mu0","componentKey":"XXXXXXcmp-ui-dev","componentName":"CMP Development UI","componentQualifier":"TRK","analysisId":"AWQXyeRvZSHmKx_UWZLd","status":"SUCCESS","submittedAt":"2018-06-19T11:24:23+0000","submitterLogin":"XXXXXX","startedAt":"2018-06-19T11:24:23+0000","executedAt":"2018-06-19T11:24:29+0000","executionTimeMs":5631,"logs":false,"hasScannerContext":true,"organization":"default-organization"}}" ##[debug][SQ] Task status:SUCCESS ##[debug][SQ] Task complete: {"id":"AWQXyd5mNr8GlRD53mvW","type":"REPORT","componentId":"AWPvWj0KNr8GlRD53mu0","componentKey":"XXXXXXcmp-ui-dev","componentName":"CMP Development UI","componentQualifier":"TRK","analysisId":"AWQXyeRvZSHmKx_UWZLd","status":"SUCCESS","submittedAt":"2018-06-19T11:24:23+0000","submitterLogin":"XXXXXX","startedAt":"2018-06-19T11:24:23+0000","executedAt":"2018-06-19T11:24:29+0000","executionTimeMs":5631,"logs":false,"hasScannerContext":true,"organization":"default-organization"} ##[debug][SQ] Retrieve Analysis id 'AWQXyeRvZSHmKx_UWZLd.' ##[debug][SQ] API GET: '/api/qualitygates/project_status' with query "{"analysisId":"AWQXyeRvZSHmKx_UWZLd"}" ##[debug]Response: 200 Body: "{"projectStatus":{"status":"ERROR","conditions":[{"status":"ERROR","metricKey":"coverage","comparator":"LT","errorThreshold":"18","actualValue":"0.0"},{"status":"OK","metricKey":"new_reliability_rating","comparator":"GT","periodIndex":1,"warningThreshold":"1","actualValue":"1"},{"status":"OK","metricKey":"new_security_rating","comparator":"GT","periodIndex":1,"actualValue":"1"},{"status":"OK","metricKey":"sqale_rating","comparator":"GT","warningThreshold":"1","actualValue":"1"},{"status":"ERROR","metricKey":"new_coverage","comparator":"LT","periodIndex":1,"errorThreshold":"25","actualValue":"0.0"}],"periods":[{"index":1,"mode":"previous_version","date":"2018-06-11T14:56:55+0000"}],"ignoredConditions":false}}" ##[debug][SQ] Generate analysis report.' ##[debug]Response: 404 Body: "{"errors":[{"msg":"No activity found for task 'AV2jO_7EtQnci7vN0TrW'"}]}" ##[debug][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[error][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[debug]Processed: ##vso[task.issue type=error;][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[debug]Response: 404 Body: "{"errors":[{"msg":"No activity found for task 'AViCXLBOyOPDYliRRPPD'"}]}" ##[debug][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[error][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[debug]Processed: ##vso[task.issue type=error;][SQ] API GET '/api/ce/task' failed, status code was: 404 ##[section]Finishing: Publish Quality Gate Result ``` **UPDATE: Definition** [![prepare](https://i.stack.imgur.com/KXakR.png)](https://i.stack.imgur.com/KXakR.png) [![sources dir](https://i.stack.imgur.com/IhjCu.png)](https://i.stack.imgur.com/IhjCu.png) **UPDATE: Details of the analysis task** ``` ##[debug]Evaluating condition for step: 'Run Code Analysis' ##[debug]Evaluating: succeeded() ##[debug]Evaluating succeeded: ##[debug]=> True ##[debug]Result: True ##[section]Starting: Run Code Analysis ============================================================================== Task : Run Code Analysis Description : Run scanner and upload the results to the SonarQube server. Version : 4.3.0 Author : sonarsource Help : This task is not needed for Maven and Gradle projects since the scanner should be run as part of the build. [More Information](http://redirect.sonarsource.com/doc/install-configure-scanner-tfs-ts.html) ============================================================================== ##[debug]agent.TempDirectory=E:\VSTSAgent-XXXXXX\_work\_temp ##[debug]loading inputs and endpoints ##[debug]loading ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN ##[debug]loading ENDPOINT_AUTH_SCHEME_SYSTEMVSSCONNECTION ##[debug]loading ENDPOINT_AUTH_SYSTEMVSSCONNECTION ##[debug]loading SECRET_SONARQUBE_ENDPOINT ##[debug]loaded 4 ##[debug]Agent.ProxyUrl=undefined ##[debug]Agent.CAInfo=undefined ##[debug]Agent.ClientCert=undefined ##[debug]Agent.SkipCertValidation=undefined ##[debug]SONARQUBE_SCANNER_MODE=CLI ##[debug]Absolute path for pathSegments: E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0,sonar-scanner,bin,sonar-scanner = E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner ##[debug]which 'E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat' ##[debug]found: 'E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat' ##[debug]which 'E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat' ##[debug]found: 'E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat' ##[debug]system.debug=true ##[debug]E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat arg: -X ##[debug]exec tool: E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat ##[debug]arguments: ##[debug] -X [command]C:\Windows\system32\cmd.exe /D /S /C "E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\sonar-scanner.bat -X" INFO: Scanner configuration file: E:\VSTSAgent-XXXXXX\_work\_tasks\SonarQubeAnalyze_6d01813a-9589-4b15-8491-8164aeb38055\4.3.0\sonar-scanner\bin\..\conf\sonar-scanner.properties INFO: Project root configuration file: NONE INFO: SonarQube Scanner 3.2.0.1227 INFO: Java 1.8.0_171 Oracle Corporation (64-bit) INFO: Windows Server 2016 10.0 amd64 DEBUG: keyStore is : DEBUG: keyStore type is : jks DEBUG: keyStore provider is : DEBUG: init keystore DEBUG: init keymanager of type SunX509 DEBUG: Create: C:\Windows\ServiceProfiles\NetworkService\.sonar\cache INFO: User cache: C:\Windows\ServiceProfiles\NetworkService\.sonar\cache DEBUG: Create: C:\Windows\ServiceProfiles\NetworkService\.sonar\cache\_tmp DEBUG: Extract sonar-scanner-api-batch in temp... DEBUG: Get bootstrap index... DEBUG: Download: https://XXXXXX.com/batch/index DEBUG: Get bootstrap completed DEBUG: Create isolated classloader... DEBUG: Start temp cleaning... DEBUG: Temp cleaning done DEBUG: Execution getVersion INFO: SonarQube server 6.7.3 INFO: Default locale: "en_US", source code encoding: "windows-1252" (analysis is platform dependent) DEBUG: Work directory: E:\VSTSAgent-XXXXXX\_work\4\s\.scannerwork DEBUG: Execution execute INFO: Publish mode INFO: Load global settings DEBUG: GET 200 https://XXXXXX.com/api/settings/values.protobuf | time=172ms INFO: Load global settings (done) | time=219ms INFO: Server id: AWKRJbujkvyHj7QIqwwz INFO: User cache: C:\Windows\ServiceProfiles\NetworkService\.sonar\cache INFO: Load plugins index DEBUG: GET 200 https://XXXXXX.com/api/plugins/installed | time=15ms INFO: Load plugins index (done) | time=62ms DEBUG: Load plugins DEBUG: Load plugins (done) | time=47ms DEBUG: Plugins: DEBUG: * SonarPython 1.9.1.2080 (python) DEBUG: * Azure Active Directory (AAD) Authentication Plug-in for SonarQube 1.0 (authaad) DEBUG: * Svn 1.7.0.1017 (scmsvn) DEBUG: * SonarJS 4.1.0.6085 (javascript) DEBUG: * SonarC# 7.0.1.4822 (csharp) DEBUG: * SonarJava 5.2.0.13398 (java) DEBUG: * SonarWeb 2.6.0.1053 (web) DEBUG: * Git 1.4.0.1037 (scmgit) DEBUG: * SonarFlex 2.4.0.1222 (flex) DEBUG: * SonarXML 1.5.0.1373 (xml) DEBUG: * SonarPHP 2.13.0.3107 (php) DEBUG: * SonarTS 1.6.0.2388 (typescript) INFO: Process project properties DEBUG: Process project properties (done) | time=15ms INFO: Load project repositories DEBUG: GET 200 https://XXXXXX.com/batch/project.protobuf?key=XXXXXX-dev | time=47ms INFO: Load project repositories (done) | time=109ms DEBUG: Available languages: DEBUG: * Python => "py" DEBUG: * JavaScript => "js" DEBUG: * C# => "cs" DEBUG: * Java => "java" DEBUG: * Web => "web" DEBUG: * Flex => "flex" DEBUG: * XML => "xml" DEBUG: * PHP => "php" DEBUG: * TypeScript => "ts" INFO: Load quality profiles DEBUG: GET 200 https://XXXXXX.com/api/qualityprofiles/search.protobuf?projectKey=XXXXXX-dev | time=93ms INFO: Load quality profiles (done) | time=93ms INFO: Load active rules DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJphzkvyHj7QIqxLM&p=1&ps=500 | time=421ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJqUlkvyHj7QIqxSs&p=1&ps=500 | time=500ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRRrIwhnDVpZCHB5jb&p=1&ps=500 | time=40ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJq2xkvyHj7QIqxYS&p=1&ps=500 | time=32ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJqxokvyHj7QIqxXT&p=1&ps=500 | time=46ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJrTlkvyHj7QIqxd4&p=1&ps=500 | time=157ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJrdokvyHj7QIqxf3&p=1&ps=500 | time=130ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJsMgkvyHj7QIqxio&p=1&ps=500 | time=94ms DEBUG: GET 200 https://XXXXXX.com/api/rules/search.protobuf?f=repo,name,severity,lang,internalKey,templateKey,params,actives,createdAt&activation=true&qprofile=AWKRJsfzkvyHj7QIqxjs&p=1&ps=500 | time=188ms INFO: Load active rules (done) | time=1834ms INFO: Load metrics repository DEBUG: GET 200 https://XXXXXX.com/api/metrics/search?f=name,description,direction,qualitative,custom&ps=500&p=1 | time=16ms INFO: Load metrics repository (done) | time=79ms INFO: Project key: XXXXXX-dev DEBUG: Start recursive analysis of project modules INFO: ------------- Scan CMP Development UI INFO: Load server rules DEBUG: GET 200 https://XXXXXX.com/api/rules/list.protobuf | time=94ms INFO: Load server rules (done) | time=125ms INFO: Base dir: E:\VSTSAgent-XXXXXX\_work\4\s INFO: Working dir: E:\VSTSAgent-XXXXXX\_work\4\s\.scannerwork INFO: Source paths: src INFO: Source encoding: windows-1252, default locale: en_US DEBUG: Declared extensions of language Python were converted to sonar.lang.patterns.py : **/*.py DEBUG: Declared extensions of language JavaScript were converted to sonar.lang.patterns.js : **/*.js,**/*.jsx,**/*.vue DEBUG: Declared extensions of language C# were converted to sonar.lang.patterns.cs : **/*.cs DEBUG: Declared extensions of language Java were converted to sonar.lang.patterns.java : **/*.java,**/*.jav DEBUG: Declared extensions of language Web were converted to sonar.lang.patterns.web : **/*.html,**/*.xhtml,**/*.rhtml,**/*.shtml DEBUG: Declared extensions of language Flex were converted to sonar.lang.patterns.flex : **/*.as DEBUG: Declared extensions of language XML were converted to sonar.lang.patterns.xml : **/*.xml,**/*.xsd,**/*.xsl DEBUG: Declared extensions of language PHP were converted to sonar.lang.patterns.php : **/*.php,**/*.php3,**/*.php4,**/*.php5,**/*.phtml,**/*.inc DEBUG: Declared extensions of language TypeScript were converted to sonar.lang.patterns.ts : **/*.ts,**/*.tsx DEBUG: Initializers : INFO: Index files INFO: Excluded sources: INFO: **/node_modules/** INFO: **/*.test.tsx INFO: **/*.test.ts INFO: **/*.test.js DEBUG: 'src\components\App\App.css' indexed with language 'null' DEBUG: 'src\components\App\App.scss' indexed with language 'null' DEBUG: 'src\components\App\App.tsx' indexed with language 'ts' DEBUG: 'src\components\Footer\Footer.css' indexed with language 'null' DEBUG: 'src\components\Footer\Footer.scss' indexed with language 'null' DEBUG: 'src\components\Footer\Footer.tsx' indexed with language 'ts' DEBUG: 'src\components\Header\Header.css' indexed with language 'null' DEBUG: 'src\components\Header\Header.scss' indexed with language 'null' DEBUG: 'src\components\Header\Header.tsx' indexed with language 'ts' DEBUG: 'src\components\PendingIssues\Actions.ts' indexed with language 'ts' DEBUG: 'src\components\PendingIssues\index.ts' indexed with language 'ts' DEBUG: 'src\components\PendingIssues\Models.ts' indexed with language 'ts' DEBUG: 'src\components\PendingIssues\PendingIssues.tsx' indexed with language 'ts' DEBUG: 'src\components\PendingIssues\Reducer.ts' indexed with language 'ts' DEBUG: 'src\index.css' indexed with language 'null' DEBUG: 'src\index.scss' indexed with language 'null' DEBUG: 'src\index.tsx' indexed with language 'ts' DEBUG: 'src\logo.svg' indexed with language 'null' DEBUG: 'src\registerServiceWorker.ts' indexed with language 'ts' DEBUG: 'src\screens\Home.tsx' indexed with language 'ts' DEBUG: 'src\store\index.ts' indexed with language 'ts' DEBUG: 'src\store\root-action.ts' indexed with language 'ts' DEBUG: 'src\store\root-epic.ts' indexed with language 'ts' DEBUG: 'src\store\root-reducer.ts' indexed with language 'ts' DEBUG: 'src\store\store.ts' indexed with language 'ts' DEBUG: 'src\styles\_theme.scss' indexed with language 'null' INFO: 26 files indexed INFO: 1 file ignored because of inclusion/exclusion patterns INFO: Quality profile for ts: Sonar way DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing DEBUG: 'Python Squid Sensor' skipped because there is no related file in current project DEBUG: 'PylintSensor' skipped because there is no related file in current project DEBUG: 'PylintImportSensor' skipped because there is no related file in current project DEBUG: 'PythonXUnitSensor' skipped because there is no related file in current project DEBUG: 'SonarJS' skipped because there is no related file in current project DEBUG: 'SonarJS Coverage' skipped because there is no related file in current project DEBUG: 'C#' skipped because there is no related file in current project DEBUG: 'C# Properties' skipped because there is no related file in current project DEBUG: 'C# Tests Coverage Report Import' skipped because there is no related file in current project DEBUG: '[Deprecated] C# Integration Tests Coverage Report Import' skipped because there is no related file in current project DEBUG: 'C# Unit Test Results Import' skipped because there is no related file in current project DEBUG: 'SurefireSensor' skipped because there is no related file in current project DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project DEBUG: 'Web' skipped because there is no related file in current project DEBUG: 'Flex' skipped because there is no related file in current project DEBUG: 'Flex Cobertura' skipped because there is no related file in current project DEBUG: 'XML Sensor' skipped because there is no related file in current project DEBUG: 'PHP sensor' skipped because there is no related file in current project DEBUG: 'Analyzer for "php.ini" files' skipped because there is no related file in current project DEBUG: 'Generic Coverage Report' skipped because one of the required properties is missing DEBUG: 'Generic Test Executions Report' skipped because one of the required properties is missing DEBUG: 'Python Squid Sensor' skipped because there is no related file in current project DEBUG: 'PylintSensor' skipped because there is no related file in current project DEBUG: 'PylintImportSensor' skipped because there is no related file in current project DEBUG: 'PythonXUnitSensor' skipped because there is no related file in current project DEBUG: 'SonarJS' skipped because there is no related file in current project DEBUG: 'SonarJS Coverage' skipped because there is no related file in current project DEBUG: 'C#' skipped because there is no related file in current project DEBUG: 'C# Properties' skipped because there is no related file in current project DEBUG: 'C# Tests Coverage Report Import' skipped because there is no related file in current project DEBUG: '[Deprecated] C# Integration Tests Coverage Report Import' skipped because there is no related file in current project DEBUG: 'C# Unit Test Results Import' skipped because there is no related file in current project DEBUG: 'SurefireSensor' skipped because there is no related file in current project DEBUG: 'JaCoCoSensor' skipped because there is no related file in current project DEBUG: 'JavaSquidSensor' skipped because there is no related file in current project DEBUG: 'Web' skipped because there is no related file in current project DEBUG: 'Flex' skipped because there is no related file in current project DEBUG: 'Flex Cobertura' skipped because there is no related file in current project DEBUG: 'XML Sensor' skipped because there is no related file in current project DEBUG: 'PHP sensor' skipped because there is no related file in current project DEBUG: 'Analyzer for "php.ini" files' skipped because there is no related file in current project DEBUG: Sensors : SonarJavaXmlFileSensor -> SonarTS -> SonarTS Coverage -> Zero Coverage Sensor -> CPD Block Indexer INFO: Sensor SonarJavaXmlFileSensor [java] INFO: Sensor SonarJavaXmlFileSensor [java] (done) | time=0ms INFO: Sensor SonarTS [typescript] DEBUG: TypeScript compiler is found in this directory E:\VSTSAgent-XXXXXX\_work\4\s\node_modules DEBUG: It will be used for analysis of typescript files DEBUG: Deploying bundle from `/sonarts-bundle.zip` to `E:\VSTSAgent-XXXXXX\_work\4\s\.scannerwork` DEBUG: Checking node version DEBUG: Using Node.js v8.11.1 DEBUG: Analyzing 16 typescript file(s) with the following configuration file E:\VSTSAgent-XXXXXX\_work\4\s\tsconfig.json DEBUG: Setting 'NODE_PATH' to E:\VSTSAgent-XXXXXX\_work\4\s\node_modules DEBUG: Starting external process `node --max-old-space-size=2048 E:\VSTSAgent-XXXXXX\_work\4\s\.scannerwork\sonarts-bundle\node_modules\tslint-sonarts\bin\tsrunner` DEBUG: 'src/components/App/App.tsx' generated metadata with charset 'windows-1252' DEBUG: 'src/components/Footer/Footer.tsx' generated metadata with charset 'UTF-8' DEBUG: 'src/components/Header/Header.tsx' generated metadata with charset 'UTF-8' DEBUG: 'src/components/PendingIssues/Actions.ts' generated metadata with charset 'windows-1252' DEBUG: Not enough content in 'src/components/PendingIssues/Actions.ts' to have CPD blocks, it will not be part of the duplication detection DEBUG: 'src/components/PendingIssues/Models.ts' generated metadata with charset 'windows-1252' DEBUG: Not enough content in 'src/components/PendingIssues/Models.ts' to have CPD blocks, it will not be part of the duplication detection DEBUG: 'src/components/PendingIssues/PendingIssues.tsx' generated metadata with charset 'windows-1252' DEBUG: 'src/components/PendingIssues/Reducer.ts' generated metadata with charset 'windows-1252' DEBUG: 'src/components/PendingIssues/index.ts' generated metadata with charset 'windows-1252' DEBUG: 'src/index.tsx' generated metadata with charset 'windows-1252' DEBUG: 'src/registerServiceWorker.ts' generated metadata with charset 'windows-1252' DEBUG: 'src/screens/Home.tsx' generated metadata with charset 'windows-1252' DEBUG: Not enough content in 'src/screens/Home.tsx' to have CPD blocks, it will not be part of the duplication detection DEBUG: 'src/store/index.ts' generated metadata with charset 'windows-1252' DEBUG: Not enough content in 'src/store/index.ts' to have CPD blocks, it will not be part of the duplication detection DEBUG: 'src/store/root-action.ts' generated metadata with charset 'windows-1252' DEBUG: Not enough content in 'src/store/root-action.ts' to have CPD blocks, it will not be part of the duplication detection DEBUG: 'src/store/root-epic.ts' generated metadata with charset 'windows-1252' DEBUG: Not enough content in 'src/store/root-epic.ts' to have CPD blocks, it will not be part of the duplication detection DEBUG: 'src/store/root-reducer.ts' generated metadata with charset 'windows-1252' DEBUG: 'src/store/store.ts' generated metadata with charset 'windows-1252' INFO: Sensor SonarTS [typescript] (done) | time=16740ms INFO: Sensor SonarTS Coverage [typescript] INFO: Analysing [E:\VSTSAgent-XXXXXX\_work\4\s\coverage\lcov.info] INFO: Sensor SonarTS Coverage [typescript] (done) | time=0ms INFO: Sensor Zero Coverage Sensor INFO: Sensor Zero Coverage Sensor (done) | time=94ms INFO: Sensor CPD Block Indexer DEBUG: org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer is used for ts DEBUG: No CpdMapping for language ts INFO: Sensor CPD Block Indexer (done) | time=0ms INFO: 6 files had no CPD blocks INFO: Calculating CPD for 10 files DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/components/PendingIssues/PendingIssues.tsx DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/components/App/App.tsx DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/components/PendingIssues/Reducer.ts DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/components/Header/Header.tsx DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/components/Footer/Footer.tsx DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/store/root-reducer.ts DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/components/PendingIssues/index.ts DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/registerServiceWorker.ts DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/store/store.ts DEBUG: Detection of duplications for E:/VSTSAgent-XXXXXX/_work/4/s/src/index.tsx INFO: CPD calculation finished INFO: Analysis report generated in 750ms, dir size=62 KB INFO: Analysis reports compressed in 125ms, zip size=39 KB INFO: Analysis report generated in E:\VSTSAgent-XXXXXX\_work\4\s\.scannerwork\scanner-report DEBUG: Upload report DEBUG: POST 200 https://XXXXXX.com/api/ce/submit?projectKey=XXXXXX-dev&projectName=CMP%20Development%20UI | time=172ms INFO: Analysis report uploaded in 172ms INFO: ANALYSIS SUCCESSFUL, you can browse https://XXXXXX.com/dashboard/index/XXXXXX-dev INFO: Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report INFO: More about the report processing at https://XXXXXX.com/api/ce/task?id=AWQ8KpFCNr8GlRD53mvk DEBUG: Report metadata written to E:\VSTSAgent-XXXXXX\_work\4\s\.scannerwork\report-task.txt DEBUG: Post-jobs : INFO: Task total time: 24.325 s INFO: ------------------------------------------------------------------------ INFO: EXECUTION SUCCESS INFO: ------------------------------------------------------------------------ INFO: Total time: 27.262s INFO: Final Memory: 20M/261M INFO: ------------------------------------------------------------------------ ##[debug]rc:0 ##[debug]success:true ##[section]Finishing: Run Code Analysis ```
2018/06/18
[ "https://Stackoverflow.com/questions/50906497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/551698/" ]
The SonarQube extension make various http requests to the SonarQube server for various reasons. If your SonarQube server is using a custom/self-signed SSL certificate, it will fail for security reasons. You have to tell node.js that you trust this certificate using [NODE\_EXTRA\_CA\_CERTS](https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file). See details: <https://jira.sonarsource.com/browse/VSTS-147>
Seems it SSL issues, i have faced the same issues when try to use http service connection.
9,511,380
I have added the Devise gem to the ruby on rails app version 1.8.7. I using devise to authenticate and also I have created a model called user which will connect another database, I have mentioned/specified the database configurations in the create\_connection,whenever I run the app in the local host, I am getting this error message "undefined method `password\_salt=' for #" As soon as I register a new member I am getting this error. I am a newbie to rails, Kindly help me out
2012/03/01
[ "https://Stackoverflow.com/questions/9511380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449344/" ]
i had this error once before, try the following **1.Re-run your migrations again** ``` rake db:migrate VERSION=0 #to rollback migrations to the first one if needed<br /> ``` Just in case you have forgotten, uncomment the following line ``` t.string :password_salt ``` then migrate your database ``` rake db:migrate ``` Also make sure that encryptable is added to your database model ``` devise :encryptable ..... ``` **2.Update your devise gem** bundle update or specify in your gem file to use latest devise gem 2.x
You will need to add the `password_salt` column to your users table. It appears to be missing.
35,474,417
Consider the following set of examples. 1. The function `takeOnlyVoidFunction` takes a function with zero arguments and simply executes it. 2. The function `takeVariableArguments` takes a variable number of arguments and executes the function using the arguments. 3. The function `captureVariableArgs` attempts to convert the second function into a lambda form that is acceptable by the first function, but it does not compile. **How can I make the function `captureVariableArgs` compile and exhibit the correct behavior of converting a function with a variable number of arguments into a closure with no arguments?** ``` #include <stdio.h> #include <functional> void takeOnlyVoidFunction(std::function<void()> task) { task(); } template<typename _Callable, typename... _Args> void takeVariableArguments(_Callable&& __f, _Args&&... __args) { __f(__args...); } // How can I make this function compile? template<typename _Callable, typename... _Args> void captureVariableArgs(_Callable&& __f, _Args&&... __args) { takeOnlyVoidFunction([=]() { __f(__args...);}); } void normalFunction(int a, int b) { printf("I am a normal function which takes params (%d,%d)\n", a, b); } int main() { int a = 7; int b = 8; takeVariableArguments(normalFunction, a, b); takeOnlyVoidFunction([=](){ normalFunction(a,b);}); captureVariableArgs(normalFunction, a, b); } ``` I'm running `gcc 4.9.2`. Here is the compiler error I see. ``` g++ -std=c++11 Test.cc -o Test Test.cc: In instantiation of ‘captureVariableArgs(_Callable&&, _Args&& ...)::<lambda()> [with _Callable = void (&)(int, int); _Args = {int&, int&}]’: Test.cc:16:38: required from ‘struct captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>’ Test.cc:16:50: required from ‘void captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]’ Test.cc:28:45: required from here Test.cc:16:34: error: variable ‘__f’ has function type takeOnlyVoidFunction([=]() { __f(__args...);}); ^ Test.cc:16:34: error: variable ‘__f’ has function type Test.cc: In instantiation of ‘struct captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>’: Test.cc:16:50: required from ‘void captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]’ Test.cc:28:45: required from here Test.cc:16:34: error: field ‘captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>::<__f capture>’ invalidly declared function type In file included from Test.cc:2:0: /usr/include/c++/4.9/functional:2418:7: error: ‘std::function<_Res(_ArgTypes ...)>::function(_Functor) [with _Functor = captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>; <template-parameter-2-2> = void; _Res = void; _ArgTypes = {}]’, declared using local type ‘captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>’, is used but never defined [-fpermissive] function<_Res(_ArgTypes...)>:: ^ ``` --- **Update**: A more minimal example demonstrating this problem. ``` #include <stdio.h> // How can I make this function compile? template<typename _Callable> void captureVariableArgs(_Callable&& __f) { takeOnlyVoidFunction( [=]{ __f(); } ); } void normalFunction() { printf("I am a normal function\n"); } int main(){ captureVariableArgs(normalFunction); } ```
2016/02/18
[ "https://Stackoverflow.com/questions/35474417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391161/" ]
I put together a test, and it seems to work well. I updated the load event to add a second series, using the same `series.data[len -1]` values; then in the setInterval portion, we update that new point at each iteration. That way, by updating the existing marker rather than destroying one marker and creating another, the animation works as desired. Code: ``` events: { load: function () { var series = this.series[0], len = series.data.length; //------------------------------------- //added this part -> this.addSeries({ id: 'end point', type: 'scatter', marker: { enabled:true, symbol:'circle', radius:5, fillColor:'white', lineColor: 'black', lineWidth:2 }, data: [[ series.data[len - 1].x, series.data[len - 1].y ]] }); var series2 = this.get('end point'); //------------------------------------- setInterval(function () { var x = (new Date()).getTime(), y = Math.random(); len = series.data.length; series.addPoint([x,y], true, true); //and added this line --> series2.data[0].update([x,y]); }, 1000); } } ``` Fiddle: * <http://jsfiddle.net/jlbriggs/a6pshutt/>
You can try this : ``` series: [{ name: 'Random data', marker : { enabled : false, lineWidth: 0, radius: 0 }, data: (function () { // generate an array of random data var data = [], time = (new Date()).getTime(), i; for (i = -19; i <= 0; i += 1) { data.push({ x: time + i * 1000, y: Math.random() }); } return data; }()) }] ``` Its works. Greg.
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Be wary of `invalidateOptionsMenu()`. It recreates the entire menu. This has a lot of overhead and will reset embedded components like the `SearchView`. It took me quite a while to track down why my `SearchView` would "randomly" close. I ended up capturing the menu as posted by Dark and then call `onPrepareOptionsMenu(Menu)` as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call `onPrepareOptionsMenu()` before the menu is created. I did this as below: ``` private Menu mOptionsMenu; @Override public boolean onCreateOptionsMenu(final Menu menu) { mOptionsMenu = menu ... } private void updateOptionsMenu() { if (mOptionsMenu != null) { onPrepareOptionsMenu(mOptionsMenu); } } ```
Android now has the [Toolbar](https://developer.android.com/reference/android/widget/Toolbar) widget which was a Menu you can set/get. Set the Toolbar in your Activity with some variation of setSupportActionBar(Toolbar) for stuff like onCreateOptionsMenu from a Fragment for example. Thread revived!
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Be wary of `invalidateOptionsMenu()`. It recreates the entire menu. This has a lot of overhead and will reset embedded components like the `SearchView`. It took me quite a while to track down why my `SearchView` would "randomly" close. I ended up capturing the menu as posted by Dark and then call `onPrepareOptionsMenu(Menu)` as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call `onPrepareOptionsMenu()` before the menu is created. I did this as below: ``` private Menu mOptionsMenu; @Override public boolean onCreateOptionsMenu(final Menu menu) { mOptionsMenu = menu ... } private void updateOptionsMenu() { if (mOptionsMenu != null) { onPrepareOptionsMenu(mOptionsMenu); } } ```
As far as I could understand what you want here is which may help you: **1.** Refer this tutorial over [option menu](http://developer.android.com/guide/topics/ui/menus.html#options-menu). **2.** Every time user presses menu button you can check it's title thru `getTitle()`. **3.** Or if you want to know the last menu item checked or selected when user has not pressed the menu button then you need to store the preferences when user presses.
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Call invalidateOptionsMenu() instead of passing menu object around.
Android now has the [Toolbar](https://developer.android.com/reference/android/widget/Toolbar) widget which was a Menu you can set/get. Set the Toolbar in your Activity with some variation of setSupportActionBar(Toolbar) for stuff like onCreateOptionsMenu from a Fragment for example. Thread revived!
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
you could do it by passing the Menu object to your Activity class ``` public class MainActivity extends Activity { ... ... private Menu _menu = null; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); _menu = menu; return true; } private Menu getMenu() { //use it like this return _menu; } } ```
There several callback methods that provide menu as a parameter. You might wanna manipulate it there. For example: ``` onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) onCreateOptionsMenu(Menu menu) onCreatePanelMenu(int featureId, Menu menu) ``` There several more, best you take a look in activity documentation and look for your desired method: <http://developer.android.com/reference/android/app/Activity.html>
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Be wary of `invalidateOptionsMenu()`. It recreates the entire menu. This has a lot of overhead and will reset embedded components like the `SearchView`. It took me quite a while to track down why my `SearchView` would "randomly" close. I ended up capturing the menu as posted by Dark and then call `onPrepareOptionsMenu(Menu)` as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call `onPrepareOptionsMenu()` before the menu is created. I did this as below: ``` private Menu mOptionsMenu; @Override public boolean onCreateOptionsMenu(final Menu menu) { mOptionsMenu = menu ... } private void updateOptionsMenu() { if (mOptionsMenu != null) { onPrepareOptionsMenu(mOptionsMenu); } } ```
you could do it by passing the Menu object to your Activity class ``` public class MainActivity extends Activity { ... ... private Menu _menu = null; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); _menu = menu; return true; } private Menu getMenu() { //use it like this return _menu; } } ```
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Be wary of `invalidateOptionsMenu()`. It recreates the entire menu. This has a lot of overhead and will reset embedded components like the `SearchView`. It took me quite a while to track down why my `SearchView` would "randomly" close. I ended up capturing the menu as posted by Dark and then call `onPrepareOptionsMenu(Menu)` as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call `onPrepareOptionsMenu()` before the menu is created. I did this as below: ``` private Menu mOptionsMenu; @Override public boolean onCreateOptionsMenu(final Menu menu) { mOptionsMenu = menu ... } private void updateOptionsMenu() { if (mOptionsMenu != null) { onPrepareOptionsMenu(mOptionsMenu); } } ```
Call invalidateOptionsMenu() instead of passing menu object around.
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Call invalidateOptionsMenu() instead of passing menu object around.
There several callback methods that provide menu as a parameter. You might wanna manipulate it there. For example: ``` onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) onCreateOptionsMenu(Menu menu) onCreatePanelMenu(int featureId, Menu menu) ``` There several more, best you take a look in activity documentation and look for your desired method: <http://developer.android.com/reference/android/app/Activity.html>
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
There several callback methods that provide menu as a parameter. You might wanna manipulate it there. For example: ``` onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) onCreateOptionsMenu(Menu menu) onCreatePanelMenu(int featureId, Menu menu) ``` There several more, best you take a look in activity documentation and look for your desired method: <http://developer.android.com/reference/android/app/Activity.html>
Android now has the [Toolbar](https://developer.android.com/reference/android/widget/Toolbar) widget which was a Menu you can set/get. Set the Toolbar in your Activity with some variation of setSupportActionBar(Toolbar) for stuff like onCreateOptionsMenu from a Fragment for example. Thread revived!
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
you could do it by passing the Menu object to your Activity class ``` public class MainActivity extends Activity { ... ... private Menu _menu = null; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); _menu = menu; return true; } private Menu getMenu() { //use it like this return _menu; } } ```
As far as I could understand what you want here is which may help you: **1.** Refer this tutorial over [option menu](http://developer.android.com/guide/topics/ui/menus.html#options-menu). **2.** Every time user presses menu button you can check it's title thru `getTitle()`. **3.** Or if you want to know the last menu item checked or selected when user has not pressed the menu button then you need to store the preferences when user presses.
10,579,333
In some methods of my Activity I want to check the title of menu or know if it is checked or not. How can I get Activity's menu. I need something like `this.getMenu()`
2012/05/14
[ "https://Stackoverflow.com/questions/10579333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779408/" ]
Be wary of `invalidateOptionsMenu()`. It recreates the entire menu. This has a lot of overhead and will reset embedded components like the `SearchView`. It took me quite a while to track down why my `SearchView` would "randomly" close. I ended up capturing the menu as posted by Dark and then call `onPrepareOptionsMenu(Menu)` as necessary. This met my requirement without an nasty side effects. Gotcha: Make sure to do a null check in case you call `onPrepareOptionsMenu()` before the menu is created. I did this as below: ``` private Menu mOptionsMenu; @Override public boolean onCreateOptionsMenu(final Menu menu) { mOptionsMenu = menu ... } private void updateOptionsMenu() { if (mOptionsMenu != null) { onPrepareOptionsMenu(mOptionsMenu); } } ```
There several callback methods that provide menu as a parameter. You might wanna manipulate it there. For example: ``` onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) onCreateOptionsMenu(Menu menu) onCreatePanelMenu(int featureId, Menu menu) ``` There several more, best you take a look in activity documentation and look for your desired method: <http://developer.android.com/reference/android/app/Activity.html>
33,529,678
I am new to javascript and want to use C3.js for streaming time series data visualization. I want to display the 5 most recent data points on the chart. The new data point is streamed every 2 seconds. So, the display should discard the oldest data point and refresh the graph with this additional data point. Example: x axis has time in seconds: ``` xData = [ 0, 2, 4, 6, 8] yData = [10, 11, 12, 13, 14] ``` The new data point (arriving after 2 seconds) would be `x = 10, y = 16` So, I want to update the xData and yData arrays as, ``` xData = [ 2, 4, 6, 8, 10] yData = [ 11, 12, 13, 14, 16] ``` I looked at the 'flow' API [example](http://c3js.org/samples/api_flow.html) of C3.js. But it appears like a new array is created everytime. Could someone please illustrate how to accomplish this in c3? I am using node.js.
2015/11/04
[ "https://Stackoverflow.com/questions/33529678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253795/" ]
This code will never exit the loop. The reason for this is that adding `1` to a sufficiently large `double` number does not change its value: ``` double a = 1.7976931348623155E308; double old = a; a++; System.out.println(a); // prints 1.7976931348623155E308 System.out.println(old); // prints 1.7976931348623155E308 System.out.println(a==old); // prints "true" ``` [Demo.](http://ideone.com/NCg92J) In fact, when the value of `double` gets sufficiently close to positive infinity, you need to add a number well above 10200 in order to make your large double change value and become `POSITIVE_INFINITY`. The reason for this is the way `double` represents large numbers. It uses a short *mantissa* to represent the most significant digits of the value, and an exponent to indicate where the fractional point should be placed. In case of very large numbers, the exponent is essentially an indication of how many zeros need to be added after the binary representation of the mantissa. In order to make your `double` number change value through addition, you need to add a number that is at least as large as the least significant bit of the mantissa. Once the binary exponent goes above 48, the smallest number that you need to add in order for the result to be different becomes 2, meaning that `++` would no longer change the value.
At some point, `i++` will stop having any effect, because for very large values of `i`, consecutive `double` values are far apart. Therefore it is an infinite loop. To prove there are `double` values for which `i == i + 1` try this: ``` for (double i = 1;; i *= 2){ if (i == i + 1) { System.out.println(i); break; } } ``` It prints ``` 9.007199254740992E15 ```
4,508,376
I'm trying to find analytically all the integer points of $y^2 = x^3 - 4x + 9$. The integer solutions I found so far are $\{-2, 3\}, \{0, 3\}, \{2, 3\}, \{7, 18\}, \{11, 36\}, \{646, 16419\}$ The first five are easy to find with modulo considerations, but how can I find $\{646, 16419\}$? How to prove there are no more solutions?
2022/08/08
[ "https://math.stackexchange.com/questions/4508376", "https://math.stackexchange.com", "https://math.stackexchange.com/users/967210/" ]
All integral points are given by $$ (-2,\pm 3), (0,\pm 3), (2,\pm 3), (7,\pm 18), (11,\pm 36), (646,\pm 16419) $$ see the reference for the database in [LMFDB](https://www.lmfdb.org/EllipticCurve/Q/7724/a/1).
In SageMath 8.0: ``` R.<x,y> = QQ[] E = EllipticCurve(x^3-4*x+9-y^2) E.integral_points(both_signs=true): ``` $$\eqalign{&[(-2 : -3 : 1),\cr &(-2 : 3 : 1),\cr &(0 : -3 : 1),\cr &(0 : 3 : 1),\cr &(2 : -3 : 1),\cr &(2 : 3 : 1),\cr &(7 : -18 : 1),\cr &(7 : 18 : 1),\cr &(11 : -36 : 1),\cr &(11 : 36 : 1),\cr &(646 : -16419 : 1),\cr &(646 : 16419 : 1)]}$$
4,508,376
I'm trying to find analytically all the integer points of $y^2 = x^3 - 4x + 9$. The integer solutions I found so far are $\{-2, 3\}, \{0, 3\}, \{2, 3\}, \{7, 18\}, \{11, 36\}, \{646, 16419\}$ The first five are easy to find with modulo considerations, but how can I find $\{646, 16419\}$? How to prove there are no more solutions?
2022/08/08
[ "https://math.stackexchange.com/questions/4508376", "https://math.stackexchange.com", "https://math.stackexchange.com/users/967210/" ]
For your first question > > ,but how can I find $(646,16419)$? > > > There is an easy method using lines intersecting the curve $y^2 = x^3-4x+9.$ Given any two points on the curve, the unique line they determine intersects the curve in another point. In the case of the points $(2,3)$ and $(-2,-3)$ this third point is $(9/4,27/8)$. With this new point and the point $(2,-3)$ the third point is $(646,16419).$ Your second question > > How to prove there are no more solutions? > > > is much harder. Perhaps descent methods may work here.
In SageMath 8.0: ``` R.<x,y> = QQ[] E = EllipticCurve(x^3-4*x+9-y^2) E.integral_points(both_signs=true): ``` $$\eqalign{&[(-2 : -3 : 1),\cr &(-2 : 3 : 1),\cr &(0 : -3 : 1),\cr &(0 : 3 : 1),\cr &(2 : -3 : 1),\cr &(2 : 3 : 1),\cr &(7 : -18 : 1),\cr &(7 : 18 : 1),\cr &(11 : -36 : 1),\cr &(11 : 36 : 1),\cr &(646 : -16419 : 1),\cr &(646 : 16419 : 1)]}$$
42,075
I want to use Bebas Neue in my commercial html5-based game for mobile devices. 1. My game mechanics implies the *use of letters as sprites*. 2. The fact that this game is html5-based game means, that *I'll put the whole font in the application distributive*. But Dharma Type EULA imposes some restrictions: 1. You may not redistribute this font without permission. 2. You may not modify, adapt, translate, reverse engineer, decompile, disassemble, or create derivative works based on this font. Does restriction of redistribution means that i can't use this font im my app? Does restriction of modify and adapt means that i can't make sprites from letters?
2014/11/12
[ "https://graphicdesign.stackexchange.com/questions/42075", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/33458/" ]
Your use of the font file *implies* that you aren't re-distributing the font file, as you aren't putting the file itself into your app. Will downloading your app allow me to extract the font file and use it on my own machine? Are you copying the font file as-is into the app? If the answer to either is 'no', then you should have a good case for including it and not break your license agreement. A better idea though, is to contact Dharma type and ask them. If their answer is 'you can't', they'll probably be happy to quote you for a license that makes them go 'yes, you can'.
Take a look at this: I have given the link just as example.You have to check the licensing with your font type whether it is available for the particular use or not. <http://www.myfonts.com/fonts/flat-it/dharma-gothic/licensing.html> Font for application uses and see the EULA.
46,582,242
I would like to change the color of the text value based on the value of a switch statement. For example if the value equals 'Hello' then make it green. I have included some code and would be grateful if someone could offer some assistance as to how I can achieve this. Many thanks. ``` switch ($row['destroydate']) { case NULL: $destroydate = 'No Date Set'; <---MAKE RED //echo $destroyeddate; break; case "0000-00-00": $destroydate = 'No Date Set'; <--- MAKE GREEN break; default: $destroydate = $row['destroydate']; <--- MAKE BLUE break; } ```
2017/10/05
[ "https://Stackoverflow.com/questions/46582242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1532468/" ]
you can try using ``` switch ($row['destroydate']) { case NULL: $destroydate = '<span style="color:#FF0000">No Date Set</span>'; <---MAKE RED //echo $destroyeddate; break; case "0000-00-00": $destroydate = '<span style="color:#39CD0D">No Date Set</span>'; <--- MAKE GREEN break; default: $destroydate = '<span style="color:#0808D8 ">'.$row["destroydate"].'</span>'; <--- MAKE BLUE break; } ```
You should use this below. Create a function and use it with sending the Date data. The switch will return a result, always. This way you can always use your new function at any file. If there is anything needs to be added/changed, you don't need to change all the files who are using this switch, but only have to change the function. If you prefer: you could also make it a static function (because it's only returning some html). ``` /** * @param $date * * @return string */ Public function getDateColor($date) { // Check on date and return result switch($date): case(empty($date)): return '<span color="red">No Date Set</span>'; break; case($date == 0000-00-00): return '<span color="Green">No Date Set</span>'; break; default: return '<span color="blue">' . $date . '</span>'; endswitch; } ```
581,716
I see a couple of tutorials here on using `dd`, but I wanted to ask to make 100% sure. Can I clone my XBox360 hdd over to a larger hdd using dd? I just dont want to lose my current data thats there. Also, is it really as simple as ``` dd if=/dev/sdb of=/dev/sdc ``` If it matters, Im running Lubuntu 14.04 64bit
2015/02/04
[ "https://askubuntu.com/questions/581716", "https://askubuntu.com", "https://askubuntu.com/users/301105/" ]
That depends. If you have two original Xbox 360 drives you can clone one to the other and everything should work just fine. Using a regular 2,5" drive in an Xbox 360 does not work. Unless you have a drive that can be *"hacked"*, e.g. you copy the *"security sector"* with a DOS tool onto the drive's firmware so that the Xbox 360 detects it as a legit drive. * No, this is not about modifying the Xbox firmware for warezing games (you're console might not get banned, but it's possible). * Yes you need a DOS boot disk/drive and a machine that boots legacy. Try to avoid FreeDOS if you're unsure, because I found other programs for modifying firmware that really rely on DOS boot disks the way Windows 9x creates them. I have 2 "hacked" drives and backup one to the other using `dd` without issues. (Just dd'ing to the other drive didn't work.) I'm not sure if linking to a certain site that provides the tool and sectors for different disk sizes (including a list of compatible disks) is legal. Search for terms like *Xbox 360 hddhackr* and stay away from typical download fraud. Using standard drives with the Xbox One seems to be [easier](http://withinrafael.com/taking-a-peek-at-xbox-one-formatted-disks-in-windows/). **Note:** `dd` puts a lot of stress on a drive. If you have a failing drive, try to copy only the necessary data through the Xbox user interface onto USB storage first if that is possible.
I would be very careful when cloning disks with dd, as you have to pay attention to the disc's labels, as described by [this question](https://stackoverflow.com/questions/18874441/hard-drive-clone-using-dd). I don't know exactly how the XboX handles this, but I prefer using [Clonezilla](http://www.clonezilla.org/) for performing such tasks. It features a textual user interface and a beginner mode for easy cloning disks. Furthermore, it also offers a special mode for cloning data from one hdd to a larger one. Nevertheless, I have already copied Cubian OS images to my Cubieboard's SD card using the dd command described by you. Moreover, I have also used the bs argument for specifying how many bytes can be read and write at a time as well as the argument conv=notrunc,noerror,sync for ignoring erros, for avoiding truncating the output as well as for making sure the operations have finished.
43,813,032
I am recently working on a project which has an algorithm to tell whether a point is inside an area. The area looks like this: ``` {"state": "Washington", "border": [[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]} ``` It is easy if the area is a rectangle. However, the area is irregular. One of the idea I have is to check whether a point is in the 'inner' side of every line of the area. However, the performance is not good. Any idea?
2017/05/05
[ "https://Stackoverflow.com/questions/43813032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7970767/" ]
First of all, very interesting question!! Although it might be a duplicated question, but I am still going to post another workable answer different from that post to encourage this new guy. The idea is to use the sum of angles to decide whether the target is inside or outside. If the target is inside an area, the sum of angle form by the target and every two border points will be 360. If the target is outside, the sum will not be 360. The angle has direction. If the angle going backward, the angle is a negative one. This is just like calculating the [winding number](https://en.wikipedia.org/wiki/Winding_number). The provided input data `[[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]` is clockwise (you can check google map). Therefore, my code assume that the positive angle is clockwise one. Refer this for the idea: [![enter image description here](https://i.stack.imgur.com/Zbcec.jpg)](https://i.stack.imgur.com/Zbcec.jpg) The following is the python code that implements it. ``` def isInside(self, border, target): degree = 0 for i in range(len(border) - 1): a = border[i] b = border[i + 1] # calculate distance of vector A = getDistance(a[0], a[1], b[0], b[1]); B = getDistance(target[0], target[1], a[0], a[1]) C = getDistance(target[0], target[1], b[0], b[1]) # calculate direction of vector ta_x = a[0] - target[0] ta_y = a[1] - target[1] tb_x = b[0] - target[0] tb_y = b[1] - target[1] cross = tb_y * ta_x - tb_x * ta_y clockwise = cross < 0 # calculate sum of angles if(clockwise): degree = degree + math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C))) else: degree = degree - math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C))) if(abs(round(degree) - 360) <= 3): return True return False ```
Here is a pseudo code: ``` var point = [x,y] // Point to evaluate int i, j, c = 0 int size = border.count for (i = 0, j = size-1; i < size; j = i++) { var ii = border[i] var jj = border[j] if ( ((ii.[1] > point.[1]) != (jj.[1] > point.[1])) && (point.[0] < (jj.[0]-ii.[0]) * (point.[1]-ii.[1]) / (jj.[1]-ii.[1]) + ii.[0])) { c = !c } } return c ```
43,813,032
I am recently working on a project which has an algorithm to tell whether a point is inside an area. The area looks like this: ``` {"state": "Washington", "border": [[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]} ``` It is easy if the area is a rectangle. However, the area is irregular. One of the idea I have is to check whether a point is in the 'inner' side of every line of the area. However, the performance is not good. Any idea?
2017/05/05
[ "https://Stackoverflow.com/questions/43813032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7970767/" ]
First of all, very interesting question!! Although it might be a duplicated question, but I am still going to post another workable answer different from that post to encourage this new guy. The idea is to use the sum of angles to decide whether the target is inside or outside. If the target is inside an area, the sum of angle form by the target and every two border points will be 360. If the target is outside, the sum will not be 360. The angle has direction. If the angle going backward, the angle is a negative one. This is just like calculating the [winding number](https://en.wikipedia.org/wiki/Winding_number). The provided input data `[[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]` is clockwise (you can check google map). Therefore, my code assume that the positive angle is clockwise one. Refer this for the idea: [![enter image description here](https://i.stack.imgur.com/Zbcec.jpg)](https://i.stack.imgur.com/Zbcec.jpg) The following is the python code that implements it. ``` def isInside(self, border, target): degree = 0 for i in range(len(border) - 1): a = border[i] b = border[i + 1] # calculate distance of vector A = getDistance(a[0], a[1], b[0], b[1]); B = getDistance(target[0], target[1], a[0], a[1]) C = getDistance(target[0], target[1], b[0], b[1]) # calculate direction of vector ta_x = a[0] - target[0] ta_y = a[1] - target[1] tb_x = b[0] - target[0] tb_y = b[1] - target[1] cross = tb_y * ta_x - tb_x * ta_y clockwise = cross < 0 # calculate sum of angles if(clockwise): degree = degree + math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C))) else: degree = degree - math.degrees(math.acos((B * B + C * C - A * A) / (2.0 * B * C))) if(abs(round(degree) - 360) <= 3): return True return False ```
Sounds like a good use case for a modified [convex hull](https://en.wikipedia.org/wiki/Convex_hull) algorithm. 1. Start out with all points inside of the "area" (since no hull is yet created). 2. Then, as you progress through your chosen algorithm (e.g. Graham scan is `O(nlog(n))` performance), if the point is chosen as part of the convex hull, it is no longer inside of the "area" -- (i.e. a point that comprises the convex hull is not is not part of the final answer). 3. Repeat until you have created the convex hull. The leftover points which are not part of the hull is therefore inside the area, which is the answer you are looking for.
43,813,032
I am recently working on a project which has an algorithm to tell whether a point is inside an area. The area looks like this: ``` {"state": "Washington", "border": [[-122.402015, 48.225216], [-117.032049, 48.999931], [-116.919132, 45.995175], [-124.079107, 46.267259], [-124.717175, 48.377557], [-122.92315, 47.047963], [-122.402015, 48.225216]]} ``` It is easy if the area is a rectangle. However, the area is irregular. One of the idea I have is to check whether a point is in the 'inner' side of every line of the area. However, the performance is not good. Any idea?
2017/05/05
[ "https://Stackoverflow.com/questions/43813032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7970767/" ]
Sounds like a good use case for a modified [convex hull](https://en.wikipedia.org/wiki/Convex_hull) algorithm. 1. Start out with all points inside of the "area" (since no hull is yet created). 2. Then, as you progress through your chosen algorithm (e.g. Graham scan is `O(nlog(n))` performance), if the point is chosen as part of the convex hull, it is no longer inside of the "area" -- (i.e. a point that comprises the convex hull is not is not part of the final answer). 3. Repeat until you have created the convex hull. The leftover points which are not part of the hull is therefore inside the area, which is the answer you are looking for.
Here is a pseudo code: ``` var point = [x,y] // Point to evaluate int i, j, c = 0 int size = border.count for (i = 0, j = size-1; i < size; j = i++) { var ii = border[i] var jj = border[j] if ( ((ii.[1] > point.[1]) != (jj.[1] > point.[1])) && (point.[0] < (jj.[0]-ii.[0]) * (point.[1]-ii.[1]) / (jj.[1]-ii.[1]) + ii.[0])) { c = !c } } return c ```
239,808
I'm looking for a closed form for the expression $$ \sum\_{k=1}^{\infty}\frac{1}{(2k)^5-(2k)^3} $$ I know that Ramanujan gave the following closed form for a similar expression $$ \sum\_{k=1}^{\infty}\frac{1}{(2k)^3-2k}= \ln(2)-\frac{1}{2} $$ I wonder if it is possible to find such a similarly simple and nice closed form for the above case. Thanks.
2016/05/26
[ "https://mathoverflow.net/questions/239808", "https://mathoverflow.net", "https://mathoverflow.net/users/6842/" ]
$$  \frac{1}{(2k)^5 - (2k)^3} + \frac{1}{(2k)^3} = \frac{1 + (2k)^2 - 1}{(2k)^5 - (2k)^3} = \frac{1}{(2k)^3 -2k}$$ So by Ramanujan's result: $$\sum\_{k=1}^{\infty} \frac{1}{(2k)^5 - (2k)^3} = \ln(2) - \frac{1}{2} - \frac{1}{8}\zeta(3)$$
Not an answer, but if you want to look for different solutions in the future in the same vein as these you posed, this might be a general method. For an alternate representation for $$: $$\frac{1}{a-b}=\frac{1}{a}+\frac{b}{a^2}+\frac{a^2}{b^3}+\frac{b^3}{a^4}+\cdots\qquad(1)$$ Plugging in $a=(2k)^{5}$ and $b=(2k)^3$ $$\frac{1}{(2k)^3}+\frac{(2k)^3}{(2k)^{10}}+\frac{(2k)^6}{(2k)^{15}}+\cdots=\sum\_{n\geqslant 1}\frac{1}{(2k)^{2n+1}}$$ And thus your sum can be evaluated as $$\sum\_{k\geqslant 1}\sum\_{n\geqslant 1}\frac{1}{(2k)^{2n+1}}$$ I am not entirely convinced if this was helpful to you. I am sorry if it was not. $(1)$ [Reason](https://www.wolframalpha.com/input/?i=1%2F((a)-(b)))
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Sort the array by date, and then get the front value of the array. ``` $dates = array(5) { /** omitted to keep code compact */ } $dates = array_combine($dates, array_map('strtotime', $dates)); arsort($dates); echo $dates[0]; ```
``` $arrayy = array( "2012-06-11 08:30:49","2012-06-07 08:03:54","2012-05-26 23:04:04", "2012-05-27 08:30:00","2012-06-08 08:30:55" ); function getMostRecent($array){ $current = date("Y-m-d h:i:s"); $diff1 = NULL; $recent = NULL; foreach($array as $date){ if($diff = strcmp($current,$date)){ if($diff1 == NULL){ $diff1 = $diff; $recent = $date; } else{ if($diff < $diff1){ $diff1 = $diff; $recent = $date; } } } } return $recent; } ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Sort the array by date, and then get the front value of the array. ``` $dates = array(5) { /** omitted to keep code compact */ } $dates = array_combine($dates, array_map('strtotime', $dates)); arsort($dates); echo $dates[0]; ```
After nearly 10 years and nearly 50,000 page views, it seems that no one could see the forest from the trees. The array of datetime stamps is perfectly formatted for simple string comparison. There is absolutely NO reason to call anything other than `max()` to get the highest/latest string. Your `Y-m-d H:i:s` formatted values can be compared as strings because the unit integers are arranged from greatest magnitude to least magnitude. All integers are consistently zero-padded. There is literally no preparation required. Code: ([Demo](https://3v4l.org/AdoDV)) ``` $dates = [ "2012-06-11 08:30:49", "2012-06-07 08:03:54", "2012-05-26 23:04:04", "2012-05-27 08:30:00", "2012-06-08 08:30:55", ]; echo max($dates); // 2012-06-11 08:30:49 ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Do a loop, convert the values to date, and store the most recent, in a var. ``` $mostRecent= 0; foreach($dates as $date){ $curDate = strtotime($date); if ($curDate > $mostRecent) { $mostRecent = $curDate; } } ``` something like that... you get the idea If you want most recent BEFORE today : ``` $mostRecent= 0; $now = time(); foreach($dates as $date){ $curDate = strtotime($date); if ($curDate > $mostRecent && $curDate < $now) { $mostRecent = $curDate; } } ```
**Try this works 100%** ``` function getRecentDate($date_list,$curDate){ $curDate = strtotime($curDate); $mostRecent = array(); foreach($date_list as $date){ $diff = strtotime($date)-$curDate; if($diff>0){ $mostRecent[$diff] = $date; } } if(!empty($mostRecent)){ ksort($mostRecent); $mostRecent_key = key($mostRecent); if($mostRecent_key){ return $mostRecent[$mostRecent_key]; } }else{ return false; } } $date_list = array('15-05-2015','14-01-2015','18-03-2015','20-10-2016','12-12-2014','12-12-2015'); $curDate = '14-01-2015'; $get_recent = getRecentDate($date_list,$curDate); if($get_recent){ echo $get_recent; }else{ echo 'No recent date exists'; } ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Sort the array by date, and then get the front value of the array. ``` $dates = array(5) { /** omitted to keep code compact */ } $dates = array_combine($dates, array_map('strtotime', $dates)); arsort($dates); echo $dates[0]; ```
**Try this works 100%** ``` function getRecentDate($date_list,$curDate){ $curDate = strtotime($curDate); $mostRecent = array(); foreach($date_list as $date){ $diff = strtotime($date)-$curDate; if($diff>0){ $mostRecent[$diff] = $date; } } if(!empty($mostRecent)){ ksort($mostRecent); $mostRecent_key = key($mostRecent); if($mostRecent_key){ return $mostRecent[$mostRecent_key]; } }else{ return false; } } $date_list = array('15-05-2015','14-01-2015','18-03-2015','20-10-2016','12-12-2014','12-12-2015'); $curDate = '14-01-2015'; $get_recent = getRecentDate($date_list,$curDate); if($get_recent){ echo $get_recent; }else{ echo 'No recent date exists'; } ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Thats my variant. It works with date in future. ``` $Dates = array( "2012-06-11 08:30:49", "2012-06-07 08:03:54", "2012-05-26 23:04:04", "2012-05-27 08:30:00", "2012-06-08 08:30:55", "2012-06-12 07:45:45" ); $CloseDate = array(); $TimeNow = time(); foreach ($Dates as $Date) { $DateToCompare = strtotime($Date); $Diff = $TimeNow - $DateToCompare; if ($Diff < 0) $Diff *= -1; if (count($CloseDate) == 0) { $CloseDate['Date'] = $Date; $CloseDate['Diff'] = $Diff; continue; } if ($Diff < $CloseDate['Diff']) { $CloseDate['Date'] = $Date; $CloseDate['Diff'] = $Diff; } } var_dump($CloseDate); ```
Here is my suggestion: ``` $most_recent = 0; foreach($array as $key => $date){ if( strtotime($date) < strtotime('now') && strtotime($date) > strtotime($array[$most_recent]) ){ $most_recent = $key; } } print $array[$most_recent]; //prints most recent day ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Use [`max()`](http://php.net/max), [`array_map()`](http://php.net/array_map), and [`strtotime()`](http://php.net/strtotime). ``` $max = max(array_map('strtotime', $arr)); echo date('Y-m-j H:i:s', $max); // 2012-06-11 08:30:49 ```
After nearly 10 years and nearly 50,000 page views, it seems that no one could see the forest from the trees. The array of datetime stamps is perfectly formatted for simple string comparison. There is absolutely NO reason to call anything other than `max()` to get the highest/latest string. Your `Y-m-d H:i:s` formatted values can be compared as strings because the unit integers are arranged from greatest magnitude to least magnitude. All integers are consistently zero-padded. There is literally no preparation required. Code: ([Demo](https://3v4l.org/AdoDV)) ``` $dates = [ "2012-06-11 08:30:49", "2012-06-07 08:03:54", "2012-05-26 23:04:04", "2012-05-27 08:30:00", "2012-06-08 08:30:55", ]; echo max($dates); // 2012-06-11 08:30:49 ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Here is my suggestion: ``` $most_recent = 0; foreach($array as $key => $date){ if( strtotime($date) < strtotime('now') && strtotime($date) > strtotime($array[$most_recent]) ){ $most_recent = $key; } } print $array[$most_recent]; //prints most recent day ```
After nearly 10 years and nearly 50,000 page views, it seems that no one could see the forest from the trees. The array of datetime stamps is perfectly formatted for simple string comparison. There is absolutely NO reason to call anything other than `max()` to get the highest/latest string. Your `Y-m-d H:i:s` formatted values can be compared as strings because the unit integers are arranged from greatest magnitude to least magnitude. All integers are consistently zero-padded. There is literally no preparation required. Code: ([Demo](https://3v4l.org/AdoDV)) ``` $dates = [ "2012-06-11 08:30:49", "2012-06-07 08:03:54", "2012-05-26 23:04:04", "2012-05-27 08:30:00", "2012-06-08 08:30:55", ]; echo max($dates); // 2012-06-11 08:30:49 ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
``` $arrayy = array( "2012-06-11 08:30:49","2012-06-07 08:03:54","2012-05-26 23:04:04", "2012-05-27 08:30:00","2012-06-08 08:30:55" ); function getMostRecent($array){ $current = date("Y-m-d h:i:s"); $diff1 = NULL; $recent = NULL; foreach($array as $date){ if($diff = strcmp($current,$date)){ if($diff1 == NULL){ $diff1 = $diff; $recent = $date; } else{ if($diff < $diff1){ $diff1 = $diff; $recent = $date; } } } } return $recent; } ```
After nearly 10 years and nearly 50,000 page views, it seems that no one could see the forest from the trees. The array of datetime stamps is perfectly formatted for simple string comparison. There is absolutely NO reason to call anything other than `max()` to get the highest/latest string. Your `Y-m-d H:i:s` formatted values can be compared as strings because the unit integers are arranged from greatest magnitude to least magnitude. All integers are consistently zero-padded. There is literally no preparation required. Code: ([Demo](https://3v4l.org/AdoDV)) ``` $dates = [ "2012-06-11 08:30:49", "2012-06-07 08:03:54", "2012-05-26 23:04:04", "2012-05-27 08:30:00", "2012-06-08 08:30:55", ]; echo max($dates); // 2012-06-11 08:30:49 ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Do a loop, convert the values to date, and store the most recent, in a var. ``` $mostRecent= 0; foreach($dates as $date){ $curDate = strtotime($date); if ($curDate > $mostRecent) { $mostRecent = $curDate; } } ``` something like that... you get the idea If you want most recent BEFORE today : ``` $mostRecent= 0; $now = time(); foreach($dates as $date){ $curDate = strtotime($date); if ($curDate > $mostRecent && $curDate < $now) { $mostRecent = $curDate; } } ```
Here is my suggestion: ``` $most_recent = 0; foreach($array as $key => $date){ if( strtotime($date) < strtotime('now') && strtotime($date) > strtotime($array[$most_recent]) ){ $most_recent = $key; } } print $array[$most_recent]; //prints most recent day ```
11,012,891
I have the array of dates in `Y-m-d H:i:s` format like: ``` array(5) { [0]=> string(19) "2012-06-11 08:30:49" [1]=> string(19) "2012-06-07 08:03:54" [2]=> string(19) "2012-05-26 23:04:04" [3]=> string(19) "2012-05-27 08:30:00" [4]=> string(19) "2012-06-08 08:30:55" } ``` I would like to know the ***most recent date***. In other words, today is June 13th 2012, which datetime is closest to today's date? From my sample array, I am expecting `2012-06-11 08:30:49`. How can I do that?
2012/06/13
[ "https://Stackoverflow.com/questions/11012891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1453373/" ]
Sort the array by date, and then get the front value of the array. ``` $dates = array(5) { /** omitted to keep code compact */ } $dates = array_combine($dates, array_map('strtotime', $dates)); arsort($dates); echo $dates[0]; ```
Here is my suggestion: ``` $most_recent = 0; foreach($array as $key => $date){ if( strtotime($date) < strtotime('now') && strtotime($date) > strtotime($array[$most_recent]) ){ $most_recent = $key; } } print $array[$most_recent]; //prints most recent day ```