text:
Q: Poincaré' lemma and EM potential $A^{\mu}$ My lecturer said that given the sourceless Maxwell's equations $$ \partial_{\mu}\, ^ *F^{\mu\nu} = 0 $$,
we can find a solution $$ F^{\mu\nu}  = \partial_{\mu}A_{\nu} - \partial_{\nu}A_{\mu},$$
that only exists locally.
The fact that there always is a $A_{\nu}$ that can locally give $ F^{\mu\nu}$ is a consequence of Poincaré's lemma, and extending it to a global solution would introduce/require magnetic monopoles.
I tried to read up on the Poincore lemma but it's all maths and I was hoping for a physical explanation. Does it make sense that $A_{\nu}$ is local? How do mangetic monopoles enter the picture?

A: First of all some clarifications to make sure we are on the same page. The phrase "$A_\nu$ is local" is slightly misleading as it implies that A is only defined in some (small) neighborhood of the total manifold/space. This is not true. A is defined everywhere on the manifold. The correct expression is that "the theory is invariant under a local symmetry" ie that transformations of the form
$$A_\nu(x)\rightarrow A_\nu(x)+L(x)$$
do not change the physics. The above are known as local/gauge transformations and they are distinctly different from global transformations in which the function does not depend on the position, ie:
$$A_\nu(x)\rightarrow A_\nu(x)+L$$
Now the statement about the Maxwell's equation mentioned, is that we can find a solution to it at any small neighborhood of the manifold, but when we try to patch together solutions in nearby neighborhoods to find a solution that will satisfy the equation everywhere, then this is impossible (for manifolds that have "holes").
The basic (physical) reason behind this is that for manifolds with no holes a field of the form $A=$constant is not physical and we can do a gauge transformation of the type described above to bring it to the form $A=0$ everywhere. However, for manifolds with holes (an example would be the circle) a field that is constant everywhere is physical, it cannot be gauged away and has observable consequences. This is another manifestation of the Aharonov–Bohm effect.
So in the example above, if the constant magnetic field along the circle is physical then what creates it? We can think of its source as an electric current flowing through a long wire passing through the center of the circle and being perpendicular to the plane of the circle, or equivalently we can think about it as having placed a magnetic monopole at the center of the circle. This simple example hopefully demonstrates why magnetic monopoles are needed to be introduced to justify global solutions of Maxwell's equaitons on a space with non-trivial topology (ie with holes).


text:
Q: Download the subspecies data using R packages (dismo) I would like to use dismo (R packages) to download gbif species occurrence data for species distribution analysis.
I have read the guideline and successfully proceeded our analysis in most cases.
I used the code here.
gbif("genus","species", geo=FALSE)

However, I would like to divided certain subspecies for analysis separately.
Would there be any ways I can do to extract information from certain subspecies?

A: Based on the documentation of gbif and the vignettes of dismo, we can append * to the species name to get all the variants under that species name. The following example, from the vignettes, downloads all records under Solanum acaule.
acaule <- gbif("solanum", "acaule*", geo = FALSE)

The resulting dataframe, acaule, contains 115 variables with about 7000 records. Among these variables, the scientificName column contains full names of that records. We can use that column to identify the records related to a certain subspecies.
For example, we can first use the table function to see the number of each species name.
table(acaule$scientificName)

                             Solanum acaule Bitter
                                              5608
                      Solanum acaule subsp. acaule
                                              1444
Solanum acaule subsp. punae (Juz.) Hawkes & Hjert.
                                                14
           Solanum acaule var. punae (Juz.) Hawkes
                                                 9
       Solanum acaule var. subexinterruptum Bitter
                                                 2
                        Solanum schreiteri Bukasov
                                                 2
                         Solanum uyunense Cárdenas
                                                 2

Now we can subset the dataframe to find the records we want based on the key words in scientificName. Suppose we only want records with subsp. in its scientificName, we can do the following:
acaule_sub <- subset(acaule, grepl("subsp.", scientificName, fixed = TRUE))

Now acaule_sub is a dataframe with 1458 records, which are all the records with a scientific name associated with "subsp.".
Not sure if this is what you need, but I hope it helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: when I try to translate the element through js, it doesn't work All the elements with class em, needs to be shown once at the time on the basis of the rating.
I made the emoji contaneir as big as the icons, so with overflow hidden only one can be shown.
The problem is that when i try to modify the transform property, it doesn't work.

const starsEl = document.querySelectorAll(".fa-star");
const ratingcEl = document.querySelectorAll(".em");
console.log(ratingcEl)

starsEl.forEach((starsEl, index) => {
  starsEl.addEventListener("click", () => {
    console.log('click')
    updateRating(index);
  });
});

function updateRating(index) {
  starsEl.forEach((starsEl, idx) => {
    if (idx <= index) {
      starsEl.classList.add("active");
    } else {
      starsEl.classList.remove("active");
    }
  });

  ratingcEl.forEach((ratingcEl) => {
    console.log(index)
    ratingcEl.style.transform = `translateX(- ${ 50 * index}px)`;
  });

}
.emoji-container {
  position: absolute;
  top: 20%;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  overflow: hidden;
}

.emoji-container i {
  margin: 1px;
  transform: translateX(-200px);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />

I want the icons to translate left, in order to show the right face for the rating.

A: This can be greatly simplified. Removed all position/transform/display rules from CSS. They bring unnecessary complexity for such a simple task. Also added gold color for stars with active class and started with 5 active star.

const starsEl = document.querySelectorAll(".fa-star");
const emoji = document.getElementById("emoji");
const emojis = ["angry", "frown", "meh", "smile", "laugh"]; // just the changing parts

starsEl.forEach((starsEl, index) => {
  starsEl.addEventListener("click", () => {
    updateRating(index);
  });
});

function updateRating(index) {
  starsEl.forEach((starsEl, idx) => {
    if (idx <= index) {
      starsEl.classList.add("active");
    } else {
      starsEl.classList.remove("active");
    }
  });

  emoji.classList = ["em fa-regular fa-face-" + emojis[index] + " fa-3x"];
}
#rating-container > .active {
  color: gold;
}
#emoji-container {
  text-align: center;
  margin-top: 2rem;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />


text:
Q: Omit rows that contain duplicates in columns based on conditions in two more columns I have a dataframe with +/- 300000 observations of 11 variables. A snapshot is given of the ones that I would like to use.
Location.type  Package.ID     Version    WeekID     Name
Office         301502         3.0        201542     William
Office         301502         2.7        201542     Claire
Production     9764933        1.6        201214     John
Home           298793         2.6        201746     Bill
Home           298793         2.5        201738     William
Production     2803789        4.2        201605     Brad
Production     2803789        4.19       201605     Richard
Production     2803789        4.18       201605     Vanessa

I want to omit the rows that have both a duplicated Package.ID and WeekID and keep the row with the highest value in Version, but keep all other information. My desired output is:
Location.type  Package.ID     Version    WeekID     Name
Office         301502         3.0        201542     William
Production     9764933        1.6        201214     John
Home           298793         2.6        201746     Bill
Home           298793         2.5        201738     William
Production     2803789        4.2        201605     Brad

My question is similar to Remove duplicates with largest absolute value. However, in that case picking the highest value depends on one column, in my case on two. Maybe this is a simple adjustment, but I could not figure it out myself.


text:
Q: How can I show the week numbers in the calendar shown at the top in GNOME Shell? I would like to display the week numbers in the calendar that is shown in Ubuntu with GNOME shell v3.26 when clicking on the date in bar at the top of the screen.

A: If you have dconf Editor, launch it and navigate to /org/gnome/desktop/calendar/show-weekdate. Then disable Use default value and set Custom value to True.
Alternatively just open Terminal and run
gsettings set org.gnome.desktop.calendar show-weekdate true

A: You can do that with the GNOME Tweak Tool.
sudo apt update
sudo apt install gnome-tweak-tool

Open the application after installing it.

*

*Go to the "Top Bar" menu item from left.

*There's an option called "Show week numbers". Check it.


text:
Q: How to add working filters for max_sale_qty and manage_stock in Product grid in Magento 2.3? I am trying to add working filters for max_sale_qty and manage_stock in product grid in Magento 2.3. I got the columns Max Sale Qty and Manage Stock in product grid to display the records using addField() methods and dataSource/dataProvider. But I couldn't get the filters to work though. I am fairly new to Magento and couldn't get the filters to work after hours of looking up online.
How do I get these filters working? Thanks.
Here is my code (All the required module files are given):
VendorName/ProductMaxSaleQty/view/adminhtml/ui_component/product_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">

    <dataSource name="product_listing_data_source" component="Magento_Ui/js/grid/provider">

        <settings>
            <storageConfig>
                <param name="dataScope" xsi:type="string">filters.store_id</param>
            </storageConfig>
            <updateUrl path="mui/index/render"/>
        </settings>

        <aclResource>Magento_Catalog::products</aclResource>

        <dataProvider class="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider" name="product_listing_data_source">

            <settings>
                <requestFieldName>id</requestFieldName>
                <primaryFieldName>entity_id</primaryFieldName>
            </settings>

        </dataProvider>

    </dataSource>

    <columns name="product_columns">

        <column name="manage_stock" component="Magento_Ui/js/grid/columns/select" sortOrder="76">
                <settings>
                    <addField>true</addField>
                    <options class="Magento\Config\Model\Config\Source\Yesno"/>
                    <filter>select</filter>
                    <dataType>select</dataType>
                    <sortable>false</sortable>
                    Managed Stock
                </settings>
           </column>

        <column name="max_sale_qty" sortOrder="77">
            <settings>
                <addField>true</addField>
                <filter>textRange</filter>
                Max Sale Qty
            </settings>
        </column>

    </columns>

</listing>

VendorName/ProductMaxSaleQty/etc/adminhtml/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider">
        <arguments>

            <argument name="addFieldStrategies" xsi:type="array">
                <item name="max_sale_qty" xsi:type="object">VendorName\ProductMaxSaleQty\Ui\DataProvider\Product\AddMaxSaleQtyFieldToCollection</item>
            </argument>
            <argument name="addFilterStrategies" xsi:type="array">
                <item name="max_sale_qty" xsi:type="object">VendorName\ProductMaxSaleQty\Ui\DataProvider\Product\AddMaxSaleQtyFilterToCollection</item>
            </argument>

            <argument name="addFieldStrategies" xsi:type="array">
                <item name="manage_stock" xsi:type="object">VendorName\ProductMaxSaleQty\Ui\DataProvider\Product\AddManageStockFieldToCollection</item>
            </argument>
            <argument name="addFilterStrategies" xsi:type="array">
                <item name="manage_stock" xsi:type="object">VendorName\ProductMaxSaleQty\Ui\DataProvider\Product\AddManageStockFilterToCollection</item>
            </argument>

        </arguments>
    </type>
