问:
How to do when selecting select option toggleClass not force close
I made a button that works to select the number of passengers with the select option. but there was a problem when I selected the number of passengers force close.

How to do when selecting passenger numbers is not force close.

Thanks in advance

I've put his code on > https://jsfiddle.net/devefrontend/vaqdsmjk/1/

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    $(".passenger-box").toggleClass("s");
    e.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

```

答:
Based on your code, the div.btn-passenger element gets the click event even when you click on the 3 dropdowns as they all are inside the div element.And, I see the click event toggles the visibility on and off. That's why all the dropdown disappear when you try to select an item.

Perhaps, it's better to replace the div.btn-passenger element with a button.

```<code><input type="button" value="0 click buttton" class="btn-passenger"/>

<div class="passenger-box">
<label>Dewasa 12+ Thn</label>
<select name="adult" id="adult" class="form-control passenger">
  <option selected="selected">1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
</select>
<label>Anak 2-12 Thn</label>
<select name="child" id="child" class="form-control passenger">
  <option>0</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
</select>
<label>Bayi
  < 2 Thn</label>
    <select name="infant" id="infant" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
</div>
</code>```

Have a look at this fiddle: https://jsfiddle.net/huxgcj0q/1/

Body:
I made a button that works to select the number of passengers with the select option. but there was a problem when I selected the number of passengers force close.

How to do when selecting passenger numbers is not force close.

Thanks in advance

I've put his code on > https://jsfiddle.net/devefrontend/vaqdsmjk/1/

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    $(".passenger-box").toggleClass("s");
    e.stopPropagation();
  });
});

.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

Body:
Based on your code, the div.btn-passenger element gets the click event even when you click on the 3 dropdowns as they all are inside the div element.And, I see the click event toggles the visibility on and off. That's why all the dropdown disappear when you try to select an item.

Perhaps, it's better to replace the div.btn-passenger element with a button.

<input type="button" value="0 click buttton" class="btn-passenger"/>

<div class="passenger-box">
<label>Dewasa 12+ Thn</label>
<select name="adult" id="adult" class="form-control passenger">
  <option selected="selected">1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
</select>
<label>Anak 2-12 Thn</label>
<select name="child" id="child" class="form-control passenger">
  <option>0</option>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
</select>
<label>Bayi
  < 2 Thn</label>
    <select name="infant" id="infant" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
</div>

Have a look at this fiddle: https://jsfiddle.net/huxgcj0q/1/


来源: stackexchange

问:
Python AttributeError : Object has no attribute in QGIS Plugin
I'm trying to create a GUI with QT Designer. I've converted my .ui designer file to a .py.

Here is my code:

```<code>from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtGui import QAction, QIcon
from qgis.core import *
import resources
from delete_feature_dialog import DeleteFeatureDialog
import os.path

class DeleteFeature:

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&DeleteFeature')
        self.toolbar = self.iface.addToolBar(u'DeleteFeature')
        self.toolbar.setObjectName(u'DeleteFeature')

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):

        # Create the dialog (after translation) and keep reference
        self.dlg = DeleteFeatureDialog()

        ....

        return action

    def initGui(self):
        icon_path = ':/plugins/DeleteFeature/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u''),
            callback=self.run,
            parent=self.iface.mainWindow())

    def run(self):
        #this code will populate the combo box with all vector layer
    self.dlg.layerListCombo.clear()
    layers = self.iface.legendInterface().layers()
    layer_list = []
    for layer in layers:
            layerType = layer.type()
            if layerType == QgsMapLayer.VectorLayer:
                layer_list.append(layer.name())
    self.dlg.layerListCombo.addItems(layer_list)
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            selectedLayerIndex = self.dlg.layerlistcombo.currentIndex()
            selectedLayer = layers [selectedLayerIndex]
            .....
</code>```

Then when I open the plugin, I get the following error:

'DeleteFeatureDialog' objectObject has no attribute
  'layerlistcombo'in QGIS Plugin

Any suggestion for this.

答:
Seems that you wrote:

```<code>selectedLayerIndex = self.dlg.layerlistcombo.currentIndex()
</code>```

but you should have written:

```<code>selectedLayerIndex = self.dlg.layerListCombo.currentIndex()
</code>```

Like you did previously in your code (notice the Camel Notation when writing, not just lower-case letters), which is probably causing the No Attribute error you get.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a GUI with QT Designer. I've converted my .ui designer file to a .py.

Here is my code:

from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtGui import QAction, QIcon
from qgis.core import *
import resources
from delete_feature_dialog import DeleteFeatureDialog
import os.path

class DeleteFeature:

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&DeleteFeature')
        self.toolbar = self.iface.addToolBar(u'DeleteFeature')
        self.toolbar.setObjectName(u'DeleteFeature')

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):

        # Create the dialog (after translation) and keep reference
        self.dlg = DeleteFeatureDialog()

        ....

        return action

    def initGui(self):
        icon_path = ':/plugins/DeleteFeature/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u''),
            callback=self.run,
            parent=self.iface.mainWindow())

    def run(self):
        #this code will populate the combo box with all vector layer
    self.dlg.layerListCombo.clear()
    layers = self.iface.legendInterface().layers()
    layer_list = []
    for layer in layers:
            layerType = layer.type()
            if layerType == QgsMapLayer.VectorLayer:
                layer_list.append(layer.name())
    self.dlg.layerListCombo.addItems(layer_list)
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            selectedLayerIndex = self.dlg.layerlistcombo.currentIndex()
            selectedLayer = layers [selectedLayerIndex]
            .....

Then when I open the plugin, I get the following error:

'DeleteFeatureDialog' objectObject has no attribute
  'layerlistcombo'in QGIS Plugin

Any suggestion for this.

Body:
Seems that you wrote:

selectedLayerIndex = self.dlg.layerlistcombo.currentIndex()

but you should have written:

selectedLayerIndex = self.dlg.layerListCombo.currentIndex()

Like you did previously in your code (notice the Camel Notation when writing, not just lower-case letters), which is probably causing the No Attribute error you get.


问:
How to display the current tab in HTML?
I am using HTML link attribute

```<code><a href="http://www.google.com" target="_blank">Click me</a>
</code>```

Here If I click the "Click me Link" it is opening a new tab.but it should display the current tab only.

May anyone help me to do this.

Thanks In advance

答:
Just remove the target attribute from anchor tag if you want to open this link in the same tab .</p>

```<code><a href="http://www.google.com">Click me</a>
</code>```

Title: How to display the current tab in HTML?

Body:
I am using HTML link attribute

Click me

Here If I click the "Click me Link" it is opening a new tab.but it should display the current tab only.

May anyone help me to do this.

Thanks In advance

Body:
Just remove the target attribute from anchor tag if you want to open this link in the same tab .

<a href="http://www.google.com">Click me</a>


问:
Extract And Save mysql data
I have a data is about 30-40GB and it represents as XML and stored as BLOB in MySQL server.
I want to create a new table, that should parse the XML and extract particular attributes to store as different columns(10-20 columns).

Is there any good ETL tool is available to do this?

NOTE: Currently i am simply using JDBC and Java to this transformation.

答: Try Talend Open Studio for data integration. You will need to use the tFileInputXML component to read the file, you can check this tutorial out. The result from this component can be processed and loaded into your database using a tMySQLOutput or tOracleOutput or any other database input component.</p>

Title: Extract And Save mysql data


问:
modify a column in pandas data-frame selecting a sub-string
This is my pandas data-frame. I want to modify values of first column (System) by extracting just a,b,c,d. How can this be done in python</p>

```<code> System       mem
/vol/a/        10
/vol/b/        20
/vol/c/        30
/vol/d/        40
</code>```

答:
Can be done in multiple ways, here is one

```<code>df['System'] = df['System'].str.split('/').str[-2]

    System  mem
0   a       10
1   b       20
2   c       30
3   d       40
</code>```

Option 2:

```<code>df['System'] = df.System.str.replace('[/vol/|/]', '')
</code>```

Andy Hayden already covered str.extract

Body:
This is my pandas data-frame. I want to modify values of first column (System) by extracting just a,b,c,d. How can this be done in python

 System       mem
/vol/a/        10
/vol/b/        20
/vol/c/        30
/vol/d/        40

Body:
Can be done in multiple ways, here is one

df['System'] = df['System'].str.split('/').str[-2]

    System  mem
0   a       10
1   b       20
2   c       30
3   d       40

Option 2:

df['System'] = df.System.str.replace('[/vol/|/]', '')

Andy Hayden already covered str.extract


答:
Using str.extract:

```<code>import pandas as pd

df = pd.DataFrame({'System': ['/vol/a/', '/vol/b/', '/vol/c/', '/vol/d/'], 'mem': [10, 20, 30, 40]})

df['new_column'] = df['System'].str.extract(r'([^/]+)/?$')
print(df)
</code>```

This yields

```<code>    System  mem new_column
0  /vol/a/   10          a
1  /vol/b/   20          b
2  /vol/c/   30          c
3  /vol/d/   40          d
</code>```

Title: modify a column in pandas data-frame selecting a sub-string

Body:
Using str.extract:

import pandas as pd

df = pd.DataFrame({'System': ['/vol/a/', '/vol/b/', '/vol/c/', '/vol/d/'], 'mem': [10, 20, 30, 40]})

df['new_column'] = df['System'].str.extract(r'([^/]+)/?$')
print(df)

This yields

    System  mem new_column
0  /vol/a/   10          a
1  /vol/b/   20          b
2  /vol/c/   30          c
3  /vol/d/   40          d


问:
How to convert XML to JSON in Python?

Possible Duplicate:

  Converting XML to JSON using Python?

I'm doing some work on App Engine and I need to convert an XML document being retrieved from a remote server into an equivalent JSON object.

I'm using xml.dom.minidom to parse the XML data being returned by urlfetch. I'm also trying to use django.utils.simplejson to convert the parsed XML document into JSON. I'm completely at a loss as to how to hook the two together. Below is the code I'm tinkering with:

```<code>from xml.dom import minidom
from django.utils import simplejson as json

