问:
Make nested accordion with jquery
I am trying to make nested accordion with jQuery. So far I made this:

$('.toggle').click(function(e) {
  e.preventDefault();
  var $this = $(this);

  if ($this.next().hasClass('show')) {
    $this.next().removeClass('show');
    $this.next().slideUp(350);
  } else {
    $this.parent().parent().find('li .inner').removeClass('show');
    $this.parent().parent().find('li .inner').slideUp(350);
    $this.next().toggleClass('show');
    $this.next().slideToggle(350);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="accordion">
  <li>
    Item :A
    <ul class="inner">
      <li>
        Item : a1
        <div class="inner show">
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus placerat fringilla. Duis a elit et dolor laoreet volutpat. Aliquam ultrices mauris id mattis imperdiet. Aenean cursus ultrices justo et varius. Suspendisse aliquam orci id dui dapibus
            blandit. In hac habitasse platea dictumst. Sed risus velit, pellentesque eu enim ac, ultricies pretium felis.
          </p>
        </div>
      </li>
      <li>
        Item a2
        <div class="inner">
          <p>
            Children will automatically close upon closing its parent.
          </p>
        </div>
      </li>
      <li>Option 2</li>
    </ul>
  </li>
</ul></code>```

However I am not satisfied with that, what am trying to achieve is something like this:

Can somebody help me with this? Also, I created jsfiddle link: https://jsfiddle.net/9d3pnyc6/1/

答:
Here you have the code:

html: in Option2 you have to add a class(
Option 2
)

```<code><ul class="accordion">

    <li>
        <a class="toggle" href="javascript:void(0);">Item :A </a>

        <ul class="inner">
            <li>
                <a href="#" class="toggle">Item : a1</a>
                <div class="inner show">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus placerat fringilla. Duis a elit et dolor laoreet volutpat. Aliquam ultrices mauris id mattis imperdiet. Aenean cursus ultrices justo et varius. Suspendisse aliquam orci id dui dapibus blandit. In hac habitasse platea dictumst. Sed risus velit, pellentesque eu enim ac, ultricies pretium felis.
                    </p>
                </div>
            </li>

            <li>
                <a href="#" class="toggle">Item a2</a>
                <div class="inner">
                    <p>
                        Children will automatically close upon closing its parent.
                    </p>
                </div>
            </li>
            <li class="parentChild">Option 2</li>

        </ul>
    </li>
</ul>
</code>```

css: in ul parent you have to add display:block!important; and in the Option 2 li.parentChild display:none;

```<code>ul {
  display:block!important;
  list-style: none;
  padding: 0;
}

ul .inner {
  padding-left: 1em;
  overflow: hidden;
  display: none;
}

ul .inner.show {
  /*display: block;*/
}

ul li {
  margin: .5em 0;
}

ul li a.toggle {
  width: 100%;
  display: block;
  background: rgba(0, 0, 0, 0.78);
  color: #fefefe;
  padding: .75em;
  border-radius: 0.15em;
  transition: background .3s ease;
}

ul li a.toggle:hover {
  background: rgba(0, 0, 0, 0.9);
}
ul li.parentChild{
  display:none;
}
</code>```

javascript: you have to add $this.parent().parent().find('li .parentChild').toggle(); to both conditions

```<code>$('.toggle').click(function (e) {
            e.preventDefault();
            var $this = $(this);
            if ($this.next().hasClass('show')) {
                $this.next().removeClass('show');
                $this.next().slideUp(350);
                $this.parent().parent().find('li .parentChild').toggle();
            } else {
                $this.parent().parent().find('li .inner').removeClass('show');
                $this.parent().parent().find('li .inner').slideUp(350);
                $this.parent().parent().find('li .parentChild').toggle();
                $this.next().toggleClass('show');
                $this.next().slideToggle(350);
            }
        });
</code>```

You can see the result in your jsfiddle link: https://jsfiddle.net/mwpo7d3L/20/

Title: Make nested accordion with jquery

Body:
I am trying to make nested accordion with jQuery. So far I made this:

$('.toggle').click(function(e) {
  e.preventDefault();
  var $this = $(this);

  if ($this.next().hasClass('show')) {
    $this.next().removeClass('show');
    $this.next().slideUp(350);
  } else {
    $this.parent().parent().find('li .inner').removeClass('show');
    $this.parent().parent().find('li .inner').slideUp(350);
    $this.next().toggleClass('show');
    $this.next().slideToggle(350);
  }
});

    Item :A

        Item : a1

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus placerat fringilla. Duis a elit et dolor laoreet volutpat. Aliquam ultrices mauris id mattis imperdiet. Aenean cursus ultrices justo et varius. Suspendisse aliquam orci id dui dapibus
            blandit. In hac habitasse platea dictumst. Sed risus velit, pellentesque eu enim ac, ultricies pretium felis.

        Item a2

            Children will automatically close upon closing its parent.

Option 2

However I am not satisfied with that, what am trying to achieve is something like this:

Can somebody help me with this? Also, I created jsfiddle link: https://jsfiddle.net/9d3pnyc6/1/

Body:
Here you have the code:

html: in Option2 you have to add a class(<li class="parentChild">Option 2</li>)

<ul class="accordion">

    <li>
        <a class="toggle" href="javascript:void(0);">Item :A </a>

        <ul class="inner">
            <li>
                <a href="#" class="toggle">Item : a1</a>
                <div class="inner show">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tempus placerat fringilla. Duis a elit et dolor laoreet volutpat. Aliquam ultrices mauris id mattis imperdiet. Aenean cursus ultrices justo et varius. Suspendisse aliquam orci id dui dapibus blandit. In hac habitasse platea dictumst. Sed risus velit, pellentesque eu enim ac, ultricies pretium felis.
                    </p>
                </div>
            </li>

            <li>
                <a href="#" class="toggle">Item a2</a>
                <div class="inner">
                    <p>
                        Children will automatically close upon closing its parent.
                    </p>
                </div>
            </li>
            <li class="parentChild">Option 2</li>

        </ul>
    </li>
</ul>

css: in ul parent you have to add display:block!important; and in the Option 2 li.parentChild display:none;

ul {
  display:block!important;
  list-style: none;
  padding: 0;
}

ul .inner {
  padding-left: 1em;
  overflow: hidden;
  display: none;
}

ul .inner.show {
  /*display: block;*/
}

ul li {
  margin: .5em 0;
}

ul li a.toggle {
  width: 100%;
  display: block;
  background: rgba(0, 0, 0, 0.78);
  color: #fefefe;
  padding: .75em;
  border-radius: 0.15em;
  transition: background .3s ease;
}

ul li a.toggle:hover {
  background: rgba(0, 0, 0, 0.9);
}
ul li.parentChild{
  display:none;
}

javascript: you have to add $this.parent().parent().find('li .parentChild').toggle(); to both conditions

$('.toggle').click(function (e) {
            e.preventDefault();
            var $this = $(this);
            if ($this.next().hasClass('show')) {
                $this.next().removeClass('show');
                $this.next().slideUp(350);
                $this.parent().parent().find('li .parentChild').toggle();
            } else {
                $this.parent().parent().find('li .inner').removeClass('show');
                $this.parent().parent().find('li .inner').slideUp(350);
                $this.parent().parent().find('li .parentChild').toggle();
                $this.next().toggleClass('show');
                $this.next().slideToggle(350);
            }
        });

You can see the result in your jsfiddle link: https://jsfiddle.net/mwpo7d3L/20/


来源: stackexchange

问:
How to handle semi-relative include paths with cppcheck
Our C++ project is organized in several modules (== subfolders) and headers are placed next to the .cpp files:

```<code>CMakeLists.txt
src
│
└───folder1
│   │
│   └───subfolder1
│       │   MyClass1.h
│       │   MyClass1.cpp
│       │   ...
│
└───folder2
│   │
│   └───subfolder2
│       │   MyClass2.h
│       │   MyClass2.cpp
│       │   ...

</code>```

Include directives are always defined relative to the folder src and not relative to the code file e.g. in MyClass1.cpp:

```<code>#include "folder1/subfolder1/MyClass1.h" // even the own header is defined semi-relatively
#include "folder2/subfolder2/MyClass2.h"

MyClass1::MyClass1() {
// some code
}
</code>```

I recently noticed that cppcheck (version 1.89) has problems with this and does not correctly

resolve macros defined in a header file -> False complaints about correct code

find problems with class member initialization (e.g. MyClass::MyClass() : _foo(_foo) {}) -> No complaints about incorrect code

When providing -I src to the cppcheck CLI, macros are correctly identified and actual issues like above are found, but analysis time skyrockets from 2 to 20 minutes.

I suspect, that by providing the whole source code again via -I, the files are all re-parsed as header files. Unfortunately, I don't have a specific include/ sub folder which I can use here. What is advised here? I am already using multiple jobs: -j 4.

答:
After some further investigation, this might actually not be a valid question:

I manually took all header files and copied them to a separate folder: find . -type f \( -iname \*.h -o -iname \*.inl -o -iname \*.hpp \) -exec cp --parents \{\} ./../__cppcheckWorkaroundInclude \; which I then provided via -I to cppcheck

The check still took 20 minutes, so my assumption that cppcheck wrongfully scans too much is invalid - it actually takes this long because it is a lot of code.

So providing -I __cppcheckWorkaroundInclude or -I src to cppcheck did not make a difference - at least I did not observe one. Meaning, that -I works as expected

To solve the performance issues (I run the job inside a CI and 20 minutes is a lot of time which I would rather spend on executing automated tests), I did the following:

Reduce the checked configurations --max-configs=5

Used incremental checking via --cppcheck-build-dir=CppcheckBuildDir

To integrate this in our Gitlab CI, I had to cache this directory:

```<code>  cache:
    paths:
      - CppcheckBuildDir
</code>```

and before the cppcheck call, the directory has to be created (but with the -p flag because the dir might already be there, taken from the cache!):

```<code>mkdir -p CppcheckBuildDir
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Our C++ project is organized in several modules (== subfolders) and headers are placed next to the .cpp files:

CMakeLists.txt
src
│
└───folder1
│   │
│   └───subfolder1
│       │   MyClass1.h
│       │   MyClass1.cpp
│       │   ...
│
└───folder2
│   │
│   └───subfolder2
│       │   MyClass2.h
│       │   MyClass2.cpp
│       │   ...

Include directives are always defined relative to the folder src and not relative to the code file e.g. in MyClass1.cpp:

#include "folder1/subfolder1/MyClass1.h" // even the own header is defined semi-relatively
#include "folder2/subfolder2/MyClass2.h"

MyClass1::MyClass1() {
// some code
}

I recently noticed that cppcheck (version 1.89) has problems with this and does not correctly

resolve macros defined in a header file -> False complaints about correct code

find problems with class member initialization (e.g. MyClass::MyClass() : _foo(_foo) {}) -> No complaints about incorrect code

When providing -I src to the cppcheck CLI, macros are correctly identified and actual issues like above are found, but analysis time skyrockets from 2 to 20 minutes.

I suspect, that by providing the whole source code again via -I, the files are all re-parsed as header files. Unfortunately, I don't have a specific include/ sub folder which I can use here. What is advised here? I am already using multiple jobs: -j 4.

Body:
After some further investigation, this might actually not be a valid question:

I manually took all header files and copied them to a separate folder: find . -type f \( -iname \*.h -o -iname \*.inl -o -iname \*.hpp \) -exec cp --parents \{\} ./../__cppcheckWorkaroundInclude \; which I then provided via -I to cppcheck

The check still took 20 minutes, so my assumption that cppcheck wrongfully scans too much is invalid - it actually takes this long because it is a lot of code.

So providing -I __cppcheckWorkaroundInclude or -I src to cppcheck did not make a difference - at least I did not observe one. Meaning, that -I works as expected

To solve the performance issues (I run the job inside a CI and 20 minutes is a lot of time which I would rather spend on executing automated tests), I did the following:

Reduce the checked configurations --max-configs=5

Used incremental checking via --cppcheck-build-dir=CppcheckBuildDir

To integrate this in our Gitlab CI, I had to cache this directory:

  cache:
    paths:
      - CppcheckBuildDir

and before the cppcheck call, the directory has to be created (but with the -p flag because the dir might already be there, taken from the cache!):

mkdir -p CppcheckBuildDir


问:
Uncaught Error: Call to undefined function stats_cdf_t()
I have to calculate an Excel formula(F.DIST.RT) in PHP. but receiving an error.
e.g,

```<code>F.DIST.RT(4, 2, 1)
</code>```

As defined here:
https://www.php.net/manual/en/function.stats-cdf-t.php

答:
First

you need to install PECL and Stat library in PHP to fix this problem.

```<code> sudo apt-get install php-pear
 sudo apt-get install php7.4-dev
 sudo pecl install stats-2.0.3
</code>```

then added extension=stats.so to my php.ini

Second

restart apache.

Third

In order to match the output of this function with Excel's TDIST function, you must take 1 - the value.  For example, for a two-tailed T-distribution for x=4 and degrees of freedom=2, the formula would be:

```<code>(1 - stats_cdf_t(4, 2, 1)) * 2
</code>```

Body:
I have to calculate an Excel formula(F.DIST.RT) in PHP. but receiving an error.
e.g,

F.DIST.RT(4, 2, 1)

As defined here:
https://www.php.net/manual/en/function.stats-cdf-t.php

Body:
First

you need to install PECL and Stat library in PHP to fix this problem.

 sudo apt-get install php-pear
 sudo apt-get install php7.4-dev
 sudo pecl install stats-2.0.3

then added extension=stats.so to my php.ini

Second

restart apache.

Third

In order to match the output of this function with Excel's TDIST function, you must take 1 - the value.  For example, for a two-tailed T-distribution for x=4 and degrees of freedom=2, the formula would be:

(1 - stats_cdf_t(4, 2, 1)) * 2


问:
Can you use template literal for function name in javascript?
can you use template literals to name functions dynamically

```<code>let variable = "something"

function `constant${variable}` () {
               //do something
}
</code>```

答:
The correct way to achieve is below your original code shouldnt work because you are trying to put string where variable name expected.

PS. By using this instead of window or global you can use snippet in both browser and node.js

let variable = "something"

this[ `constant${variable}`]= ()=> {
               console.log("it works");
}
constantsomething()```

Body:
can you use template literals to name functions dynamically

let variable = "something"

function `constant${variable}` () {
               //do something
}


问:
How to check whether date widget is empty?
I tried to check whether date widget is empty. If it is empty, it shouldn't show up.

```<code><div class="field"
    tal:define="value widget/value;
                valueexists python:value not in (None, '',);
                label widget/label"
    tal:condition="python:widget.__name__ not in ('IBasic.title', 'IBasic.description', 'title', 'description',) and valueexists">
</code>```

Problem is the below expression doesn't seem able to check for date:

```<code>python:value not in (None, '',)
</code>```

答: I'm not sure I understood your question correctly, but I'd also like to suggest jQuery as a way to check and conditionally hide (remove) a widget, if it's for aesthetic reasons.</p>

ContentLicense: CC BY-SA 3.0

Body:
I tried to check whether date widget is empty. If it is empty, it shouldn't show up.

Problem is the below expression doesn't seem able to check for date:

python:value not in (None, '',)


问:
Magento 1.9.1.0 - Unable to generate the sitemap
I guess if you meet the same error when trying to create the Google Sitemap from Magento 1.9.1.0 backend (Unable to generate the sitemap).
Under is what I found from the Exception Log:

```<code>2015-05-09T09:52:02+00:00 DEBUG (7): Exception message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'main_table.entity_id' in 'on clause', query was: SELECT `e`.`entity_id`, `e`.`created_at`, `e`.`updated_at`, `ur`.`request_path` AS `url` FROM `tts_catalog_category_entity` AS `e`
 LEFT JOIN `tts_core_url_rewrite` AS `ur` ON e.entity_id=ur.category_id AND ur.store_id='1' AND ur.product_id IS NULL AND ur.is_system=1
 INNER JOIN `tts_catalog_category_entity_int` AS `t1_is_active` ON main_table.entity_id=t1_is_active.entity_id AND t1_is_active.store_id=0
 LEFT JOIN `tts_catalog_category_entity_int` AS `t2_is_active` ON t1_is_active.entity_id = t2_is_active.entity_id AND t1_is_active.attribute_id = t2_is_active.attribute_id AND t2_is_active.store_id = '1' WHERE (e.path LIKE '1/2/%') AND (t1_is_active.attribute_id='42') AND ((IF(t2_is_active.value_id > 0, t2_is_active.value, t1_is_active.value))=1)
Trace: #0 /home/blairsin/public_html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /home/blairsin/public_html/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /home/blairsin/public_html/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 /home/blairsin/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `e`.`ent...', Array)
#4 /home/blairsin/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('SELECT `e`.`ent...', Array)
#5 /home/blairsin/public_html/app/code/community/Activo/Xmlsitemap/Model/Sitemap/Resource/Catalog/Category.php(47): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select))
#6 /home/blairsin/public_html/app/code/community/Activo/Xmlsitemap/Model/Sitemap/Sitemap.php(28): Activo_Xmlsitemap_Model_Sitemap_Resource_Catalog_Category->getCollection('1')
#7 /home/blairsin/public_html/app/code/core/Mage/Adminhtml/controllers/SitemapController.php(255): Activo_Xmlsitemap_Model_Sitemap_Sitemap->generateXml()
#8 /home/blairsin/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_SitemapController->generateAction()
#9 /home/blairsin/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('generate')
#10 /home/blairsin/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#11 /home/blairsin/public_html/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#12 /home/blairsin/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#13 /home/blairsin/public_html/index.php(87): Mage::run('base', 'website')
#14 {main}
</code>```

This should be an error happened when generating the MySQL sentence, a "main_table" table was inserted and it cannot be found in the database.
I think this is a Magento core code error - please help me figure it out.

Thank you.

答:
You are using a module (Activo_Xmlsitemap) which is rewriting the model of sitemap based on the code of an older Magento version.
I used to have the same issue after upgrading Magento 1.7 to Magento 1.9

The override needs to be adjusted by changing the table alias of catalog_category_entity from "e" to "main_table"

Body:
I guess if you meet the same error when trying to create the Google Sitemap from Magento 1.9.1.0 backend (Unable to generate the sitemap).
Under is what I found from the Exception Log:

2015-05-09T09:52:02+00:00 DEBUG (7): Exception message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'main_table.entity_id' in 'on clause', query was: SELECT `e`.`entity_id`, `e`.`created_at`, `e`.`updated_at`, `ur`.`request_path` AS `url` FROM `tts_catalog_category_entity` AS `e`
 LEFT JOIN `tts_core_url_rewrite` AS `ur` ON e.entity_id=ur.category_id AND ur.store_id='1' AND ur.product_id IS NULL AND ur.is_system=1
 INNER JOIN `tts_catalog_category_entity_int` AS `t1_is_active` ON main_table.entity_id=t1_is_active.entity_id AND t1_is_active.store_id=0
 LEFT JOIN `tts_catalog_category_entity_int` AS `t2_is_active` ON t1_is_active.entity_id = t2_is_active.entity_id AND t1_is_active.attribute_id = t2_is_active.attribute_id AND t2_is_active.store_id = '1' WHERE (e.path LIKE '1/2/%') AND (t1_is_active.attribute_id='42') AND ((IF(t2_is_active.value_id > 0, t2_is_active.value, t1_is_active.value))=1)
Trace: #0 /home/blairsin/public_html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 /home/blairsin/public_html/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 /home/blairsin/public_html/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 /home/blairsin/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `e`.`ent...', Array)
#4 /home/blairsin/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('SELECT `e`.`ent...', Array)
#5 /home/blairsin/public_html/app/code/community/Activo/Xmlsitemap/Model/Sitemap/Resource/Catalog/Category.php(47): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select))
#6 /home/blairsin/public_html/app/code/community/Activo/Xmlsitemap/Model/Sitemap/Sitemap.php(28): Activo_Xmlsitemap_Model_Sitemap_Resource_Catalog_Category->getCollection('1')
#7 /home/blairsin/public_html/app/code/core/Mage/Adminhtml/controllers/SitemapController.php(255): Activo_Xmlsitemap_Model_Sitemap_Sitemap->generateXml()
#8 /home/blairsin/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_SitemapController->generateAction()
#9 /home/blairsin/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('generate')
#10 /home/blairsin/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#11 /home/blairsin/public_html/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#12 /home/blairsin/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#13 /home/blairsin/public_html/index.php(87): Mage::run('base', 'website')
#14 {main}

This should be an error happened when generating the MySQL sentence, a "main_table" table was inserted and it cannot be found in the database.
I think this is a Magento core code error - please help me figure it out.

Thank you.


问:
How to pass multiple parameters with using RxSwift?
I did with below code for passing single parameter.

```<code>lazy var priceListData: Observable<FoodPrice> = {
        return self.foodNamesparams1.asObservable()
                   .flatMapLatest(ApiCallViewModel.foodList(_:))
}
</code>```

But I don't know how to pass multiple parameters..

If I need to pass foodNamesparams1, foodNamesparams2 to ApiCallViewModel.foodList

How can I do it with RxSwift?

foodNamesparams1 and foodNamesparams2 both are BehaviorRelay

答:
You most likely want to combine the parameters first, most likely via combineLatest or zip.

This will looks something like this

```<code>Observable.combineLatest(
    foodNamesparams1.asObservable(),
    foodNamesparams2.asObservable()
  )
  .flatMapLatest(ApiCallViewModel.foodList)

</code>```

CombineLatest will not emit anything unless both combined observables have emitted at least once - and then it will commit on any update of either combined observable.

Check out the combining section here
http://reactivex.io/documentation/operators.html#combining to find the best suited combination method

Body:
I did with below code for passing single parameter.

lazy var priceListData: Observable<FoodPrice> = {
        return self.foodNamesparams1.asObservable()
                   .flatMapLatest(ApiCallViewModel.foodList(_:))
}

But I don't know how to pass multiple parameters..

If I need to pass foodNamesparams1, foodNamesparams2 to ApiCallViewModel.foodList

How can I do it with RxSwift?

foodNamesparams1 and foodNamesparams2 both are BehaviorRelay

Body:
You most likely want to combine the parameters first, most likely via combineLatest or zip.

This will looks something like this

Observable.combineLatest(
    foodNamesparams1.asObservable(),
    foodNamesparams2.asObservable()
  )
  .flatMapLatest(ApiCallViewModel.foodList)

CombineLatest will not emit anything unless both combined observables have emitted at least once - and then it will commit on any update of either combined observable.

Check out the combining section here
http://reactivex.io/documentation/operators.html#combining to find the best suited combination method


问:
Argument 1 passed to Illuminate\\Database\\Eloquent\\Model::__construct() must be of the type array, object given
I want to add product to wishlist and following repository pattern to store product id and user id of the user who wants to add product to his wishlist but when i run my code i get

Argument 1 passed to
Illuminate\Database\Eloquent\Model::__construct() must be of the
type array, object given, called in .... WishlistRepository.php

This is my Code:

WishlistController.php

```<code>namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Contracts\WishlistContract;

class WishlistController extends Controller
{
    protected $wishlistRepository;

    public function __construct(WishlistContract $wishlistRepository)
    {
        $this->wishlistRepository = $wishlistRepository;
    }

    public function show()
    {
        $wishlist  = $this->wishlistRepository->listWishlist();
        return view('site.pages.wishlist', compact('wishlist'));
    }

    public function addToWishlist(Request $request)
    {
        $productID=$request->p_id;
        $userID=auth()->user()->id;
        $data=array('product_id'=>$productID,'user_id'=>$userID);
        $wishlist  = $this->wishlistRepository->addToWishlist($data);
    }
}
</code>```

WishlistContract.php

```<code><?php
namespace App\Contracts;

/**
 * Interface WishlistContract
 * @package App\Contracts
 */
interface WishlistContract
{
    /**
     * @param string $order
     * @param string $sort
     * @param array $columns
     * @return mixed
     */
    public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*']);

    /**
     * @param array $params
     * @return mixed
     */
    public function addToWishlist(array $params);

    /**
     * @param  $id
     * @return mixed
     */
    //public function deleteFromWishlist($id);

    /**
     * @param array $params
     * @return bool
     */
    //public function updateWishlist(array $params);

    }

?>
</code>```

WishlistRepository.php

```<code><?php
namespace App\Repositories;

use App\Models\Wishlist;
use App\Traits\UploadAble;
use Illuminate\Http\UploadedFile;
use App\Contracts\WishlistContract;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Doctrine\Instantiator\Exception\InvalidArgumentException;

/**
 * Class WishlistRepository
 *
 * @package \App\Repositories
 */
class WishlistRepository extends BaseRepository implements WishlistContract
{
    use UploadAble;
    public function __construct(Wishlist $model)
{
    parent::__construct($model);
    $this->model = $model;
}

public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
{
    return $this->all($columns, $order, $sort);
}

    public function addToWishlist(array $params)
    {
        try {
            $collection = collect($params);
            $wishlist = new Wishlist($collection);
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }

    public function removefromWishlist($id)
    {
        $wishlist = $this->findAttributeById($id);

        $wishlist->delete();

        return $wishlist;
    }

    public function updateToWishlist(array $params)
    {
        $wishlist = $this->findWishlistById($params['id']);

        $collection = collect($params)->except('_token');

        $is_filterable = $collection->has('is_filterable') ? 1 : 0;
        $is_required = $collection->has('is_required') ? 1 : 0;

        $merge = $collection->merge(compact('is_filterable', 'is_required'));

        $wishlist->update($merge->all());

        return $wishlist;
    }

}
?>
</code>```

view (script):

```<code>$('body').on('click', '.wishlist', function(e){
    e.preventDefault();
    var product_id=$(this).attr('data-wishlist');

     jQuery.ajax({

              url: "{{ url('/add-wishlist') }}",
              method: 'post',
              data: {
                 "p_id": product_id,"_token": "{{ csrf_token() }}",
              },
              success: function(result){
                // input.val(result.status);

              }});

});
</code>```

答:
You may fix it by removing this line

```<code> $collection = collect($params);
</code>```

You don't need it : because collect will convert your array to Illuminate\Support\Collection object.

Class WishlistRepository

```<code>public function addToWishlist(array $params) {
        try {

            $wishlist = new Wishlist($params);
            // OR
            // $wishlist = new Wishlist();
            // $wishlist->column = $params['column'];
            //...
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
}
</code>```

Body:
I want to add product to wishlist and following repository pattern to store product id and user id of the user who wants to add product to his wishlist but when i run my code i get

Argument 1 passed to
Illuminate\Database\Eloquent\Model::__construct() must be of the
type array, object given, called in .... WishlistRepository.php

This is my Code:

WishlistController.php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Contracts\WishlistContract;

class WishlistController extends Controller
{
    protected $wishlistRepository;

    public function __construct(WishlistContract $wishlistRepository)
    {
        $this->wishlistRepository = $wishlistRepository;
    }

    public function show()
    {
        $wishlist  = $this->wishlistRepository->listWishlist();
        return view('site.pages.wishlist', compact('wishlist'));
    }

    public function addToWishlist(Request $request)
    {
        $productID=$request->p_id;
        $userID=auth()->user()->id;
        $data=array('product_id'=>$productID,'user_id'=>$userID);
        $wishlist  = $this->wishlistRepository->addToWishlist($data);
    }
}

WishlistContract.php

<?php
namespace App\Contracts;

/**
 * Interface WishlistContract
 * @package App\Contracts
 */
interface WishlistContract
{
    /**
     * @param string $order
     * @param string $sort
     * @param array $columns
     * @return mixed
     */
    public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*']);

    /**
     * @param array $params
     * @return mixed
     */
    public function addToWishlist(array $params);

    /**
     * @param  $id
     * @return mixed
     */
    //public function deleteFromWishlist($id);

    /**
     * @param array $params
     * @return bool
     */
    //public function updateWishlist(array $params);

    }

?>

WishlistRepository.php

<?php
namespace App\Repositories;

use App\Models\Wishlist;
use App\Traits\UploadAble;
use Illuminate\Http\UploadedFile;
use App\Contracts\WishlistContract;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Doctrine\Instantiator\Exception\InvalidArgumentException;

/**
 * Class WishlistRepository
 *
 * @package \App\Repositories
 */
class WishlistRepository extends BaseRepository implements WishlistContract
{
    use UploadAble;
    public function __construct(Wishlist $model)
{
    parent::__construct($model);
    $this->model = $model;
}

public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
{
    return $this->all($columns, $order, $sort);
}

    public function addToWishlist(array $params)
    {
        try {
            $collection = collect($params);
            $wishlist = new Wishlist($collection);
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }

    public function removefromWishlist($id)
    {
        $wishlist = $this->findAttributeById($id);

        $wishlist->delete();

        return $wishlist;
    }

    public function updateToWishlist(array $params)
    {
        $wishlist = $this->findWishlistById($params['id']);

        $collection = collect($params)->except('_token');

        $is_filterable = $collection->has('is_filterable') ? 1 : 0;
        $is_required = $collection->has('is_required') ? 1 : 0;

        $merge = $collection->merge(compact('is_filterable', 'is_required'));

        $wishlist->update($merge->all());

        return $wishlist;
    }

}
?>

view (script):

$('body').on('click', '.wishlist', function(e){
    e.preventDefault();
    var product_id=$(this).attr('data-wishlist');

     jQuery.ajax({

              url: "{{ url('/add-wishlist') }}",
              method: 'post',
              data: {
                 "p_id": product_id,"_token": "{{ csrf_token() }}",
              },
              success: function(result){
                // input.val(result.status);

              }});

});

Body:
You may fix it by removing this line

 $collection = collect($params);

You don't need it : because collect will convert your array to Illuminate\Support\Collection object.

Class WishlistRepository

public function addToWishlist(array $params) {
        try {

            $wishlist = new Wishlist($params);
            // OR
            // $wishlist = new Wishlist();
            // $wishlist->column = $params['column'];
            //...
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
}


问:
vue.js loop option value in object
i have the object like this;

```<code>fluit:[
    {id:'001', name:"Apple"},
    {id:'002', name:"Banana"},
    {id:'003', name:"Mango"},
    {id:'004', name:"orange"},
    {id:'005', name:"papaya"},
  ]
</code>```

And code in vuejs like this

```<code><select >
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"{{item.name</option>
</select>
</code>```

and what i get from this tag it's like this

and what i want to ask is how can i get the value as the id of each option. like a when i select Mango and the value is 003.
if you know how to solve this please help me.
thank you.

答:
add a v-model to your select and that is it:

```<code><select v-model="selectedItem">
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select">
   {{item.name}}
  </option>
</select>
</code>```

now selectedItem will contain the value of the fruit, working example :
https://codesandbox.io/s/fruit-select-vs709

Title: vue.js loop option value in object

Body:
i have the object like this;

fluit:[
    {id:'001', name:"Apple"},
    {id:'002', name:"Banana"},
    {id:'003', name:"Mango"},
    {id:'004', name:"orange"},
    {id:'005', name:"papaya"},
  ]

And code in vuejs like this

<select >
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"{{item.name</option>
</select>

and what i get from this tag it's like this

and what i want to ask is how can i get the value as the id of each option. like a when i select Mango and the value is 003.
if you know how to solve this please help me.
thank you.

Body:
add a v-model to your select and that is it:

<select v-model="selectedItem">
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select">
   {{item.name}}
  </option>
</select>

now selectedItem will contain the value of the fruit, working example :
https://codesandbox.io/s/fruit-select-vs709


问:
Nesting tibbles and performing calculations on each with a group_by
I want to find out what the dominant class of of each id_b is. To calculate it I need to find out the sum of size per class for each id_b. Whichever class is largest is the new dominant class assigned to id_b.

The script below does what I want it to do but it feels quite clunky and over complicated. I've not worked with nested data much before so I'm not sure if I've used the best methods possible Can anyone think of a neater way of achieving the same output in tidyverse or data.table?

Thanks!

```<code>library(tidyverse)

# sample data
set.seed(123)
input <- tibble(id_a = c(letters[seq(1,10)]),
                size = runif(10, min = 10, max = 50),
                class = c("x","x","y","x","y",
                          "y","x","y","x","x"),
                id_b = c("A1","A1","B1","B1","B1",
                         "C1","C1","C1","D1","E1"))
print(input)

</code>```

```<code>   id_a   size class id_b
   <chr> <dbl> <chr> <chr>
 1 a      23.6 x     A1
 2 b      43.6 x     A1
 3 c      23.9 y     B1
 4 d      23.4 x     B1
 5 e      29.1 y     B1
 6 f      45.7 y     C1
 7 g      44.6 x     C1
 8 h      25.6 y     C1
 9 i      41.1 x     D1
10 j      48.4 x     E1
</code>```

```<code># nest input to create a nested tibble for each id_b
input_nest <- input %>% group_by(id_b) %>% nest()

# calculate dominant class
input_nest_dominant <- input_nest %>% mutate(DOMINANT_CLASS = lapply(data, function(x){
  # group each nested tibble by class, and calculate total size. Then find the biggest size and extract
  # the class value
  output <- x %>% group_by(class) %>%
            summarise(total_size = sum(size)) %>%
            top_n(total_size, n = 1) %>%
            pull(class)
  return(output)
} ))

# unnest to end up with a tibble
input_nest_dominant_clean <- input_nest_dominant %>%
                             unnest(cols = c(DOMINANT_CLASS)) %>%
                             select(-data) %>%
                             ungroup()

print(input_nest_dominant_clean)
</code>```

```<code>  id_b  DOMINANT_CLASS
  <chr> <chr>
1 A1    x
2 B1    y
3 C1    y
4 D1    x
5 E1    x
</code>```

答:
Here is a base R solution, which used aggregate twice, i.e.,

```<code>agg <-aggregate(size ~ class + id_b, input, FUN = sum)
output <- aggregate(agg[-2],agg[2],FUN = max)[-3]
</code>```

or a more compact version

```<code>output <- aggregate(.~id_b,
                    aggregate(size ~ class + id_b,
                              input,
                              FUN = function(v) sum(v)),
                    FUN = function(v) tail(sort(v),1))[-3]
</code>```

such that

```<code>> output
  id_b class
1   A1     x
2   B1     y
3   C1     y
4   D1     x
5   E1     x
</code>```

Body:
I want to find out what the dominant class of of each id_b is. To calculate it I need to find out the sum of size per class for each id_b. Whichever class is largest is the new dominant class assigned to id_b.

The script below does what I want it to do but it feels quite clunky and over complicated. I've not worked with nested data much before so I'm not sure if I've used the best methods possible Can anyone think of a neater way of achieving the same output in tidyverse or data.table?

Thanks!

library(tidyverse)

# sample data
set.seed(123)
input <- tibble(id_a = c(letters[seq(1,10)]),
                size = runif(10, min = 10, max = 50),
                class = c("x","x","y","x","y",
                          "y","x","y","x","x"),
                id_b = c("A1","A1","B1","B1","B1",
                         "C1","C1","C1","D1","E1"))
print(input)

   id_a   size class id_b
   <chr> <dbl> <chr> <chr>
 1 a      23.6 x     A1
 2 b      43.6 x     A1
 3 c      23.9 y     B1
 4 d      23.4 x     B1
 5 e      29.1 y     B1
 6 f      45.7 y     C1
 7 g      44.6 x     C1
 8 h      25.6 y     C1
 9 i      41.1 x     D1
10 j      48.4 x     E1

# nest input to create a nested tibble for each id_b
input_nest <- input %>% group_by(id_b) %>% nest()

# calculate dominant class
input_nest_dominant <- input_nest %>% mutate(DOMINANT_CLASS = lapply(data, function(x){
  # group each nested tibble by class, and calculate total size. Then find the biggest size and extract
  # the class value
  output <- x %>% group_by(class) %>%
            summarise(total_size = sum(size)) %>%
            top_n(total_size, n = 1) %>%
            pull(class)
  return(output)
} ))

# unnest to end up with a tibble
input_nest_dominant_clean <- input_nest_dominant %>%
                             unnest(cols = c(DOMINANT_CLASS)) %>%
                             select(-data) %>%
                             ungroup()

print(input_nest_dominant_clean)

  id_b  DOMINANT_CLASS
  <chr> <chr>
1 A1    x
2 B1    y
3 C1    y
4 D1    x
5 E1    x

Body:
Here is a base R solution, which used aggregate twice, i.e.,

agg <-aggregate(size ~ class + id_b, input, FUN = sum)
output <- aggregate(agg[-2],agg[2],FUN = max)[-3]

or a more compact version

output <- aggregate(.~id_b,
                    aggregate(size ~ class + id_b,
                              input,
                              FUN = function(v) sum(v)),
                    FUN = function(v) tail(sort(v),1))[-3]

such that

> output
  id_b class
1   A1     x
2   B1     y
3   C1     y
4   D1     x
5   E1     x


问:
Long json request from pojo class having too many fields
I want to know how to create a long JSON request from POJO classes and maintain code quality?
I have around 34 classes and I have to create a JSON request using it. My class having around 30 private fields with getters and setters.

I used ObjectMapper to create JSON, but I want to know how to maintain the setter of different classes?

Example

```<code>class A{
 private int a1;
 private int a2;
 private int an;
 private B b;
}

class B{
 private int b1;
 private int b2;
 private int bn;
 private C c;
}

I did code like below for above class

    A a =new A();
    a.setA1();
    a.setA2();
    a.setA3();
    A.setAn();

    B b=new B();
    b.setB1();
    b.setB2();
    b.setB3();
    b.setBn();
    A.setB(b);

    ObjectMapper Obj = new ObjectMapper();
    String jsonStr = Obj.writeValueAsString(request);
    System.out.println(jsonStr);
</code>```

Is it correct wary or how can I remove the setter part from the main code and manage another location?

答:
You can create a top level class and add all the 34 classes as properties to your top level class and getters and setters for those properties and annotate those properties with jackson @JsonProperty("value")

Example:-

```<code>public class TopLevel{

@JsonProperty("A")
private A a;
@JsonProperty("B")
private B b;
@JsonProperty("C")
private C c;
..
..
..
..
..
your 34 classes and
//constructor with all the parameters....
</code>```

And call the Topleve class in your object mapper as

```<code>ObjectMapper mapper = new ObjectMapper();
     A a = new A(a1,a2,an);
     B b = new B(b1,b2,bn);
     ..
     .. so on..
     TopLevel top= new TopLevel(a, b, c,........so on);
     String jsonWriter = mapper.writerWithDefaultPrettyPrinter()
         .writeValueAsString(top);
     System.out.println(jsonWriter);
</code>```

Body:
I want to know how to create a long JSON request from POJO classes and maintain code quality?
I have around 34 classes and I have to create a JSON request using it. My class having around 30 private fields with getters and setters.

I used ObjectMapper to create JSON, but I want to know how to maintain the setter of different classes?

Example

class A{
 private int a1;
 private int a2;
 private int an;
 private B b;
}

class B{
 private int b1;
 private int b2;
 private int bn;
 private C c;
}

I did code like below for above class

    A a =new A();
    a.setA1();
    a.setA2();
    a.setA3();
    A.setAn();

    B b=new B();
    b.setB1();
    b.setB2();
    b.setB3();
    b.setBn();
    A.setB(b);

    ObjectMapper Obj = new ObjectMapper();
    String jsonStr = Obj.writeValueAsString(request);
    System.out.println(jsonStr);

Is it correct wary or how can I remove the setter part from the main code and manage another location?

Body:
You can create a top level class and add all the 34 classes as properties to your top level class and getters and setters for those properties and annotate those properties with jackson @JsonProperty("value")

Example:-

public class TopLevel{

@JsonProperty("A")
private A a;
@JsonProperty("B")
private B b;
@JsonProperty("C")
private C c;
..
..
..
..
..
your 34 classes and
//constructor with all the parameters....

And call the Topleve class in your object mapper as

ObjectMapper mapper = new ObjectMapper();
     A a = new A(a1,a2,an);
     B b = new B(b1,b2,bn);
     ..
     .. so on..
     TopLevel top= new TopLevel(a, b, c,........so on);
     String jsonWriter = mapper.writerWithDefaultPrettyPrinter()
         .writeValueAsString(top);
     System.out.println(jsonWriter);


答:
You can try like below, we can use window or separate object to create a dynamic function using template literal

```<code>let variable = "something"

    window[`constant${variable}`] = function  () {
         console.log('dynamic func')
    }
</code>```

(or)

```<code>let variable = "something"

var obj = {
    [`constant${variable}`]: function  () {
         console.log('dynamic func')
    }
}

obj.constantsomething()
</code>```

Title: Can you use template literal for function name in javascript?

Body:
You can try like below, we can use window or separate object to create a dynamic function using template literal

let variable = "something"

    window[`constant${variable}`] = function  () {
         console.log('dynamic func')
    }

(or)

let variable = "something"

var obj = {
    [`constant${variable}`]: function  () {
         console.log('dynamic func')
    }
}

obj.constantsomething()


问:
php java batch processing
I work in Linux. I have 3 file (about 2Gb each containing human genome sequence). I have java codes to process those files via web interface developed in PHP. The processing time is about 24 hours or even more.

How can i run the Java code from PHP so that the processing does not terminate when I close the browser.

Since the processing time is so long, it is not practicable to keep the browser open until the process get completed.

I assume it requires batch processing.

答: Based on your comment, the approach used in the accepted answer for php execute a background process should do just fine. Just start the process, fetch the process id and store it in a DB together with the user that started the process (or use a filename that can be used to identify the user that started it). Using the isRunning method provided (that just does a ps for the process id provided) you can check if the process is still running.

Title: php java batch processing


问:
Best way to convert String to Boolean in Java
I currently have a question about the database of my work.

They use a String based on 0 and 1 to indicate whether it is active or not. But for my logic I would like to use true or false.

Why? Because have redundant code. For example:

```<code>if(foo.getStateClient().equals("1"))
   //Do things...
</code>```

Imagine that with 6 or 7 fields more.

Cant modify the database. And I dont know if use Strings like the before example, or do anything to cast the String a Boolean.

And, always the state is 0 or 1

I appreciate any advice to be more optimal

Edit 1
I am not asking how doing, i am asking the Best practice to do that.

I am using Spring with Hibernate that for people ask me what ORM i am using.

答:
You can use Boolean type for your attribute in your entity and use AttributeConverter for handling conversions between Boolean in entity and String/varchar in database.

```<code>@Converter
public class BooleanConverter implements AttributeConverter<Boolean, String> {

    @Override
    public Character convertToDatabaseColumn(Boolean value) {
        if (value != null) {
            if (value) {
                return '1';
            } else {
                return '0';
            }

        }
        return null;
    }

    @Override
    public Boolean convertToEntityAttribute(String value) {
        if (value != null) {
            return !value.equals('0');
        }
        return null;
    }

}
</code>```

Entity:

```<code>@Convert(converter = BooleanConverter.class)
private boolean status;
</code>```

Body:
I currently have a question about the database of my work.

They use a String based on 0 and 1 to indicate whether it is active or not. But for my logic I would like to use true or false.

Why? Because have redundant code. For example:

if(foo.getStateClient().equals("1"))
   //Do things...

Imagine that with 6 or 7 fields more.

Cant modify the database. And I dont know if use Strings like the before example, or do anything to cast the String a Boolean.

And, always the state is 0 or 1

I appreciate any advice to be more optimal

Edit 1
I am not asking how doing, i am asking the Best practice to do that.

I am using Spring with Hibernate that for people ask me what ORM i am using.

Body:
You can use Boolean type for your attribute in your entity and use AttributeConverter for handling conversions between Boolean in entity and String/varchar in database.

@Converter
public class BooleanConverter implements AttributeConverter<Boolean, String> {

    @Override
    public Character convertToDatabaseColumn(Boolean value) {
        if (value != null) {
            if (value) {
                return '1';
            } else {
                return '0';
            }

        }
        return null;
    }

    @Override
    public Boolean convertToEntityAttribute(String value) {
        if (value != null) {
            return !value.equals('0');
        }
        return null;
    }

}

Entity:

@Convert(converter = BooleanConverter.class)
private boolean status;


问:
How to specify a SmartREST 2.0 template with fragment/series name given by user
How can I define a custom SmartREST 2.0 template which behaves like the pre-defined static template 200 for creating measurements?
My goal is that the user can pass the name of fragment and series via MQTT to add generic properties.
I can only find documentation/examples for measurement creation where fragment and series are hard coded in the SmartREST template.

答:
SmartREST 2.0 does not provide functionality to set keys as payload parameters. In general I would recommend making SmartREST templates as specific as possible. This saves transfer data volume and makes configuration more granular.

SmartREST 1.0 provides the functionality you are looking for. It provides full access to the associated JSON structure. Unfortunately this flexibility comes with the downside that it is only available though API and not via user interface. See here: https://cumulocity.com/guides/reference/smartrest/ and here: https://cumulocity.com/guides/device-sdk/mqtt/#smartrest-1


问:
Ignore yarn missing unmet dependencies warning in azure pipelines
I'm struggling to get a build with yarn working on azure pipelines build. I'm running on a self hosted windows 10 machine, with Node 8 and Yarn 1.13.

My pipeline definition can be boiled down to:

```<code>steps:
  - powershell: |
      yarn install --frozen-lockfile
</code>```

and the output I'm getting is

```<code>##[section]Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Windows, macOS, or Linux.
Version      : 2.140.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
==============================================================================
Generating script.
##[command]"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\24a48e14-3107-454e-bb0b-28c377addce3.ps1'"
yarn install v1.13.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.7: The platform "win32" is incompatible with this module.
info "fsevents@1.2.7" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
##[error]yarn : warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
##[error]At C:\agent\_work\_temp\24a48e14-3107-454e-bb0b-28c377addce3.ps1:3 char:1

##[error]+ yarn install --frozen-lockfile

##[error]+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

##[error]    + CategoryInfo          : NotSpecified: (warning " > boo...ery@1.9.1 - 3".:String) [], RemoteException

##[error]    + FullyQualifiedErrorId : NativeCommandError

##[error]

##[error]PowerShell exited with code '1'.
##[section]Finishing: PowerShell

</code>```

I'm expecting to get many unmet peer dependency warnings (bootstrap is just the first of many) (and it's basically impossible to resolve them by installing the correct packages since they are mutually exclusive - e.g. webpack stylelint hasnt been correctly updated for half a year)

I've tried redirecting stderr to a file, since yarn logs the error as a warning (source) and that uses stderr (source)

```<code>steps:
  - powershell: |
      yarn install --frozen-lockfile 2>err.txt
</code>```

but that produces the same output, and err.txt is empty.

I also tried capturing the output into a variable, but it still writes the error

```<code>steps:
  - powershell: |
      $foo = yarn install --frozen-lockfile 2>err.txt
</code>```

produces:

```<code>##[section]Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Windows, macOS, or Linux.
Version      : 2.140.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
==============================================================================
Generating script.
##[command]"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\743ab1e7-3b9a-4659-89b9-7320da0ea69a.ps1'"
##[error]yarn : warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
##[error]At C:\agent\_work\_temp\743ab1e7-3b9a-4659-89b9-7320da0ea69a.ps1:3 char:8

##[error]+ $foo = yarn install --frozen-lockfile 2>err.txt

##[error]+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

##[error]    + CategoryInfo          : NotSpecified: (warning " > boo...ery@1.9.1 - 3".:String) [], RemoteException

##[error]    + FullyQualifiedErrorId : NativeCommandError

##[error]

##[error]PowerShell exited with code '1'.
##[section]Finishing: PowerShell
</code>```

As requested, redirecting stderr to stdout doesnt work either:

```<code>steps:
  - powershell: |
      $foo = yarn install --frozen-lockfile 2>&1
</code>```

or

```<code>steps:
  - powershell: |
      yarn install --frozen-lockfile 2>&1 | Out-Null
</code>```

produces:

```<code>##[section]Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Windows, macOS, or Linux.
Version      : 2.140.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
==============================================================================
Generating script.
##[command]"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\e34f54b3-f15e-426c-aa65-1476ed3d3d34.ps1'"
##[error]yarn : warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
##[error]At C:\agent\_work\_temp\e34f54b3-f15e-426c-aa65-1476ed3d3d34.ps1:3 char:8
+ $foo = yarn install --frozen-lockfile 2>&1

##[error]+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

##[error]    + CategoryInfo          : NotSpecified: (warning " > boo...ery@1.9.1 - 3".:String) [], RemoteException

##[error]    + FullyQualifiedErrorId : NativeCommandError

##[error]

##[error]PowerShell exited with code '1'.
##[section]Finishing: PowerShell
</code>```

答:
You should set Powershell Task.input.errorActionPreference to Continue. It defaults to Stop which causes powershell to throw exception on first error emitted into the stream.

This is code taken from our pipeline yml

```<code>Write-Host "Set ErrorAction=Continue. Previous value: $ErrorActionPreference"
$prev = $ErrorActionPreference
$ErrorActionPreference="Continue"

try {

    & yarn --pure-lockfile *>&1 | ForEach-Object {

        $obj = $_
        if ( $obj -is [System.Management.Automation.ErrorRecord] ) {
           $s = $obj.Exception.Message
        }
        else {
           $s = $obj.ToString()
        }
        if ( $s.Contains('error') ) {
            Write-Error $s
        }
        elseif ($s.Contains('warning')) {
            Write-Warning $s
        }
        else {
            Write-Host $s
        }
     }
}
finally {
    $ErrorActionPreference = $prev
}

$LASTEXITCODE = 0
</code>```

We actually redirect all streams to default one, and then process messages one by one to detect only errors which sent to agent for fail tasks

Body:
I'm struggling to get a build with yarn working on azure pipelines build. I'm running on a self hosted windows 10 machine, with Node 8 and Yarn 1.13.

My pipeline definition can be boiled down to:

steps:
  - powershell: |
      yarn install --frozen-lockfile

and the output I'm getting is

##[section]Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Windows, macOS, or Linux.
Version      : 2.140.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
==============================================================================
Generating script.
##[command]"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\24a48e14-3107-454e-bb0b-28c377addce3.ps1'"
yarn install v1.13.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.7: The platform "win32" is incompatible with this module.
info "fsevents@1.2.7" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
##[error]yarn : warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
##[error]At C:\agent\_work\_temp\24a48e14-3107-454e-bb0b-28c377addce3.ps1:3 char:1

##[error]+ yarn install --frozen-lockfile

##[error]+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

##[error]    + CategoryInfo          : NotSpecified: (warning " > boo...ery@1.9.1 - 3".:String) [], RemoteException

##[error]    + FullyQualifiedErrorId : NativeCommandError

##[error]

##[error]PowerShell exited with code '1'.
##[section]Finishing: PowerShell

I'm expecting to get many unmet peer dependency warnings (bootstrap is just the first of many) (and it's basically impossible to resolve them by installing the correct packages since they are mutually exclusive - e.g. webpack stylelint hasnt been correctly updated for half a year)

I've tried redirecting stderr to a file, since yarn logs the error as a warning (source) and that uses stderr (source)

steps:
  - powershell: |
      yarn install --frozen-lockfile 2>err.txt

but that produces the same output, and err.txt is empty.

I also tried capturing the output into a variable, but it still writes the error

steps:
  - powershell: |
      $foo = yarn install --frozen-lockfile 2>err.txt

produces:

##[section]Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Windows, macOS, or Linux.
Version      : 2.140.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
==============================================================================
Generating script.
##[command]"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\743ab1e7-3b9a-4659-89b9-7320da0ea69a.ps1'"
##[error]yarn : warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
##[error]At C:\agent\_work\_temp\743ab1e7-3b9a-4659-89b9-7320da0ea69a.ps1:3 char:8

##[error]+ $foo = yarn install --frozen-lockfile 2>err.txt

##[error]+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

##[error]    + CategoryInfo          : NotSpecified: (warning " > boo...ery@1.9.1 - 3".:String) [], RemoteException

##[error]    + FullyQualifiedErrorId : NativeCommandError

##[error]

##[error]PowerShell exited with code '1'.
##[section]Finishing: PowerShell

As requested, redirecting stderr to stdout doesnt work either:

steps:
  - powershell: |
      $foo = yarn install --frozen-lockfile 2>&1

or

steps:
  - powershell: |
      yarn install --frozen-lockfile 2>&1 | Out-Null

produces:

##[section]Starting: PowerShell
==============================================================================
Task         : PowerShell
Description  : Run a PowerShell script on Windows, macOS, or Linux.
Version      : 2.140.2
Author       : Microsoft Corporation
Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613736)
==============================================================================
Generating script.
##[command]"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\e34f54b3-f15e-426c-aa65-1476ed3d3d34.ps1'"
##[error]yarn : warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".
##[error]At C:\agent\_work\_temp\e34f54b3-f15e-426c-aa65-1476ed3d3d34.ps1:3 char:8
+ $foo = yarn install --frozen-lockfile 2>&1

##[error]+        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

##[error]    + CategoryInfo          : NotSpecified: (warning " > boo...ery@1.9.1 - 3".:String) [], RemoteException

##[error]    + FullyQualifiedErrorId : NativeCommandError

##[error]

##[error]PowerShell exited with code '1'.
##[section]Finishing: PowerShell

Body:
You should set Powershell Task.input.errorActionPreference to Continue. It defaults to Stop which causes powershell to throw exception on first error emitted into the stream.

This is code taken from our pipeline yml

Write-Host "Set ErrorAction=Continue. Previous value: $ErrorActionPreference"
$prev = $ErrorActionPreference
$ErrorActionPreference="Continue"

try {

    & yarn --pure-lockfile *>&1 | ForEach-Object {

        $obj = $_
        if ( $obj -is [System.Management.Automation.ErrorRecord] ) {
           $s = $obj.Exception.Message
        }
        else {
           $s = $obj.ToString()
        }
        if ( $s.Contains('error') ) {
            Write-Error $s
        }
        elseif ($s.Contains('warning')) {
            Write-Warning $s
        }
        else {
            Write-Host $s
        }
     }
}
finally {
    $ErrorActionPreference = $prev
}

$LASTEXITCODE = 0

We actually redirect all streams to default one, and then process messages one by one to detect only errors which sent to agent for fail tasks


答:
Not like that, because a template literal evaluates to a string, and you can't write function "abc"() { ... } either.

However, you can try putting it in global context using the name + bracket notation. E.g. when running in a browser:

let variable = "something"

window[`constant${variable}`] = function() {
  console.log("Hello!");
}

constantsomething();```
</div>
</div>
</p>

<p>And with a <em>Node</em> project, it will probably go something like this:</p>

```let variable = "something"

global[`constant${variable}`] = function() {
  console.log("Hello!");
}

constantsomething();
```

Body:
can you use template literals to name functions dynamically

let variable = "something"

function `constant${variable}` () {
               //do something
}

Body:
Not like that, because a template literal evaluates to a string, and you can't write function "abc"() { ... } either.

However, you can try putting it in global context using the name + bracket notation. E.g. when running in a browser:

let variable = "something"

window[`constant${variable}`] = function() {
  console.log("Hello!");
}

constantsomething();

And with a Node project, it will probably go something like this:

let variable = "something"

global[`constant${variable}`] = function() {
  console.log("Hello!");
}

constantsomething();


问:
Event Listener for Web XR
In the Web VR API there was an event listener for entering/exiting VR display;

```<code>window.addEventListener('vrdisplaypresentchange', function() {
//do something
}
</code>```

Is there an equivalent for the Web XR API?

答:
Not really sure why it was downvoted (twice!).

The WebXR specs define a few events:

https://www.w3.org/TR/webxr/#event-types

As you can see there, there is a visibilitychange event (https://www.w3.org/TR/webxr/#eventdef-xrsession-visibilitychange) that might be helpful, but it really depends on what you are trying to achieve.

Title: Event Listener for Web XR

Body:
In the Web VR API there was an event listener for entering/exiting VR display;

window.addEventListener('vrdisplaypresentchange', function() {
//do something
}

Is there an equivalent for the Web XR API?


问:
How to post the time ReactJs
I explain my problem of the day

in the following code, I post objects

my question, is it possible to post the time at which the post was made?

```<code>postbackend = () =>{
const config = {
method: "POST",
headers: {
  "Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
  if (res.error) {
    alert(res.error);
  } else {
    alert(`ajouté avec l'ID ${res}!`);
  }
}).catch(e => {
  console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}
</code>```

I would simply like to recover the time at which the post was made
Do you have an idea of how to fix this? Neff

答:
```<code>postbackend = () => {
    startDate = new Date(); // add this date
    const config = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            ...this.state,
            items: this.props.items
        }),
    };
    const url = entrypoint + "/alluserpls";
    fetch(url, config)
        .then(res => res.json())
        .then(res => {
            if (res.error) {
                alert(res.error);
            } else {
                alert(`ajouté avec l'ID ${res}!`);
            }
        }).catch(e => {
            console.error(e);
        }).finally(() => this.setState({
            redirect: true
        }));
    return startDate; // return it
}
</code>```

After that you get a date for each postbackend:

```<code>const date1 = postbackend();
const date2 = postbackend();
const date3 = postbackend();
</code>```

You can save them in a list

```<code>const dates = [];
dates.push(postbackend());
</code>```

Persist them to a DB and so on

Title: How to post the time ReactJs

Body:
I explain my problem of the day

in the following code, I post objects

my question, is it possible to post the time at which the post was made?

postbackend = () =>{
const config = {
method: "POST",
headers: {
  "Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
  if (res.error) {
    alert(res.error);
  } else {
    alert(`ajouté avec l'ID ${res}!`);
  }
}).catch(e => {
  console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}

I would simply like to recover the time at which the post was made
Do you have an idea of how to fix this? Neff

Body:
postbackend = () => {
    startDate = new Date(); // add this date
    const config = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            ...this.state,
            items: this.props.items
        }),
    };
    const url = entrypoint + "/alluserpls";
    fetch(url, config)
        .then(res => res.json())
        .then(res => {
            if (res.error) {
                alert(res.error);
            } else {
                alert(`ajouté avec l'ID ${res}!`);
            }
        }).catch(e => {
            console.error(e);
        }).finally(() => this.setState({
            redirect: true
        }));
    return startDate; // return it
}