</config>

VendorName/ProductMaxSaleQty/Ui/DataProvider/Product/AddManageStockFieldToCollection.php
<?php

namespace VendorName\ProductMaxSaleQty\Ui\DataProvider\Product;

class AddManageStockFieldToCollection implements \Magento\Ui\DataProvider\AddFieldToCollectionInterface
{
    public function addField(\Magento\Framework\Data\Collection $collection, $field, $alias = null)
    {
        $collection->joinField('manage_stock', 'cataloginventory_stock_item', 'manage_stock', 'product_id=entity_id', null, 'left');
    }
}

VendorName/ProductMaxSaleQty/Ui/DataProvider/Product/AddManageStockFilterToCollection.php
<?php

namespace VendorName\ProductMaxSaleQty\Ui\DataProvider\Product;

class AddManageStockFilterToCollection implements \Magento\Ui\DataProvider\AddFilterToCollectionInterface
{

    public function addFilter(\Magento\Framework\Data\Collection $collection, $field, $condition = null)
    {
        if (isset($condition['eq'])) {
            $collection->addFieldToFilter($field, $condition);

        }
    }
}

VendorName/ProductMaxSaleQty/Ui/DataProvider/Product/AddMaxSaleQtyFieldToCollection.php
<?php

namespace VendorName\ProductMaxSaleQty\Ui\DataProvider\Product;

class AddMaxSaleQtyFieldToCollection implements \Magento\Ui\DataProvider\AddFieldToCollectionInterface
{
    public function addField(\Magento\Framework\Data\Collection $collection, $field, $alias = null)
    {
        $collection->joinField('max_sale_qty', 'cataloginventory_stock_item', 'max_sale_qty', 'product_id=entity_id', null, 'left');
    }
}

VendorName/ProductMaxSaleQty/Ui/DataProvider/Product/AddMaxSaleQtyFilterToCollection.php
<?php

namespace VendorName\ProductMaxSaleQty\Ui\DataProvider\Product;

use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection as AttributesCollection;
use Magento\Framework\Data\Collection;
use Magento\Ui\DataProvider\AddFilterToCollectionInterface;

class AddMaxSaleQtyFilterToCollection implements \Magento\Ui\DataProvider\AddFilterToCollectionInterface
{
    public function addFilter(\Magento\Framework\Data\Collection $collection, $field, $condition = null)
    {
        if (isset($condition['eq'])) {
            $collection->addFieldToFilter($field, $condition);
        }
    }
}

VendorName/ProductMaxSaleQty/etc/module.xml
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
  <module name="VendorName_ProductMaxSaleQty" setup_version="0.0.1">
    <sequence>
      <module name="Magento_Catalog"/>
    </sequence>
  </module>
</config>

VendorName/ProductMaxSaleQty/registration.php
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'VendorName_ProductMaxSaleQty',
    __DIR__
);

A: Looks like the logic inside these files make it not work.
Pls try changing them as following;
VendorName/ProductMaxSaleQty/Ui/DataProvider/Product/AddManageStockFilterToCollection.php
<?php

namespace VendorName\ProductMaxSaleQty\Ui\DataProvider\Product;

use Magento\Eav\Model\Entity\Collection\AbstractCollection;

class AddManageStockFilterToCollection implements \Magento\Ui\DataProvider\AddFilterToCollectionInterface
{

    public function addFilter(\Magento\Framework\Data\Collection $collection, $field, $condition = null)
    {
//        if (isset($condition['eq'])) {
//            $collection->addFieldToFilter($field, $condition);
//
//        }

//        if (isset($condition['in'])) {
//            $collection->getSelect()->where(
//                AbstractCollection::ATTRIBUTE_TABLE_ALIAS_PREFIX .  'qty.manage_stock IN (?)',
//                implode($condition['in'])
//            );
//        }

        if (isset($condition['eq'])) {
                $collection->getSelect()->where(
                    AbstractCollection::ATTRIBUTE_TABLE_ALIAS_PREFIX . 'qty.manage_stock = ?',
                    (float)$condition['eq']
                );
        }
    }
}

VendorName/ProductMaxSaleQty/Ui/DataProvider/Product/AddMaxSaleQtyFilterToCollection.php
<?php

namespace VendorName\ProductMaxSaleQty\Ui\DataProvider\Product;

use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection as AttributesCollection;
use Magento\Eav\Model\Entity\Collection\AbstractCollection;
use Magento\Framework\Data\Collection;
use Magento\Ui\DataProvider\AddFilterToCollectionInterface;

class AddMaxSaleQtyFilterToCollection implements \Magento\Ui\DataProvider\AddFilterToCollectionInterface
{
    public function addFilter(\Magento\Framework\Data\Collection $collection, $field, $condition = null)
    {
//        if (isset($condition['eq'])) {
//            $collection->addFieldToFilter($field, $condition);
//        }
        if (isset($condition['gteq'])) {
            $collection->getSelect()->where(
                AbstractCollection::ATTRIBUTE_TABLE_ALIAS_PREFIX . 'qty.max_sale_qty >= ?',
                (float)$condition['gteq']
            );
        }
        if (isset($condition['lteq'])) {
            $collection->getSelect()->where(
                AbstractCollection::ATTRIBUTE_TABLE_ALIAS_PREFIX . 'qty.max_sale_qty <= ?',
                (float)$condition['lteq']
            );
        }
    }
}


text:
Q: undefined reference to `pvPortMalloc' I'm tying to build project with FreeRTOS(last version).
And I have 20170907-1650 version of Eclipse.
And in process of buld I have got the errors what I can't solve by myself.
Cause of what, I asking help in this event.
Pasting list of similar errors:

*

*undefined reference to `pvPortMalloc'

*undefined reference to `vPortFree'

*undefined reference to `vApplicationStackOverflowHook'

A: As pointed in comment, see Heap Memory Management, freertos doesn't provide malloc/free functions.
You'll have to:

*

*Modify FreeRTOSConfig.h to set

*

*configSUPPORT_DYNAMIC_ALLOCATION to 1

*configAPPLICATION_ALLOCATED_HEAP to 4 (you can replace 4 according to your needs)

*Add the file heap_4.c to your project (same remark as above)


text:
Q: A Lebesgue integral problem that seems very intuitive! I am trying to solve the following Lebesgue integral problem:
Suppose $\mu(X)$ is finite. Let $f$ be an integrable function such that $f>0$ almost everywhere. For any $\varepsilon > 0$, there is a $\lambda>0$ such that $$\int_E f \,d\mu \geq \lambda$$ for all measurable $E$ with measure $\mu(E) \geq \varepsilon$
This question seems really intuitive in that set of nonnegative measure will have nonnegative integral, but I really have no idea where to start.
Thank!

A: Suppose $\mu$ is finite. Let $A_n = \{ x | f(x) \in [{1 \over n},0] \}$. Since
$f(x) >0$ ae. [$\mu$], we see that $\mu A_n \to 0$. Choose $n$ such that
$\mu A_n < { 1\over 2} \epsilon$.
Suppose $\mu E \ge \epsilon$, then $\mu (E \setminus A_n) \ge {1 \over 2 } \epsilon$ and
$\int_E f d \mu  \ge {1 \over n} {1 \over 2 } \epsilon$.


text:
Q: MS Access - execute a saved query by name in VBA How do I execute a saved query in MS Access 2007 in VBA?
I do not want to copy and paste the SQL into VBA. I rather just execute the name of the query.
This doesn't work ... VBA can't find the query.
CurrentDb.Execute queryname

A: To use CurrentDb.Execute, your query must be an action query, AND in quotes.
CurrentDb.Execute "queryname"

A: You can do it the following way:
DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR
CurrentDb.OpenRecordset("yourQueryName")

A: You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table.  That query runs successfully when called by name by CurrentDb.Execute.
CurrentDb.Execute "qryAddLoginfoRow"

My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection.  Add these 2 lines to your VBA code just before the CurrentDb.Execute line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name

The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection."  Then go to the Immediate window to verify the name of the query you're asking CurrentDb to Execute.

A: Thre are 2 ways to run Action Query in MS Access VBA:

*

*You can use DoCmd.OpenQuery statement. This allows you to control these warnings:

BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs
Function RunActionQuery(QueryName As String)
    On Error GoTo Hell              'Set Error Hanlder
    DoCmd.SetWarnings True          'Turn On Warnings
    DoCmd.OpenQuery QueryName       'Execute Action Query
    DoCmd.SetWarnings False         'Turn On Warnings
    Exit Function
Hell:
    If Err.Number = 2501 Then       'If Query Was Canceled
        MsgBox Err.Description, vbInformation
    Else                            'Everything else
        MsgBox Err.Description, vbCritical
    End If
End Function

*You can use CurrentDb.Execute method. This alows you to keep Action Query failures
under control. The SetWarnings flag does not affect it. Query is executed always without warnings.

Function RunActionQuery()
    'To Catch the Query Error use dbFailOnError option
    On Error GoTo Hell
    CurrentDb.Execute "Query1", dbFailOnError
    Exit Function
Hell:
    Debug.Print Err.Description
End Function

It is worth noting that the dbFailOnError option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified

In addition, you can use DoCmd.Hourglass True and DoCmd.Hourglass False to control the mouse pointer if your Query takes longer


text:
Q: REST API and navigation properties I have REST API and Blazor application.
I have following Model logic:
public class Offer
{
    [Required]
    public int OfferId { get; set; }

    public string OfferName { get; set; }
    public ICollection<Item> Items { get; set; }
}

public class Item
{
    public int ItemId { get; set; }
    public string PartNo { get; set; }
    ....
    public int OfferId { get; set; }
    public Offer Offer { get; set; }

    public Nullable<int> ParentId { get; set; }
    public Item Parent { get; set; }
    public IEnumerable<Item> Children { get; set; }

}

Offer can have more items, every item can have children items. Let's assume that there can be only one level of children.
I wanted to ask rest API for list of items with their children. So I created controller like this:
[HttpGet("offer/{offerId}/{parentId}")]
    public IActionResult GetItemsForOffer(int offerId, Nullable<int> parentId, [FromQuery] ItemParameters parameters)
    {
        if (parentId == 0) parentId = null;
        var items = _repository.Item.GetItemsByOffer(offerId, parentId, parameters);

        Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(items.MetaData));

        return Ok(items);
    }