#pseudo code that returns actual xml data as a string from remote server.
result = urlfetch.fetch(url,'','get');

dom = minidom.parseString(result.content)
json = simplejson.load(dom)

self.response.out.write(json)
</code>```

答:
I think the XML format can be so diverse that it's impossible to write a code that could do this without a very strict defined XML format. Here is what I mean:

```<code><persons>
    <person>
        <name>Koen Bok</name>
        <age>26</age>
    </person>
    <person>
        <name>Plutor Heidepeen</name>
        <age>33</age>
    </person>
</persons>
</code>```

Would become

```<code>{'persons': [
    {'name': 'Koen Bok', 'age': 26},
    {'name': 'Plutor Heidepeen', 'age': 33}]
}
</code>```

But what would this be:

```<code><persons>
    <person name="Koen Bok">
        <locations name="defaults">
            <location long=123 lat=384 />
        </locations>
    </person>
</persons>
</code>```

See what I mean?

Edit: just found this article: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html

OwnerDisplayName: Geuis

Title: How to convert XML to JSON in Python?

Body:
Possible Duplicate:

  Converting XML to JSON using Python?

I'm doing some work on App Engine and I need to convert an XML document being retrieved from a remote server into an equivalent JSON object.

I'm using xml.dom.minidom to parse the XML data being returned by urlfetch. I'm also trying to use django.utils.simplejson to convert the parsed XML document into JSON. I'm completely at a loss as to how to hook the two together. Below is the code I'm tinkering with:

from xml.dom import minidom
from django.utils import simplejson as json

#pseudo code that returns actual xml data as a string from remote server.
result = urlfetch.fetch(url,'','get');

dom = minidom.parseString(result.content)
json = simplejson.load(dom)

self.response.out.write(json)

Body:
I think the XML format can be so diverse that it's impossible to write a code that could do this without a very strict defined XML format. Here is what I mean:

<persons>
    <person>
        <name>Koen Bok</name>
        <age>26</age>
    </person>
    <person>
        <name>Plutor Heidepeen</name>
        <age>33</age>
    </person>
</persons>

Would become

{'persons': [
    {'name': 'Koen Bok', 'age': 26},
    {'name': 'Plutor Heidepeen', 'age': 33}]
}

But what would this be:

<persons>
    <person name="Koen Bok">
        <locations name="defaults">
            <location long=123 lat=384 />
        </locations>
    </person>
</persons>

See what I mean?

Edit: just found this article: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html

OwnerDisplayName: Koen Bok

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Koen Bok


问:
Splitting string on commas when data can contain commas
I have a CSV file (which I didn't design and I can't change now nor will I ever be able to change it) that contains lines like the following:

"Surname, Firstname", yes, no, somestring, whatever, etc

As you can see here, the first , is not a comma on which I'd want to split the string. Notice that this particular comma is enclosed within the quotation marks.

Because of this, a simple string.split(',') obviously won't work, as it would give me an array of length 7 for the above string instead of 6.

Is there a way to get around this? I was thinking of using regex to split the string instead but I'm not competent enough in regex to think of a pattern that would only split on commas that are not enclosed inside quotation marks.

I can think of ugly, hacky ways to do it by reading each string char by char but this would have to be a last resort as I'm sure there's a better way to do it!

答: You can handle this easily by using the TextFieldParser class.  Just set HasFieldsEnclosedInQuotes to true.


问:
Use ActiveRecord to count rows where id is matched and another column matches one of two values
I need to create a query in CodeIgniter as follows:

```<code>SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE (
       LOWER(ResponseStatus) = 'submitted'
       OR LOWER(ResponseStatus) = 'inqueue'
      )
      AND `SMSUsageID` = '1'
</code>```

so I created a function in my model as:

```<code>function submittedSMSCount($smsUsageID) {
    $this->db->where('lower(ResponseStatus)', 'submitted');
    $this->db->or_where('lower(ResponseStatus)', 'inqueue');
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}
</code>```

but this function generates a query like:

```<code>SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE LOWER(ResponseStatus) = 'submitted'
      OR LOWER(ResponseStatus) = 'inqueue'
      AND `SMSUsageID` = '1'
</code>```

These two queries generate different results because of the conditions. I need to group the OR conditions to get the correct result. How can I do this with CodeIgniter's Active Record query building methods?

答:
```<code>function submittedSMSCount($smsUsageID) {

$this->db->where(
       "(lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue')",
       NULL,
       FALSE
 );
$this->db->where('SMSUsageID', $smsUsageID);

return $this->db->count_all_results('smslog_tbl');

}
</code>```

$this->db->where() accepts an optional third parameter. If you set
  it to FALSE, CodeIgniter will not try to protect your field or table
  names with backticks.

Ref : https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data

ContentLicense: CC BY-SA 4.0

Body:
I need to create a query in CodeIgniter as follows:

SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE (
       LOWER(ResponseStatus) = 'submitted'
       OR LOWER(ResponseStatus) = 'inqueue'
      )
      AND `SMSUsageID` = '1'

so I created a function in my model as:

function submittedSMSCount($smsUsageID) {
    $this->db->where('lower(ResponseStatus)', 'submitted');
    $this->db->or_where('lower(ResponseStatus)', 'inqueue');
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}

but this function generates a query like:

SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE LOWER(ResponseStatus) = 'submitted'
      OR LOWER(ResponseStatus) = 'inqueue'
      AND `SMSUsageID` = '1'

These two queries generate different results because of the conditions. I need to group the OR conditions to get the correct result. How can I do this with CodeIgniter's Active Record query building methods?

Body:
function submittedSMSCount($smsUsageID) {

$this->db->where(
       "(lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue')",
       NULL,
       FALSE
 );
$this->db->where('SMSUsageID', $smsUsageID);

return $this->db->count_all_results('smslog_tbl');

}

$this->db->where() accepts an optional third parameter. If you set
  it to FALSE, CodeIgniter will not try to protect your field or table
  names with backticks.

Ref : https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-specific-data


问:
Get HTTP Text from JavaScript
How do you get the full HTTP text from JavaScript? I'm talking about the thing that looks like:

```<code>HTTP/1.1 200 OK
Date: Tue, 14 Nov 2017 04:03:27 GMT
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
<html>
    ....
</html>
</code>```

JavaScript provides nice high-level functions for headers, status codes, etc., but something is going wrong with an external server and I need direct access to the text exactly as it's sent over TCP.

Here's the relevant code:

```<code>const xhr = new XMLHttpRequest();
xhr.onload = function () {
    // TODO: get HTTP response text
};
xhr.open('GET', '/');
xhr.send();
</code>```

I'm looking for a programmatic solution; I can't just "look at the dev tools" because I need to parse the full HTTP response text as part of my application.

答:
I don't think this is exact solution you are looking for. But this might help you</p>

```<code>fetch("<your-url>")
.then(function(resp){
    resp.headers.forEach(function(v,h){
        console.log(h,":",v);
    });
    return resp.text();
})
.then(function(text){
    console.log(text);
})
</code>```

Title: Get HTTP Text from JavaScript

Body:
How do you get the full HTTP text from JavaScript? I'm talking about the thing that looks like:

HTTP/1.1 200 OK
Date: Tue, 14 Nov 2017 04:03:27 GMT
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1

    ....

JavaScript provides nice high-level functions for headers, status codes, etc., but something is going wrong with an external server and I need direct access to the text exactly as it's sent over TCP.

Here's the relevant code:

const xhr = new XMLHttpRequest();
xhr.onload = function () {
    // TODO: get HTTP response text
};
xhr.open('GET', '/');
xhr.send();

I'm looking for a programmatic solution; I can't just "look at the dev tools" because I need to parse the full HTTP response text as part of my application.

Body:
I don't think this is exact solution you are looking for. But this might help you

fetch("<your-url>")
.then(function(resp){
    resp.headers.forEach(function(v,h){
        console.log(h,":",v);
    });
    return resp.text();
})
.then(function(text){
    console.log(text);
})


问:
Upload image with HttpClient

Problem

I try to upload an image with angular's HttpClient to API Content-Type: multipart/form-data (angular v4+). Is it supported? How to do it?

The upload works with XMLHttpRequest when using module like ng2-fancy-image-uploader. I would prefer to use a custom method with HttpClient which i could put into a http service together with other methods for accessing API.

Here is what i have tried so far:

model.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ModelService {
  constructor(private http: HttpClient) { }

  public async updateAvatar(file: File): Promise<void> {

    // headers
    const headers = new HttpHeaders()
      .append('Content-Type', 'multipart/form-data');

    const formData: FormData = new FormData();
    formData.append('avatar', file, file.name);

    const response: HttpResponse = await this.http
      .patch('https://example.com/avatar', formData, { headers, observe: 'response' })
      .toPromise();

    console.log(response.status);
  }
}
```

<h2>avatar-uploader.component.ts</h2>

<pre class="lang-ts prettyprint-override"><code>import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ModelService } from './path/to/model.service';

@Component({
  selector: 'app-avatar-uploader',
  template: '<input type="file" #fileInput (changes)="uploadAvatar()">'
})
export class AvatarUploaderComponent implements OnInit {

  @ViewChild('fileInput') fileInputElement: ElementRef;

  constructor() { }

  ngOnInit() { }

  public async uploadAvatar() {
    const file: File = this.fileInputElement.nativeElement.files[0];

    await this.model.updateAvatar(file);
  }

}
</code>```

This version sends a request to (express) API, but multer (a library for parsing multipart/form-data requests) fails to parse the request.

So i guess i either use the HttpClient incorrectly, or it doesn't support multipart/form-data requests.

I guess one could send base64 encoded file or use XmlHttpRequest, but i ask specifically about HttpClient's ability to do it.

答:
For me the trick was not to set the content-type to multipart/form-data. But that was done automatically for me.

```<code><label>
  <input type="file" (change)="setFiles($event)" style="display:none" multiple/>
  <a mat-raised-button color="primary">
    <mat-icon>file_upload</mat-icon>
    Select Documents
  </a>
