问:
Grouping css selectors
Is it possible to group two selectors so that an element is matched only if both selectors are satisfied?  For example, if I want the element to satisfy both the selectors .a>.b~.c and .d~.e, is it possible to write a selector that matches the intersection of these selectors?

答:
If you're using class selectors as in your example, you can chain classes like this:

```<code>.a > .b.d ~ .c.e
</code>```

Selects an element that has both class="c e"

  which is a sibling of (i.e. comes, directly or not, after) an element that has both class="b d"

  which is a child of some element of class="a"

Or, like this, if you want .c.e to occur after an element that has either class b or d:

```<code>.a > .b ~ .c.e, .a > .d ~ .c.e
</code>```

Selects an element that has both class="c e"

  which is a sibling of an element with either class="b" or class="d" (or both)

  which is a child of some element of class="a"

Both selectors imply that .b, .d and .c.e are all children of .a. I should also think it gives you the class selector intersection that you're looking for.

Title: Grouping css selectors

Body:
If you're using class selectors as in your example, you can chain classes like this:

.a > .b.d ~ .c.e

Selects an element that has both class="c e"

  which is a sibling of (i.e. comes, directly or not, after) an element that has both class="b d"

  which is a child of some element of class="a"

Or, like this, if you want .c.e to occur after an element that has either class b or d:

.a > .b ~ .c.e, .a > .d ~ .c.e

Selects an element that has both class="c e"

  which is a sibling of an element with either class="b" or class="d" (or both)

  which is a child of some element of class="a"

Both selectors imply that .b, .d and .c.e are all children of .a. I should also think it gives you the class selector intersection that you're looking for.


来源: stackexchange

问:
CSS - position: absolute; - auto height
I am having a problem with some div's

The outer div has a min-height, but the inner divs are all varying heights. Because the inner divs are absolute positioned, they do not affect the outer divs height. Is there a way to make these inner divs affect the height of the outer div?

The reason I am styling these divs with position:absolute is so that they all start at the top of the container div.

答:
Here is a long overdue cross-browser solution to your problem. No more static width, no more em hack.

```<code><style>
  /* clearfix */
  .container:after {
    content: '';
    display: table;
    clear: left;
  }

  .page {
    float: left; /* display side-by-side */
    width: 100%; /* be as wide as parent */
    margin-right: -100%; /* take up no width */
  }
</style>

<div class="container">
  <div class="page"></div>
  <div class="page"></div>
</div>
</code>```

After searching for a solution to this problem for so long, I am baffled to see how simple it is. Granted, the .page elements are not absolutely positioned. However, all the same goals can be achieved through this method, with almost no pain or sacrifice.

Here's a demo: https://jsfiddle.net/eqe2muhv/

This also works for inline-blocks, of course. Though you might need to set the font-size or letter-spacing of the container to 0. I would also recommend using vertical-align: top on the .page, to simulate a regular block element.

Here's a demo: https://jsfiddle.net/dzouxurs/8/

ContentLicense: CC BY-SA 3.0

Title: CSS - position: absolute; - auto height

Body:
Here is a long overdue cross-browser solution to your problem. No more static width, no more em hack.

<style>
  /* clearfix */
  .container:after {
    content: '';
    display: table;
    clear: left;
  }

  .page {
    float: left; /* display side-by-side */
    width: 100%; /* be as wide as parent */
    margin-right: -100%; /* take up no width */
  }
</style>

<div class="container">
  <div class="page"></div>
  <div class="page"></div>
</div>

After searching for a solution to this problem for so long, I am baffled to see how simple it is. Granted, the .page elements are not absolutely positioned. However, all the same goals can be achieved through this method, with almost no pain or sacrifice.

Here's a demo: https://jsfiddle.net/eqe2muhv/

This also works for inline-blocks, of course. Though you might need to set the font-size or letter-spacing of the container to 0. I would also recommend using vertical-align: top on the .page, to simulate a regular block element.

Here's a demo: https://jsfiddle.net/dzouxurs/8/


问:
Google Translate API - English subscripts to translated script
I am trying to convert English to Hindi via Google's API but I also need the English translation of the Hindi string.

To illustrate, if I convert

"a quick brown fox...."

to Hindi , it reads

"फुर्तीली भूरी लोमड़ी आलसी कुत्ते के उपर से कूद गई।"

But if you look at the web interface, Google also translates the Hindi version as

"phurtilee bhoori lomdi ..".

This doesn't show up in the response format of Translate API. I tried searching all their docs but this is all I got https://cloud.google.com/translate/docs/reference/translate#translatetextresponsetranslation and it just has a translated text in the response.

答:
Google Translation API does not currently offer phonetic translation, despite being available in the web interface.

You can file a request for that feature to be included in the API by following the procedure explained in this forum where your same question is made.

ContentLicense: CC BY-SA 4.0


问:
getting GMSServicesException error
Am trying to execute my project, while going to home page itself am getting this error and app is crashing

Terminating app due to uncaught exception 'GMSServicesException', reason: 'Google Maps SDK for iOS requires GoogleMaps.bundle to be part of your target under 'Copy Bundle Resources''

答:
Please select project name from Xcode, select "Targets", select Build Phases . Open "Copy Bundle Resources" , then click on "+" button. It will open an windows containing the name of bundle file. Click on ADD to add in your bundle resources.

Steps:-

ProjectName -> Targets -> Build Phases -> Copy bundle Resources -> Click on "+" Button -> Add the specified file

Title: getting GMSServicesException error


问:
Extracting whole words
I have a large set of real-world text that I need to pull words out of to input into a spell checker. I'd like to extract as many meaningful words as possible without too much noise. I know there's plenty of regex ninjas around here, so hopefully someone can help me out.

Currently I'm extracting all alphabetical sequences with '[a-z]+'. This is an okay approximation, but it drags a lot of rubbish out with it.