And Repisotory looks like this:
public PagedList<Item> GetItemsByOffer(int offerId, Nullable<int> parentId, ItemParameters parameters)
    {
        var items = FindByCondition(a => a.OfferId.Equals(offerId) && a.ParentId == parentId )
            .Include(item => item.Children)
            .Sort(parameters.OrderBy);

        return PagedList<Item>.ToPagedList(items,
            parameters.PageNumber,
            parameters.PageSize);
    }

The code was working before I added .Include(item => item.Children)
PagedList (but this is not important for this case I think):
public class PagedList<T> : List<T>
{
    public MetaData MetaData { get; set; }
    public PagedList(List<T> items, int count, int pageNumber, int pageSize)
    {
        MetaData = new MetaData
        {
            TotalCount = count,
            PageSize = pageSize,
            CurrentPage = pageNumber,
            TotalPages = (int)Math.Ceiling(count / (double)pageSize)
        };
        AddRange(items);
    }
    public static PagedList<T> ToPagedList(IQueryable<T> source, int pageNumber, int pageSize)
    {
        var count = source.Count();
        var items = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
        return new PagedList<T>(items, count, pageNumber, pageSize);
    }
}

My idea of response is this:
[
{
    "itemId": 1,
    "partNo": "ABC",
    ...
    "parentId": null,
    "parent": null,
    "children": [
    {
        "itemId": 2,
        "partNo": "DEF",
        "children": []
    }
]
},
{
    "itemId": 3,
    "partNo": "GHI",
    ...
    "parentId": null,
    "parent": null,
    "children": null
}

]
But I get this error instead: System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
I googled it and found similiar topic: .Net Core 3.0 possible object cycle was detected which is not supported
Best answer (I think) is
"This happens because of the 2 way relationship between your data model when it comes to be JSON serialized.
You should not return your data model diectly. Map it to a new response model then return it."
So it seems my idea of using REST API is wrong. I thought that REST API should handle all joining and including. But maybe I should do it in a Blazor http repository? Or where is a proper place to do joining?
And while I am writing this, I realized that I actually dont need Children, I just need information that Children exists. But I dont know how to write it.


text:
Q: Get data out of array of dictionaries from JSON response I am trying to get data out of an array of nested dictionaries which is the result of a JSON response.
func fetchData() {
    let urlString = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?api_key=\(self.apiKey)"
    let url = URL(string: urlString)

    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print(error ?? "ERROR!")
        } else {
            do {

                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
                print(parsedData)
                print(parsedData["type"] ?? "")
                print(parsedData["version"] ?? "")

                print(type(of: parsedData))
                print(type(of: parsedData["data"]!))

                //ERROR HERE.
                //"Cannot subscript a value of type '[String, Any]' with an index of type '(String, (String, Any).Type)'
                let innerItem = parsedData["Aatrox", (String, Any)]

            } catch let error as NSError {
                print(error)
            }
        }

    }.resume()

Here is what is printed:
["type": champion, "version": 7.4.3, "data": {
Aatrox =     {
    id = 266;
    key = Aatrox;
    name = Aatrox;
    title = "the Darkin Blade";
};
Ahri =     {
    id = 103;
    key = Ahri;
    name = Ahri;
    title = "the Nine-Tailed Fox";
};
Akali =     {
    id = 84;
    key = Akali;
    name = Akali;
    title = "the Fist of Shadow";
};
Alistar =     {
    id = 12;
    key = Alistar;
    name = Alistar;
    title = "the Minotaur";
};
}]

champion
7.4.3

Dictionary<String, Any>
__NSDictionaryI

I am trying to get the "id" for "Aatrox".
How would i go about doing this?
is it because the type of parsedData["data"]! is __NSDictionaryI??
Thanks for the help.

A: First you need to extract data Dictionary then access other dictionary.
do {
    let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
    if let passDic = parsedData["data"] as? [String:Any],
       let innerItem = passDic["Aatrox"] as? [String: Any] {
          print(innerItem)
    }

} catch  {
     print(error)
}

A: Seems like it should be let innerItem: [String: Any] = parsedData["Aatrox"]

A: let data : [string:Any] = parsedData.value(key: "data")
let aatrox : [string:Any] = data["Aatrox"]
print("**id**\(aatrox["id"])")

this thing work for me..


text:
Q: Remove empty string in array of strings It seems that there are dozens of topic with similar problem, and mostly all have the same answer: use array_filter, array_map. The problem is that I used them, but it didn't quite help. So I have an array (is built from data in csv file):
Array
(
[0] => Array
    (
        [0] => name
        [1] => title
        [2] => email
    )

[1] => Array
    (
        [0] => First
        [1] => title 1
        [2] => email1@ex.com
    )

[2] => Array
    (
        [0] => second
        [1] => title 1
        [2] => email2@ex.com
    )

[3] => Array
    (
        [0] =>
    )

[4] => Array
    (
        [0] => third
        [1] => title 1
        [2] => email3@ex.com
    )

[5] => Array
    (
        [0] =>
    )

[6] => Array
    (
        [0] =>
        [1] =>
        [2] =>
    )
 )

I have to delete all empty arrays. So I use such code:
    while (($row = fgetcsv($file, 8192, ';')) !== false) {
        if (array(null) !== $row) { // ignore blank lines
            $csv[] = $row;
        }
    }
    $array = array_filter(array_map('array_filter', $csv));

$array now is:
 Array
(
[0] => Array
    (
        [0] => name
        [1] => title
        [2] => email
    )

[1] => Array
    (
        [0] => First
        [1] => title 1
        [2] => email1@ex.com
    )

[2] => Array
    (
        [0] => second
        [1] => title 1
        [2] => email2@ex.com
    )

[3] => Array
    (
        [0] => third
        [1] => title 1
        [2] => email3@ex.com
    )

[4] => Array
    (
        [1] =>
    )
)

Why there is a 4th array with empty value? I need to get rid of it.
gettype($array[4][1])  = string
UPDATE
The csv has empty rows, and even just a ";" delimiter without any string. I cannot influence on the process of inserting data into this csv.
The csv looks like this:
 1 row: name;title;email
 2 row: First;title 1;email1@ex.com
 3 row: second;title 1;email2@ex.com
 4 row:
 5 row: third;title 1;email3@ex.com
 6 row:
 7 row: ; ;

A:
and mostly all have the same answer: use array_filter, array_map.

array_filter is a good approach, but I wouldn't use array_map, but array_reduce:
$array = array_filter(
    $csv,
    function ($value) {
        return 0 < array_reduce(
            $value,
            function ($carry, $item) {
                return empty(trim($item)) ? $carry : $carry + 1;
            },
            0
        );
    }
);

With array_reduce, I count the non-empty elements in an array. And if there are zero non-empty elements, the array is thrown away with array_filter.
For reference, the PHP 7.4-syntax, which looks nicer in my eyes, but could be a bit confusing at first
$array = array_filter(
    $csv,
    fn ($val) => 0 < array_reduce(
        $val,
        fn ($carry, $item) => empty(trim($item)) ? $carry : $carry + 1,
        0
    )
);