</label>
</code>```

Here's my code that uploads multipart/form-data. No need to set the headers.

```<code>private setFile(event) {
    let files = event.srcElement.files
    if (!files) {
      return
    }

    let path = `${environment.celoApiEndpoint}/api/patientFiles`
    let data = {"patientData": {
      "uid": "",
      "firstName": "",
      "lastName": "",
      "gender": "Not Specified",
      "dateOfBirth": ""
    }}
    // let headers = new HttpHeaders()
    //   .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW')
    // let headers = new HttpHeaders().set('content-type', 'multipart/form-data')
    const formData: FormData = new FormData();

    for (let i = 0; i < files.length; i++) {
      formData.append(i.toString(), files[i], files[i].name);
    }
    formData.append("data", JSON.stringify(data));
    this.http.post(path, formData).subscribe(
      (r)=>{console.log('got r', r)}
    )
  }
</code>```

Title: Upload image with HttpClient

Body:
Problem

I try to upload an image with angular's HttpClient to API Content-Type: multipart/form-data (angular v4+). Is it supported? How to do it?

The upload works with XMLHttpRequest when using module like ng2-fancy-image-uploader. I would prefer to use a custom method with HttpClient which i could put into a http service together with other methods for accessing API.

Here is what i have tried so far:

model.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class ModelService {
  constructor(private http: HttpClient) { }

  public async updateAvatar(file: File): Promise<void> {

    // headers
    const headers = new HttpHeaders()
      .append('Content-Type', 'multipart/form-data');

    const formData: FormData = new FormData();
    formData.append('avatar', file, file.name);

    const response: HttpResponse = await this.http
      .patch('https://example.com/avatar', formData, { headers, observe: 'response' })
      .toPromise();

    console.log(response.status);
  }
}

avatar-uploader.component.ts

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ModelService } from './path/to/model.service';

@Component({
  selector: 'app-avatar-uploader',
  template: '<input type="file" #fileInput (changes)="uploadAvatar()">'
})
export class AvatarUploaderComponent implements OnInit {

  @ViewChild('fileInput') fileInputElement: ElementRef;

  constructor() { }

  ngOnInit() { }

  public async uploadAvatar() {
    const file: File = this.fileInputElement.nativeElement.files[0];

    await this.model.updateAvatar(file);
  }

}

This version sends a request to (express) API, but multer (a library for parsing multipart/form-data requests) fails to parse the request.

So i guess i either use the HttpClient incorrectly, or it doesn't support multipart/form-data requests.

I guess one could send base64 encoded file or use XmlHttpRequest, but i ask specifically about HttpClient's ability to do it.

Body:
For me the trick was not to set the content-type to multipart/form-data. But that was done automatically for me.

<label>
  <input type="file" (change)="setFiles($event)" style="display:none" multiple/>
  <a mat-raised-button color="primary">
    <mat-icon>file_upload</mat-icon>
    Select Documents
  </a>
</label>

Here's my code that uploads multipart/form-data. No need to set the headers.

private setFile(event) {
    let files = event.srcElement.files
    if (!files) {
      return
    }

    let path = `${environment.celoApiEndpoint}/api/patientFiles`
    let data = {"patientData": {
      "uid": "",
      "firstName": "",
      "lastName": "",
      "gender": "Not Specified",
      "dateOfBirth": ""
    }}
    // let headers = new HttpHeaders()
    //   .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW')
    // let headers = new HttpHeaders().set('content-type', 'multipart/form-data')
    const formData: FormData = new FormData();

    for (let i = 0; i < files.length; i++) {
      formData.append(i.toString(), files[i], files[i].name);
    }
    formData.append("data", JSON.stringify(data));
    this.http.post(path, formData).subscribe(
      (r)=>{console.log('got r', r)}
    )
  }


问:
Is there a way to avoid calling a function multiple times in an 'elsif' branch?
I have a function that returns either nil or a non-nil value, and I use it in the following if-else clause:

```<code>if condition_that_doesnt_involve_my_func
  # do stuff
elsif my_func(cur_line)
  headers_found = my_func(cur_line)
end
</code>```

I feel the above block is slightly wasteful because it calls the function twice and it could just save the result once and then use it in the following clause if the branch evaluates to non-nil.

Is there a way to rewrite this so that I only invoke the function once?

答:
If you are worry about it assign the return value to headers_found. It will ended up being false (headers_found.present? #false) or containing the headers.

```<code>if condition_that_doesnt_involve_my_func
  # do stuff
else
  headers_found = my_func(cur_line)
end
</code>```

Body:
I have a function that returns either nil or a non-nil value, and I use it in the following if-else clause:

if condition_that_doesnt_involve_my_func
  # do stuff
elsif my_func(cur_line)
  headers_found = my_func(cur_line)
end

I feel the above block is slightly wasteful because it calls the function twice and it could just save the result once and then use it in the following clause if the branch evaluates to non-nil.

Is there a way to rewrite this so that I only invoke the function once?

Body:
If you are worry about it assign the return value to headers_found. It will ended up being false (headers_found.present? #false) or containing the headers.

if condition_that_doesnt_involve_my_func
  # do stuff
else
  headers_found = my_func(cur_line)
end


答:
I would suggest using a CSV parser library - there are other cases that you wouldn't have thought of (new line as part of a quoted field).

The VisualBasic namespace has a nice library that can help - the TextFieldParser.

Title: Splitting string on commas when data can contain commas

Body:
I have a CSV file (which I didn't design and I can't change now nor will I ever be able to change it) that contains lines like the following:

"Surname, Firstname", yes, no, somestring, whatever, etc

As you can see here, the first , is not a comma on which I'd want to split the string. Notice that this particular comma is enclosed within the quotation marks.

Because of this, a simple string.split(',') obviously won't work, as it would give me an array of length 7 for the above string instead of 6.

Is there a way to get around this? I was thinking of using regex to split the string instead but I'm not competent enough in regex to think of a pattern that would only split on commas that are not enclosed inside quotation marks.

I can think of ugly, hacky ways to do it by reading each string char by char but this would have to be a last resort as I'm sure there's a better way to do it!


问:
Tooltip cutoff at the edge of the containing element
I have the following html:

```<code><div class="container">
  <span class="word-container" >
    <span tooltip-def="To sign or give formal approval to.">
      <span class="define-word highlight-word">ratifying</span>
    </span>
  </span>
</div>
</code>```

CSS:

```<code>.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}
</code>```

The tooltip is cut off on the left side. I tried overflow: visible and higher z-index on .word-container [tooltip-def]:after, but none of the working.

Here is the jsfiddle demo: https://jsfiddle.net/mddc/5dtwr6zc/10/

How can I make minimal CSS changes to make the tooltip visible? Move to the right side when the left side touches the browser edge?

答:
you are going great you only need to change the css. below is the css code apply and check.  </p>

```<code>.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 10%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 20%;
  position: relative;
  transform: translateX(-50%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}
</code>```

Body:
I have the following html:

      ratifying

CSS:

.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 50%;
  position: absolute;
  transform: translateX(-50%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}

The tooltip is cut off on the left side. I tried overflow: visible and higher z-index on .word-container [tooltip-def]:after, but none of the working.

Here is the jsfiddle demo: https://jsfiddle.net/mddc/5dtwr6zc/10/

How can I make minimal CSS changes to make the tooltip visible? Move to the right side when the left side touches the browser edge?

Body:
you are going great you only need to change the css. below is the css code apply and check.

.container {
  margin-top: 100px;
}
.word-container [tooltip-def] {
  display: inline-block;
  position: relative;
}
.word-container [tooltip-def]:before {
  left: 10%;
  position: absolute;
  transform: translateX(-50%);
  border-color: #323232 transparent transparent transparent;
  border-style: solid;
  border-width: 4px 6px 0 6px;
  content: "";
  display: none;
  top: -6px;
  z-index: 99;
}
.word-container [tooltip-def]:after {
  left: 20%;
  position: relative;
  transform: translateX(-50%);
  content: attr(tooltip-def);
  background: #323232;
  border-radius: 5px;
  color: #fff;
  display: none;
  font-family: open sans;
  font-size: 12px;
  height: auto;
  min-width: 250px;
  padding: 5px;
  text-align: center;
  top: -6px;
  transform: translateX(-50%) translateY(-100%);
  width: auto;
  z-index: 99;
}
.word-container [tooltip-def]:hover:after,
.word-container [tooltip-def]:hover:before {
  display: inline-block;
}


问:
Selenium fails to start Chromedriver in CentOS
I try to start Chromedriver with Selenium

```<code>from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.google.com/")
print(driver.title)
</code>```

and error msg below:

```<code>raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
 (Driver info: chromedriver=2.33.506092,platform=Linux 3.10.0-693.5.2.el7.x86_64 x86_64)
</code>```

I am using these:

```<code>[root@jdu4e00u53f7 workspace]# ll /usr/local/bin/chromedriver
lrwxrwxrwx 1 root root 17 11月 14 00:31 /usr/local/bin/chromedriver -> /opt/chromedriver
</code>```

CentOS 7.3

Python(3.6.2)

selenium (3.7.0)

Google Chrome (62.0.3202.89)

chromedriver(2.9）/ I changed to chromedriver=2.33.506092

Xvfb

ps, I also tried

driver = webdriver.Chrome('/usr/local/bin/chromedriver'),it not work...

test.py
output

ref :Selenium fails to start Chromedriver

On my server start Xvfb in the background:
Xvfb :0 -ac -screen 0 1024x768x24 &
and also not work

ref:unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

答:
It is much evident from your mentioned configuration that you are using Selenium v3.7.0, Google Chrome 62.0 along with chromedriver v2.9 which is not compatible. Hence we are seeing the error WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally

The Release Notes of ChromeDriver v2.33 clearly mentions Supports Chrome v60-62

Solution:

Download the latest chromedriver v2.33 from this link and execute your testcase.

Update :

Try the following code block :

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()
</code>```