Ideally I would like some regex (doesn't have to be pretty or efficient) that extracts all alphabetical sequences delimited by natural word separators (such as [/-_,.: ] etc.), and ignores any alphabetical sequences with illegal bounds.

However I'd also be happy to just be able to get all alphabetical sequences that ARE NOT adjacent to a number. So for instance 'pie21' would NOT extract 'pie', but 'http://foo.com' would extract ['http', 'foo', 'com'].

I tried lookahead and lookbehind assertions, but they were applied per-character (so for example re.findall('(?<!\d)[a-z]+(?!\d)', 'pie21') would return 'pi' when I want it to return nothing). I tried wrapping the alpha part as a term ((?:[a-z]+)) but it didn't help.

More detail: The data is an email database, so it's mostly plain English with normal numbers, but occasionally there's rubbish strings like GIHQ4NWL0S5SCGBDD40ZXE5IDP13TYNEA and AC7A21C0 that I'd like to ignore completely. I'm assuming any alphabetical sequence with a number in it is rubbish.

答:
Sample code

```<code>print re.search(ur'(?u)ривет\b', ur'Привет')
print re.search(ur'(?u)\bривет\b', ur'Привет')
</code>```

or

```<code>s = ur"abcd ААБВ"
import re
rx1 = re.compile(ur"(?u)АБВ")
rx2 = re.compile(ur"(?u)АБВ\b")
rx3 = re.compile(ur"(?u)\bАБВ\b")
print rx1.findall(s)
print rx2.findall(s)
print rx3.findall(s)
</code>```

Title: Extracting whole words

Body:
Sample code

print re.search(ur'(?u)ривет\b', ur'Привет')
print re.search(ur'(?u)\bривет\b', ur'Привет')

or

s = ur"abcd ААБВ"
import re
rx1 = re.compile(ur"(?u)АБВ")
rx2 = re.compile(ur"(?u)АБВ\b")
rx3 = re.compile(ur"(?u)\bАБВ\b")
print rx1.findall(s)
print rx2.findall(s)
print rx3.findall(s)


问:
dataframe + pandas + select specific rows
I'm new in using pandas and one of my functions does not behave as expected. I have this dataframe:

```<code>     title_year        gross
0          2009  7.60506e+08
1          2007  3.09404e+08
2          2015  2.00074e+08
3          2012  4.48131e+08
5          2012  7.30587e+07
6          2007   3.3653e+08
7          2010  2.00807e+08
8          2015  4.58992e+08
9          2009  3.01957e+08
</code>```

The function is:

```<code>def analysis_gross_per_year(year1, year2):
    year_df = data[['title_year', 'gross']]
    check = True
    year_df.title_year = year_df.title_year.fillna('Not Given')
    year_df.gross = year_df.gross.fillna('Not Given')
    year_df = year_df[year_df.gross != 'Not Given']
    gross_year = year_df[year_df.title_year.str.contains(year1, na=True)]
    number = int(year1)
    while check :
        if str(number) == year2:
            check = False
        else:
            number = number + 1
            df1 = year_df[year_df.title_year.str.contains(str(number), na=False)]
            gross_year = pd.concat([gross_year, df1])
            print (df1)
</code>```

I give the function 2 parameters year 1 and year 2 and it should display a line graph for average, min, max based on gross earning for the years provided.

E.g if 2013 and 2015. It should display a line graph for 2013, 2014, 2015. However when I run str.contains(year1, na=True) it returns an empty dataframe. Can you tell me why ?

答:
I am also a bit confused by the given code snippet, but if you just want to select certain years (as str values) in the dataframe, you could for example create a list of the years and then filter the dataframe accordingly.</p>

```<code>years_to_select = ['2012', '2013', '2014']
filtered_df = original_df[original_df['year'].isin(years_to_select)]
</code>```

Body:
I'm new in using pandas and one of my functions does not behave as expected. I have this dataframe:

     title_year        gross
0          2009  7.60506e+08
1          2007  3.09404e+08
2          2015  2.00074e+08
3          2012  4.48131e+08
5          2012  7.30587e+07
6          2007   3.3653e+08
7          2010  2.00807e+08
8          2015  4.58992e+08
9          2009  3.01957e+08

The function is:

def analysis_gross_per_year(year1, year2):
    year_df = data[['title_year', 'gross']]
    check = True
    year_df.title_year = year_df.title_year.fillna('Not Given')
    year_df.gross = year_df.gross.fillna('Not Given')
    year_df = year_df[year_df.gross != 'Not Given']
    gross_year = year_df[year_df.title_year.str.contains(year1, na=True)]
    number = int(year1)
    while check :
        if str(number) == year2:
            check = False
        else:
            number = number + 1
            df1 = year_df[year_df.title_year.str.contains(str(number), na=False)]
            gross_year = pd.concat([gross_year, df1])
            print (df1)

I give the function 2 parameters year 1 and year 2 and it should display a line graph for average, min, max based on gross earning for the years provided.

E.g if 2013 and 2015. It should display a line graph for 2013, 2014, 2015. However when I run str.contains(year1, na=True) it returns an empty dataframe. Can you tell me why ?

Body:
I am also a bit confused by the given code snippet, but if you just want to select certain years (as str values) in the dataframe, you could for example create a list of the years and then filter the dataframe accordingly.

years_to_select = ['2012', '2013', '2014']
filtered_df = original_df[original_df['year'].isin(years_to_select)]


问:
Magento Reports - Products - Products Ordered issue: Item (Mage_Catalog_Model_Product) with the same id already exist
The issue:
In Magento admin panel,  when generating report via Reports - Products - Products Ordered, an error occurs:

```

    Item (Mage_Catalog_Model_Product) with the same id "45" already exist
    #0 /home/glassesm/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(236): Varien_Data_Collection->addItem(Object(Mage_Catalog_Model_Product))
    #1 /home/glassesm/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(964): Mage_Eav_Model_Entity_Collection_Abstract->addItem(Object(Mage_Catalog_Model_Product))
    #2 /home/glassesm/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(794): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false)
    #3 /home/glassesm/public_html/lib/Varien/Data/Collection.php(729): Mage_Eav_Model_Entity_Collection_Abstract->load()
    #4 /home/glassesm/public_html/app/code/core/Mage/Reports/Model/Totals.php(53): Varien_Data_Collection->getIterator()
    #5 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Report/Grid.php(368): Mage_Reports_Model_Totals->countTotals(Object(Mage_Adminhtml_Block_Report_Product_Sold_Grid), '2011-12-10 00:0...', '2011-12-10 23:5...')
    #6 /home/glassesm/public_html/app/design/adminhtml/default/default/template/report/grid.phtml(138): Mage_Adminhtml_Block_Report_Grid->getReport('2011-12-10 00:0...', '2011-12-10 23:5...')
    #7 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(216): include('/home/glassesm/...')
    #8 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(247): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
    #9 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(261): Mage_Core_Block_Template->renderView()
    #10 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
    #11 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Adminhtml_Block_Template->_toHtml()
    #12 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(525): Mage_Core_Block_Abstract->toHtml()
    #13 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(476): Mage_Core_Block_Abstract->_getChildHtml('grid', true)
    #14 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php(70): Mage_Core_Block_Abstract->getChildHtml('grid')
    #15 /home/glassesm/public_html/app/design/adminhtml/default/default/template/widget/grid/container.phtml(36): Mage_Adminhtml_Block_Widget_Grid_Container->getGridHtml()
    #16 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(216): include('/home/glassesm/...')
    #17 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(247): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
    #18 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(261): Mage_Core_Block_Template->renderView()
    #19 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
    #20 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Container.php(295): Mage_Adminhtml_Block_Template->_toHtml()
    #21 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Adminhtml_Block_Widget_Container->_toHtml()
    #22 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Text/List.php(43): Mage_Core_Block_Abstract->toHtml()
    #23 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Core_Block_Text_List->_toHtml()
    #24 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(525): Mage_Core_Block_Abstract->toHtml()
    #25 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(476): Mage_Core_Block_Abstract->_getChildHtml('content', true)
    #26 /home/glassesm/public_html/app/design/adminhtml/default/default/template/page.phtml(74): Mage_Core_Block_Abstract->getChildHtml('content')
    #27 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(216): include('/home/glassesm/...')
    #28 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(247): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
    #29 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(261): Mage_Core_Block_Template->renderView()
    #30 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
    #31 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Adminhtml_Block_Template->_toHtml()
    #32 /home/glassesm/public_html/app/code/core/Mage/Core/Model/Layout.php(529): Mage_Core_Block_Abstract->toHtml()
    #33 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(389): Mage_Core_Model_Layout->getOutput()
    #34 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/controllers/Report/ProductController.php(97): Mage_Core_Controller_Varien_Action->renderLayout()
    #35 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Report_ProductController->soldAction()
    #36 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch('sold')
    #37 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
    #38 /home/glassesm/public_html/app/code/core/Mage/Core/Model/App.php(340): Mage_Core_Controller_Varien_Front->dispatch()
    #39 /home/glassesm/public_html/app/Mage.php(627): Mage_Core_Model_App->run(Array)
    #40 /home/glassesm/public_html/index.php(80): Mage::run('', 'store')
    #41 {main}

```

Could you help me with this issue ?

答:
Got the same error at the same spot, here is why and how I fixed.

Magento ordered products reports builds the "list" from "sales_flat_order_item" then join "catalog/product" for further information about the product (sku, type, options, attribute_set, etc..).

In my case, 3 products was deleted from store, when Magento build the list and join in catalog/product, all the information that I listed above was NULL. When Report module build the collection, at the method addItem, it tries to set an ID as key in the collection array, in those deleted product there is no ID, so NULL is set.

Imagine this set of items to build an report.

ID - Name: 1, 2, 3, DELETED ITEM, 4

When the "DELETE ITEM" is added to the collection, will look like this:

```<code>Array(
    1 => Object,
    2 => Object,
    3 => Object,
    4 => Object (DELETED ITEM)
)
</code>```

This is because in addItem, when there is no ID Magento add an new position in array with auto incremenet:

```<code>if (!is_null($itemId)) {
    .
    .
    .
} else {
    $this->_items[] = $item;
}
</code>```

Then, when the collection add the next item (ID: 4) will throw the exception you are looking at:

```<code>if (isset($this->_items[$itemId])) {
    throw new Exception('Item ('.get_class($item).') with the same id "'.$item->getId().'" already exist');
}
</code>```

Changing the way addItem works is very dangerous!! Collections are used everywhere in Magento, adding an trycatch block will definitly affect how your store work in other places/modules. Here is how I fixed:

You can either copy to local or ovewrite with an custom module, its up to you:

Add an new method in "Reports_Product/Collection" to filter only "existing products"

app/code/local/Mage/Reports/Model/Mysql4/Product/Collection.php

```<code>public function addNotDeletedProductRestrition(){
    $this->getSelect()->where('order_items.product_id is NOT NULL');

    return $this;
}
</code>```

Call this method in the ORDERED Collection.

app/code/local/Mage/Reports/Model/Mysql4/Product/Ordered/Collection.php

```<code>protected function _joinFields($from = '', $to = '')
{
    $this->addAttributeToSelect('*')
        ->addOrderedQty($from, $to)
        ->setOrder('ordered_qty', 'desc')
        ->addNotDeletedProductRestrition();

    return $this;
}
</code>```

I've placed inside _joinFields, but you can call wherever you want.

Sorry about my rusty english, i dont have much time to review, this bug already took me a lot of it.

Body:
The issue:
In Magento admin panel,  when generating report via Reports - Products - Products Ordered, an error occurs:

    Item (Mage_Catalog_Model_Product) with the same id "45" already exist
    #0 /home/glassesm/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(236): Varien_Data_Collection->addItem(Object(Mage_Catalog_Model_Product))
    #1 /home/glassesm/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(964): Mage_Eav_Model_Entity_Collection_Abstract->addItem(Object(Mage_Catalog_Model_Product))
    #2 /home/glassesm/public_html/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(794): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false)
    #3 /home/glassesm/public_html/lib/Varien/Data/Collection.php(729): Mage_Eav_Model_Entity_Collection_Abstract->load()
    #4 /home/glassesm/public_html/app/code/core/Mage/Reports/Model/Totals.php(53): Varien_Data_Collection->getIterator()
    #5 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Report/Grid.php(368): Mage_Reports_Model_Totals->countTotals(Object(Mage_Adminhtml_Block_Report_Product_Sold_Grid), '2011-12-10 00:0...', '2011-12-10 23:5...')
    #6 /home/glassesm/public_html/app/design/adminhtml/default/default/template/report/grid.phtml(138): Mage_Adminhtml_Block_Report_Grid->getReport('2011-12-10 00:0...', '2011-12-10 23:5...')
    #7 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(216): include('/home/glassesm/...')
    #8 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(247): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
    #9 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(261): Mage_Core_Block_Template->renderView()
    #10 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
    #11 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Adminhtml_Block_Template->_toHtml()
    #12 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(525): Mage_Core_Block_Abstract->toHtml()
    #13 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(476): Mage_Core_Block_Abstract->_getChildHtml('grid', true)
    #14 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php(70): Mage_Core_Block_Abstract->getChildHtml('grid')
    #15 /home/glassesm/public_html/app/design/adminhtml/default/default/template/widget/grid/container.phtml(36): Mage_Adminhtml_Block_Widget_Grid_Container->getGridHtml()
    #16 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(216): include('/home/glassesm/...')
    #17 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(247): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
    #18 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(261): Mage_Core_Block_Template->renderView()
    #19 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
    #20 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Widget/Container.php(295): Mage_Adminhtml_Block_Template->_toHtml()
    #21 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Adminhtml_Block_Widget_Container->_toHtml()
    #22 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Text/List.php(43): Mage_Core_Block_Abstract->toHtml()
    #23 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Core_Block_Text_List->_toHtml()
    #24 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(525): Mage_Core_Block_Abstract->toHtml()
    #25 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(476): Mage_Core_Block_Abstract->_getChildHtml('content', true)
    #26 /home/glassesm/public_html/app/design/adminhtml/default/default/template/page.phtml(74): Mage_Core_Block_Abstract->getChildHtml('content')
    #27 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(216): include('/home/glassesm/...')
    #28 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(247): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
    #29 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Template.php(261): Mage_Core_Block_Template->renderView()
    #30 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
    #31 /home/glassesm/public_html/app/code/core/Mage/Core/Block/Abstract.php(758): Mage_Adminhtml_Block_Template->_toHtml()
    #32 /home/glassesm/public_html/app/code/core/Mage/Core/Model/Layout.php(529): Mage_Core_Block_Abstract->toHtml()
    #33 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(389): Mage_Core_Model_Layout->getOutput()
    #34 /home/glassesm/public_html/app/code/core/Mage/Adminhtml/controllers/Report/ProductController.php(97): Mage_Core_Controller_Varien_Action->renderLayout()
    #35 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_Report_ProductController->soldAction()
    #36 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch('sold')
    #37 /home/glassesm/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
    #38 /home/glassesm/public_html/app/code/core/Mage/Core/Model/App.php(340): Mage_Core_Controller_Varien_Front->dispatch()
    #39 /home/glassesm/public_html/app/Mage.php(627): Mage_Core_Model_App->run(Array)
    #40 /home/glassesm/public_html/index.php(80): Mage::run('', 'store')
    #41 {main}

Could you help me with this issue ?

Body:
Got the same error at the same spot, here is why and how I fixed.

Magento ordered products reports builds the "list" from "sales_flat_order_item" then join "catalog/product" for further information about the product (sku, type, options, attribute_set, etc..).

In my case, 3 products was deleted from store, when Magento build the list and join in catalog/product, all the information that I listed above was NULL. When Report module build the collection, at the method addItem, it tries to set an ID as key in the collection array, in those deleted product there is no ID, so NULL is set.

Imagine this set of items to build an report.

ID - Name: 1, 2, 3, DELETED ITEM, 4

When the "DELETE ITEM" is added to the collection, will look like this:

Array(
    1 => Object,
    2 => Object,
    3 => Object,
    4 => Object (DELETED ITEM)
)

This is because in addItem, when there is no ID Magento add an new position in array with auto incremenet:

if (!is_null($itemId)) {
    .
    .
    .
} else {
    $this->_items[] = $item;
}

Then, when the collection add the next item (ID: 4) will throw the exception you are looking at:

if (isset($this->_items[$itemId])) {
    throw new Exception('Item ('.get_class($item).') with the same id "'.$item->getId().'" already exist');
}

Changing the way addItem works is very dangerous!! Collections are used everywhere in Magento, adding an trycatch block will definitly affect how your store work in other places/modules. Here is how I fixed:

You can either copy to local or ovewrite with an custom module, its up to you:

Add an new method in "Reports_Product/Collection" to filter only "existing products"

app/code/local/Mage/Reports/Model/Mysql4/Product/Collection.php

public function addNotDeletedProductRestrition(){
    $this->getSelect()->where('order_items.product_id is NOT NULL');

    return $this;
}

Call this method in the ORDERED Collection.

app/code/local/Mage/Reports/Model/Mysql4/Product/Ordered/Collection.php

protected function _joinFields($from = '', $to = '')
{
    $this->addAttributeToSelect('*')
        ->addOrderedQty($from, $to)
        ->setOrder('ordered_qty', 'desc')
        ->addNotDeletedProductRestrition();

    return $this;
}

I've placed inside _joinFields, but you can call wherever you want.

Sorry about my rusty english, i dont have much time to review, this bug already took me a lot of it.


问:
React Select - How to show / iterate through data from api call in option instead of hardcoding options?
I am using react-select and I don't want to hard code the options which should be displayed, but options is data I am fetching from an api. I can't really find anything and what I was trying to do doesn't work as nothing gets displayed. Anyone knows? Thanks!!!

api.js:

```<code>export function availableCities() {
   return axios.get('/cities').then(function (response) {
      return response.data;
   })
}
</code>```

Component:

```<code>import Select from 'react-select';
import {availableCities} from '../utils/api.js';

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
     }
   }
   componentDidMount() {
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            })
            console.log("hello", this.state.cities)
        })
   }

   handleChange(selectedOption) {
    this.setState({selectedOption});
   }
 render(){
    let options = this.state.cities.map(function (city) {
            return city.name;
    })
 return (
      <div>
           <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                options={options}
            />
      </div>
  )
 }
}
</code>```

Data( this.state.cities is an array of objects and looks like:

```<code>{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}

...
</code>```

答:
In your return component you can simply pass the cities that is fetched from api as

```<code>import Select from 'react-select';
import {availableCities} from '../utils/api.js';

let isLoadingExternally = false;

class App extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
    }
}
componentDidMount() {
    isLoadingExternally = true;
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            }, () => {
                isLoadingExternally = false;
            })
            console.log("hello", this.state.cities)
        })
}

handleChange(selectedOption) {
    this.setState({selectedOption});
}
render(){
return (
    <div>
        <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                labelKey={'name'}
                valueKey={'code'}
                isLoading={isLoadingExternally}
                options={this.state.cities}
            />
    </div>
)
}
}
</code>```

There are lots of configurable options available in the docs.

Body:
I am using react-select and I don't want to hard code the options which should be displayed, but options is data I am fetching from an api. I can't really find anything and what I was trying to do doesn't work as nothing gets displayed. Anyone knows? Thanks!!!

api.js:

export function availableCities() {
   return axios.get('/cities').then(function (response) {
      return response.data;
   })
}

Component:

import Select from 'react-select';
import {availableCities} from '../utils/api.js';

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
     }
   }
   componentDidMount() {
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            })
            console.log("hello", this.state.cities)
        })
   }

   handleChange(selectedOption) {
    this.setState({selectedOption});
   }
 render(){
    let options = this.state.cities.map(function (city) {
            return city.name;
    })
 return (

           <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                options={options}
            />

  )
 }
}