text:
Q: Cambiar el color de un botón MaterialButton de manera programática Estoy usando MaterialButton de la librería support.design.
Comunmente para cambiar el color de un botón normal uso este código:
var myButton = findViewByid(.....)
myButton.setBackground(ContextCompat.getColor(this@MyActivity, R.color.myColor)

Pero para este MaterialButton el mismo código no me funciona.

A: Encontré la respuesta,
para este caso particular cambie:
myButton.setBackground(ContextCompat.getColor(this@MyActivity, R.color.myColor)

por lo siguiente:
myButton.backgroundTintList = ContextCompat.getColorStateList(this@MyActivity, R.color.myColor)

Esto mismo lo he testeado y funciona perfectamente.


text:
Q: Standard output from MSTest, NUnit, MbUnit, xUnit.NET test runners How do you, in any of the common .NET testing frameworks MSTest, NUnit, MbUnit, or xUnit.NET, get the command line test runner to output a simple yes/no or true/false or 1/0 on whether all the tests passed or failed?
I'm open to workarounds like:

*

*No output if all the tests passed, output if anything fails.

*Count of tests that failed. I could look for zero or non-zero values.

*Other things similar to #1 or #2

Which of these frameworks provide this kind of capability?
I did some playing with MSTest today and didn't see a way to make MSTest.exe output something I could use.

A: They all output XML if you want (especially MSTest). You can use XSLT like my version for MSTest.

A: Have a look at Gallio, a framework and other tools (test runner, etc.) that MbUnit is built on, but that also handles the outputs MSTest, NUnit, RSpec, etc.
While that isn't exactly what you asked for, if you use the output from the Gallio test-runner, then you've got free support for the test formats - it's essentially a standard output.

A: MSTest and most other runners return an exitcode you can check on.


text:
Q: Multiprocessing Pooling and Lightgbm i am trying to train completely independent tasks using multiprocess pooling in python, which lightgbm for training(i am not sure if this is relevant for problem). Here is the code
from sklearn.datasets import load_breast_cancer
import pandas as pd
from sklearn.model_selection import train_test_split, KFold
import lightgbm as lgb
import numpy as np

def functionToParallize(splitnumber=2):

    data = load_breast_cancer()
    X = pd.DataFrame(data.data, columns=data.feature_names)
    y = pd.Series(data.target)
    X_train, X_test, y_train, y_test = train_test_split(X, y)
    folds = KFold(splitnumber)
    results = lgb.cv({}, lgb.Dataset(X_train, y_train), folds=folds,metrics=['rmse'])
    return results

to parallelize i use multiprocessing pooling with say 2 pool workers. But the it's really inefficient as it takes 1000 times more time to finish a task with 2 pools as it takes with just one. For eg.
from multiprocessing import Pool
import psutil
print(psutil.cpu_count())

output

4

starttime=time.time()
pool = Pool(2)
multiple_results = [pool.apply_async(functionToParallize) for i in [3]]
p=[res.get() for res in multiple_results]
print((time.time()-starttime)/60)

output

0.007067755858103434

but with two pools
starttime=time.time()
pool = Pool(2)
multiple_results = [pool.apply_async(functionToParallize) for i in [2,3]]
p=[res.get() for res in multiple_results]
print((time.time()-starttime)/60)

1.026989181836446

This is actually not the original task, but i am doing something similar there. But for that single task takes about a minute and pool 2 process never ends there at all.
Am i doing something wrong here ?? I am doing this on a jupyter notebook, If that's relevant.
Any help is appreciated! Thanks!

A: I found the reason, it's because lgb's internal threading conflicts with custom pooling. Forcing lgb not to use threading helps.
results = lgb.cv({'num_threads':1}, lgb.Dataset(X_train, y_train), folds=folds,metrics=['rmse'])

Thanks Manzi,
Cheers


text:
Q: Access session from view I built login from scratch using adonisjs but I don't know how to check session from view. I need to check when a user is logged-in and the session can be shared everywhere.
I am trying to use global in service provider but it's not possible.

A: If you use authentication with auth you can use this tag on view: Adonis - Authentication
@loggedIn
  <h2> Hello {{ auth.user.username }} </h2>
@else
  <p> Please login </p>
@endloggedIn

To manipulate the session object you can access it in HTTP Context: Adonis - Session
// Example
Route.get('/login', ({ session }) => {
  return session.get('username') // 'virk'
})


text:
Q: Exit condition 41 on SNOPT I'm trying to run an optimization with SNOPT.
Right now as I run it I consistently get exit condition 41.
I've added the following parameters to the solver:
prog.SetSolverOption(solver.solver_id(),"Function Precision","1e-6")
prog.SetSolverOption(solver.solver_id(),"Major Optimality Tolerance","1e-3")
prog.SetSolverOption(solver.solver_id(),"Superbasics limit","600")
#print("Trying to Solve")
result = solver.Solve(prog)
print(result.is_success())

But I still contently get the same exit condition.
The error seems to be from the interpolation function I'm using. (When I remove it I no longer get the error).
t, c, k = interpolate.splrep(sref, kapparef, s=0, k=3)

kappafnc = interpolate.BSpline(t, c, k, extrapolate=False)

Here is the function I think I determined was causing the issue:
  def car_continous_dynamics(self, state, force, steering):
        beta = steering
        s = state[0]
        #print(s)
        n = state[1]
        alpha = state[2]
        v = state[3]
        #State = s, n, alpha , v
        #s= distance along the track, n = perpendicular distance along the track
        #alpha = velocity angle relative to the track
        #v= magnitude of the velocity of the car

        s_val = 0
        if s.value() >0:
          s_val = s.value()

        Cm1 = 0.28
        Cm2 = 0.05
        Cr0 = 0.011
        Cr2 = 0.006
        m = 0.043
        phi_dot = v*beta*15.5
        Fxd = (Cm1 - Cm2 * v) * force - Cr2 * v * v - Cr0 *tanh(5 * v)
        s_dot = v*cos(alpha+.5*beta)/(1)##-n*self.kappafunc(s_val))
        n_dot= v*sin(alpha+.5*beta)
        alpha_dot = phi_dot #-s_dot*self.kappafunc(s_val)
        v_dot=Fxd/m*cos(beta*.5)

        # concatenate velocity and acceleration
        #print(s_dot)
        #print(n_dot)
        #print(alpha_dot)
        #print(v_dot)
        state_dot = np.array((s_dot,n_dot,alpha_dot,v_dot))
        #print("State dot")

        #print(state_dot.dtype.name)
        #print(state_dot)
        #print(state_dot)
        return state_dot
``

A: Debugging INFO 41 in SNOPT is generally challenging, it is often caused by some bad gradient (but could also due to the problem being really hard to optimize).
You should check if your gradient is well-behaved. I see you have
s_val = 0
if s.value() >0:
    s_val = s.value()

There are two potential problems

*

*Your s carries the gradient (you could check s.derivatives(), it has non-zero gradient), but when you compute s_val, this is a float object with no gradient. Hence you lose the gradient information.

*s_val is non-differentiable at 0.

I would use s instead of s_val in your function (without the branch if s.value() > 0). And also add a constraint s>=0 by
prog.AddBoundingBoxConstraint(0, np.inf, s)

With this bounding box constraint, SNOPT guarantees that in each iteration, the value of is is always non-negative.


text:
Q: Has an entire AWS region gone down? I'm trying to work out if previous datacenter failures on AWS have just applied to a single "availability zone" or the whole region. Does anyone know the details of the extent of the worst AWS failure?

A: Amazon AWS has suffered at least two major outages in its life.
The first, in April of 2011, affected one of the availability zones in US-East.
The second, in June of 2012, affected one of the availability zones in US-East. During this event, for a short period of time it was not possible to start new instances in any US-East availability zone.
Both failures were pretty bad, though they seem to have resolved them pretty well overall.


text:
Q: can we get the onedrive uploaded file link after upload is completed? I am uploading the file to One drive using Rest Api c# successfully.My requirement is to get the uploaded file link and push that into database.when I Googled I cannot find any relevant information on that.kindly help me to solve this query

A: Getting a download link is documented here: Downloading and Uploading files (REST) (https://msdn.microsoft.com/en-us/library/dn659726.aspx). At the bottom, it states "To get a download link to the contents of a file, photo, video, or audio, use code like this.
GET https://apis.live.net/v5.0/file.a6b2a7e8f2515e5e.A6B2A7E8F2515E5E!126/content?suppress_redirects=true?
    access_token=ACCESS_TOKEN
"
I hope this helps.


text:
Q: MPI Newbie - some questions on how 'mpirun' works and process management First of all, I'm not a programmer by profession but I have to program a code for my project (I have some proficiency in C++ and python though). I came in here often when I got stuck, and most of the time got nice solutions from here, but now I have essential questions on MPI programming, else I couldn't really proceed until I know the concepts of it.
Here is my description of problems,
I would like to create a code for an algorithm for a scientific calculation. The code can be divided into 2 parts.
A.) Matrix-vector multiplication and inversion of a matrix. This part is relatively straightforward and I even have my own working MPI code for this part
B.) Calling an external MPI-ready program for a more complicated calculation (This part should also be simple, as it's simply calling a UNIX command line).
The problem I'm having is how to join these 2 parts together? My algorithm goes like this,

for k in specified range
   dividing a state vector of size 6NMx1 into M blocks, let each of M nodes handle these.
   Manipulate a state vector of size 6NMx1 according to A.) in parallel
   After A.) is done, run B.) using M nodes in parallel /* THIS IS WHERE I GOT STUCK */
   Update state vector
end for

To run B.), I have to use mpirun to call a UNIX command,
mpirun -np #PPN my_app > some_output

The questions I have are,

*

*How does 'mpirun' actually work? Does it spawn new processes upon calling?

*Let's say if I'm using M cluster compute nodes, and each one has 16 processors per node, if I use only 1 process of the node to call the above UNIX command, will it generate 16 more processes? If so, I will end up with 256M processes running in total, am I correct?

*My main goal is to use each compute node handles a block in the system vector (blocks are independent, with size 6Nx1), and will use numbers from each block as an input for B.) I'm working with clusters, so when I submit my job, I have to define number of nodes beforehand, and I strictly want each node to also run B.) in parallel after A.) is done. Are there any suggestions on how to do this using MPI? Some people told me to write codes separately for A.) and B.), and use a python script to control them at the top layer, so it should look like..
Python script:
for k in specified range
   mpirun A.) --> This is straightforward for me
   mpirun B.)
end for

Pseudocode for B.)
/* THIS PROGRAM SHOULD HAVE 16M PROCESSES */
if rank % 16 == 0
   mpirun -np 16 my_app > output
end if
/* I WANT M CALLS TO THIS PROGRAM IN PARALLEL */
MPI_COMM.BARRIER

Do you think this scheme will use 16M process in parallel for B.)? If there are better ways to implement B.) than this, or even better, to wrap it in the same code as A.), please suggest me!
3.) This is my prototype code, so I don't really care about efficiency. I just need it to work, and I will care about optimization later on.
If my descriptions are confusing, please ask me and I will come back and clarify. Thank you for your time, and I really appreciate your helps! :)

A: Mpirun is just a command that runs the number of jobs that you required in the option command line, it will probably detect what kind of machine you have and work with.
It's complicated to answer to the second question because if you are using a cluster with multiple nodes you should probably work with a dedicated protocol. For example, with slurm you run your program through a sbatch protocol which is like:
// number of proc on one node
#SBATCH -n 2
// number of node
#SBATCH -N 4

run ./a.out

That means you will run your program on 4 nodes with 2 procs on each nodes.
I don't really know about the following cause it's a lil bit confuse for me but maybe you should reconsider your problem with something else. You don't need MPI if you are working within a node but you should use openMP.
MPI is needed if you are working with a non-shared memory, within a node that's not the case.
I hope it can help you in your work.


text:
Q: iOS decline iphone 5 resize I have been recently building an application, and although I love how the iPhone 5 has a bunch more space, I hate their autoresize in storyboard (regardless of unchecking autoresize). Is there a way to turn off autoresize somewhere for the entire project?

A: 1: Head into storyboard
2: Click any view controller you might have
3: Click on file inspector
4: Turn off autolayout there

Then you can use the good old struts and springs again, but it can cause you a bit of trouble when making layouts for the different formats.
Explanation on what Autolayout is and why you should probably use it: http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2


text:
Q: Where does a war server on JBOSS Standalone see as its Home directory on Linux? I am running JBOSS AS-7 on Centos 6.4 and running it in standalone mode. I have deployed a .war and everything is fine. I now want to start using AWS DynamoDB and it requires me to store a credentials file at ~/.aws/credentials
Now, I understand that the tilde (~) means 'Home directory' but I have no idea how to find out where the deployed .war sees as it's own home directory.
I 'THINK' that the Standalone.sh is being run by a user called jboss (a local user), but any way to confirm that would be helpful.
I am able to login as root.
I hope that is enough information, and any help would be appreciated.
Many thanks

A: OK, after a lot of hacking around, I found the answer.... and here's how to find yours....
The code from here:
here
which at the time of writing was:
    Properties p = System.getProperties();
Enumeration keys = p.keys();
while (keys.hasMoreElements()) {
    String key = (String)keys.nextElement();
    String value = (String)p.get(key);
    System.out.println(key + ": " + value);
}

Allowed me to get the dump of all the details I needed. Now look for:
jboss.home.dir:
which in my case was:
jboss.home.dir: /usr/local/jboss
And thus I could create a directory (.aws) and put my credentials file there. Sorted.

A: As @jww says, this is wrong forum, but considering the ease of answer. . .
I assume you installed jboss via yum instead of downloading it yourself. From the command line, while jboss is running, enter:
 ps -ef | grep jboss

or
 ps -ef | grep java

You should be able to note the user running the process from the results. It is indeed likely that there is a jboss user you can su to if you installed via yum.
Some good tutorials that would've served you better to read instead of ask us:
Installing JBoss 7.1.1.Final on CentOS 6.x
Installing and setting-up JAVA & JBoss 7 Final on a CentOS 6 Linux VPS
They generally follow the same process and show you what the yum install probably is doing for you.