OR

```<code>from selenium import webdriver
driver = webdriver.Chrome(executable_path='/opt/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()
</code>```

Body:
I try to start Chromedriver with Selenium

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.google.com/")
print(driver.title)

and error msg below:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
 (Driver info: chromedriver=2.33.506092,platform=Linux 3.10.0-693.5.2.el7.x86_64 x86_64)

I am using these:

[root@jdu4e00u53f7 workspace]# ll /usr/local/bin/chromedriver
lrwxrwxrwx 1 root root 17 11月 14 00:31 /usr/local/bin/chromedriver -> /opt/chromedriver

CentOS 7.3

Python(3.6.2)

selenium (3.7.0)

Google Chrome (62.0.3202.89)

chromedriver(2.9）/ I changed to chromedriver=2.33.506092

Xvfb

ps, I also tried

driver = webdriver.Chrome('/usr/local/bin/chromedriver'),it not work...

test.py
output

ref :Selenium fails to start Chromedriver

On my server start Xvfb in the background:
Xvfb :0 -ac -screen 0 1024x768x24 &
and also not work

ref:unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

Body:
It is much evident from your mentioned configuration that you are using Selenium v3.7.0, Google Chrome 62.0 along with chromedriver v2.9 which is not compatible. Hence we are seeing the error WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally

The Release Notes of ChromeDriver v2.33 clearly mentions Supports Chrome v60-62

Solution:

Download the latest chromedriver v2.33 from this link and execute your testcase.

Update :

Try the following code block :

from selenium import webdriver
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()

OR

from selenium import webdriver
driver = webdriver.Chrome(executable_path='/opt/chromedriver')
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()


问:
Array/Results Code not working
Good afternoon! I have 5 job titles in an array (mechanic, cleaner, driver, cashier, electrician). I'm also looking to have an input box and a submit button. I want to be able to put a number (let's say 3) and have the JS print out jobs 1,2 and 3, in this case it would print out mechanic, cleaner and driver. I'm a little confused on what to do. I'd appreciate some help.</p>

答:
The Javascript for your program would be as below:</p>

```<code><html>
<head>
<title>Find the profession</title>
</head>
<body>
<p id="txt">Output will appear here.</p>
    Enter your number:<input type="number" id="number">
    <button type="submit" id="button1" onclick="load()">Submit</button>
<script>
function load()
    {
var prof = ["mechanic", "cleaner", "driver", "cashier", "electrician"];
        var number=document.getElementById("number");
        var text="The answer is: ";
        document.getElementById("txt").innerHTML=number.value;
        if(number.value<=5)
            {
                for(i=0;i<=number.value-1;i++)
                    {
                        text=text+prof[i]+" ";

                    }
                document.getElementById("txt").innerHTML=text;
            }
    }
</script>
</body>
</html>
</code>```

Title: Array/Results Code not working

Body:
The Javascript for your program would be as below:

<html>
<head>
<title>Find the profession</title>
</head>
<body>
<p id="txt">Output will appear here.</p>
    Enter your number:<input type="number" id="number">
    <button type="submit" id="button1" onclick="load()">Submit</button>
<script>
function load()
    {
var prof = ["mechanic", "cleaner", "driver", "cashier", "electrician"];
        var number=document.getElementById("number");
        var text="The answer is: ";
        document.getElementById("txt").innerHTML=number.value;
        if(number.value<=5)
            {
                for(i=0;i<=number.value-1;i++)
                    {
                        text=text+prof[i]+" ";

                    }
                document.getElementById("txt").innerHTML=text;
            }
    }
</script>
</body>
</html>


问:
How to get dropdown value as a textbox name?
https://jsfiddle.net/t12x9boj/

```<code><select id="drop" name="1" class="form-control">
  <option value="policy_no">Policy No</option>
  <option value="claim_no">Claim No</option>
  <option value="acc_no">Account No</option>
  <option value="client_no">Client No</option>
</select>

<input type="text" name="selectValue">
</code>```

for example, if user selected Policy No from dropdown, the code textbox code statement become <input type="text" name="policy_no">

or if user select Claim No then <input type="text" name="claim_no">

SOLUTIONS
by @NewToJS

```<code><select id="drop" name="1" class="form-control" onchange="setname(this.value)">
<option value="policy_no">Policy No</option>
<option value="claim_no">Claim No</option>
<option value="acc_no">Account No</option>
<option value="client_no">Client No</option>
</select>
<input id="dropvalue" type="text" name="selectValue" onclick="this.value='';alert(this.name);">

function setname(e){
var input=document.getElementById('dropvalue');
input.name=e;
input.value="Click Me!";
}
</code>```

SOLUTIONS by @Milan Chheda

```<code>$("#drop").on('change', function() {
  $("#inputId").prop('name', $(this).val());
  //2nd method
  //$("#inputId").attr('name', $(this).val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="drop" name="1" class="form-control">
  <option value="policy_no">Policy No</option>
  <option value="claim_no">Claim No</option>
  <option value="acc_no">Account No</option>
  <option value="client_no">Client No</option>
</select>

<input type="text" name="selectValue" id='inputId'>
</code>```

答:
Use Jquery prop to achieve this. You need to inspect and check the name attribute of input while changing the dropdown options:

$("#drop").on('change', function() {
  $("#inputId").prop('name', $(this).val());
  //2nd method
  //$("#inputId").attr('name', $(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="drop" name="1" class="form-control">
  <option value="policy_no">Policy No</option>
  <option value="claim_no">Claim No</option>
  <option value="acc_no">Account No</option>
  <option value="client_no">Client No</option>
</select>

<input type="text" name="selectValue" id='inputId'></code>```

Body:
https://jsfiddle.net/t12x9boj/

<select id="drop" name="1" class="form-control">
  <option value="policy_no">Policy No</option>
  <option value="claim_no">Claim No</option>
  <option value="acc_no">Account No</option>
  <option value="client_no">Client No</option>
</select>

<input type="text" name="selectValue">

for example, if user selected Policy No from dropdown, the code textbox code statement become <input type="text" name="policy_no">

or if user select Claim No then <input type="text" name="claim_no">

SOLUTIONS
by @NewToJS

<select id="drop" name="1" class="form-control" onchange="setname(this.value)">
<option value="policy_no">Policy No</option>
<option value="claim_no">Claim No</option>
<option value="acc_no">Account No</option>
<option value="client_no">Client No</option>
</select>
<input id="dropvalue" type="text" name="selectValue" onclick="this.value='';alert(this.name);">

function setname(e){
var input=document.getElementById('dropvalue');
input.name=e;
input.value="Click Me!";
}

SOLUTIONS by @Milan Chheda

$("#drop").on('change', function() {
  $("#inputId").prop('name', $(this).val());
  //2nd method
  //$("#inputId").attr('name', $(this).val());
});

<select id="drop" name="1" class="form-control">
  <option value="policy_no">Policy No</option>
  <option value="claim_no">Claim No</option>
  <option value="acc_no">Account No</option>
  <option value="client_no">Client No</option>
</select>

<input type="text" name="selectValue" id='inputId'>

Body:
Use Jquery prop to achieve this. You need to inspect and check the name attribute of input while changing the dropdown options:

$("#drop").on('change', function() {
  $("#inputId").prop('name', $(this).val());
  //2nd method
  //$("#inputId").attr('name', $(this).val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="drop" name="1" class="form-control">
  <option value="policy_no">Policy No</option>
  <option value="claim_no">Claim No</option>
  <option value="acc_no">Account No</option>
  <option value="client_no">Client No</option>
</select>

<input type="text" name="selectValue" id='inputId'>


问:
Forming linq query to get table data using table name
I have a table name stored in a string.
I want to be able to do something like this:

```<code>string tableName = "sometable";

var query = from m in _Context[tableName]
            select m;
</code>```

I am trawling the internet as I type this...

Any help appreciated.

答:
You can use Reflection on entities to get the required table DbSet and then run LINQ query on it

```<code>var data = entity.GetType().GetProperty(tableName).GetValue(entity, null);
var query = from m in data
            select m;
</code>```

But anyways you will get it as type of object which will not give access to properties unless you cast it correctly.

Body:
I have a table name stored in a string.
I want to be able to do something like this:

string tableName = "sometable";

var query = from m in _Context[tableName]
            select m;

I am trawling the internet as I type this...

Any help appreciated.

Body:
You can use Reflection on entities to get the required table DbSet and then run LINQ query on it

var data = entity.GetType().GetProperty(tableName).GetValue(entity, null);
var query = from m in data
            select m;

But anyways you will get it as type of object which will not give access to properties unless you cast it correctly.


问:
How to display the dropdown & checkbox selected value in redirected page for confirmation IN PHP?
```<code><form action="action.php" method="POST"  target="_self">
<table class="main"  border="1"  height="100%" align="center">
<h3>
<p id="id1" style="background-color: #9FF" >Registration form</p></h3>

 <tr><td> First Name:<span style="color:red">*</span> </td>
<td> <input type="text"  name="fname" value="" placeholder="firstname"    required="required" maxlength="25"></td></tr>
 <tr><td> SurName:<span style="color:red">*</span></td>
 <td><input type="text"  name="sname" value=""  placeholder="lastname" required="required" maxlength="20"/> </td></tr>
 <tr><td>Age:<span style="color:red">*</span></td>
 <td> <input type="text" name="age" value="" required/></td></tr>
 <tr><td>Date of Birth:<span style="color:red">*</span></td>
 <td><input type="date" name="DOB" value="" required/></td></tr>
 <tr><td> Gender:<span style="color:red">*</span></td>
  <td><input type="radio" name="gender" value="male" required/>Male
   <input type="radio" name="gender" value="Female" />Female</td></tr>
  <tr><td>Qualification:<span style="color:red">*</span></td>
   <td> <select name="study" required>
   <option value="">---Select---</option>
  <option value="btech">B.Tech</option>
  <option value="BSc">BSc</option>
  <option value="BCom">BCom</option>
 </select></td></tr>
  <tr><td> State:<span style="color:red">*</span></td>
<td><Select name="state" required >
<option value="">---Select---</option>
<option valuie="AndhraPradesh">AndhraPradesh</option>
<option value="Telangana">Telangana</option>
<option value="Tamilnadu">Tamilnadu</option>
<option value="Kerala">Kerala</option>
<option vgalue="Maharastra">Maharastra</option>
</Select></td></tr>

<tr><td>Profile:<span style="color:red">*</span></td><td><input type="checkbox" name="profile" value="Java" />Java
                            <input type="checkbox" name="profile" value="PHP" />PHP
                            <input type="checkbox" name="profile" val

    ue="Android" />Android</td> </tr>
    <tr><td> Address for Communication:</td><td><textarea name="adr" rows="5" cols="30" ></textarea></td></tr>
            <tr><td colspan="2" align="center"><input type="submit" value="submit" /></td></tr>
    </table></form>
</code>```

** this is my register form and now i want to display all the selected values in next page i.e in action.php and its code is as follows********

```<code>    <form action="store.php" method="post" align="center" target="_self">
    <label>Name of the person:</label>
   <input type="hidden" name="person" value="<?= $_POST['fname'];?>"></input><?=$_POST['fname'];?>  <br />
    <label>Name of the Surname:</label>
    <input type="hidden" name="surname" value="<?= $_POST['sname'];?>"></input><?=$_POST['sname'];?>  <br />
    <label>His Age:</label>
     <input type="hidden" name="age" value="<?= $_POST['age'];?>"></input><?=$_POST['age'];?> <br />
     <label>Date of Birth:</label>
     <input type="hidden" name="dob" value="<$_POST['DOB'];?>"></input><?=$_POST['DOB'];?>  <br />
      <label>Gender:</label>
     <input type="hidden" name="gender" value="<?= $_POST['gender'];?>"></input><?=$_POST['gender'];?> <br />
      <label>Education:</label>
     <input type="hidden" name="edu" value="<?php if(isset($_POST['submit']))echo $_POST['study']?>"></input><?php if(isset($_POST['submit'])) echo $_POST['study']?>;?>
      <br />
      <label>State:</label>
      <input type="hidden" name="state" value="<?if(isset($_POST['submit']))echo $_POST['state']?>"></input><?php if(isset($_POST['submit'])) echo $_POST['state']?>;?>
      <br />
      <label>Good At:</label>
     <input type="hidden" name="profile" value="<?= $_POST['profile'];?>"></input><?=$_POST['profile'];?>  <br />
      <label>Address:</label>
      <input type="hidden" name="adr" value="<?= $_POST['adr'];?>"></input><?=$_POST['adr'];?>  <br /><br /><br />
      <input type="submit" value="confirm" name="submit"></input>
</code>```

****the dropdown is not displaying and also please suggest if after click on confirm then the values that are confirmed has to be stored in database.For that shall I get the values from names of input hidden fields in action.php or  registration input field names?

答:
I have changed a bit of the code... You had some minor syntax mistakes... </p>

```<code> <form action="store.php" method="post" align="center" target="_self">
    <label>Name of the person:</label>
   <input type="hidden" name="person" value="<?= $_POST['fname'];?>"></input><?=$_POST['fname'];?>  <br />
    <label>Name of the Surname:</label>
    <input type="hidden" name="surname" value="<?= $_POST['sname'];?>"></input><?=$_POST['sname'];?>  <br />
    <label>His Age:</label>
     <input type="hidden" name="age" value="<?= $_POST['age'];?>"></input><?=$_POST['age'];?> <br />
     <label>Date of Birth:</label>
     <input type="hidden" name="dob" value="<$_POST['DOB'];?>"></input><?=$_POST['DOB'];?>  <br />
      <label>Gender:</label>
     <input type="hidden" name="gender" value="<?= $_POST['gender'];?>"></input><?=$_POST['gender'];?> <br />
      <label>Education:</label>
     <input type="hidden" name="edu" value="<?php echo $_POST['study']; ?>"></input><?php echo $_POST['study'];?>
      <br />
      <label>State:</label>
      <input type="hidden" name="state" value="<?php echo $_POST['state'];?>"></input><?php  echo $_POST['state'];?>
      <br />
      <label>Good At:</label>
     <input type="hidden" name="profile" value="<?= $_POST['profile'];?>"></input><?=$_POST['profile'];?>  <br />
      <label>Address:</label>
      <input type="hidden" name="adr" value="<?= $_POST['adr'];?>"></input><?=$_POST['adr'];?>  <br /><br /><br />
      <input type="submit" value="confirm" name="submit"></input>
</code>```

Body:
<form action="action.php" method="POST"  target="_self">

Registration form

 First Name:*
 <input type="text"  name="fname" value="" placeholder="firstname"    required="required" maxlength="25">

 SurName:*
 <input type="text"  name="sname" value=""  placeholder="lastname" required="required" maxlength="20"/>

Age:*
  <input type="text" name="age" value="" required/>

Date of Birth:*
 <input type="date" name="DOB" value="" required/>

 Gender:*
  <input type="radio" name="gender" value="male" required/>Male
   <input type="radio" name="gender" value="Female" />Female

Qualification:*
    <select name="study" required>
   <option value="">---Select---</option>
  <option value="btech">B.Tech</option>
  <option value="BSc">BSc</option>
  <option value="BCom">BCom</option>
 </select>

 State:*
<Select name="state" required >
<option value="">---Select---</option>
<option valuie="AndhraPradesh">AndhraPradesh</option>
<option value="Telangana">Telangana</option>
<option value="Tamilnadu">Tamilnadu</option>
<option value="Kerala">Kerala</option>
<option vgalue="Maharastra">Maharastra</option>
</Select>

Profile:*	<input type="checkbox" name="profile" value="Java" />Java
                            <input type="checkbox" name="profile" value="PHP" />PHP
                            <input type="checkbox" name="profile" val

    ue="Android" />Android

 Address for Communication:	<textarea name="adr" rows="5" cols="30" ></textarea>

<input type="submit" value="submit" />

</form>

** this is my register form and now i want to display all the selected values in next page i.e in action.php and its code is as follows********

    <form action="store.php" method="post" align="center" target="_self">
    Name of the person:
   <input type="hidden" name="person" value="<?= $_POST['fname'];?>"></input><?=$_POST['fname'];?>

    Name of the Surname:
    <input type="hidden" name="surname" value="<?= $_POST['sname'];?>"></input><?=$_POST['sname'];?>

    His Age:
     <input type="hidden" name="age" value="<?= $_POST['age'];?>"></input><?=$_POST['age'];?>

     Date of Birth:
     <input type="hidden" name="dob" value="<$_POST['DOB'];?>"></input><?=$_POST['DOB'];?>

      Gender:
     <input type="hidden" name="gender" value="<?= $_POST['gender'];?>"></input><?=$_POST['gender'];?>

      Education:
     <input type="hidden" name="edu" value="<?php if(isset($_POST['submit']))echo $_POST['study']?>"></input><?php if(isset($_POST['submit'])) echo $_POST['study']?>;?>

      State:
      <input type="hidden" name="state" value="<?if(isset($_POST['submit']))echo $_POST['state']?>"></input><?php if(isset($_POST['submit'])) echo $_POST['state']?>;?>

      Good At:
     <input type="hidden" name="profile" value="<?= $_POST['profile'];?>"></input><?=$_POST['profile'];?>

      Address:
      <input type="hidden" name="adr" value="<?= $_POST['adr'];?>"></input><?=$_POST['adr'];?>

      <input type="submit" value="confirm" name="submit"></input>

****the dropdown is not displaying and also please suggest if after click on confirm then the values that are confirmed has to be stored in database.For that shall I get the values from names of input hidden fields in action.php or  registration input field names?

Body:
I have changed a bit of the code... You had some minor syntax mistakes...

 <form action="store.php" method="post" align="center" target="_self">
    <label>Name of the person:</label>
   <input type="hidden" name="person" value="<?= $_POST['fname'];?>"></input><?=$_POST['fname'];?>  <br />
    <label>Name of the Surname:</label>
    <input type="hidden" name="surname" value="<?= $_POST['sname'];?>"></input><?=$_POST['sname'];?>  <br />
    <label>His Age:</label>
     <input type="hidden" name="age" value="<?= $_POST['age'];?>"></input><?=$_POST['age'];?> <br />
     <label>Date of Birth:</label>
     <input type="hidden" name="dob" value="<$_POST['DOB'];?>"></input><?=$_POST['DOB'];?>  <br />
      <label>Gender:</label>
     <input type="hidden" name="gender" value="<?= $_POST['gender'];?>"></input><?=$_POST['gender'];?> <br />
      <label>Education:</label>
     <input type="hidden" name="edu" value="<?php echo $_POST['study']; ?>"></input><?php echo $_POST['study'];?>
      <br />
      <label>State:</label>
      <input type="hidden" name="state" value="<?php echo $_POST['state'];?>"></input><?php  echo $_POST['state'];?>
      <br />
      <label>Good At:</label>
     <input type="hidden" name="profile" value="<?= $_POST['profile'];?>"></input><?=$_POST['profile'];?>  <br />
      <label>Address:</label>
      <input type="hidden" name="adr" value="<?= $_POST['adr'];?>"></input><?=$_POST['adr'];?>  <br /><br /><br />
      <input type="submit" value="confirm" name="submit"></input>


问:
Return object from list while looping java 8
Is there some straight forward way to return object from list which map to condition we passed.

Ex :

```<code>public enum CarType {
    TOYOTA,
    NISSAN,
    UNKNOWN;

    public static CarType getByName(String name) {
        for (CarType carType : values()) {
            if (carType.name().equals(name)) {
                return carType;
            }
        }
        return UNKNOWN;
    }
}
</code>```

Is there some another way support by java 8 below method and for loop I have used.

```<code>public static CarType getByName(String name) {
    for (CarType carType : values()) {
        if (carType.name().equals(name)) {
            return carType;
        }
    }
    return UNKNOWN;
}
</code>```

答:
another option</p>

```<code>enum CarType {
    TOYOTA, NISSAN, UNKNOWN;

    public static CarType getByName(String name) {
        return Stream.of(CarType.values())
          .filter(x -> x.name().equals(name))
          .findFirst()
          .orElse(UNKNOWN);
    }
}
</code>```

Body:
Is there some straight forward way to return object from list which map to condition we passed.

Ex :

public enum CarType {
    TOYOTA,
    NISSAN,
    UNKNOWN;

    public static CarType getByName(String name) {
        for (CarType carType : values()) {
            if (carType.name().equals(name)) {
                return carType;
            }
        }
        return UNKNOWN;
    }
}

Is there some another way support by java 8 below method and for loop I have used.

public static CarType getByName(String name) {
    for (CarType carType : values()) {
        if (carType.name().equals(name)) {
            return carType;
        }
    }
    return UNKNOWN;
}

Body:
another option

enum CarType {
    TOYOTA, NISSAN, UNKNOWN;

    public static CarType getByName(String name) {
        return Stream.of(CarType.values())
          .filter(x -> x.name().equals(name))
          .findFirst()
          .orElse(UNKNOWN);
    }
}


问:
Ice Chat Application
I'm ICE starter. At http://zeroc.com there is good tutorial on how to create chat. I decided to use the tutorial as base. And first thing I tried to do was writing ChatRoom class in c# instead of given c++ implementation. I tried to do the same in my c# code. ChatRoom implementation in c++:

```<code>// C++
class ChatRoomCallbackAdapter { /* ... */ };
typedef IceUtil::Handle<ChatRoomCallbackAdapter> ChatRoomCallbackAdapterPtr;
class ChatRoom : public IceUtil::Shared
{
public:
    ChatRoom(bool trace, const Ice::LoggerPtr& logger);
    void reserve(const std::string&);
    void unreserve(const std::string&);
    void join(const std::string&, const ChatRoomCallbackAdapterPtr&);
    void leave(const std::string&);
    Ice::Long send(const std::string&, const std::string&);
private:
    typedef std::map<std::string, ChatRoomCallbackAdapterPtr> ChatRoomCallbackMap;
    ChatRoomCallbackMap _members;
    std::set<std::string> _reserved;
    IceUtil::Mutex _mutex;
    const bool _trace;
    const Ice::LoggerPtr _logger;
};
</code>```

Some piece of class-members implementation:

```<code>// ...
void ChatRoom::reserve(const string& name)
{
    IceUtil::Mutex::Lock sync(_mutex);
    if(_reserved.find(name) != _reserved.end() ||
       _members.find(name) != _members.end())
    {
        throw string("The name " + name + " is already in use.");
    }
    _reserved.insert(name);
}
// ...
</code>```

I was writng next:

```<code>public class ChatRoom : IceUtil
</code>```

when I encountered an error. I found that IceUtil dll in distribution package isn't COM-visible therefore I can't use it in my c# project.

What can I use instead of c++

```<code>IceUtil::Handle<T>
</code>```

as far as I understand it is a smart pointer.
How can I implement server like the one's given in c#?

Would it be the same in c# (talking about mutexes) comparing to above c++ class:

```<code>public class ChatRoom
{
    // ...
    void Reserve(System.String Name)
    {
        lock(this)
        {
            // operations
        }
    }
}
</code>```

?

Thanks!

答: C++ does not support reference counted pointers out of the box, that is why C++ API has IceUtil::Handle<> template. C# obviously does not need it. I'd recommend you start learning Ice for C# using C# examples rather than C++. You can find a lot of C# client/server examples in democs folder of demos packages. And, of course, Ice has absolutely nothing to do with COM technology, except that it is kind of a replacement.

Title: Ice Chat Application

Body:
I'm ICE starter. At http://zeroc.com there is good tutorial on how to create chat. I decided to use the tutorial as base. And first thing I tried to do was writing ChatRoom class in c# instead of given c++ implementation. I tried to do the same in my c# code. ChatRoom implementation in c++:

// C++
class ChatRoomCallbackAdapter { /* ... */ };
typedef IceUtil::Handle<ChatRoomCallbackAdapter> ChatRoomCallbackAdapterPtr;
class ChatRoom : public IceUtil::Shared
{
public:
    ChatRoom(bool trace, const Ice::LoggerPtr& logger);
    void reserve(const std::string&);
    void unreserve(const std::string&);
    void join(const std::string&, const ChatRoomCallbackAdapterPtr&);
    void leave(const std::string&);
    Ice::Long send(const std::string&, const std::string&);
private:
    typedef std::map<std::string, ChatRoomCallbackAdapterPtr> ChatRoomCallbackMap;
    ChatRoomCallbackMap _members;
    std::set<std::string> _reserved;
    IceUtil::Mutex _mutex;
    const bool _trace;
    const Ice::LoggerPtr _logger;
};

Some piece of class-members implementation:

// ...
void ChatRoom::reserve(const string& name)
{
    IceUtil::Mutex::Lock sync(_mutex);
    if(_reserved.find(name) != _reserved.end() ||
       _members.find(name) != _members.end())
    {
        throw string("The name " + name + " is already in use.");
    }
    _reserved.insert(name);
}
// ...

I was writng next:

public class ChatRoom : IceUtil

when I encountered an error. I found that IceUtil dll in distribution package isn't COM-visible therefore I can't use it in my c# project.

What can I use instead of c++

IceUtil::Handle<T>

as far as I understand it is a smart pointer.
How can I implement server like the one's given in c#?

Would it be the same in c# (talking about mutexes) comparing to above c++ class:

public class ChatRoom
{
    // ...
    void Reserve(System.String Name)
    {
        lock(this)
        {
            // operations
        }
    }
}

?

Thanks!


问:
How do I reverse each word in a sentence string like "I love computer science" using c++
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

```<code>#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}
</code>```

答:
You can directly use std::reverse

```<code>#include <iostream>
#include <string>
#include <sstream>
#include<algorithm>
using namespace std;

int main()
{
    // Vars
    string sentence;

    // Input
    cout << "Welcome to Reverse-the-words" << endl;
    cout << "Enter your sentence, word, or phrase" << endl;
    getline(cin, sentence);

    istringstream iss(sentence);
    string word;
    cout << "Your phrase with all of the words reversed is " << endl;
    while (iss >> word) {
        std::reverse(word.begin(), word.end());
        cout<<word.c_str()<<" ";
    }
    return 0;
}
</code>```

output

```<code>Welcome to Reverse-the-words
Enter your sentence, word, or phrase
I love science
Your phrase with all of the words reversed is
I evol ecneics
</code>```

Body:
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}

Body:
You can directly use std::reverse

#include <iostream>
#include <string>
#include <sstream>
#include<algorithm>
using namespace std;

int main()
{
    // Vars
    string sentence;

    // Input
    cout << "Welcome to Reverse-the-words" << endl;
    cout << "Enter your sentence, word, or phrase" << endl;
    getline(cin, sentence);

    istringstream iss(sentence);
    string word;
    cout << "Your phrase with all of the words reversed is " << endl;
    while (iss >> word) {
        std::reverse(word.begin(), word.end());
        cout<<word.c_str()<<" ";
    }
    return 0;
}

output

Welcome to Reverse-the-words
Enter your sentence, word, or phrase
I love science
Your phrase with all of the words reversed is
I evol ecneics


问:
Way to go from recursion to iteration
I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems.

So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help.

Are there general rules?

Is there a "pattern"?

答: There is a general way of converting recursive traversal to iterator by using a lazy iterator which concatenates multiple iterator suppliers (lambda expression which returns an iterator). See my Converting Recursive Traversal to Iterator.</p>

OwnerDisplayName: Gustavo Carreno

Title: Way to go from recursion to iteration


问:
How to click dynamic id button in selenium IDE?
I am searching it from 2 days but still unable to get satisfying answer..please help
I am using liferay, i want to open dropdown which name is "Add" and then want to click on submit button named as "Blank Site"..and both "Add" and "Blank site" button contains dynamic values/id which changes each time..attaching image for reference..

Image: Add
Image: blanksite

答:
You can use xpath with any combination, one is already suggested by @PedroMiguel other one is like that</p>

```<code>//*[contains(@id, 'yui-patched') and contains(@role,'menuitem')]
</code>```

Body:
You can use xpath with any combination, one is already suggested by @PedroMiguel other one is like that

//*[contains(@id, 'yui-patched') and contains(@role,'menuitem')]


问:
Any SharePoint geek to comment on architecture?
We are working with an existing SharePoint solution for a Company (its an Intranet). Now, the company is splitting into two and so is their intranet. Each company, of these two, from now on will have their own Intranet. So, idea is to split this Intranet (which is just a web application) into two web applications. But wait, these companies will also have some information to share in between. So, the idea is to put the shared information (Administrative stuff etc) into a separate web application. So, we have three web apps so far.

Previously, Company's intranet was managing the data of about 50 facilities in the form of Subsites. Now, according to new design, each web application will have 25 facilities each. In other words, each company will have 25 facilities. But, problem is that each facility is having large amounts of data almost 5GB+. So, its not possible for me to put the restriction quota at the site level. Although, we can put restriction on the size at SiteCollection level (as per my understanding). So, the idea so far is to create one site collection for each facility, it means we will have 25 site collections in a web applications. Navigation could be a nightmare. But, can we solve navigation problem with managed path etc?

any other suggestions/improvements will be warmly welcome and appreciated! Even your little comment may help me to improve my design ;)

答:
In the proposed design, you will have to manually setup the navigation (managed paths will probably not help unless you want to have something other than /sites/ in the url).

I do question why you now have to split each of the facilities into their own site collection when, before the split, subsites worked.  I would only recommend each facility be a unique site collection if you can forsee being asked to move facilities between the two new companies.


问:
Espresso testing with never ending AsyncTask
I am trying to run an Espresso test under real conditions in my app. Problem is that tests never run because Espresso cannot detect an idle state in order to inject it's event to queue. Therefore it hangs and ends with known ASYNC_TASKS_HAVE_IDLED error.

Why this happens?

The application is using SignalR library and it is initialized on app start. "Library GitHub url". This library creates multiple long polling connections in order to send and receive all kind of messages and events to/from the server.

These connections are implemented with AsyncTask (class url) and since they end rarely (and when they do, they are restarted instantly), Espresso has very little chance to detect idle state and continue the execution.

So, is there some workaround for this problem? Am I really forced to switch to UIAutomator because of this?

Notes:

Disabling the SignalR is not an option (tried, tests work but then I'm missing the point of the app)

Mocking the SignalR is also not an option. I want to test the real data.

Thank you for your time.

答:
I also have many Async. tasks on my app..
So what I do is :

Registered idling resource.

Made it false when I need to stop/wait.

Made it true when I want to proceed.

But when there is a lot of calls then this won't work. Else it works fine in my simple cases.

```<code>@Before
    public void registerIdlingResource() {
        Utils.idle = true;
        mIdlingResource = mActivityRule.getActivity().getIdlingResource();
        Espresso.registerIdlingResources(mIdlingResource);

}

-----------------------------

 @After
    public void unregisterIdlingResource() {
        if (mIdlingResource != null) {
            Espresso.unregisterIdlingResources(mIdlingResource);
        }
    }

-------------------
signIn();
Utils.idle = false;
onView(withId(R.id.ll_reports)).perform(click());
Utils.idle = false;
</code>```

After sign in method i wait until the mail page is loaded. Then I click on my layout with id ll_reports. Then again I wait for next task that I want to perform.

Body:
I also have many Async. tasks on my app..
So what I do is :

Registered idling resource.

Made it false when I need to stop/wait.

Made it true when I want to proceed.

But when there is a lot of calls then this won't work. Else it works fine in my simple cases.

@Before
    public void registerIdlingResource() {
        Utils.idle = true;
        mIdlingResource = mActivityRule.getActivity().getIdlingResource();
        Espresso.registerIdlingResources(mIdlingResource);

}

-----------------------------

 @After
    public void unregisterIdlingResource() {
        if (mIdlingResource != null) {
            Espresso.unregisterIdlingResources(mIdlingResource);
        }
    }

-------------------
signIn();
Utils.idle = false;
onView(withId(R.id.ll_reports)).perform(click());
Utils.idle = false;

After sign in method i wait until the mail page is loaded. Then I click on my layout with id ll_reports. Then again I wait for next task that I want to perform.


问:
Use ActiveRecord to count rows where id is matched and another column matches one of two values
I need to create a query in CodeIgniter as follows:

```<code>SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE (
       LOWER(ResponseStatus) = 'submitted'
       OR LOWER(ResponseStatus) = 'inqueue'
      )
      AND `SMSUsageID` = '1'
</code>```

so I created a function in my model as:

```<code>function submittedSMSCount($smsUsageID) {
    $this->db->where('lower(ResponseStatus)', 'submitted');
    $this->db->or_where('lower(ResponseStatus)', 'inqueue');
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}
</code>```

but this function generates a query like:

```<code>SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE LOWER(ResponseStatus) = 'submitted'
      OR LOWER(ResponseStatus) = 'inqueue'
      AND `SMSUsageID` = '1'
</code>```

These two queries generate different results because of the conditions. I need to group the OR conditions to get the correct result. How can I do this with CodeIgniter's Active Record query building methods?

答:
```<code>function submittedSMSCount($smsUsageID) {
    $where = "(lower(ResponseStatus) = 'submitted' OR lower(ResponseStatus) = 'inqueue')";
    $this->db->where($where);
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}
</code>```

Body:
I need to create a query in CodeIgniter as follows:

SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE (
       LOWER(ResponseStatus) = 'submitted'
       OR LOWER(ResponseStatus) = 'inqueue'
      )
      AND `SMSUsageID` = '1'

so I created a function in my model as:

function submittedSMSCount($smsUsageID) {
    $this->db->where('lower(ResponseStatus)', 'submitted');
    $this->db->or_where('lower(ResponseStatus)', 'inqueue');
    $this->db->where('SMSUsageID', $smsUsageID);
    return $this->db->count_all_results('smslog_tbl');
}

but this function generates a query like:

SELECT COUNT(*) AS `numrows`
FROM `smslog_tbl`
WHERE LOWER(ResponseStatus) = 'submitted'
      OR LOWER(ResponseStatus) = 'inqueue'
      AND `SMSUsageID` = '1'

These two queries generate different results because of the conditions. I need to group the OR conditions to get the correct result. How can I do this with CodeIgniter's Active Record query building methods?


问:
How do you set a string data member from a base class, with a derived classed?
I have figured out most of the code/assignment, here is part of the "To-Do" I can't figure out:

The derived classes set the m_type, but note, there is no setType function to do
so (and you can't add one).

Here is my code (nothing in main can be changed):

```<code>#include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
const double PI = 3.14159265359;

class Geometry
 {
 public:
     Geometry(std::string name)
        :m_name(name)
    {

    }
    virtual double computeVolume() = 0;
    virtual double computeSurfaceArea() = 0;

    std::string getName() { return m_name; }
    std::string getType() { return m_type; }

protected:
    std::string m_name;
    std::string m_type;

 };

class Box : public Geometry
{
 public:

    Box(std::string name, double length, double width, double height)
        : Geometry(name), m_length(length), m_width(width), m_height(height)
    {

    }

    virtual double computeSurfaceArea()
    {
        return (2 * (m_height * m_width)) + (2 * (m_height * m_length)) + (2
        * (m_length * m_width));
    }

     virtual double computeVolume()
    {
        return m_length * m_width * m_height;
    }
 protected:
     double m_length;
     double m_width;
     double m_height;
};

class Sphere : public Geometry
{
public:
    Sphere(std::string name, double radius)
        :Geometry(name), m_radius(radius)
    {

    }

    virtual double computeVolume()
    {
        return  (4.0/3.0) * PI * (m_radius * m_radius * m_radius);
    }

    virtual double computeSurfaceArea()
    {
        return 4 * PI * (m_radius * m_radius);
    }

 protected:
     double m_radius;

 };

void report(Geometry* obj)
{

     std::cout << "----- Geometry Report -----" << std::endl << std::endl
        << "Type: " << obj->getType() << std::endl
        << "Name: " << obj->getName() << std::endl
        << "Volume " << obj->computeVolume() << std::endl
        << "Surface Area " << obj->computeSurfaceArea() << std::endl <<
std::endl;
}

int main()
{
    std::vector<Geometry*> items;

    items.push_back(new Box("Box 1", 1, 2, 3));
    items.push_back(new Box("Box 2", 2, 3, 4));
    items.push_back(new Sphere("Sphere 1", 5));
    items.push_back(new Sphere("Sphere 2", 6));

    for (int i = 0; i < items.size(); i++)
    {
        report(items[i]);
    }

    system("PAUSE");
    return 0;
}
</code>```

Thanks

答:
If I understand your question correctly then you just need to set the m_type variable directly within the constructor of each of your derived classes. You are able to do this because this variable has protected access which means derived classes can manipulate it directly. So you should simply be able to do:

```<code>Box(std::string name, double length, double width, double height)
    : Geometry(name), m_length(length), m_width(width), m_height(height)
{
   m_type = "Box type";
}
</code>```

Body:
I have figured out most of the code/assignment, here is part of the "To-Do" I can't figure out:

The derived classes set the m_type, but note, there is no setType function to do
so (and you can't add one).

Here is my code (nothing in main can be changed):

#include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
const double PI = 3.14159265359;

class Geometry
 {
 public:
     Geometry(std::string name)
        :m_name(name)
    {

    }
    virtual double computeVolume() = 0;
    virtual double computeSurfaceArea() = 0;

    std::string getName() { return m_name; }
    std::string getType() { return m_type; }

protected:
    std::string m_name;
    std::string m_type;

 };

class Box : public Geometry
{
 public:

    Box(std::string name, double length, double width, double height)
        : Geometry(name), m_length(length), m_width(width), m_height(height)
    {

    }

    virtual double computeSurfaceArea()
    {
        return (2 * (m_height * m_width)) + (2 * (m_height * m_length)) + (2
        * (m_length * m_width));
    }

     virtual double computeVolume()
    {
        return m_length * m_width * m_height;
    }
 protected:
     double m_length;
     double m_width;
     double m_height;
};

class Sphere : public Geometry
{
public:
    Sphere(std::string name, double radius)
        :Geometry(name), m_radius(radius)
    {

    }

    virtual double computeVolume()
    {
        return  (4.0/3.0) * PI * (m_radius * m_radius * m_radius);
    }

    virtual double computeSurfaceArea()
    {
        return 4 * PI * (m_radius * m_radius);
    }

 protected:
     double m_radius;

 };

void report(Geometry* obj)
{

     std::cout << "----- Geometry Report -----" << std::endl << std::endl
        << "Type: " << obj->getType() << std::endl
        << "Name: " << obj->getName() << std::endl
        << "Volume " << obj->computeVolume() << std::endl
        << "Surface Area " << obj->computeSurfaceArea() << std::endl <<
std::endl;
}

int main()
{
    std::vector<Geometry*> items;

    items.push_back(new Box("Box 1", 1, 2, 3));
    items.push_back(new Box("Box 2", 2, 3, 4));
    items.push_back(new Sphere("Sphere 1", 5));
    items.push_back(new Sphere("Sphere 2", 6));

    for (int i = 0; i < items.size(); i++)
    {
        report(items[i]);
    }

    system("PAUSE");
    return 0;
}

Thanks

Body:
If I understand your question correctly then you just need to set the m_type variable directly within the constructor of each of your derived classes. You are able to do this because this variable has protected access which means derived classes can manipulate it directly. So you should simply be able to do:

Box(std::string name, double length, double width, double height)
    : Geometry(name), m_length(length), m_width(width), m_height(height)
{
   m_type = "Box type";
}


问:
SQL Set Question
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence? </p>

```<code>DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';
</code>```

<p>I want to use something like the following to have it query against instead of the 034100-3JK: </p>

```<code>select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'
</code>```

答:
EDITED: Based on asker's comments

I noticed that you are explicitly writing out the item code (or ID, whatever you want to call it).  If you have a static list of codes that cannot be easily retrieved from your database, you can do something like this:

```<code>DECLARE @Items TABLE
(
  item varchar(10)
)
INSERT INTO @Items
VALUES ('034007-3CL'),
('next_code'),
('next_next_code')
</code>```

Alternatively, if that list of codes can be grabbed easily:

```<code>DECLARE @Items TABLE
(
  item varchar(10)
)
INSERT INTO @Items
SELECT a.items
FROM mytable AS a
WHERE a.column = condition
</code>```

Then you can use the variable like a normal table:

```<code>select
   a.t_sitm as StartItem
   ,a.t_mitm
   ,a.t_sitm
   ,b.t_ctyp
   ,a.t_qana
from
   ttibom010101 as a
   INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
   INNER JOIN @items as c on a.t_sitm = c.item
where
   b.t_ctyp != 'TOP'
   and b.t_ctyp != 'SUB'
</code>```

Title: SQL Set Question

Body:
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence?

DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';

I want to use something like the following to have it query against instead of the 034100-3JK:

select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'

Body:
EDITED: Based on asker's comments

I noticed that you are explicitly writing out the item code (or ID, whatever you want to call it).  If you have a static list of codes that cannot be easily retrieved from your database, you can do something like this:

DECLARE @Items TABLE
(
  item varchar(10)
)
INSERT INTO @Items
VALUES ('034007-3CL'),
('next_code'),
('next_next_code')

Alternatively, if that list of codes can be grabbed easily:

DECLARE @Items TABLE
(
  item varchar(10)
)
INSERT INTO @Items
SELECT a.items
FROM mytable AS a
WHERE a.column = condition

Then you can use the variable like a normal table:

select
   a.t_sitm as StartItem
   ,a.t_mitm
   ,a.t_sitm
   ,b.t_ctyp
   ,a.t_qana
from
   ttibom010101 as a
   INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
   INNER JOIN @items as c on a.t_sitm = c.item
where
   b.t_ctyp != 'TOP'
   and b.t_ctyp != 'SUB'


问:
Angular5 [routerLink]="['/url']" Error trying to diff '[object Object]'. Only arrays and iterables are allowed
```<code><a [routerLink]="['/url']" class="weui-cell__ft text-d">title</a>
</code>```

Angular5 [routeLink]="['/url']" throw a Error trying to diff '[object Object]'. Only arrays and iterables are allowed.

```<code>ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:18645)
at NgForOf.ngDoCheck (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:35895)
at checkAndUpdateDirectiveInline (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:23401)
at checkAndUpdateNodeInline (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:24901)
at checkAndUpdateNode (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:24844)
at debugCheckAndUpdateNode (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:25716)
at debugCheckDirectivesFn (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:25657)
at Object.View_HomeComponent_0.__WEBPACK_IMPORTED_MODULE_0__angular_core__.ɵvid._co [as updateDirectives] (home.component.html:78)
at Object.debugUpdateDirectives [as updateDirectives] (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:25642)
at checkAndUpdateView (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:24811)
</code>```

答:
Try this:

```<code><a routerLink="/url"  class="weui-cell__ft text-d">title</a>
</code>```

And you will have to define your "url" route into your route.config also. For more info : https://angular.io/guide/router

Body:
title

Angular5 [routeLink]="['/url']" throw a Error trying to diff '[object Object]'. Only arrays and iterables are allowed.

ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:18645)
at NgForOf.ngDoCheck (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:35895)
at checkAndUpdateDirectiveInline (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:23401)
at checkAndUpdateNodeInline (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:24901)
at checkAndUpdateNode (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:24844)
at debugCheckAndUpdateNode (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:25716)
at debugCheckDirectivesFn (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:25657)
at Object.View_HomeComponent_0.__WEBPACK_IMPORTED_MODULE_0__angular_core__.ɵvid._co [as updateDirectives] (home.component.html:78)
at Object.debugUpdateDirectives [as updateDirectives] (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:25642)
at checkAndUpdateView (vendor.js?v=zEe6VsaL2DL3c66V6dkahN0BFDflNeSabH3Fz48ci10:24811)

Body:
Try this:

<a routerLink="/url"  class="weui-cell__ft text-d">title</a>

And you will have to define your "url" route into your route.config also. For more info : https://angular.io/guide/router


问:
Getting obscure error when using Google sign-in in Android
I'm getting com.google.android.gms.common.api.ApiException: 10: when trying to use Google sign-in.

Here is the code itself:

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        // The Task returned from this call is always completed, no need to attach
        // a listener.
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        //handleSignInResult(task);
        GoogleSignInAccount account = getAccount(task);
        System.out.println("asti00");
    }
}

public GoogleSignInAccount getAccount(Task<GoogleSignInAccount> task) {
    GoogleSignInAccount account = null;
    try {
        account = task.getResult(ApiException.class);
    } catch (ApiException ex) {
        // TODO: handle exception
        System.out.println("asti01");
        System.out.println("MESSAGE: " + ex.getMessage());
        ex.printStackTrace();
        System.out.println("asti02");
    }

    return account;
}
</code>```

As you can see I'm using the exact code as in the tutorial but I'm getting the error com.google.android.gms.common.api.ApiException: 10:.

I can't figure out where the error is coming from. Can anyone please help me?

Thanks

答:
Try to add to your app level build.gradle

compile 'com.google.android.gms:play-services-auth:9.8.0'

Body:
I'm getting com.google.android.gms.common.api.ApiException: 10: when trying to use Google sign-in.

Here is the code itself:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        // The Task returned from this call is always completed, no need to attach
        // a listener.
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        //handleSignInResult(task);
        GoogleSignInAccount account = getAccount(task);
        System.out.println("asti00");
    }
}