Data( this.state.cities is an array of objects and looks like:

{code: "LTS", name: "Altus", countryCode: "US", countryName: "United States", regionName: "North America", …}

...

Body:
In your return component you can simply pass the cities that is fetched from api as

import Select from 'react-select';
import {availableCities} from '../utils/api.js';

let isLoadingExternally = false;

class App extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
        selectedOption: '',
        clearable: true,
        cities: [],
    }
}
componentDidMount() {
    isLoadingExternally = true;
    availableCities()
        .then(res => {
            this.setState({
                cities: res.Cities.name
            }, () => {
                isLoadingExternally = false;
            })
            console.log("hello", this.state.cities)
        })
}

handleChange(selectedOption) {
    this.setState({selectedOption});
}
render(){
return (
    <div>
        <Select
                name="form-field-name"
                value={this.state.value}
                onChange={this.handleChange}
                clearable={this.state.clearable}
                searchable={this.state.searchable}
                labelKey={'name'}
                valueKey={'code'}
                isLoading={isLoadingExternally}
                options={this.state.cities}
            />
    </div>
)
}
}

There are lots of configurable options available in the docs.


问:
Quitting VLC processes while streaming
I have two programs that start a VLC instance through the command line.
One streams video, the other streams audio, both from dshow://

When I ask the programs to stop recording and quit VLC, even though both instances quit, the second one always leaves the process running in the background.
Now, I can forcefully kill it, but that would mean my recording is somehow not released and stays corrupted, and I don't want that.