text:
Q: java.lang.OutOfMemoryError: Java heap space when i tried to create a BufferedImage I'm having problem while trying to create a BufferedImage. I have this problem just on the server I rented, not on my development environment (my computer).
I have a form to upload image. After the image is uploaded I save it to the file system.
I save it immediately because, according to what some of you said, I can "release" resources from the server memory, since I use the image on my file system and not the object Part to make the image resizes, controls, etc. I need.
As soon as I try to create a BufferedImage, from an image bigger than 2-3 mb, I get that error.
While executing this line my Application stop working and I get that error
BufferedImage immagineTemporaneaBufferizzata = ImageIO.read(new File...);

I used a method found on the internet to check the memory on the server. This is what I get before encountering the error:
Used Memory:26
Free Memory:30
Total Memory:57
Max Memory:57
Should I increase the heap memory? I tried to do it both on catalina.bat and catalina.sh but I didn't see changes in my Max Memory. Probably I did something wrong. What's the right way to increase heap size on linux?

A: Max memory 57 MB is frankly quite low for Java applications processing images with 2-3 MB. Yes, you should definitely increase the memory if you can.
To clarify: Image size 2-3 MB. What is this 2-3 MB? The size of the compressed image? If it is a JPG with 2-3 MB, that can be hell of a big image (depending on the quality). E.g. it might even be an image of 3200x2000 pixels which is 6.4 million pixels, and with 3 byte RGB pixel model it would be ~20 MB of binary data in memory.
About increasing tomcat memory see these questions:
Dealing with "java.lang.OutOfMemoryError: PermGen space" error
Increase Tomcat memory settings


text:
Q: I want that only logged user can see a determinate page Hi Guys I'm learning node.js with expressjs framework. Now I want create a simple site with two page(login page and logged page). With this exercise my main goal is to authorized only the logged user to see the logged page.
I want prevent that a user not registered can see the logged page using www.mysite.com/logged
So in app.js I have added this
app.get('/logged', routes.logged);

Then in index.js(that it's located in ./routes folder) I have wrote this
exports.logged = function(req, res) {
if(req.session.isLogged) {
        res.status(200);
        res.render('logged', {Title: req.session.name});
} else {
    res.status(403);
    res.render('403');
}
}

But when I try to access to the logged page via www.example.com/logged I always get 500 Error Internal server error
The error that I receive is this:
Express
500 Error: Failed to lookup view "TypeError: Cannot read property 'commonUserId' of undefined" in views directory "C:\Users\Fabio\Desktop\SitoStatistica\views"
at Function.app.render (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\application.js:493:17)
at ServerResponse.res.render (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\response.js:798:7)
at Object.handle (C:\Users\Fabio\Desktop\SitoStatistica\app.js:32:6)
at next (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\node_modules\connect\lib\proto.js:188:17)
at next (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\node_modules\connect\lib\proto.js:190:11)
at next (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\node_modules\connect\lib\proto.js:190:11)
at pass (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:110:24)
at nextRoute (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:100:7)
at callbacks (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:167:11)
at callbacks (C:\Users\Fabio\Desktop\SitoStatistica\node_modules\express\lib\router\index.js:170:9)

@pero

A: Implementing your own authentication system is not a good ideal.
For NodeJS authentication, you should take a look at PassportJS
Authentication then turn out to be very simple:
app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                failureRedirect: '/login' }));

then
app.get('/logged', function (req, res, next) {
    if (req.isAuthenticated()) {
        return res.redirect('/login');
    }
    return res.render('login');
});


text:
Q: How to loop two DateTime by minutes? JavaScript var start = "13.04.2019 10:00:00";
var end = "14.04.2019 16:00:00";
I need to loop minute by minute. please help me.
// var start = "13.04.2019 10:00:00";
// var end = "14.04.2019 16:00:00";

var start = new Date(2019,05,13,11,00,00,00);
var end = new Date(2019,05,14,16,00,00,00);

var loop = start;
while(loop <= end){
   console.log(loop);

   var loop = loop.setTime(loop.getMinutes() + 1);
}