public GoogleSignInAccount getAccount(Task<GoogleSignInAccount> task) {
    GoogleSignInAccount account = null;
    try {
        account = task.getResult(ApiException.class);
    } catch (ApiException ex) {
        // TODO: handle exception
        System.out.println("asti01");
        System.out.println("MESSAGE: " + ex.getMessage());
        ex.printStackTrace();
        System.out.println("asti02");
    }

    return account;
}

As you can see I'm using the exact code as in the tutorial but I'm getting the error com.google.android.gms.common.api.ApiException: 10:.

I can't figure out where the error is coming from. Can anyone please help me?

Thanks


问:
Joining one column from a file to another file based on matched value of first column in both
Using join command in linux, I would like to compare first column of file1.csv and file2.csv and where the column matches, I would like to add a column of file2.csv to file1.csv. The first column in file1.csv and file2.csv differs and file1.csv is a subset of file2.csv (first column wise).

```<code>head file1.csv
column1, column2, column3
1.0, 5, 3
1.5, 4, 9
2.1, 2, 1
</code>```

and

```<code>head file2.csv
column1, column2, column4
1.0, 5, 9
1.2, 0, 0
1.3, 0, 1
1.5, 4, 3
2.1, 2, 5
</code>```

I want to join such that afterwards:

```<code>head file1.csv
column1, column2, column3, column4
1.0, 5, 3, 9
1.5, 4, 9, 3
2.1, 2, 1, 5
</code>```