I've tried several quitting methods:

Calling CTRL+Q (I have it set as the quit Global HotKey)

taskkill /PID xxx on cmd.exe

Adding vlc://quit to the end of my command line and calling next (I have ALT+N set as the next Global HotKey)

Calling stop (again through HotKeys) and then quit.

None of these seems to work. Any ideas?

I'm running Windows 7 x64, and VLC 2.2.2 (I tried both 32 and 64 bit)

答:
So I know this is two years later but I think this may help people. Like you I searched everywhere with nothing working until I tried this:

If nothing works try using the option --ignore-config at the beginning after vlc in addition to http://quit at the end

and it finally worked

Hope some one finds this useful

Title: Quitting VLC processes while streaming


问:
SQL - AVG and Group by
I have the following table:

```<code>Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40
</code>```

I am having hard time finding a query in SQL Server that can give me this result:

```<code>Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30
</code>```

I want the average price for each product everyday

Product starting from 1.1 to 24.4

答:
There depending on which number you want as output.
Like if

FLOOR() of every number

cast(product as int) convert to int

Query:

```<code> SELECT
  Date,
  FLOOR(product) product, // This function can be replaced with above according to the output
  AVG(price) price

FROM your_table
GROUP BY date, FLOOR(product) order by Date
</code>```

As you say that output as the error you can also try the following.

```<code> SELECT
  Date,
  FLOOR(convert(float, product)) product, // This function can be replaced by FLOOR(cast(product as float))
  AVG(price) price

FROM your_table
GROUP BY date, FLOOR(convert(float, product)) order by Date;
</code>```

Title: SQL - AVG and Group by

Body:
I have the following table:

Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40

I am having hard time finding a query in SQL Server that can give me this result:

Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30

I want the average price for each product everyday

Product starting from 1.1 to 24.4

Body:
There depending on which number you want as output.
Like if

FLOOR() of every number

cast(product as int) convert to int

Query:

 SELECT
  Date,
  FLOOR(product) product, // This function can be replaced with above according to the output
  AVG(price) price

FROM your_table
GROUP BY date, FLOOR(product) order by Date

As you say that output as the error you can also try the following.

 SELECT
  Date,
  FLOOR(convert(float, product)) product, // This function can be replaced by FLOOR(cast(product as float))
  AVG(price) price

FROM your_table
GROUP BY date, FLOOR(convert(float, product)) order by Date;


问:
Getting a list of results by using CRUD Repository
I am new to using CRUD Repository.

I have a database table with three columns:

course_id, name, course

I want to get a list of course_id give name, example,

```<code>SELECT id FROM table WHERE name='charmaine';
</code>```

However, I do not want to do it with query but using crud repository.

There is an error shown in my controller.
May I know there is this error?

My controller

```<code>@GetMapping(value = "getting/{name}")
    //@ResponseBody
     public String getting(@PathVariable("name") String name) {
        List<CourseMaster> getIds =  CourseService.findIdByName(Name);   —> error icon here
        return getIds;  —> error icon here
     }
</code>```

Service

```<code>public List<CourseMaster> findIdByName(String Name) {
    return CourseMasterRepo.findByName(Name);
}
</code>```

Repository

```<code>public interface CourseMasterRepo extends CrudRepository<CourseMaster, Long> {
    List<CourseMaster> findByName(String Name);
}
</code>```

答:
You have to autowired service class in your controller like.</p>

```<code> @Autowired
 CourseService courseService;

 @GetMapping(value = "getting/{name}")
 public String getting(@PathVariable("name") String name) {
    List<CourseMaster> getIds =  courseService.findIdByName(Name);
    return getIds;
 }
</code>```

Body:
I am new to using CRUD Repository.

I have a database table with three columns:

course_id, name, course

I want to get a list of course_id give name, example,

SELECT id FROM table WHERE name='charmaine';

However, I do not want to do it with query but using crud repository.

There is an error shown in my controller.
May I know there is this error?

My controller

@GetMapping(value = "getting/{name}")
    //@ResponseBody
     public String getting(@PathVariable("name") String name) {
        List<CourseMaster> getIds =  CourseService.findIdByName(Name);   —> error icon here
        return getIds;  —> error icon here
     }

Service

public List<CourseMaster> findIdByName(String Name) {
    return CourseMasterRepo.findByName(Name);
}

Repository

public interface CourseMasterRepo extends CrudRepository<CourseMaster, Long> {
    List<CourseMaster> findByName(String Name);
}

Body:
You have to autowired service class in your controller like.

 @Autowired
 CourseService courseService;

 @GetMapping(value = "getting/{name}")
 public String getting(@PathVariable("name") String name) {
    List<CourseMaster> getIds =  courseService.findIdByName(Name);
    return getIds;
 }


问:
MySQL Notifier High Cpu Load
I'm using Windows 10 and latest MySQL version Community Edition, configured as development machine. Recently when I was playing game, I've discovered that I have FPS drops every few seconds (about 5), overall system slow down, and high CPU usage spikes. After long investigation using Process Explorer, TaskMgr, then manually disabling services and startup applications, I've found that it is caused by MySQL Notifier, which causes services.exe to use high cpu usage about 20-50% of CPU. Workaround is to disable MySQL Notifier in Startup Management in Windows 10.

Why this happen, and how to fix it? Reinstallation didn't solve issue.
Does anyone have same problem?

答: The Startup Management in Windows 10 is found my loading up Task Manager, and switching to the Start-up tab. From there you can locate MySQL Notified and change its status to Disabled.</p>

Title: MySQL Notifier High Cpu Load


问:
Change Login Status on Database after browser force closed or session expired
I have a user login data in MySQL, in condition user only can login 1 times in session. If using logout button, code are running well but if the user close the browser

```<code>// user_table in MySQL
   user_id      user_username      user_password      is_login
     1              xyzabc             xxxxx             0  // 0 is not
     2              abcdef             xxxxx             1  // 1 is login
     3              efghij             xxxxx             1
</code>```

I used is_login for blocking access from 2nd login user. So, each account only can login once and is_login we used to kick user from logged in session on set is_login to 0.

```<code>// Inside my login function
public function login()
{
   ... some validation login code ...
   // User ID accepted & login = TRUE
   $this->session->set_userdata('id', $data->user_id);
   // this query is in model, I just copy it to here
   $this->db->query('UPDATE user_table SET is_login = "1" WHERE user_id = ".$id."');
   $this->session->sess_expiration = 7200;
   $this->session->sess_expire_on_close = TRUE;
}

// Logout function in controller
public function logout() {
   $id = $this->session->userdata('id');
   // this query is in model, I just copy it to here
   $this->db->query('UPDATE user_table SET is_login = "0" WHERE user_id = ".$id."');
   $this->session->sess_destroy();
}
</code>```

If the user are logged out using logout function, the code are running well.

The is_login column will be set on 0 again. But if the browser force closed is_login status is still 1. Any solution ?

答:
As indicated by @Tpojka change the is_login column to INT(11)

Add another column to your user table to shows the last user activity

Add a cronjob to SET is_login = 0 if the current system time and the last user activity is greater than expiration time

Whenever a user logs in, store time() value from php into DB

Store the same value of login time() into user session. so everytime that the user refresh a page you make check the value that you have in session with DB to understand that the user is the same or not. if not, logout the user and destroy the same. it might mean that the user is logged in from another device so he/she should be logged out from the current browser

every time that the user send a request and the is_login value matches the value that you have in DB, you may add and update another value in the user session. for example dte_last_activity then you can understand that if the session is expired or not for the user. don't rely on the session expiration time of the server as you might need a different expiration time.

Okay, let say that we have a user table like below:

```<code> CREATE TABLE IF NOT EXISTS `system_users` (
   `id` smallint(5) unsigned NOT NULL,
   `fullname` varchar(90) COLLATE utf8_persian_ci NOT NULL,
   `username` varchar(40) COLLATE utf8_persian_ci NOT NULL,
   `password` varchar(32) COLLATE utf8_persian_ci DEFAULT NULL,
   `dte_login` int(11) unsigned NOT NULL DEFAULT '0',
   `dte_activity` int(11) unsigned NOT NULL DEFAULT '0',
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci;
</code>```

dte_login is timestamp value that we set into the database whenever a user log in
dte_activity is timestamp value for the last time that the user requested something from your server and off course he was log in

Note that dte_activity is only needed if you need to check that a user is still active or not.

```<code>function login($username, $password) {
    $result = false;

    // Check from DB that the username and password is valid or not
    // IF user is valid, retrieve user_id from DB
    If (USER_IS_VALID) {
        $_SESSION['user_id'] = $user_id;
        $_SESSION['dte_activity'] = time();
        $_SESSION['dte_login'] = time();

        $result = true;
    }

    return $result;
}
</code>```

Okay now whenever the user ask to access a page you call a sample function like below:

```<code>function checkLogin() {
    $result = false;

    if (!empty($_SESSION['user_id'])) {
         // This means that somebody is already logged in
         $user_id = $_SESSION['user_id'];
         $dte_login = $_SESION['dte_login'];

         // We need to check if the user which is login is the same as the last user that used our website so we compare the dte_login value that we stored in session with what we have in DB
         $db_connection->query("SELECT `id` FROM `system_users` WHERE `id`={$user_id} AND `dte_login`={$dte_login};");
         // If the above query return no result, it means that someone else logged in meanwhile and we have to log out the current user

         if ($db_connection->num_rows>0) {
             // Now we need to check if his/her session is still valid or not
             $EXPIERY = 300; // in seconds (in this case, 5 minutes)
             $now = time();
             if ($now-$_SESSION['dte_activity']<$EXPIERY) {
                 // The user session is still valid and we need to update database
                 $db_connection->query("UPDATE `system_users` SET `dte_activity`={$now} WHERE id={$user_id};");
                 $_SESSION['dte_activity'] = $now;

                 $result = true; // Means that someone is active
             } else {
                 session_destroy();
             }
         } else {
             session_destroy();
         }
    }

    return $result;
}
</code>```

Body:
I have a user login data in MySQL, in condition user only can login 1 times in session. If using logout button, code are running well but if the user close the browser

// user_table in MySQL
   user_id      user_username      user_password      is_login
     1              xyzabc             xxxxx             0  // 0 is not
     2              abcdef             xxxxx             1  // 1 is login
     3              efghij             xxxxx             1

I used is_login for blocking access from 2nd login user. So, each account only can login once and is_login we used to kick user from logged in session on set is_login to 0.

// Inside my login function
public function login()
{
   ... some validation login code ...
   // User ID accepted & login = TRUE
   $this->session->set_userdata('id', $data->user_id);
   // this query is in model, I just copy it to here
   $this->db->query('UPDATE user_table SET is_login = "1" WHERE user_id = ".$id."');
   $this->session->sess_expiration = 7200;
   $this->session->sess_expire_on_close = TRUE;
}

// Logout function in controller
public function logout() {
   $id = $this->session->userdata('id');
   // this query is in model, I just copy it to here
   $this->db->query('UPDATE user_table SET is_login = "0" WHERE user_id = ".$id."');
   $this->session->sess_destroy();
}

If the user are logged out using logout function, the code are running well.

The is_login column will be set on 0 again. But if the browser force closed is_login status is still 1. Any solution ?

Body:
As indicated by @Tpojka change the is_login column to INT(11)

Add another column to your user table to shows the last user activity

Add a cronjob to SET is_login = 0 if the current system time and the last user activity is greater than expiration time

Whenever a user logs in, store time() value from php into DB

Store the same value of login time() into user session. so everytime that the user refresh a page you make check the value that you have in session with DB to understand that the user is the same or not. if not, logout the user and destroy the same. it might mean that the user is logged in from another device so he/she should be logged out from the current browser

every time that the user send a request and the is_login value matches the value that you have in DB, you may add and update another value in the user session. for example dte_last_activity then you can understand that if the session is expired or not for the user. don't rely on the session expiration time of the server as you might need a different expiration time.