not working :(

A: You should use setMinutes instead of setTime You can modify your code to this and everything will work,
var start = new Date(2019,05,13,11,00,00,00);
var end = new Date(2019,05,14,16,00,00,00);
var loop = start;
while(loop <= end){
    loop.setMinutes(loop.getMinutes() + 1);
}

A: You can change to this
loop = loop.setTime(loop.getMinutes() + 1);

it will change type of loop to number and cant call getMinutes()

var start = new Date(2019,05,13,11,00,00,00);
var end = new Date(2019,05,14,16,00,00,00);

var loop = start;
while(loop <= end){
   console.log(loop);

   loop.setTime(loop.getTime() + 1000 * 60);
}

A: use moment library for date operations
    var start = moment('13-04-2019 10:00','DD-MM-YYYY HH:mm');
    var end = moment('14-04-2019 16:00','DD-MM-YYYY HH:mm');

    var diffInMinutes = end.diff(start,'minutes');
    var res=moment('13-04-2019 10:00','DD-MM-YYYY HH:mm');

    for(let i=0;i<diffInMinutes;i++){
       console.log(res.add(1,'minutes'));
    }

sample output
   13-04-2019 10:01
   13-04-2019 10:02
   13-04-2019 10:03
   13-04-2019 10:04
   13-04-2019 10:05


text:
Q: Using sleep_for() in Qt application In my application I want to display some image with this code
myImage = scene->addPixmap(image);
myImage->setOffset(x, y);

Then I want to sleep for some seconds:
std::this_thread::sleep_for(std::chrono::seconds(2));

and then display another image. But this code waits for 2 seconds at first and then displays both images at once. How can I make the program wait between displaying those two images?

A: Use QTimer::singleShot() and connect it to a slot that updates the picture:
class MyObject : public AQObjectInheritingClass
{
    Q_OBJECT
    ...
public Q_SLOTS:
    void changeImage()
    {
        //change image here
    }

And in instead of sleep_for():
QTimer::singleShot(2000, &instanceOfMyObject, SLOT("changeImage()");

Two seconds later, changeImage() will be invoked.

A: You cannot sleep in event based application (GUI applications are event-based). Event based applications have main loop, that has to be running to process events, and update its state. Calling sleep_for stops that main loop, so your app doesn't process events so it doesn't react to input and doesn't repaint itself. That's why all drawing if deferred fot two seconds then flushed at once.
As an alternative, you should use timers, such as QTimer

A: there is Qt-specific non-blocking way to pause thread with QEventLoop:
QEventLoop loop;
QTimer::singleShot(1000,&loop,SLOT(quit()));
loop.exec();

While loop is being executed, all other events for this thread are processed.


text:
Q: Kubernetes: Unable to mount a projected volume, no space on device when clearly there is I have a local k3d cluster in stalled on Mac (Big Sur 12) that I am attempting to install calico (their default manifest https://k3d.io/v5.3.0/usage/advanced/calico/).  In the logs for the calico-kube-controller pod, I get this:
Warning  FailedMount  44m                   kubelet            MountVolume.  SetUp failed for volume "kube-api-access-vfdd9" : write /var/lib/kubelet/pods/faa7d654-6424-4774-bc40-71de88c1d337/volumes/kubernetes.io~projected/kube-api-access-vfdd9/..2022_03_09_20_46_13.100604692/token: no space left on device
There is clearly plenty of space:
/var/lib/kubelet/pods/faa7d654-6424-4774-bc40-71de88c1d337/volumes/kubernetes.io~projected # df -h .
Filesystem      Size  Used Avail Use% Mounted on
/dev/vda1        79G  7.7G   67G  11% /var/lib/kubelet
Google searching has yielded nothing effective.
Kubernetes version:  K8s Rev: v1.22.4+k3s1
Docker version:
Server: Docker Desktop 4.5.0 (74594)
Engine:
Version:          20.10.12
API version:      1.41 (minimum version 1.12)
Go version:       go1.16.12
Git commit:       459d0df
Built:            Mon Dec 13 11:43:56 2021
OS/Arch:          linux/amd64
Experimental:     false
containerd: Version:          1.4.12
GitCommit:        7b11cfaabd73bb80907dd23182b9347b4245eb5d
runc: Version:          1.0.2
GitCommit:        v1.0.2-0-g52b36a2
docker-init:
Version:          0.19.0
GitCommit:        de40ad0
Any tips/docs/analysis would be much appreciated!

A: double check your container resources configuration for errors. Try to increase the values.
      resources:
        limits:
          cpu: '1'
          memory: 500m
        requests:
          cpu: 50m
          memory: 100m

Mine started working when removed resources section completely. (Docker Desktop 4.3.2)

A: You can also check if there is a resourcequota configured.
kubectl get resourcequota

somequota 14d pods: 0/2, requests.cpu: 0/1, requests.memory: 0/1024m
limits.cpu: 0/4, limits.memory: 0/4096m

If you can are allowed to delete it then do and it will probably work


text:
Q: Programmatically authorize a Windows user against a string of users? Programmatically, I can authorize a Windows user based on whether they are in a particular role like this:
if(!User.Identity.IsAuthenticated)
    return false;

var isAuthroized = User.IsInRole(@"DOMAIN\Some Role");

// ...

return isAuthorized;

What I can't figure out how to do, is how to match a user's name if, for instance, a list of individual users is given access.
So imagine you're trying to authenticate a user against the given string of authorized users, like you would using the normal AuthorizeAttribute:
[Authorize(Users = @"DOMAIN\User1, DOMAIN\User2, DOMAIN\User3")]
public ActionResult SomeAction(){ ... }

How do you programmatically authorize a user against that string of users?
@"DOMAIN\User1, DOMAIN\User2, DOMAIN\User3"

EDIT: Ok, this is my point of confusion: What is the point of specifying multiple users if you have (in a normal AuthorizeAttribute) a declaration as follows:
[Authorize(Users=@"User1,User2,User3", Roles=@"SomeRole"]

// I can do this:

User.IsInRole(roles);

// But what's the equivalent for the specified users?

User.Identity.Name.IsInNames(names); // <-- How is the done programmatically?

I'm probably off the mark here, and am missing some piece of information. Please enlighten me!
EDIT 2: The MVC source demystified some of this for me. It is indeed done similar to what was suggested in one of the answers below:
if (_usersSplit.Length > 0 &&
   !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
    return false;
}

A: I would use a HashSet, as testing the existence of a user is a very fast operation for this collection type.
First, split the string, and then add it to a HashSet.
string[] splittedUsers = usersString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
var users = new HashSet<string>(splittedUsers);

Test a user like this
string user = "xy";
if (users.Contains(user)) {
    // Do something with user
}


text:
Q: Checking password against non sha bcrypts in meteor I'm migrating an app from parse to meteor. In parse, users' password are stocked as bcrypt(password) whereas meteor does bcrypt(sha256(password)). How can I plug the old bcrypt list to meteor so that the old users can login seamlessly?

A: I recommend taking a look at the following on how accounts-password defines a password login method, then define you own. Method signature for registerLoginHandler.

In the server (recommend this is done during server startup):
import bcrypt from 'bcrypt';

import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';

Accounts.registerLoginHandler('parsePassword', function (options) {
  // Validate options
  /* TODO Fill in yourself */

  // Find the user to login
  /* TODO Fill in yourself */

  const result = {
    userId: user._id,
  };

  // Prepare the bcrypt method
  const bcryptCompare = Meteor.wrapAsync(bcrypt.compare);

  if (! bcryptCompare(options.password, hashedPassword)) {
    result.error = new Meteor.Error(403, 'Incorrect password');
  }

  return result;
});

Then you would use this login method, like so on the client:
import { Meteor } from 'meteor/meteor';

Meteor.loginWithParsePassword({ user: /* TODO Define the query for finding your user */, password: passwordInput }, function () { console.log(arguments); });

Make sure to have the bcrypt module listed in your package.json

I left part of the example blank simply because I don't know how the asker has imported their users from Parse and what the db structure of that imported data is like. So I'll leave that part of the code as an exercise for the asker to do.


text:
Q: JSON - object in array in object - how to parse through loop with JS? If I had this schema:
[{
    "Id": 2,
    "Prizes": [{
        "Id": 5,
        "Status": 0,
        "ClaimCode": "PN0016CXC1WPM64P",
        "User": {
            "FirstName": "John",
            "SecondName": "Doe",
        },
        "DrawId": 2,
        "PrizeId": 22,
        "Prize": null
    }]
}]

How could I get the first name or any value under object User that is in array prizes, that is in the main JSON?
I have tried this:
 const response = JSON.parse(this.responseText);
 response.Prizes[0].User.forEach(function(a) {
     output += `<li>${a.FirstName}</li>`;
 });

But getting the error undefined, I believe it can be extracted but only need right syntax. Or this can't be done with for loop?

A: First of all Response is an Array and User is an object, this should be working :
const response = JSON.parse(this.responseText);

response.map((resp) => {
    resp.Prizes.map((prize) => {
        output += `<li>${prize.User.FirstName}</li>`;

    })
})

A: Since you have an array of objects, and inside the object an array of values (Prizes), you can use nested Array.forEach() calls to get the internal values, wrap them with a string, and push to the items array:

const response = [{"Id":2,"Prizes":[{"Id":5,"Status":0,"ClaimCode":"PN0016CXC1WPM64P","User":{"FirstName":"John","SecondName":"Doe"},"DrawId":2,"PrizeId":22,"Prize":null}]}];

const items = [];

response.forEach((o) =>
  o.Prizes.forEach((p) =>
    items.push(`<li>${p.User.FirstName}</li>`)
  ));

list.innerHTML = items.join('');

A: As you have multidimensional array  and you need to use Prizes as inside of array.
So first you can combine all Prizes into one using reduce() and the Spread_syntax then after you use map() with join mehod to get the required result.
DEMO

const response = [{"Id":2,"Prizes":[{"Id":5,"Status":0,"ClaimCode":"PN0016CXC1WPM64P","User":{"FirstName":"John","SecondName":"Doe"},"DrawId":2,"PrizeId":22,"Prize":null}]}];

let res = response.reduce((r,{Prizes}) =>[...r,...Prizes],[]).map(({User})=>`<li>${User.FirstName}</li>`).join('');

document.querySelector('ul').innerHTML =res ;


text:
Q: Nothing happend when clicking a button in selenium from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
time.sleep(1)
button = driver.execute_script("window.scrollTo(0, 5500)")
button1 = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div[1]/div[8]/div/div[9]/a/button')
button1.click()

Trying to click this button using xpath but it just doesn't seem to click the button to extend the webpage. I first tried to copy by xpath which didn't work and then I copied the full xpath which also didn't work. After that, I tried to find by name and enter the text on the button and click the button. But none of these methods actually worked and clicked the button. So how can I click this button so that it extends the webpage allowing me to scrape more of the webpage?

A: The problem was that the button wasn't at "clickable state" despite was rendered in page at moment.
To obviate this, you have to add an explicit wait to tell the driver to wait until it's state change to clickable.
Try to use this code instead :
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
time.sleep(1)
button = driver.execute_script("window.scrollTo(0, 5500)")
button1 = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div[2]/div[1]/div[8]/div/div[9]/a/button')))
button1.click()

A: To click on View more News Induce WebdriverWait and wait for presence_of_element_located() and following css selector.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
button=WebDriverWait(driver,20).until(EC.presence_of_element_located((By.CSS_SELECTOR,"a.load-more__btn>.btn")))
button.location_once_scrolled_into_view
button.click()

Or Use following xpath
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
button=WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH,"//a[@class='load-more__btn']/button[@class='btn']")))
button.location_once_scrolled_into_view
button.click()


text:
Q: IE click event span not triggered I'm having this webpage
http://pocolocoadventures.be/reizen/
And it should filter (with isotope.js) the travelboxes on the page.It does in safari, chrome, firefox, opera, .. but in IE, the filter doesn't work. Even worse, JS doesn't react at all at a click event on te span.
This is the piece of js
    // Travel Isotope
var container = $('#travel-wrap');
container.isotope({
    animationEngine : 'best-available',
    itemSelector: '.travel-box ',
    animationOptions : {
        duration : 200,
        queue : false
    },
});

$(".filters span").click(function(){

    var elfilters = $(this).parents().eq(1);

    if( (elfilters.attr("id") == "alleReizen") && elfilters.hasClass("non-active") )
    {
        $(".label").each(function(){
            inActive( $(this) );
        });
        setActive(elfilters);
    }
    else{
        //set label alleReizen inactive
        inActive( $("#alleReizen") );
        if( elfilters.hasClass("non-active") ){
            setActive(elfilters);
        }
        else{
            inActive(elfilters);
        }
    }
    checkFilter();

    var filters=[];

    $(".search.filters").children().each(function(){
        var filter = $(this).children().children().attr("data-filter");

        if( $(this).hasClass("non-active") ){

            filters = jQuery.grep(filters, function(value){
                return value != filter;
            });

        }
        else{
            if(jQuery.inArray(filter,filters) == -1){
                filters.push(filter);
            }
        }

    });

    filters = filters.join("");
    filterItems(filters);

});

function filterItems(filters){
    console.log("filter items with filters:" + filters);
    container.isotope({
        filter : filters,
    }, function noResultsCheck(){
            var numItems = $('.travel-box:not(.isotope-hidden)').length;
            if (numItems == 0) {
                $("#no-results").fadeIn();
                $("#no-results").css("display", "block");
            }
            else{
                $("#no-results").fadeOut();
                $("#no-results").css("display", "none");
            }
        });
}

function setActive(el){
    el.removeClass("non-active");
    var span = el.find('i');
    span.removeClass("fa-check-circle-o").addClass("fa-ban");
}

function inActive(el){
    el.addClass("non-active");
    var span = el.find('i');
    span.removeClass("fa-ban").addClass("fa-check-circle-o")
}
function checkFilter(){

    var filterdivs = $('.filters span').parent().parent();

    if( filterdivs.not('.non-active').length == 0 ){
        setActive( $("#alleReizen") );
    }

    var filterLabels = $(".filters .label");

    if( filterLabels.not('.non-active').length == 0){
        setActive( $("#alleReizen") );
    }

}
function noResultsCheck() {
    var numItems = $('.item:not(.isotope-hidden)').length;
    if (numItems == 0) {
        //do something here, like turn on a div, or insert a msg with jQuery's .html() function
        alert("There are no results");
    }
}

Probably something small and stupid; but I can't find it..
Thanks in advance!

A: played around in the console a bit, and this seemed to work well.
$(".filters").on('click', 'span', function(){
    // foo here
    console.log('foo');
});

Maybe the filters are manipulated by one of your js files after page load?
.on will allow you to select a container which listens on changes that happen inside it, passing the element you want the actual action to work on.
If it's ok for you, I'd suggest to use the <button> element, instead of the <span>.
Let me know if that works for you.

A: On your website you've build the buttons like this:
<button>
     <span>

     </span>
</button>

Now the button element is designed to be a button. It differs from the input button. In the latter you'd set the caption using value. In the button element you set it as a text node. The button element can contain elements like a span. The spec isn't very clear about whether or not you should have event handlers on the children of the button element. It's a browser developers interpretation of allowing it or not.
This problem has been posted here before (a few times)

*

*span inside button, is not clickable in ff

*Missing click event for <span> inside <button> element on firefox
It seems that Firefox is allowing it, based upon your findings. IE isn't. So to be on the safe side: use the button the way it was intended.

*

*Wrap the button inside a span (not really logical)

*Put the click handler on the button.

  $(".filters button").click(...);


text:
Q: Visual Voicemail won't let me play back or adjust greeting I have a new iPhone SE running iOS 9.3.1, restored from a backup of my old iPhone 4S. Also I have changed carriers upon getting the new phone to Cricket from AT&T.
When I set up the new iPhone, it installed carrier updates from iTunes and the Phone app let me set up my visual voicemail with the passcode and custom greeting, and I tested it out and the visual voicemail worked.
Now, however, when I go to the Phone app and tap Greeting in the Voicemail tab, it brings up the page that would let me play and record a new greeting, but the only working button is Cancel. All the buttons appear as if they work but they don't respond.
I've tried resetting the Voicemail passcode in the Phone settings, I've tried resetting network settings, I've tried rebooting. The problem remains. What is the solution?
One other note, though I can't tell if this is coincidence or the cause, perhaps you can enlighten me: I wanted to completely wipe my old iPhone so it would be ready for another to set up as their own, but that phone's WiFi doesn't work right, and so in order to get internet access enough to unlock iCloud and do the erase, I took my Cricket sim out, and (with a nano to micro sim adapter that came with my Cricket SIM originally) put it in to the 4S so it could get some 4G internet and authorize the erase. After I put the Cricket sim back in the iPhone SE, I noticed it occasionally lose the LTE connection that I don't recall it doing previously in the last week that I had the new phone. Could be a fluke though. And I don't know if the Voicemail greeting problem was around before because I wasn't checking it and wasn't getting lots of voicemails exactly. Also I tried giving myself a test voicemail and it wouldn't let me play it back, though after some resetting or I don't know what the playback works again. Don't know if that's useful or irrelevant or rambling.
Edit: The bit about my iPhone losing LTE, I think I've narrowed down the problem. I think it's just because Cricket isn't yet using VoLTE and I wasn't testing many phone calls. As it stands though I cannot change the greeting except through calling voicemail directly. This is not a massive problem though I would like to know what could be going on or if I should contact Apple Support since this is a new phone.
Also I kept playing around with it and at one time I did get the Greeting controls to work. And then it stopped working again. Don't know what's up or why that would be caused. Is it possible what I did with the SIM would cause this?

A: My Iphone 6 uses Verizon. I successfully changed VM greeting a couple of days ago then tried to change again the same day but none of the VM greeting buttons would work except cancel.  Called Verizon and they had me reset all settings. Still didn't work. The told me to re-set network settings and still didn't work.  The referred me to apple and I did a did a back up and restored using by back up.  Still didn't work. They wanted me to try to restore as new without the backup which I was reluctant to do.
Just deleted VMs and Delted VMs, and (for now) I'm able to record and change my VM greetings.  Thanks Kal-al

A: Mine seemed to not let me play or record a new message (or switch it back to default) and all I had to do was wait ~2 minutes with the voicemail screen pulled up. It seems like it just needed time to load. After two minutes it began working as normal.


text:
Q: Reset my google cloud VM instances, but the External IP is changed, why? I stop the instance yesterday , and today I start it.
The external Ip is changed, I don't know why they do that , how can I get my ip back?

A: You can't. As Paula says, you were assigned an ephemeral IP address, which is gone when you stop the machine.
If you don't want to lose it upon stopping the machine, you need to reserve the IP address, as explained here.


text:
Q: innertext does not run in certain url I need to read the "uploaded-date" from this url:
https://www.youtube.com/tv?vq=high#/watch/video/control?v=hqwU7nv3hTM&resume
Using this code:
window.alert(document.getElementsByClassName("uploaded-date")[0].innerText);

I got the error "Cannot read property 'innerText' of undefined".
If i use the same method in this url:
https://www.youtube.com/watch?v=hqwU7nv3hTM
with the code:
window.alert(document.getElementsByClassName("ytp-time-duration")[0].innerText);

where i only change the class name all runs well.
i don't understand where is my problem.
Any idea?
Thanks in advance.

A: The problem is about the load content.
When the script start, the page is not yet loaded.
Once loaded all is good.


text:
Q: Apache camel http4 authentication I am trying to route to intranet website to crawl the content.Below is my code
 from(DIRECT_INITIAL_CRAWL).setHeader(HTTP_METHOD, constant(GET))
 .to(http4://test.com:443/?
authMethod=BASIC&authUsername=name&authPassword=pwd&authHost=test.com)

but i am, getting

org.apache.http.NoHttpResponseException:
  test.com:443 failed to respond. at
  org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141)
    at
  org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at
  org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at
  org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at
  org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:165)
    at
  org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at
  org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at
  org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at
  org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
    at
  org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at
  org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
    at
  org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at
  org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at
  org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at
  org.apache.camel.component.http4.HttpProducer.executeMethod(HttpProducer.java:334)
    at
  org.apache.camel.component.http4.HttpProducer.process(HttpProducer.java:193)
    at
  org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)
    at
  org.apache.camel.processor.SendProcessor.process(SendProcessor.java:148)
    at
  org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:548)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:138)   at
  org.apache.camel.processor.Pipeline.process(Pipeline.java:101)    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
    at
  org.apache.camel.processor.SendProcessor.process(SendProcessor.java:148)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.processor.ChoiceProcessor.process(ChoiceProcessor.java:117)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.processor.TryProcessor.process(TryProcessor.java:113)
    at
  org.apache.camel.processor.TryProcessor.process(TryProcessor.java:84)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
    at
  org.apache.camel.processor.SendProcessor.process(SendProcessor.java:148)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:138)   at
  org.apache.camel.processor.Pipeline.process(Pipeline.java:101)    at
  org.apache.camel.processor.TryProcessor.process(TryProcessor.java:113)
    at
  org.apache.camel.processor.TryProcessor.process(TryProcessor.java:84)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:201)
    at
  org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
    at
  org.apache.camel.processor.SharedCamelInternalProcessor.process(SharedCamelInternalProcessor.java:186)
    at
  org.apache.camel.processor.SharedCamelInternalProcessor.process(SharedCamelInternalProcessor.java:86)
    at
  org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:541)
    at
  org.apache.camel.impl.ProducerCache$1.doInProducer(ProducerCache.java:506)
    at
  org.apache.camel.impl.ProducerCache.doInProducer(ProducerCache.java:369)
    at
  org.apache.camel.impl.ProducerCache.sendExchange(ProducerCache.java:506)
    at org.apache.camel.impl.ProducerCache.send(ProducerCache.java:229)
    at
  org.apache.camel.impl.DefaultProducerTemplate.send(DefaultProducerTemplate.java:144)
    at
  org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:161)
    at
  org.apache.camel.impl.DefaultProducerTemplate.sendBody(DefaultProducerTemplate.java:168)
    at
  com.abnamro.ees.connections.crawler.main.ApplicationMain.main(ApplicationMain.java:82)