I tried join -1 1 -2 1 -t, -o 1.1,1.2,1.3,2.3 <(sort -k 1 file1.csv ) <(sort -k 1 file2.csv ) but it's not working. Because it's also brings the header line bottom:

```<code>join -1 1 -2 1 -t, -o 1.1,1.2,1.3,2.3 <(sort -k 1 file1.csv ) <(sort -k 1 file2.csv )
1.0, 5, 3, 9
1.5, 4, 9, 3
2.1, 2, 1, 5
column1, column2, column3, column4
</code>```

答:
You just concerned about the head columns placed position?

Try it following one. It just modified your command line a little.

```<code>join -1 1 -2 1 -t, -o 1.1,1.2,1.3,2.3 <(head -n 1 file1.csv && tail -n+2 file1.csv | sort -k1 ) <(head -n 1 file2.csv && tail -n+2 file2.csv | sort -k1 )
</code>```

I hope this helps you.

Body:
Using join command in linux, I would like to compare first column of file1.csv and file2.csv and where the column matches, I would like to add a column of file2.csv to file1.csv. The first column in file1.csv and file2.csv differs and file1.csv is a subset of file2.csv (first column wise).

head file1.csv
column1, column2, column3
1.0, 5, 3
1.5, 4, 9
2.1, 2, 1

and

head file2.csv
column1, column2, column4
1.0, 5, 9
1.2, 0, 0
1.3, 0, 1
1.5, 4, 3
2.1, 2, 5

I want to join such that afterwards:

head file1.csv
column1, column2, column3, column4
1.0, 5, 3, 9
1.5, 4, 9, 3
2.1, 2, 1, 5

I tried join -1 1 -2 1 -t, -o 1.1,1.2,1.3,2.3 <(sort -k 1 file1.csv ) <(sort -k 1 file2.csv ) but it's not working. Because it's also brings the header line bottom:

join -1 1 -2 1 -t, -o 1.1,1.2,1.3,2.3 <(sort -k 1 file1.csv ) <(sort -k 1 file2.csv )
1.0, 5, 3, 9
1.5, 4, 9, 3
2.1, 2, 1, 5
column1, column2, column3, column4

Body:
You just concerned about the head columns placed position?

Try it following one. It just modified your command line a little.

join -1 1 -2 1 -t, -o 1.1,1.2,1.3,2.3 <(head -n 1 file1.csv && tail -n+2 file1.csv | sort -k1 ) <(head -n 1 file2.csv && tail -n+2 file2.csv | sort -k1 )

I hope this helps you.