Okay, let say that we have a user table like below:

 CREATE TABLE IF NOT EXISTS `system_users` (
   `id` smallint(5) unsigned NOT NULL,
   `fullname` varchar(90) COLLATE utf8_persian_ci NOT NULL,
   `username` varchar(40) COLLATE utf8_persian_ci NOT NULL,
   `password` varchar(32) COLLATE utf8_persian_ci DEFAULT NULL,
   `dte_login` int(11) unsigned NOT NULL DEFAULT '0',
   `dte_activity` int(11) unsigned NOT NULL DEFAULT '0',
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_persian_ci;

dte_login is timestamp value that we set into the database whenever a user log in
dte_activity is timestamp value for the last time that the user requested something from your server and off course he was log in

Note that dte_activity is only needed if you need to check that a user is still active or not.

function login($username, $password) {
    $result = false;

    // Check from DB that the username and password is valid or not
    // IF user is valid, retrieve user_id from DB
    If (USER_IS_VALID) {
        $_SESSION['user_id'] = $user_id;
        $_SESSION['dte_activity'] = time();
        $_SESSION['dte_login'] = time();

        $result = true;
    }

    return $result;
}

Okay now whenever the user ask to access a page you call a sample function like below:

function checkLogin() {
    $result = false;

    if (!empty($_SESSION['user_id'])) {
         // This means that somebody is already logged in
         $user_id = $_SESSION['user_id'];
         $dte_login = $_SESION['dte_login'];

         // We need to check if the user which is login is the same as the last user that used our website so we compare the dte_login value that we stored in session with what we have in DB
         $db_connection->query("SELECT `id` FROM `system_users` WHERE `id`={$user_id} AND `dte_login`={$dte_login};");
         // If the above query return no result, it means that someone else logged in meanwhile and we have to log out the current user

         if ($db_connection->num_rows>0) {
             // Now we need to check if his/her session is still valid or not
             $EXPIERY = 300; // in seconds (in this case, 5 minutes)
             $now = time();
             if ($now-$_SESSION['dte_activity']<$EXPIERY) {
                 // The user session is still valid and we need to update database
                 $db_connection->query("UPDATE `system_users` SET `dte_activity`={$now} WHERE id={$user_id};");
                 $_SESSION['dte_activity'] = $now;

                 $result = true; // Means that someone is active
             } else {
                 session_destroy();
             }
         } else {
             session_destroy();
         }
    }

    return $result;
}


问:
Extracting values from JSON in C#
I am working on an application that detects license plates and give me information about them. This is done by calling an Rest API called "openALPR".
As a result i get an JSON string looking like this:

{
  "uuid": "",
  "data_type": "alpr_results",
  "epoch_time": 1512554543436,
  "processing_time": {
    "plates": 145.41024780273438,
    "total": 147.6409999995667
  },
  "img_height": 233,
  "img_width": 700,
  "results": [
    {
      "plate": "MTF5101",
      "confidence": 94.978622436523438,
      "region_confidence": 0,
      "vehicle_region": {
        "y": 1,
        "x": 234,
        "height": 232,
        "width": 232
      },
      "region": "fr",
      "plate_index": 0,
      "processing_time_ms": 193.28457641601563,
      "candidates": [
        {
          "matches_template": 0,
          "plate": "MTF5101",
          "confidence": 94.978622436523438
        }
      ],
      "coordinates": [
        {
          "y": 102,
          "x": 289
        },
        {
          "y": 101,
          "x": 412
        },
        {
          "y": 126,
          "x": 412
        },
        {
          "y": 128,
          "x": 289
        }
      ],
      "matches_template": 0,
      "requested_topn": 50
    },
    {
      "plate": "MHV7718",
      "confidence": 94.9754638671875,
      "region_confidence": 0,
      "vehicle_region": {
        "y": 0,
        "x": 395,
        "height": 233,
        "width": 233
      },
      "region": "fr",
      "plate_index": 1,
      "processing_time_ms": 193.28457641601563,
      "candidates": [
        {
          "matches_template": 0,
          "plate": "MHV7718",
          "confidence": 94.9754638671875
        },
        {
          "matches_template": 0,
          "plate": "MH7718",
          "confidence": 81.550361633300781
        },
        {
          "matches_template": 0,
          "plate": "MHY7718",
          "confidence": 81.411224365234375
        }
      ],
      "coordinates": [
        {
          "y": 142,
          "x": 475
        },
        {
          "y": 148,
          "x": 676
        },
        {
          "y": 184,
          "x": 674
        },
        {
          "y": 178,
          "x": 475
        }
      ],
      "matches_template": 0,
      "requested_topn": 50
    },
    {
      "plate": "MTG7780",
      "confidence": 94.97296142578125,
      "region_confidence": 0,
      "vehicle_region": {
        "y": 1,
        "x": 91,
        "height": 232,
        "width": 232
      },
      "region": "fr",
      "plate_index": 2,
      "processing_time_ms": 193.28457641601563,
      "candidates": [
        {
          "matches_template": 0,
          "plate": "MTG7780",
          "confidence": 94.97296142578125
        },
        {
          "matches_template": 0,
          "plate": "MT7780",
          "confidence": 81.548896789550781
        },
        {
          "matches_template": 0,
          "plate": "MT67780",
          "confidence": 81.409553527832031
        }
      ],
      "coordinates": [
        {
          "y": 84,
          "x": 18
        },
        {
          "y": 96,
          "x": 202
        },
        {
          "y": 140,
          "x": 201
        },
        {
          "y": 128,
          "x": 16
        }
      ],
      "matches_template": 0,
      "requested_topn": 50
    }
  ],
  "credits_monthly_used": 48,
  "version": 2,
  "credits_monthly_total": 2000,
  "error": false,
  "regions_of_interest": [],
  "credit_cost": 1
}
```

Now i need to get the coordinates for every license plate. In this example there are 3 license plates. Each "coordinate" key includes four points (x,y).

How do I get these coordinates in C#?

Thanks for looking at my question!

With best regards,
Fabian Maurhart!

答:
For starters make C# Model classes for your REST API output like this:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JSONConversion.Models
{

    public class LicensePlateInformation
    {
        public string uuid { get; set; }
        public string data_type { get; set; }
        public long epoch_time { get; set; }
        public Processing_Time processing_time { get; set; }
        public int img_height { get; set; }
        public int img_width { get; set; }
        public List<Result> results { get; set; }
        public int credits_monthly_used { get; set; }
        public int version { get; set; }
        public int credits_monthly_total { get; set; }
        public bool error { get; set; }
        public object[] regions_of_interest { get; set; }
        public int credit_cost { get; set; }
    }

    public class Processing_Time
    {
        public float plates { get; set; }
        public float total { get; set; }
    }

    public class Result
    {
        public string plate { get; set; }
        public float confidence { get; set; }
        public int region_confidence { get; set; }
        public Vehicle_Region vehicle_region { get; set; }
        public string region { get; set; }
        public int plate_index { get; set; }
        public float processing_time_ms { get; set; }
        public Candidate[] candidates { get; set; }
        public List<Coordinate> coordinates { get; set; }
        public int matches_template { get; set; }
        public int requested_topn { get; set; }
    }

    public class Vehicle_Region
    {
        public int y { get; set; }
        public int x { get; set; }
        public int height { get; set; }
        public int width { get; set; }
    }

    public class Candidate
    {
        public int matches_template { get; set; }
        public string plate { get; set; }
        public float confidence { get; set; }
    }

    public class Coordinate
    {
        public int y { get; set; }
        public int x { get; set; }
    }
}
</code>```

After that get your JSON data from your API by making a GET request like this:

```<code>using System.Net.Http;
using Newtonsoft.Json;

public async Task<LicensePlateInformation> GetLicensePlateInfoFromAPI()
{
   try
   {
    string stringifiedJSONFromAPI = string.Empty;
    LicensePlateInformation plateInfo = new LicensePlateInformation();
    using(HttpClient client = new HttpClient())
    {
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

       HttpResponseMessage msg = await client.GetAsync($"<Insert rest api endpoint here>");

       if(msg.IsSuccessStatusCode)
       {
          stringifiedJSONFromAPI = await msg.Content.ReadAsStringAsync();
          JsonConvert.PopulateObject(stringifiedJSONFromAPI, plateInfo);
       }
       return plateInfo;
    }
   }
   catch(Exception ex)
   {
      throw;
   }
}
</code>```

Finally, after getting the C# model class, just apply LINQ to fetch all your details:

```<code>using System.Linq;
using System.Collections.Generic;

LicensePlateInformation plateInfo = await GetLicensePlateInfoFromAPI();
List<Coordinate> coOrdinatesList = new List<Coordinate>();
 foreach (var outerItem in plateInfo.results.Select(x => x.coordinates))
 {
       foreach (var innerItem in outerItem)
       {
          coOrdinatesList.Add(innerItem);
       }
 }
</code>```

Title: Extracting values from JSON in C#

Body:
I am working on an application that detects license plates and give me information about them. This is done by calling an Rest API called "openALPR".
As a result i get an JSON string looking like this:

{
  "uuid": "",
  "data_type": "alpr_results",
  "epoch_time": 1512554543436,
  "processing_time": {
    "plates": 145.41024780273438,
    "total": 147.6409999995667
  },
  "img_height": 233,
  "img_width": 700,
  "results": [
    {
      "plate": "MTF5101",
      "confidence": 94.978622436523438,
      "region_confidence": 0,
      "vehicle_region": {
        "y": 1,
        "x": 234,
        "height": 232,
        "width": 232
      },
      "region": "fr",
      "plate_index": 0,
      "processing_time_ms": 193.28457641601563,
      "candidates": [
        {
          "matches_template": 0,
          "plate": "MTF5101",
          "confidence": 94.978622436523438
        }
      ],
      "coordinates": [
        {
          "y": 102,
          "x": 289
        },
        {
          "y": 101,
          "x": 412
        },
        {
          "y": 126,
          "x": 412
        },
        {
          "y": 128,
          "x": 289
        }
      ],
      "matches_template": 0,
      "requested_topn": 50
    },
    {
      "plate": "MHV7718",
      "confidence": 94.9754638671875,
      "region_confidence": 0,
      "vehicle_region": {
        "y": 0,
        "x": 395,
        "height": 233,
        "width": 233
      },
      "region": "fr",
      "plate_index": 1,
      "processing_time_ms": 193.28457641601563,
      "candidates": [
        {
          "matches_template": 0,
          "plate": "MHV7718",
          "confidence": 94.9754638671875
        },
        {
          "matches_template": 0,
          "plate": "MH7718",
          "confidence": 81.550361633300781
        },
        {
          "matches_template": 0,
          "plate": "MHY7718",
          "confidence": 81.411224365234375
        }
      ],
      "coordinates": [
        {
          "y": 142,
          "x": 475
        },
        {
          "y": 148,
          "x": 676
        },
        {
          "y": 184,
          "x": 674
        },
        {
          "y": 178,
          "x": 475
        }
      ],
      "matches_template": 0,
      "requested_topn": 50
    },
    {
      "plate": "MTG7780",
      "confidence": 94.97296142578125,
      "region_confidence": 0,
      "vehicle_region": {
        "y": 1,
        "x": 91,
        "height": 232,
        "width": 232
      },
      "region": "fr",
      "plate_index": 2,
      "processing_time_ms": 193.28457641601563,
      "candidates": [
        {
          "matches_template": 0,
          "plate": "MTG7780",
          "confidence": 94.97296142578125
        },
        {
          "matches_template": 0,
          "plate": "MT7780",
          "confidence": 81.548896789550781
        },
        {
          "matches_template": 0,
          "plate": "MT67780",
          "confidence": 81.409553527832031
        }
      ],
      "coordinates": [
        {
          "y": 84,
          "x": 18
        },
        {
          "y": 96,
          "x": 202
        },
        {
          "y": 140,
          "x": 201
        },
        {
          "y": 128,
          "x": 16
        }
      ],
      "matches_template": 0,
      "requested_topn": 50
    }
  ],
  "credits_monthly_used": 48,
  "version": 2,
  "credits_monthly_total": 2000,
  "error": false,
  "regions_of_interest": [],
  "credit_cost": 1
}

Now i need to get the coordinates for every license plate. In this example there are 3 license plates. Each "coordinate" key includes four points (x,y).

How do I get these coordinates in C#?

Thanks for looking at my question!

With best regards,
Fabian Maurhart!

Body:
For starters make C# Model classes for your REST API output like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JSONConversion.Models
{

    public class LicensePlateInformation
    {
        public string uuid { get; set; }
        public string data_type { get; set; }
        public long epoch_time { get; set; }
        public Processing_Time processing_time { get; set; }
        public int img_height { get; set; }
        public int img_width { get; set; }
        public List<Result> results { get; set; }
        public int credits_monthly_used { get; set; }
        public int version { get; set; }
        public int credits_monthly_total { get; set; }
        public bool error { get; set; }
        public object[] regions_of_interest { get; set; }
        public int credit_cost { get; set; }
    }

    public class Processing_Time
    {
        public float plates { get; set; }
        public float total { get; set; }
    }

    public class Result
    {
        public string plate { get; set; }
        public float confidence { get; set; }
        public int region_confidence { get; set; }
        public Vehicle_Region vehicle_region { get; set; }
        public string region { get; set; }
        public int plate_index { get; set; }
        public float processing_time_ms { get; set; }
        public Candidate[] candidates { get; set; }
        public List<Coordinate> coordinates { get; set; }
        public int matches_template { get; set; }
        public int requested_topn { get; set; }
    }

    public class Vehicle_Region
    {
        public int y { get; set; }
        public int x { get; set; }
        public int height { get; set; }
        public int width { get; set; }
    }

    public class Candidate
    {
        public int matches_template { get; set; }
        public string plate { get; set; }
        public float confidence { get; set; }
    }

    public class Coordinate
    {
        public int y { get; set; }
        public int x { get; set; }
    }
}

After that get your JSON data from your API by making a GET request like this:

using System.Net.Http;
using Newtonsoft.Json;

public async Task<LicensePlateInformation> GetLicensePlateInfoFromAPI()
{
   try
   {
    string stringifiedJSONFromAPI = string.Empty;
    LicensePlateInformation plateInfo = new LicensePlateInformation();
    using(HttpClient client = new HttpClient())
    {
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

       HttpResponseMessage msg = await client.GetAsync($"<Insert rest api endpoint here>");

       if(msg.IsSuccessStatusCode)
       {
          stringifiedJSONFromAPI = await msg.Content.ReadAsStringAsync();
          JsonConvert.PopulateObject(stringifiedJSONFromAPI, plateInfo);
       }
       return plateInfo;
    }
   }
   catch(Exception ex)
   {
      throw;
   }
}

Finally, after getting the C# model class, just apply LINQ to fetch all your details:

using System.Linq;
using System.Collections.Generic;

LicensePlateInformation plateInfo = await GetLicensePlateInfoFromAPI();
List<Coordinate> coOrdinatesList = new List<Coordinate>();
 foreach (var outerItem in plateInfo.results.Select(x => x.coordinates))
 {
       foreach (var innerItem in outerItem)
       {
          coOrdinatesList.Add(innerItem);
       }
 }


问:
Warning: file.lua is not tracked by this installation of LuaRocks
I am trying to install a luarocks package called stn. The official way of installing it is by running:

```<code>luarocks install https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec
</code>```

But this gives me the unfortunate, exacerbating error:

```<code>nvcc fatal   : Value 'sm_20' is not defined for option 'gpu-architecture'
</code>```

The only way to fix this, to my knowledge, is to manually change the CMakeLists.txt file from:

```<code>IF (CUDA_FOUND)
  LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_20")
</code>```

To:

```<code>IF (CUDA_FOUND)
  LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_30")
</code>```

So that meant I had to clone the repo into a local file, change the CMakeLists file, and then luarock make it. (As a disclaimer, to do this, I had to chown my entire user because of directory writing permissions luarocks just doesnt seem to have for whatever reason. How screwed am I?).

So, I was able to get it to install the .rockspec file by cding into the master directory and:

```<code>luarocks make stnbhwd-scm-1.rockspec
</code>```

And this gave me this output:

```<code>$ luarocks make stnbhwd-scm-1.rockspec
cmake -E make_directory build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="/home/tex/torch/install/bin/.." -DCMAKE_INSTALL_PREFIX="/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1" && make

-- Found Torch7 in /home/tex/torch/install
-- Compiling with OpenMP support
-- Configuring done
-- Generating done
-- Build files have been written to: /home/tex/Downloads/stnbhwd-master/build
[ 50%] Built target stn
[ 75%] Building NVCC (Device) object CMakeFiles/custn.dir/custn_generated_init.cu.o
CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THStorage.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THStorageCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCStorage.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCStorageCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensor.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorRandom.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorMath.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorConv.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorLapack.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensor.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorRandom.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMath.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathBlas.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathMagma.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathPairwise.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathPointwise.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathReduce.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathCompare.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathCompareT.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathScan.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMasked.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorScatterGather.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorIndex.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorSort.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMode.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorTopK.h

[100%] Linking CXX shared module libcustn.so
[100%] Built target custn
cd build && make install
[ 50%] Built target stn
[100%] Built target custn
Install the project...
-- Install configuration: "Release"
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libstn.so
-- Set runtime path of "/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libstn.so" to "$ORIGIN/../lib:/home/tex/torch/install/lib"
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/test.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/AffineGridGeneratorBHWD.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/AffineTransformMatrixGenerator.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/init.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/BilinearSamplerBHWD.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libcustn.so
-- Set runtime path of "/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libcustn.so" to "$ORIGIN/../lib:/home/tex/torch/install/lib"
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/init.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/init.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineTransformMatrixGenerator.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineTransformMatrixGenerator.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/BilinearSamplerBHWD.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/BilinearSamplerBHWD.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/test.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/test.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineGridGeneratorBHWD.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineGridGeneratorBHWD.lua~~~~~~
Warning: /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libstn.so is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libstn.so~~~~~~
Warning: /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libcustn.so is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libcustn.so~~~~~
stnbhwd scm-1 is now installed in /home/tex/torch/install/ (license: MIT)
</code>```

Pay attention to the "warning" flags. I don't know why it does that, but I think it has some clear effect on the install, because when I load stn...:

```<code>Failed loading module stn in LuaRocks rock stnbhwd scm-1
    no field package.preload['stn']
    no file '/home/tex/.luarocks/share/lua/5.1/stn.lua'
    no file '/home/tex/.luarocks/share/lua/5.1/stn/init.lua'
    no file '/home/tex/torch/install/share/lua/5.1/stn.lua'
    no file '/home/tex/torch/install/share/lua/5.1/stn/init.lua'
    no file './stn.lua'
    no file '/home/tex/torch/install/share/luajit-2.1.0-beta1/stn.lua'
    no file '/usr/local/share/lua/5.1/stn.lua'
    no file '/usr/local/share/lua/5.1/stn/init.lua'
    no file '/home/tex/.luarocks/lib/lua/5.1/stn.so'
    no file '/home/tex/torch/install/lib/lua/5.1/stn.so'
    no file '/home/tex/torch/install/lib/stn.so'
    no file './stn.so'
    no file '/usr/local/lib/lua/5.1/stn.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'error'
    /home/tex/torch/install/share/lua/5.1/trepl/init.lua:389: in function 'require'
    run_model.lua:6: in main chunk
    [C]: in function 'dofile'
    .../tex/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk
    [C]: at 0x00405d50
</code>```

sigh Does anyone know a fix? Is there a workaround? LuaRocks still works for installing packages, but maybe I am doing something wrong for installing local packages. Is there a way to install the stn package while changing the cmake file before it installs (instead of downloading the package and manually changing it that way)? I doubt it, but... :(

Edit: anyone reading this, please refer to this page. I essentialy said screw this and uploaded the edited repo onto my own github page. Now, I face a different error.

答:
I can see some mismatch in the paths. When you are installing stnbhwd you use prefix:

```<code>-DCMAKE_INSTALL_PREFIX="/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1"
</code>```

but looking to the warnings you get:

```<code>Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/init.lua is not tracked by this installation of LuaRocks
</code>```

Shows that your LUA_PATH, LUA_CPATH is set to

```<code>/home/tex/torch/install/share/lua/5.1
</code>```

Firstly, try the path that you used in prefix to add into LUA_PATH, LUA_CPATH

If that doesn't help try to specify the path in the Lua script:

```<code>-- add a new directory to the path
package.path = package.path .. ";/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/?.lua"
</code>```

Alos, check this one

Body:
I am trying to install a luarocks package called stn. The official way of installing it is by running:

luarocks install https://raw.githubusercontent.com/qassemoquab/stnbhwd/master/stnbhwd-scm-1.rockspec

But this gives me the unfortunate, exacerbating error:

nvcc fatal   : Value 'sm_20' is not defined for option 'gpu-architecture'

The only way to fix this, to my knowledge, is to manually change the CMakeLists.txt file from:

IF (CUDA_FOUND)
  LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_20")

To:

IF (CUDA_FOUND)
  LIST(APPEND CUDA_NVCC_FLAGS "-arch=sm_30")

So that meant I had to clone the repo into a local file, change the CMakeLists file, and then luarock make it. (As a disclaimer, to do this, I had to chown my entire user because of directory writing permissions luarocks just doesnt seem to have for whatever reason. How screwed am I?).

So, I was able to get it to install the .rockspec file by cding into the master directory and:

luarocks make stnbhwd-scm-1.rockspec

And this gave me this output:

$ luarocks make stnbhwd-scm-1.rockspec
cmake -E make_directory build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="/home/tex/torch/install/bin/.." -DCMAKE_INSTALL_PREFIX="/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1" && make

-- Found Torch7 in /home/tex/torch/install
-- Compiling with OpenMP support
-- Configuring done
-- Generating done
-- Build files have been written to: /home/tex/Downloads/stnbhwd-master/build
[ 50%] Built target stn
[ 75%] Building NVCC (Device) object CMakeFiles/custn.dir/custn_generated_init.cu.o
CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THStorage.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THStorageCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCStorage.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCStorageCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensor.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorRandom.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorMath.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorConv.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THTensorLapack.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensor.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorCopy.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorRandom.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMath.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathBlas.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathMagma.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathPairwise.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathPointwise.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathReduce.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathCompare.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathCompareT.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMathScan.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMasked.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorScatterGather.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorIndex.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorSort.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorMode.h

CMake Warning at /usr/share/cmake-3.5/Modules/FindCUDA/make2cmake.cmake:65 (message):
   Removing non-existent dependency file: generic/THCTensorTopK.h

[100%] Linking CXX shared module libcustn.so
[100%] Built target custn
cd build && make install
[ 50%] Built target stn
[100%] Built target custn
Install the project...
-- Install configuration: "Release"
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libstn.so
-- Set runtime path of "/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libstn.so" to "$ORIGIN/../lib:/home/tex/torch/install/lib"
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/test.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/AffineGridGeneratorBHWD.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/AffineTransformMatrixGenerator.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/init.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/BilinearSamplerBHWD.lua
-- Installing: /home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libcustn.so
-- Set runtime path of "/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lib/libcustn.so" to "$ORIGIN/../lib:/home/tex/torch/install/lib"
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/init.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/init.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineTransformMatrixGenerator.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineTransformMatrixGenerator.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/BilinearSamplerBHWD.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/BilinearSamplerBHWD.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/test.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/test.lua~~~~~~
Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineGridGeneratorBHWD.lua is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/AffineGridGeneratorBHWD.lua~~~~~~
Warning: /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libstn.so is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libstn.so~~~~~~
Warning: /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libcustn.so is not tracked by this installation of LuaRocks. Moving it to /home/tex/torch/install/lib/lua/5.1/stnbhwd_scm_1-libcustn.so~~~~~
stnbhwd scm-1 is now installed in /home/tex/torch/install/ (license: MIT)

Pay attention to the "warning" flags. I don't know why it does that, but I think it has some clear effect on the install, because when I load stn...:

Failed loading module stn in LuaRocks rock stnbhwd scm-1
    no field package.preload['stn']
    no file '/home/tex/.luarocks/share/lua/5.1/stn.lua'
    no file '/home/tex/.luarocks/share/lua/5.1/stn/init.lua'
    no file '/home/tex/torch/install/share/lua/5.1/stn.lua'
    no file '/home/tex/torch/install/share/lua/5.1/stn/init.lua'
    no file './stn.lua'
    no file '/home/tex/torch/install/share/luajit-2.1.0-beta1/stn.lua'
    no file '/usr/local/share/lua/5.1/stn.lua'
    no file '/usr/local/share/lua/5.1/stn/init.lua'
    no file '/home/tex/.luarocks/lib/lua/5.1/stn.so'
    no file '/home/tex/torch/install/lib/lua/5.1/stn.so'
    no file '/home/tex/torch/install/lib/stn.so'
    no file './stn.so'
    no file '/usr/local/lib/lua/5.1/stn.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'error'
    /home/tex/torch/install/share/lua/5.1/trepl/init.lua:389: in function 'require'
    run_model.lua:6: in main chunk
    [C]: in function 'dofile'
    .../tex/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk
    [C]: at 0x00405d50

sigh Does anyone know a fix? Is there a workaround? LuaRocks still works for installing packages, but maybe I am doing something wrong for installing local packages. Is there a way to install the stn package while changing the cmake file before it installs (instead of downloading the package and manually changing it that way)? I doubt it, but... :(

Edit: anyone reading this, please refer to this page. I essentialy said screw this and uploaded the edited repo onto my own github page. Now, I face a different error.

Body:
I can see some mismatch in the paths. When you are installing stnbhwd you use prefix:

-DCMAKE_INSTALL_PREFIX="/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1"

but looking to the warnings you get:

Warning: /home/tex/torch/install/share/lua/5.1/stnbhwd_scm_1-stn/init.lua is not tracked by this installation of LuaRocks

Shows that your LUA_PATH, LUA_CPATH is set to

/home/tex/torch/install/share/lua/5.1

Firstly, try the path that you used in prefix to add into LUA_PATH, LUA_CPATH

If that doesn't help try to specify the path in the Lua script:

-- add a new directory to the path
package.path = package.path .. ";/home/tex/torch/install/lib/luarocks/rocks/stnbhwd/scm-1/lua/stn/?.lua"

Alos, check this one


问:
Access isExplicitNavigationBack from router:navigation:complete event
Aurelia doesn't automatically scroll the browser to the top of the page after navigating to a new route, so I've easily solved this using the EventAggregator, listening to the router:navigation:complete event inside my main App class (app.js):

```<code>import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class App {
    constructor (ea) {
        this.ea = ea;

        this.ea.subscribe('router:navigation:complete', e => {
            document.body.scrollTop = document.documentElement.scrollTop = 0;
        });
    }
}
</code>```

I recently noticed the isExplicitNavigationBack property on the router which would be extremely useful to prevent top scrolling when the user navigates backwards, however, the property is always false. I've tried with back button as well as Router.navigateBack().

My hope was to simply change my subscription callback to this:

```<code>if (!e.instruction.router.isExplicitNavigationBack) {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}
</code>```

But unfortunately isExplicitNavigationBack is always false - why?

答:
In the commit adding the isExplicitNavigationBack property you can see that the value is set to true when calling router.navigateBack() but it's set back to false on resolveInstruction.

Since you subscribed to the router:navigation:complete event, the routing is already complete and therefore the value is set back to false. If you subscribe to the router:navigation:processing event, it should be true if you call router.navigateBack().

```<code>this.ea.subscribe('router:navigation:processing', e => {
  if (!e.instruction.router.isExplicitNavigationBack) {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }
});
</code>```

Body:
Aurelia doesn't automatically scroll the browser to the top of the page after navigating to a new route, so I've easily solved this using the EventAggregator, listening to the router:navigation:complete event inside my main App class (app.js):

import {inject} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';

@inject(EventAggregator)
export class App {
    constructor (ea) {
        this.ea = ea;

        this.ea.subscribe('router:navigation:complete', e => {
            document.body.scrollTop = document.documentElement.scrollTop = 0;
        });
    }
}

I recently noticed the isExplicitNavigationBack property on the router which would be extremely useful to prevent top scrolling when the user navigates backwards, however, the property is always false. I've tried with back button as well as Router.navigateBack().

My hope was to simply change my subscription callback to this:

if (!e.instruction.router.isExplicitNavigationBack) {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}

But unfortunately isExplicitNavigationBack is always false - why?

Body:
In the commit adding the isExplicitNavigationBack property you can see that the value is set to true when calling router.navigateBack() but it's set back to false on resolveInstruction.

Since you subscribed to the router:navigation:complete event, the routing is already complete and therefore the value is set back to false. If you subscribe to the router:navigation:processing event, it should be true if you call router.navigateBack().

this.ea.subscribe('router:navigation:processing', e => {
  if (!e.instruction.router.isExplicitNavigationBack) {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }
});


问:
How to get minimum sdk version(minSdkVersion) at runtime?
I wanted to get the minSdkVersion used to build the app at runtime. I tried with the below code.

```<code>getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.targetSdkVersion
</code>```

In the documentation the targetSdkVersion is mentioned with the comment The minimum SDK version this application targets.. But it is providing the current version where the application is running.

Is there any predefined way is available to get the minSdkVersion? (or)
Is there any hack is possible to get the minSdkVersion?

答:
@PedroAGSantos's answer is not 100% correct, we need to use apiLevel property of minSdkVersion and we don't need extra quotes. here is the corrected version:</p>

```<code>defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 5
        versionName "some name"
        applicationId "com.myapp"
        buildConfigField "int", "MIN_SDK_VERSION", "$minSdkVersion.apiLevel"
}
</code>```

Body:
I wanted to get the minSdkVersion used to build the app at runtime. I tried with the below code.

getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.targetSdkVersion

In the documentation the targetSdkVersion is mentioned with the comment The minimum SDK version this application targets.. But it is providing the current version where the application is running.

Is there any predefined way is available to get the minSdkVersion? (or)
Is there any hack is possible to get the minSdkVersion?

Body:
@PedroAGSantos's answer is not 100% correct, we need to use apiLevel property of minSdkVersion and we don't need extra quotes. here is the corrected version:

defaultConfig {
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 5
        versionName "some name"
        applicationId "com.myapp"
        buildConfigField "int", "MIN_SDK_VERSION", "$minSdkVersion.apiLevel"
}