Any help would be appreciated


text:
Q: weird symbol is shown up in the eclipse for .java file Suddenly some weird symbol is displayed on top of my class file in eclipse and no suggestions are working in that class file.
Symbol displayed on top of the java file --> {}
Please find the below image for more details

Arrow marked in the RED is the file which is acting weird
Arrow marked in yellow  does not have the symbol and it is working as expected

A: You get weird symbols there when your java file is not a part of src folder package. You need to keep all your java files under source folder. or if this folder needs to be added as a src type, then do the same under project properties.


text:
Q: Referencing Windows Form elements in other classes I'm very new to Windows Form programming, and I'm coming across a problem.
I have a windows form, Form1, with a textbox: tbx_Log.
In another class in the same project, I want to write something to the log textbox, but I cannot reference tbx_Log in that class. How can I achieve this?

A: Accessing objects inside other class instances (objects) is bad style and violating data encapsulation. Add a method to Form1:
public void SetLogText(String text)
{
     tbx_Log.Text = text;
}

This way you can change the implementation of the method by using some other control or logging to a file later, without having to modify all the call sites. Always try to have the code outside the class not to have knowledge about what's inside. The class implementation shall be a "black box" for the outside code.

A: You either need to make the textbox public (not recommended) or add a public method to your form class that will write a string to the textbox (better).
public class Form1
{
    protected Textbox tbx_Log;
    public void Log(string str)
    {
        tbx_Log.Text += str + Environment.NewLine;
    }
}

public class Program
{
    private void DoStuff()
    {
        Form1 myForm = new Form1();
        //Make form visible, etc...
        myForm.Log("Test Log");
    }
}

A: I'd suggest that you create a method on the Form class that writes to the log textbox.  Then you would pass that method as a delegate (callback) to your non-Form class.  This gives you more flexibility down the road.  For instance, if you wanted to call the same class from a different class, and you wanted to do something different with the logging information, such as writing it to a file, then you could just pass a different callback function.

A: Rather than reference tbx_Log directly, I would suggest that at the very least you add a method to your Form which is responsible for performing the update. Then you can give your class a reference to the Form and have your class call the Forms logging function, which in turn adds the text to the text box.
I said at the very least, because you would probably want to define an interface and have your Form or later a more specific logging class that implements the interface and have your class interact with anything that implements the defined interface.

A: You could make a public method on your form. And also make it thread safe in case it's called from a thread different than the UI thread.
How the other class accesses your method depends on how your app works and the relationship between the form class and your other class.
public void SetText(string text)
{
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (this.textBox1.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        this.tbx_Log.Text = text;
    }
}

For a complete sample and explanation of thread-safe calls on winforms check MSDN, which also shows how to use BackgroundWorker in order to achieve thread-safety, which is the preferred way of doing it.


text:
Q: Building thread safe generator for keras to use multiple workers If anyone has experience building thread safe generators is there anyway to do this with a function generator? I came across this post at: https://stanford.edu/~shervine/blog/keras-how-to-generate-data-on-the-fly
and I have tried to base my code off of this post, but I am getting an error that does not really make sense to me, does anyone have any insight?
import numpy as np
import keras
import cv2
import os
from depth_functional import predict

class data_generator(keras.utils.Sequence):

    def __init__(self,ImgPath,string_ids,keys,bs,model,bboxes):
        'Initialize'
        self.ImgPath=ImgPath
        self.string_ids=string_ids
        self.keys=keys
        self.bs=bs
        self.model=model
        self.bboxes=bboxes

        #will keep track how many times we have pulled batches of data
        self.count=0
    def __len__(self):
        #Denotes Number of batches per epoch
        return (int(np.floor(len(self.list_IDs))/self.bs))

    def __getitem__(self,index):
        #Generate index of the batch
        indexes=self.indexes[index*self.bs:(index+1)*self.bs]

        #find a list of ids you want to generate
        string_ids_temp=[self.string_ids[k] for k in indexes]

        #Generate data
        RGBD,Masks=self.__data_generation(string_ids_temp)

        return RGBD,Masks

    def on_epoch_end(self):
        self.indexes=np.arange(len(self.string_ids))

    def __data_generation(self,string_ids_temp):
        os.chdir('C:\\Users\\'+self.ImgPath)
        RGBD_images=np.zeros((self.bs,240,320))
        Masks=np.zeros((self.bs,240,320,19))

        for i in range(len(string_ids_temp)):
            img=cv2.imread(string_ids_temp[i] +'.jpg')
            RGBD,masks=self.ProcessData(img,self.bboxes[self.count],self.keys[self.count])
            RGBD_images[i,:,:,:]=RGBD
            Masks[i,:,:,:]=masks
            if self.count >= len(self.keys):
                self.count=0

    def ProcessData(self,img,bbox,keys):
        zeros=np.zeros((img.shape[0],img.shape[1],18))
        mask=np.zeros((240,320,19))

        bbox_height=abs(bbox[0]-bbox[2])
        bbox_width=abs(bbox[1]-bbox[3])
        sigma_x=400*(bbox_width/224)
        sigma_y=400*(bbox_height/224)

        for part in range(18):
            if keys[part][2]==2:
                for j in range(img.shape[1]):
                    x=np.linspace(0,img.shape[0]-1,img.shape[0])
                    y=np.full((img.shape[0],),float(j))
                    x_key=np.full((img.shape[0],),keys[part][1])
                    y_key=np.full((img.shape[0],),keys[part][0])

                    zeros[:,j,part]=np.exp(-(np.square(x-x_key)/sigma_x+np.square(y-y_key)/sigma_y))

        zeros=cv2.resize(zeros,(320,240))

        mask[:,:,18]=np.amax(mask,axis=-1)

        resized_img=cv2.resize(img,(640,480))/255.0
        depth=predict(self.model,resized_img)[0]
        depth=depth/np.amax(depth)

        smaller_img=cv2.resize(img,(320,240))/255.0

        RGBD = np.concatenate((smaller_img,depth),axis=-1)

        return RGBD,mask