After that you get a date for each postbackend:

const date1 = postbackend();
const date2 = postbackend();
const date3 = postbackend();

You can save them in a list

const dates = [];
dates.push(postbackend());

Persist them to a DB and so on


问:
Ruby: Most concise way to use an ENV variable if it exists, otherwise use default value
In Ruby, I am trying to write a line that uses a variable if it has been set, otherwise default to some value:

```<code>myvar = # assign it to ENV['MY_VAR'], otherwise assign it to 'foobar'
</code>```

I could write this code like this:

```<code>if ENV['MY_VAR'].is_set? #whatever the function is to check if has been set
  myvar = ENV['MY_VAR']
else
  myvar = 'foobar'
end
</code>```

But this is rather verbose, and I'm trying to write it in the most concise way possible. How can I do this?

答:
This works best for me:</p>

```<code>ENV.fetch('VAR_NAME',"5445")
</code>```

Body:
In Ruby, I am trying to write a line that uses a variable if it has been set, otherwise default to some value:

myvar = # assign it to ENV['MY_VAR'], otherwise assign it to 'foobar'

I could write this code like this:

if ENV['MY_VAR'].is_set? #whatever the function is to check if has been set
  myvar = ENV['MY_VAR']
else
  myvar = 'foobar'
end

But this is rather verbose, and I'm trying to write it in the most concise way possible. How can I do this?

Body:
This works best for me:

ENV.fetch('VAR_NAME',"5445")


问:
How to call jar files from PHP?
I know this question is not new but I am posting this after going through enough googling around.

I have a jar file which I don't control. I mean I have not written the Java class in there and all I know is that there is a class named "hist" in it which takes two arrays and gives out the output. Now I have to use PHP to call this class "hist" in the jar file named "histvol.jar". I have installed the PHP/Java Bridge and it is installed correctly.

But I don't understand how to call this jar file in PHP and where to place this jar file.

This is what I did:

Installed tomcat and php-javabridge

Placed the jarfile "histvol.jar" under Tomcat/webapps/JavaBridgeTemplate621/webinf/lib/

Went to xampp/htdocs and created a file named testjava.php

```<code><?php
require_once("http://localhost:8080/JavaBridgeTemplate621/java/Java.inc");
$System = java("java.lang.System");
$myclass=java("histvol");
echo $System->getProperties();
?>
</code>```

Class not found exception is expected because I am not calling it anywhere in PHP, but how do I call it?

I am lost, please help (I don't know a word of Java).

答:
Ok I got it finally, I just had to do this:-

```<code>$myclass=new java("histvolone.histvol");
</code>```

instead of

```<code>$myclass=new java("histvol");
</code>```

It worked !

Title: How to call jar files from PHP?

Body:
I know this question is not new but I am posting this after going through enough googling around.

I have a jar file which I don't control. I mean I have not written the Java class in there and all I know is that there is a class named "hist" in it which takes two arrays and gives out the output. Now I have to use PHP to call this class "hist" in the jar file named "histvol.jar". I have installed the PHP/Java Bridge and it is installed correctly.

But I don't understand how to call this jar file in PHP and where to place this jar file.

This is what I did:

Installed tomcat and php-javabridge

Placed the jarfile "histvol.jar" under Tomcat/webapps/JavaBridgeTemplate621/webinf/lib/

Went to xampp/htdocs and created a file named testjava.php

<?php
require_once("http://localhost:8080/JavaBridgeTemplate621/java/Java.inc");
$System = java("java.lang.System");
$myclass=java("histvol");
echo $System->getProperties();
?>

Class not found exception is expected because I am not calling it anywhere in PHP, but how do I call it?

I am lost, please help (I don't know a word of Java).

Body:
Ok I got it finally, I just had to do this:-

$myclass=new java("histvolone.histvol");

instead of

$myclass=new java("histvol");

It worked !


问:
Pandas dataframe reverse increment dictionary in new column
I saved a dictionary with different keys in each row and all values equal to 0 in a new Dataframe column.

Starting from the end, and depending on the value of another column (same row), I would like to increment this dictionary, and store the view of this dictionary.

Incrementing is fine, but storing the view doesn't work. In the end I have the same dictionary in the whole column.

```<code>Before
col1    col_dict
1       {1:0, 2:0, 3:0}
2       {1:0, 2:0, 3:0}
3       {1:0, 2:0, 3:0}

What i want:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:0, 2:1, 3:1}
3       {1:0, 2:0, 3:1}

What I have:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:1, 2:1, 3:1}
3       {1:1, 2:1, 3:1}

</code>```

For example:

```<code>def function():
    for x in reversed(range(20)):
        #taking the value in the other column, and incrementing the value in the dictionary
        dataset["dict_column"][x][str(dataset.value[x])][0] += 1
</code>```

I have tried to pass to list format, same problem.
I think it's due to the process of pandas.

Thank you in advance.

Open to any solution to do the job

答:
You can use the copy of the dictionary for assigning to col_dict after incrementing the dictionary. Reindexing the dataframe to ensure reverse increment.

```<code>import pandas as pd
import copy
df = pd.DataFrame()
df["col1"] = [1, 2, 3]

col_dict = {i:0 for i in df["col1"]}

def get_dict(col):
    col_dict[col] = 1
    return copy.copy(col_dict)

df = df.iloc[::-1]
df["col_dict"] = df["col1"].apply(get_dict)
df = df.iloc[::-1]
print(df)
</code>```

Body:
I saved a dictionary with different keys in each row and all values equal to 0 in a new Dataframe column.

Starting from the end, and depending on the value of another column (same row), I would like to increment this dictionary, and store the view of this dictionary.

Incrementing is fine, but storing the view doesn't work. In the end I have the same dictionary in the whole column.

Before
col1    col_dict
1       {1:0, 2:0, 3:0}
2       {1:0, 2:0, 3:0}
3       {1:0, 2:0, 3:0}

What i want:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:0, 2:1, 3:1}
3       {1:0, 2:0, 3:1}

What I have:

col1    col_dict
1       {1:1, 2:1, 3:1}
2       {1:1, 2:1, 3:1}
3       {1:1, 2:1, 3:1}

For example:

def function():
    for x in reversed(range(20)):
        #taking the value in the other column, and incrementing the value in the dictionary
        dataset["dict_column"][x][str(dataset.value[x])][0] += 1

I have tried to pass to list format, same problem.
I think it's due to the process of pandas.

Thank you in advance.

Open to any solution to do the job

Body:
You can use the copy of the dictionary for assigning to col_dict after incrementing the dictionary. Reindexing the dataframe to ensure reverse increment.

import pandas as pd
import copy
df = pd.DataFrame()
df["col1"] = [1, 2, 3]

col_dict = {i:0 for i in df["col1"]}

def get_dict(col):
    col_dict[col] = 1
    return copy.copy(col_dict)

df = df.iloc[::-1]
df["col_dict"] = df["col1"].apply(get_dict)
df = df.iloc[::-1]
print(df)


问:
Html tags ul li not working in "windows outlook"?
I am trying to send HTML code as email, when I am using ul li in HTML it is not showing unordered list in windows outlook.

Ul Examples For Outlook

Type 1

Type 2

Type 3

Type 4

```

I am expecting email should contain unordered list with bullets.But it does not showing bullet in actual email.Also it adds some margin to ul.

答:
It is because outlook set some negative margin to lists(I think) so you should set some extra margin to them:</p>

```<code> <!– [if gte mso 9]>
 <style>
     li {text-align:-webkit-match-parent; display:list-item;text-indent: -1em;}
     ul, ol{    margin-left: 40px !important;}
 </style>
 <![endif]–>
</code>```

Body:
I am trying to send HTML code as email, when I am using ul li in HTML it is not showing unordered list in windows outlook.

Ul Examples For Outlook

Type 1

Type 2

Type 3

Type 4

I am expecting email should contain unordered list with bullets.But it does not showing bullet in actual email.Also it adds some margin to ul.

Body:
It is because outlook set some negative margin to lists(I think) so you should set some extra margin to them:

 <!– [if gte mso 9]>
 <style>
     li {text-align:-webkit-match-parent; display:list-item;text-indent: -1em;}
     ul, ol{    margin-left: 40px !important;}
 </style>
 <![endif]–>


问:
how to select distinct values from 2 tables in sql
table1

```<code>id
1
2
3
4
5
</code>```

table2

```<code>id
4
5
6
7
8
</code>```

I want to result in this way:

```<code>id
1
2
3
6
7
8
</code>```

答:
Here is one way to do it in MySQL, using union all and not exists:

```<code>select t1.id
from table1 t1
where not exists (select 1 from table2 t2 where t2.id = t1.id)
union all
select t2.id
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.id)
</code>```

Demo on DB Fiddle:

```
| id |
| -: |
|  1 |
|  2 |
|  3 |
|  6 |
|  7 |
|  8 |
```

Body:
table1

id
1
2
3
4
5

table2

id
4
5
6
7
8

I want to result in this way:

id
1
2
3
6
7
8

Body:
Here is one way to do it in MySQL, using union all and not exists:

select t1.id
from table1 t1
where not exists (select 1 from table2 t2 where t2.id = t1.id)
union all
select t2.id
from table2 t2
where not exists (select 1 from table1 t1 where t1.id = t2.id)

Demo on DB Fiddle:

| id |
| -: |
|  1 |
|  2 |
|  3 |
|  6 |
|  7 |
|  8 |


答:
```<code> public function addToWishlist(array $params)
    {
        try {
            $collection = collect($params);
            $wishlist = new Wishlist($collection);
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }
</code>```

You are passing $collection to a model whe it's expecting array with values.

When you are making the new instance of Wishlist pass in the array as it is, instead of creating and passing a collection

```<code> public function addToWishlist(array $params)
    {
        try {
            return (new Wishlist($params))->save();
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }
</code>```

Title: Argument 1 passed to Illuminate\\Database\\Eloquent\\Model::__construct() must be of the type array, object given

Body:
I want to add product to wishlist and following repository pattern to store product id and user id of the user who wants to add product to his wishlist but when i run my code i get

Argument 1 passed to
Illuminate\Database\Eloquent\Model::__construct() must be of the
type array, object given, called in .... WishlistRepository.php

This is my Code:

WishlistController.php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Contracts\WishlistContract;

class WishlistController extends Controller
{
    protected $wishlistRepository;

    public function __construct(WishlistContract $wishlistRepository)
    {
        $this->wishlistRepository = $wishlistRepository;
    }

    public function show()
    {
        $wishlist  = $this->wishlistRepository->listWishlist();
        return view('site.pages.wishlist', compact('wishlist'));
    }

    public function addToWishlist(Request $request)
    {
        $productID=$request->p_id;
        $userID=auth()->user()->id;
        $data=array('product_id'=>$productID,'user_id'=>$userID);
        $wishlist  = $this->wishlistRepository->addToWishlist($data);
    }
}

WishlistContract.php

<?php
namespace App\Contracts;

/**
 * Interface WishlistContract
 * @package App\Contracts
 */
interface WishlistContract
{
    /**
     * @param string $order
     * @param string $sort
     * @param array $columns
     * @return mixed
     */
    public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*']);

    /**
     * @param array $params
     * @return mixed
     */
    public function addToWishlist(array $params);

    /**
     * @param  $id
     * @return mixed
     */
    //public function deleteFromWishlist($id);

    /**
     * @param array $params
     * @return bool
     */
    //public function updateWishlist(array $params);

    }

?>

WishlistRepository.php

<?php
namespace App\Repositories;

use App\Models\Wishlist;
use App\Traits\UploadAble;
use Illuminate\Http\UploadedFile;
use App\Contracts\WishlistContract;
use Illuminate\Database\QueryException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Doctrine\Instantiator\Exception\InvalidArgumentException;

/**
 * Class WishlistRepository
 *
 * @package \App\Repositories
 */
class WishlistRepository extends BaseRepository implements WishlistContract
{
    use UploadAble;
    public function __construct(Wishlist $model)
{
    parent::__construct($model);
    $this->model = $model;
}

public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
{
    return $this->all($columns, $order, $sort);
}

    public function addToWishlist(array $params)
    {
        try {
            $collection = collect($params);
            $wishlist = new Wishlist($collection);
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }

    public function removefromWishlist($id)
    {
        $wishlist = $this->findAttributeById($id);

        $wishlist->delete();

        return $wishlist;
    }

    public function updateToWishlist(array $params)
    {
        $wishlist = $this->findWishlistById($params['id']);

        $collection = collect($params)->except('_token');

        $is_filterable = $collection->has('is_filterable') ? 1 : 0;
        $is_required = $collection->has('is_required') ? 1 : 0;

        $merge = $collection->merge(compact('is_filterable', 'is_required'));

        $wishlist->update($merge->all());

        return $wishlist;
    }

}
?>

view (script):

$('body').on('click', '.wishlist', function(e){
    e.preventDefault();
    var product_id=$(this).attr('data-wishlist');

     jQuery.ajax({

              url: "{{ url('/add-wishlist') }}",
              method: 'post',
              data: {
                 "p_id": product_id,"_token": "{{ csrf_token() }}",
              },
              success: function(result){
                // input.val(result.status);

              }});

});

Body:
 public function addToWishlist(array $params)
    {
        try {
            $collection = collect($params);
            $wishlist = new Wishlist($collection);
            $wishlist->save();
            return $wishlist;
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }

You are passing $collection to a model whe it's expecting array with values.

When you are making the new instance of Wishlist pass in the array as it is, instead of creating and passing a collection

 public function addToWishlist(array $params)
    {
        try {
            return (new Wishlist($params))->save();
        } catch (QueryException $exception) {
            throw new InvalidArgumentException($exception->getMessage());
        }
    }


问:
Applying a function n times
I am trying to apply a function to a value n times.

Currently, I have

```<code>let rec n_times (f, n, v) =
 if n > 0 then
  n_times f n-1 (f v)
 else
  v
</code>```

For some reason I keep getting an error that says

```<code>This expression has type 'a but an expression was expected of type 'a * int * 'b
The type variable 'a occurs inside 'a * int * 'b
</code>```

I saw a few posts that address the same problem I am working on but none of them gets the same error.

答:
There seems to be a misunderstanding in how OCaml functions with multiple arguments are defined. You should replace

```<code>let rec n_times (f, n, v) =
</code>```

with:

```<code>let rec n_times f n v =
</code>```

Title: Applying a function n times

Body:
I am trying to apply a function to a value n times.

Currently, I have

let rec n_times (f, n, v) =
 if n > 0 then
  n_times f n-1 (f v)
 else
  v

For some reason I keep getting an error that says

This expression has type 'a but an expression was expected of type 'a * int * 'b
The type variable 'a occurs inside 'a * int * 'b

I saw a few posts that address the same problem I am working on but none of them gets the same error.

Body:
There seems to be a misunderstanding in how OCaml functions with multiple arguments are defined. You should replace

let rec n_times (f, n, v) =

with:

let rec n_times f n v =


问:
Is not a known element (After migrate to Angular 9)
After migrate to Angular 9 (before was Angular 8), i get a problem with using some own component.
My component choose-popup-data-reference have module (declare and export), which is imported in docName module. But I get ERROR. (I try add CUSTOM_ELEMENTS_SCHEMA, but it doesn't help).

I use this component in other modules, and everything work well.

```<code>ERROR in src/app/components/feature/document/docName.html:211:1 - error NG8001: 'choose-popup-data-
reference' is not a known element:
1. If 'choose-popup-data-reference' is an Angular component, then verify that it is part of this module.
2. If 'choose-popup-data-reference' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

211 <choose-popup-data-reference
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
212     [referenceType]="'some_type'"
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213     #docComplModal
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214     (setChooseData)="fillDocAction($event)">
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

Module for component - choose-popup-data-reference

```<code>@NgModule({
    imports: [CommonModule, TranslateModule, FormsModule],
    exports: [ChoosePopupDataReferenceComponent],
    declarations: [ChoosePopupDataReferenceComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class ChoosePopupDataReferenceModule {
}
</code>```

After import in imports block docNameModule

```<code>...
imports: [
   ...
   ChoosePopupDataReferenceModule
   ...
]
...
</code>```

答:
My docNameModule has not been used anywhere. (Old page unused, but not delete).
After I import module to SubModule (lazy) the error disappeared.</p>

Body:
After migrate to Angular 9 (before was Angular 8), i get a problem with using some own component.
My component choose-popup-data-reference have module (declare and export), which is imported in docName module. But I get ERROR. (I try add CUSTOM_ELEMENTS_SCHEMA, but it doesn't help).

I use this component in other modules, and everything work well.

ERROR in src/app/components/feature/document/docName.html:211:1 - error NG8001: 'choose-popup-data-
reference' is not a known element:
1. If 'choose-popup-data-reference' is an Angular component, then verify that it is part of this module.
2. If 'choose-popup-data-reference' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

211 <choose-popup-data-reference
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
212     [referenceType]="'some_type'"
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213     #docComplModal
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214     (setChooseData)="fillDocAction($event)">
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Module for component - choose-popup-data-reference

@NgModule({
    imports: [CommonModule, TranslateModule, FormsModule],
    exports: [ChoosePopupDataReferenceComponent],
    declarations: [ChoosePopupDataReferenceComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class ChoosePopupDataReferenceModule {
}

After import in imports block docNameModule

...
imports: [
   ...
   ChoosePopupDataReferenceModule
   ...
]
...


问:
Having issues with using COM Autofilter in AHK language
I'm able to apply the Autofilter criteria but the filtered rows are not visible. However, if I go to advanced filter, and click Ok on the already applied filter, then the results appear. I don't know what's happening, here is the code.

```<code>    try xl := ComObjActive("Excel.Application")
catch e
{
xl := ComObjCreate("Excel.Application")
}

wb_YTD := xl.Workbooks.Open(A_Desktop "\R&B YTD.xlsx")

if (WinExist("BnR Weekly Counts"))
wb_bnr :=  xl.Workbooks.Item("BnR Weekly Counts")
else
wb_bnr := xl.Workbooks.Open(A_Desktop "\BnR Weekly Counts.xlsx")

wb_YTD.Sheets(1).AutoFilter.Range.Autofilter
FormatTime, current_month, YYYYMMDDHH24MISS, M

criteria1 := "> " current_month "/9/" A_Year
criteria2 := "< " current_month "/11/" A_Year

wb_YTD.Sheets(1).Range("$A$1").AutoFilter(Field := 3,Criteria1 := criteria1, Operator := 1, Criteria2 := criteria2)
</code>```

Here, Column 3 contains the dates that I want to filter, Criteria1 is > 2/9/2020 and Criteria 2 is < 2/11/2020

Thanks!

答:
Caught the error, the extra 'space' in the criteria "> " was causing this error

Working filter code:

```<code>FormatTime, current_month, YYYYMMDDHH24MISS, M ; To store the month count without extra 0
start_date := ">=" current_month "/9/" A_Year
end_date := "<=" current_month "/15/" A_Year

wb_YTD.Sheets(1).Range("A1:F10000").AutoFilter(Field := 3,Criteria1 := start_date, Operator := 1, Criteria2 := end_date)
</code>```

Body:
I'm able to apply the Autofilter criteria but the filtered rows are not visible. However, if I go to advanced filter, and click Ok on the already applied filter, then the results appear. I don't know what's happening, here is the code.

    try xl := ComObjActive("Excel.Application")
catch e
{
xl := ComObjCreate("Excel.Application")
}

wb_YTD := xl.Workbooks.Open(A_Desktop "\R&B YTD.xlsx")

if (WinExist("BnR Weekly Counts"))
wb_bnr :=  xl.Workbooks.Item("BnR Weekly Counts")
else
wb_bnr := xl.Workbooks.Open(A_Desktop "\BnR Weekly Counts.xlsx")

wb_YTD.Sheets(1).AutoFilter.Range.Autofilter
FormatTime, current_month, YYYYMMDDHH24MISS, M

criteria1 := "> " current_month "/9/" A_Year
criteria2 := "< " current_month "/11/" A_Year

wb_YTD.Sheets(1).Range("$A$1").AutoFilter(Field := 3,Criteria1 := criteria1, Operator := 1, Criteria2 := criteria2)

Here, Column 3 contains the dates that I want to filter, Criteria1 is > 2/9/2020 and Criteria 2 is < 2/11/2020

Thanks!

Body:
Caught the error, the extra 'space' in the criteria "> " was causing this error

Working filter code:

FormatTime, current_month, YYYYMMDDHH24MISS, M ; To store the month count without extra 0
start_date := ">=" current_month "/9/" A_Year
end_date := "<=" current_month "/15/" A_Year

wb_YTD.Sheets(1).Range("A1:F10000").AutoFilter(Field := 3,Criteria1 := start_date, Operator := 1, Criteria2 := end_date)


答:
```<code>body: JSON.stringify({...this.state, created: new Date().toISOString(), items:this.props.items})
</code>```

This will add the timestamp to the POST body.

You should take into consideration the fact this is considered to be a bad practice. Because users might have different time on their computers. That could lead to inconsistencies. The best way to solve the problem would be to set up the date/time on the server.

Title: How to post the time ReactJs

Body:
I explain my problem of the day

in the following code, I post objects

my question, is it possible to post the time at which the post was made?

postbackend = () =>{
const config = {
method: "POST",
headers: {
  "Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
  if (res.error) {
    alert(res.error);
  } else {
    alert(`ajouté avec l'ID ${res}!`);
  }
}).catch(e => {
  console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}

I would simply like to recover the time at which the post was made
Do you have an idea of how to fix this? Neff

Body:
body: JSON.stringify({...this.state, created: new Date().toISOString(), items:this.props.items})

This will add the timestamp to the POST body.

You should take into consideration the fact this is considered to be a bad practice. Because users might have different time on their computers. That could lead to inconsistencies. The best way to solve the problem would be to set up the date/time on the server.


问:
Steema Teechart Series X axis values overlapping
I am using Teechart pro for one of my vb.net Winform project..
I am getting one issue regarding x axis values, all values are overlapping and no gaps between them.
Below is the screenshot for reference.

Can anyone suggest me which properties or axis or method I should work on to resolve this issue?
Thanks in Advance

答: LineGraph.Width work in my case.. Implemented the same and problem resolved.</p>


问:
System.IO.Directory.Delete v Git Repository - Unauthorized access
I'm writing a piece of software that maintains files in a Git repository.

One of the executables I've written has one simple purpose: delete everything to do with the software. It is given to the user in a separate, completely unrelated Windows folder.

One of the folders it needs to delete contains a Git repository, i.e. it contains a hidden .git folder

Now here's the problem I'm having. When I'm on the PC itself looking at the file system I can find that folder, click on it, delete it .... and it's gone. Not a problem.

So I try to do the same thing in my assembly by calling System.IO.Directory.Delete on that folder.

Here is what I am finding:

Everything is removed from the folder, but the folder itself is still there

When I try to THEN manually delete the folder from Windows Explorer it gives me some Unauthorised Access message. I cannot delete it.

The only way to actually get rid of it is to then try RENAME the folder in Windows Explorer, at which point I once again get an Unauthorized Access message but wouldn't you know it.... the folder disappears.

What gives!?!? Why does a System.IO.Directory.Delete NOT do exactly the same thing as me going in through Windows Explorer and deleting the folder manually?

I have tried a number of things. For example I tried getting all the files in the directory and setting all their Attributes to Normal, and through all the folders and setting their Attributes to Directory And Not Hidden. Still no joy. I even tried using Process.Start to run a RMDIR folder /S /Q - which runs perfectly from a .bat file - but the same thing happens.

I do have TortoiseGit and all its dependencies installed in case that has anything to do with anything.... and the folder does have the green Tick on it to indicate that its content is all up to date.

So my question is:
Is there any way I can successfully delete a folder containing a Git repository though VB.NET?

答:
I finally got to the bottom of this mysterious mystery.

The culprit is TortoiseGit

When I killed the TGitCache.exe process just before deleting the folder, everything worked perfectly.

Go figure.