I keep getting the following error which I do not really understand...
  File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:\Users\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 1297, in fit_generator
    steps_name='steps_per_epoch')

  File "C:\Users\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_generator.py", line 144, in model_iteration
    shuffle=shuffle)

  File "C:\Users\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\training_generator.py", line 477, in convert_to_generator_like
    num_samples = int(nest.flatten(data)[0].shape[0])

AttributeError: 'data_generator' object has no attribute 'shape'

Edit following TheLoneDeranger skeleton:
class Generator():

    def __init__(self,ImgPath,string_ids,keys,bboxes,bs,model):

        self.ImgPath=ImgPath
        self.string_ids=string_ids
        self.keys=keys
        self.bboxes=bboxes
        self.bs=bs
        self.model=model

        #Will count how many data samples we have pulled
        self.count=0

        def __iter__(self):
            return self

        def __len__(self):
            #returns the total number of training samples
            return len(self.keys)

        def __next__(self):
            RGBD_Images=np.zeros((self.bs,240,320,4))
            Masks=np.zeros((self.bs,240,320,19))

            os.chdir('C:\\Users\\'+ImgPath)

            for i in range(self.count*self.bs,(self.count+1)*self.bs):
                img=cv2.imread(self.string_ids[i]+'.jpg')
                zeros=np.zeros((img.shape[0],img.shape[1],18),dtype='float')
                mask=np.zeros((240,320,19),dtype='float')

                bbox_height = abs(self.bboxes[i][0]-self.bboxes[i][2])
                bbox_width = abs(self.bboxes[i][1]-self.bboxes[i][3])
                sigma_x=400*(bbox_width/224)
                sigma_y=400*(bbox_height/224)

                for part in range(18):
                    if self.keys[i][part][2]==2:
                        for j in range(img.shape[1]):
                            x = np.linspace(0,img.shape[0]-1,img.shape[0])
                            y = np.full((img.shape[0],),float(j))
                            x_key = np.full((img.shape[0],),self.keys[i][part][1])
                            y_key = np.full((img.shape[0],),self.keys[i][part][0])

                            zeros[:,j,part]=np.exp(-(np.square(x-x_key)/sigma_x+np.square(y-y_key)/sigma_y))

                zeros=cv2.resize(zeros,(320,240))
                mask[:,:,18]=np.amax(mask,axis=-1)
                Masks[i%self.bs,:,:,:]=mask

                resized_img = cv2.resize(img,(640,480))/255.0
                depth = predict(self.model,resized_img)[0]    #240 x 320 x1 output
                depth=depth/np.amax(depth)

                smaller_img = cv2.resize(img,(320,240))/255.0

                RGBD = np.concatenate((smaller_img,depth),axis=2)
                RGBD_Images[i%self.bs,:,:,:]=RGBD

            self.count+=1
            if (self.count+1)*self.bs >= len(self.keys):
                self.count=0

            return (RGBD_Images,Masks)

A: I keep this on hand as a basis for quickly making new generators for TF/Keras.  There are other ways to do it, but I use this in the majority of circumstances.
class Generator:
  def __init__(self,base_path):
    # initialize however... for example:
    self.base_path = base_path
    self.files = os.listdir(self.base_path)

  def __iter__(self):
    return self

  def __len__(self):
    return len(self.files) # needs to return total training samples

  def __next__(self):
    # get your images and labels
    return (images,labels)

You can then use them like so:
train_gen = Generator(train_path)
val_gen = Generator(val_path)
model.fit_generator(train_gen,
                    validation_data=val_gen,
                    steps_per_epoch=200,
                    validation_steps=200,
                    epochs=666)

Hope that helps!


text:
Q: How to animate AJAX post? sorry for this request but I'm an AJAX beginner.
I have the following script and I'm trying to animate it (something like "fade").
jQuery(document).ready(function($){
   $(document).on("click",".ratingemo", function(){
     var rating = $(this).attr("id").substr(0, 1);
     var id = $(this).attr("id").substr(1);
     var data = "id="+id+"&rating="+rating;

     $.ajax({
       type: "POST",
       url: "/ldplug/rate.php",
       data: data,
       success: function(e){
         $("#r"+id).html(e);
       }
     })
   });
});

How can I do that?
Many thanks!

A: First of all live is deprecated, check out on instead.  But that being said, why not:
success: function(e){
         $("#r"+id).hide();
         $("#r"+id).html(e).fadeIn("slow");
       }

It would be better to just have $("#r"+id) hidden to start, I just hid it to illustrate the point.

A: Without seeing your HTML, I have to assume that something like this will work for you. Hide the element, populate it, then fade it in.
jQuery(document).ready(function ($) {
    $(".ratings").live("click", function () {
        var rating = $(this).attr("id").substr(0, 1);
        var id = $(this).attr("id").substr(1);
        var data = "id=" + id + "&rating=" + rating;

        $("#r" + id).hide();
        $.ajax({
            type: "POST",
            url: "/ratings/rate.php",
            data: data,
            success: function (e) {
                $("#r" + id).html(e);
                $("#r" + id).fadeIn();
            }
        })
    });
});


text:
Q: restore centos "/" partition back problems I am facing the problems when restoring the "/" partition into the newly centos. My plan is to restore the backed-up centos (which has few packages installed like openstack) into a new machine.
The restore process goes as part of PXE boot. I have got some kind of kickstart files which does the stuff.
My PXE is in the order

*

*Install some packages before CENT OS

*Install CENT OS

*Copy the backed-up "/" data into "/" on latest

Unfortunately, the new Cent OS is not starting going into Emergency mode and asking me to press Ctrl+D.
Any help is really great !!

A: I am using rsnapshot for backup the Cent OS stuff. I have to exclude some directories in order to make it work after restoration of Cent OS.
Here is my rsnapshot.conf file changes.
backup  root@192.168.0.1:/     remote-backup/  exclude=/proc,exclude=/sys,exclude=/boot/grub,exclude=/boot/grub2,exclude=/etc/fstab,exclude=/etc/sysconfig/network-scripts/

The above backup is with root. Make sure you exclude those specified directories. Otherwise system doesn't boot up.
rsync for restore (in the Kickstart file)
echo "Restoring snapshot *TEST*"
rsync -avr --rsh="sshpass -p mypassword ssh -o StrictHostKeyChecking=no -l root" 192.168.0.2:/.snapshots/alpha.0/remote-backup/* /

Exluding them is the key here. Followed this link https://www.serverpronto.com/kb/page.php?id=Backing+Up+and+Restore+Your+Server


text:
Q: the plural of the name of the letter e is ees According to the wikipedia article of letter e

The plural of the name of the letter e is ees (the plural of the
  letter itself is rendered E's, Es, e's, es).

Therefore, is ees then a regular plural formed from -es?


text:
Q: Comparing each element in two columns and set another column I have a data frame (after fread from a file) with two columns (dep and label). I want to set another column (mark) with id value depending on the match. If the  'dep' entry matches 'lablel' entry, mark get the 'id' of the matched 'label'. For no match, mark get the value of its own 'id'. Currently, I have work around solution with loops but I know there should be a neat way to do it in R specifics.
trace <- data.table(id=seq(1:7),dep=c(-1,45,40,47,0,45,43),
label=c(99,40,43,45,47,42,48), mark=rep("",7))
   id dep label mark
1:  1  -1    99  1
2:  2  45    40  2
3:  3  40    43  2
4:  4  47    45  4
5:  5  0     47  5
6:  6  45    42  4
7:  7  43    48  3

I know loops are slow in r and just to give example the following naive for/while works for small sizes but my data set is huge.
trace$mark <- trace$id
for (i in 1:length(trace$id)){
val <- trace$dep[i]
j <- 1
while(j<=i && val !=-1 && val!=0){ // don't compare if val is -1/0

    if(val==trace$label[j]){
            trace$mark[i] <- trace$id[j]
                    }
 j <-j +1
}
}

I have also tried using the following approach but it works only if there is a single match.
match <- which(trace$dep %in% trace$label)
match_to <- which(trace$label %in% trace$dep)
trace$mark[match] <- trace$mark[match_to]

A: This solution might help:
trace[trace[,.(id,dep=label)],mark:=as.character(i.id),on="dep"]
trace[mark=="",mark:=as.character(id)]
# id dep label mark
# 1:  1  -1    99    1
# 2:  2  45    40    4
# 3:  3  -1    43    3
# 4:  4  47    45    5
# 5:  5  -1    47    5
# 6:  6  45    42    4
# 7:  7  43    48    3

Update:
To make sure you are not matching dep with 0 or -1 values you can just add another line.
trace[dep %in% c(0,-1), mark:= as.character(id)]

OR
Try this:
trace[trace[!dep %in% c(0,-1),.(id,dep=label)],mark:=as.character(i.id),on="dep"]
trace[mark=="",mark:=as.character(id)]

The solution that worked
trace[trace[,.(id,dep=label)],on=.(id<=id,dep),mark:=as.character(i.id),allow.cartesian=TRUE]


text:
Q: Swagger Editor: Save Changes Back to Source File? From the Swagger Editor, can changes or edits be saved back to the original, imported file? Currently, I am saving the code as a yaml file, doing a compare within Intellij, accepting each change, then saving that file. Onerous at best. I'm just changing text in description tags and don't need to make calls, mess with APIs, or servers.

A: The open-source Swagger Editor has the File > Save as YAML command. For best results, configure your browser to ask for the download location and file name instead of automatically saving to the "Downloads" folder.

*

*Chrome: Open chrome://settings/downloads and select Ask where to save each file before downloading.

*Firefox: Options > General > scroll down to Downloads and select Always ask you where to save files.

SwaggerHub (commercial product, has a free plan) combines the editor with cloud storage. It can also sync OpenAPI files with an external Git repository.
There are also OpenAPI editor plugins for IntelliJ IDEA.