问:
cursor count is 1 whereas the table has 3 rows
I m trying to populate sql table and then retrieve data from it. Following is my code.

```<code>public void addQuestion(Question quest)
{
    int id = 1;
    ContentValues values = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);
    onCreate(db);
    values.put(KEY_QUES, quest.getQuestion());
    values.put(KEY_ANSWER, quest.getAnswer());
    values.put(KEY_OPTA, quest.getOptA());
    values.put(KEY_OPTB, quest.getOptB());
    values.put(KEY_OPTC, quest.getOptC());
    db.insert(TABLE_QUEST1, null, values);
    System.out.println("Added in database: " + quest.getQuestion());
}

public ArrayList<Question> getAllQuestions() {
    System.out.println("getting rows 1");
    ArrayList<Question> quesList = new ArrayList<Question>();
    System.out.println("getting rows 2");
    Cursor cursor = null;
    SQLiteDatabase db = getReadableDatabase();
    System.out.println("getting rows ");
    cursor = db.rawQuery("SELECT * FROM " + TABLE_QUEST1, null);
    if (!cursor.moveToFirst()) {
        System.out.println("No data in the database ");
    } else {
        System.out.println("theres data in the database ");
        quesList = new ArrayList<Question>();
        do {
            System.out.print("total rows " + cursor.getCount());
            Question quest = new Question();
            quest.setID(cursor.getInt(0));
            quest.setQuestion(cursor.getString(1));
            quest.setAnswer(cursor.getString(2));
            quest.setOptA(cursor.getString(3));
            quest.setOptB(cursor.getString(4));
            quest.setOptC(cursor.getString(5));
            quesList.add(quest);
        } while (cursor.moveToNext());
        cursor.close();
    }
}
</code>```

I have 4 rows of data in my table and I can see that with the print statement "added in database"

but when i actually read it the cursor just reads row 1 and moves out of the while loop. what could potentially be wrong.

tia

答: Your code was absolutely fine except placing drop command in the loop. As mentioned in the earlier comments, please make sure to avoid calling drop query each time and you'll find the result.</p>

Body:
I m trying to populate sql table and then retrieve data from it. Following is my code.

public void addQuestion(Question quest)
{
    int id = 1;
    ContentValues values = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST1);
    onCreate(db);
    values.put(KEY_QUES, quest.getQuestion());
    values.put(KEY_ANSWER, quest.getAnswer());
    values.put(KEY_OPTA, quest.getOptA());
    values.put(KEY_OPTB, quest.getOptB());
    values.put(KEY_OPTC, quest.getOptC());
    db.insert(TABLE_QUEST1, null, values);
    System.out.println("Added in database: " + quest.getQuestion());
}

public ArrayList<Question> getAllQuestions() {
    System.out.println("getting rows 1");
    ArrayList<Question> quesList = new ArrayList<Question>();
    System.out.println("getting rows 2");
    Cursor cursor = null;
    SQLiteDatabase db = getReadableDatabase();
    System.out.println("getting rows ");
    cursor = db.rawQuery("SELECT * FROM " + TABLE_QUEST1, null);
    if (!cursor.moveToFirst()) {
        System.out.println("No data in the database ");
    } else {
        System.out.println("theres data in the database ");
        quesList = new ArrayList<Question>();
        do {
            System.out.print("total rows " + cursor.getCount());
            Question quest = new Question();
            quest.setID(cursor.getInt(0));
            quest.setQuestion(cursor.getString(1));
            quest.setAnswer(cursor.getString(2));
            quest.setOptA(cursor.getString(3));
            quest.setOptB(cursor.getString(4));
            quest.setOptC(cursor.getString(5));
            quesList.add(quest);
        } while (cursor.moveToNext());
        cursor.close();
    }
}

I have 4 rows of data in my table and I can see that with the print statement "added in database"

but when i actually read it the cursor just reads row 1 and moves out of the while loop. what could potentially be wrong.

tia


来源: stackexchange

答:
```<code>--- # copying  yaml file
- hosts: localhost
  user: {{ user }}
  connection: ssh
  become: yes
  gather_facts: no
  tasks:
   - name: Creation of directory on remote server
     file:
       path: /var/lib/jenkins/.aws
       state: directory
       mode: 0755
     register: result
   - debug:
       var: result

   - name: get file names to copy
     command: "find conf/.aws -type f"
     register: files_to_copy

   - name: copy files
     copy:
      src: "{{ item }}"
      dest: "/var/lib/jenkins/.aws"
      owner: {{ user }}
      group: {{ group }}
      remote_src: True
      mode: 0644
     with_items:
      - "{{ files_to_copy.stdout_lines }}"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Move/copy all files in a directory with Ansible

Body:
How can I move or copy all the files in a directory to my localhost or another remote host with Ansible?

This question goes both to linux systems and windows.

What I've got so far:

- hosts: all
  tasks:
    - name: list the files in the folder
      command: ls /dir/
      register: dir_out

    - name: do the action
      fetch: src=/dir/{{item}} dest=/second_dir/ flat=yes
      with_items: ('{{dir_out.stdout_lines}}')

The output is as follows:

TASK [setup] *******************************************************************
ok: [remote_host]

TASK [list the files in the folder] ********************************************
changed: [remote_host]

TASK [move those files] ********************************************************
ok: [remote_host] => (item=('[u'file10003', u'file10158', u'file1032', u'file10325', u'file10630', u'file10738', u'file10818', u'file10841', u'file10980', u'file11349', u'file11589', u'file11744', u'file12003', u'file12008', u'file12234', u'file12734', u'file12768', u'file12774', u'file12816', u'file13188', u'file13584', u'file14560', u'file15512', u'file16020', u'file16051', u'file1610', u'file16610', u'file16642', u'file16997', u'file17233', u'file17522', u'file17592', u'file17908', u'file18149', u'file18311', u'file18313', u'file18438', u'file185', u'file18539', u'file18777', u'file18808', u'file18878', u'file18885', u'file19313', u'file19755', u'file19863', u'file20158', u'file20347', u'file2064', u'file20840', u'file21123', u'file21422', u'file21425', u'file21711', u'file21770', u'file21790', u'file21808', u'file22054', u'file22359', u'file22601', u'file23609', u'file23763', u'file24208', u'file24430', u'file24452', u'file25028', u'file25131', u'file25863', u'file26197', u'file26384', u'file26398', u'file26815', u'file27025', u'file27127', u'file27373', u'file2815', u'file28175', u'file28780', u'file28886', u'file29058', u'file29096', u'file29456', u'file29513', u'file29677', u'file29836', u'file30034', u'file30216', u'file30464', u'file30601', u'file30687', u'file30795', u'file31299', u'file31478', u'file31883', u'file31908', u'file32251', u'file3229', u'file32724', u'file32736', u'file3498', u'file4173', u'file4235', u'file4748', u'file4883', u'file5812', u'file6126', u'file6130', u'file6327', u'file6462', u'file6624', u'file6832', u'file7576', u'file8355', u'file8693', u'file8726', u'file8838', u'file8897', u'file9112', u'file9331', u'file993']'))

PLAY RECAP *********************************************************************
remote_host                      : ok=3    changed=1    unreachable=0    failed=0

It got all the files from the directory, I guess because of the with_items (though I don't know what the "u" stands for), but the second directory on my localhost remains empty.

Any suggestions?


问:
Split element values of xml using xslt 1.0
I have an input tag name properties which has many values in it(like key-value pair) separated by semicolon. I need to find particular strings and asigned the value(which is coming after =)into particular output node

For example in the below input.xml i want to take  mail.debug=false and assigned the value "false" into output xml debug node.

Input.xml

```<code><mail-session>
    <name>MailSession-1</name>
    <target>AdminServer</target>
    <jndi-name>MailNotification2</jndi-name>
    <properties>
    mail.debug=false;mail.smtp.user=weblogic;mail.from=master@mydom.com;
   </properties>
  </mail-session>
</code>```

My output.xml Should be like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<mail-session jndi-name="java:jboss/mail/mailservice" name="MailSession-1" debug="false" from="master@mydom.com">
<smtp-server outbound-socket-binding-ref="" tls="" ssl="">
<login name="weblogic" password=""/>
</smtp-server>
</mail-session><subsystem>
</subsystem>
</code>```

答:
For XSLT 2.0

You should take a look at Tokenize function (http://www.xsltfunctions.com/xsl/fn_tokenize.html)

```<code>tokenize('mail.debug=false;mail.smtp.user=weblogic;mail.from=master@mydom.com;', '[;\s]+')
</code>```

Older XSLT

If you are using older XSLT version, create your own function:

```<code><xsl:template name="tokenize-string">
    <xsl:param name="list" />
    <xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" />
    <xsl:variable name="first" select="substring-before($newlist, ' ')" />
    <xsl:variable name="remaining" select="substring-after($newlist, ' ')" />
    <id>
        <xsl:value-of select="$first" />
    </id>
    <xsl:if test="$remaining">
        <xsl:call-template name="tokenize-string">
            <xsl:with-param name="list" select="$remaining" />
        </xsl:call-template>
    </xsl:if>
</xsl:template>
</code>```

Body:
I have an input tag name properties which has many values in it(like key-value pair) separated by semicolon. I need to find particular strings and asigned the value(which is coming after =)into particular output node

For example in the below input.xml i want to take  mail.debug=false and assigned the value "false" into output xml debug node.

Input.xml

<mail-session>
    <name>MailSession-1</name>
    <target>AdminServer</target>
    <jndi-name>MailNotification2</jndi-name>
    <properties>
    mail.debug=false;mail.smtp.user=weblogic;mail.from=master@mydom.com;
   </properties>
  </mail-session>

My output.xml Should be like this

<?xml version="1.0" encoding="UTF-8"?>
<mail-session jndi-name="java:jboss/mail/mailservice" name="MailSession-1" debug="false" from="master@mydom.com">
<smtp-server outbound-socket-binding-ref="" tls="" ssl="">
<login name="weblogic" password=""/>
</smtp-server>
</mail-session><subsystem>
</subsystem>

Body:
For XSLT 2.0

You should take a look at Tokenize function (http://www.xsltfunctions.com/xsl/fn_tokenize.html)

tokenize('mail.debug=false;mail.smtp.user=weblogic;mail.from=master@mydom.com;', '[;\s]+')

Older XSLT

If you are using older XSLT version, create your own function:

<xsl:template name="tokenize-string">
    <xsl:param name="list" />
    <xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" />
    <xsl:variable name="first" select="substring-before($newlist, ' ')" />
    <xsl:variable name="remaining" select="substring-after($newlist, ' ')" />
    <id>
        <xsl:value-of select="$first" />
    </id>
    <xsl:if test="$remaining">
        <xsl:call-template name="tokenize-string">
            <xsl:with-param name="list" select="$remaining" />
        </xsl:call-template>
    </xsl:if>
</xsl:template>


问:
array to NSOrderedSet change size of list to 1
I have a array of 2 element, when i try to convert it to NSOrderedSet it give me a size of only one element

```<code>      LOG("\(listTwoElement.count)")
</code>```

This line give me 2

```<code>   LOG("\(NSOrderedSet.init(array: listTwoElement).count)")
</code>```

this line give me only 1 element

Why conversion to NSOrderedSet change size of array ?

thanks for your help

答:
A Set is an unordered list of unique elements.  If you try to put the same element in a set twice you will only get one

An Array is an order list of elements that needn't be unique.  You can have the same element may times in array.

A OrderedSet is a combination of both (but a subclass of neither).  The items are ordered, like an array, but each element needs to be unique.

Unique element does not (just) mean that they are stored in different locations in memory, but that they are not "equal" in some fundamental sense.  Equality can be defined differently for every class.  Classes that want to define it, implement the isEqual: and hash method of the NSObjectProtocol. (Hashes of equal objects must be equal, hashes of unequal object do not need to be different).

Without knowing more about the element you are dealing with it is hard to say why they are being evaluated as equal when you don't expect them to be.  I would start will looking at the class's implementation of the isEqual and hash.

Body:
I have a array of 2 element, when i try to convert it to NSOrderedSet it give me a size of only one element

      LOG("\(listTwoElement.count)")

This line give me 2

   LOG("\(NSOrderedSet.init(array: listTwoElement).count)")

this line give me only 1 element

Why conversion to NSOrderedSet change size of array ?

thanks for your help


问:
How use custom libraries in Kohana 3
I am trying to include a user library that includes some user related functions such as checking if the user is authenticated and such. Now I am trying to make usage of the Kohana autoloader, but can't seem to get it working.

I have the library placed under application/classes/library

```<code>class User {
 public function is_alive()
 {
   $session = Session::instance();
   $data = $session->get('alive');

   if(isset($data))
   {
    return true;
   }
   else
   {
    return false;
   }
 }
}
</code>```

And I try to call the library with

```<code>$user = new User;
</code>```

But it doesn't seem to do the trick.

How can I call a custom library?

答:
I have the library placed under application/classes/library

Place the library in /application/classes/.

Otherwise, you have to place this in your controller:

```<code>public function before() {
    require Kohana::find_file('classes', 'library/User');
}
</code>```

You can read about this here.

Now you can do the same as before, with User.php inside the directory library.

ContentLicense: CC BY-SA 2.5

Title: How use custom libraries in Kohana 3

Body:
I am trying to include a user library that includes some user related functions such as checking if the user is authenticated and such. Now I am trying to make usage of the Kohana autoloader, but can't seem to get it working.

I have the library placed under application/classes/library

class User {
 public function is_alive()
 {
   $session = Session::instance();
   $data = $session->get('alive');

   if(isset($data))
   {
    return true;
   }
   else
   {
    return false;
   }
 }
}

And I try to call the library with

$user = new User;

But it doesn't seem to do the trick.

How can I call a custom library?

Body:
I have the library placed under application/classes/library

Place the library in /application/classes/.

Otherwise, you have to place this in your controller:

public function before() {
    require Kohana::find_file('classes', 'library/User');
}

You can read about this here.

Now you can do the same as before, with User.php inside the directory library.


问:
turn switchery checkbox to uncheck
i use switchery checkbox now, how can I uncheck or checked it using jquery if I click a button, like</p>

```<code>$("button").click(function(){
    //uncheck switchery
});
</code>```

答:
I have tried everything but only one solution is possible.

```<code>$('.switcher').prop('checked', true);
</code>```

OR

```<code>$('.switcher').prop('checked', false);
</code>```

Title: turn switchery checkbox to uncheck

Body:
i use switchery checkbox now, how can I uncheck or checked it using jquery if I click a button, like

$("button").click(function(){
    //uncheck switchery
});

Body:
I have tried everything but only one solution is possible.

$('.switcher').prop('checked', true);

OR

$('.switcher').prop('checked', false);


问:
Understanding the condition for age validation logic
I am trying to calculate the age of the person based on the date of birth and doing some logic if its over 18 years. I had my code written and it was working fine, but I stumbled upon a code I found online and I am not getting one condition in that. The code is:

```<code>public class AgeValidation {
public static void main(String[] args) {
    getAge("29-12-1999");
}

private static void getAge(String dob1) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    Date dob;
    try {
        dob = format.parse(dob1);
        Calendar dob2 = Calendar.getInstance();
        dob2.setTime(dob);
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - dob2.get(Calendar.YEAR);

        if(dob2.after(today)) {
            System.out.println("Future date not allowed");
            System.exit(0);
        }

        if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH)) {
            System.out.println("First if condition");
            age--;
        } else if (today.get(Calendar.MONTH) == dob2.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) < dob2.get(Calendar.DAY_OF_MONTH)) {
            System.out.println("else if condition");
            age--;
        }

        if (age < 18) {
            System.out.println(age);
            System.out.println("Underage");
        } else {
            System.out.println(age);
            System.out.println("18 years");
            //Some logic
        }
    } catch (ParseException e) {

        e.printStackTrace();
    }
}
}
</code>```

Need addressing on below points:

I have added a condition if DOB year is after Current year it should not proceed.

```<code>if(dob2.after(today)) {
    System.out.println("Future date not allowed");
    System.exit(0);
}
</code>```

Is it correct to use System.exit(0); or is there some better approach to stop further execution.

In the code that I found online I saw a condition as

```<code>` if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH))`
</code>```

I am not getting in which scenario will this be executed.

Is there any use case in which this code will not work (I cannot think of any)

答:
java.time

You should not (as in not) want to use the long outdated classes SimpleDateFormat, Date and Calendar. Especially the first is notoriously troublesome, but we have better replacements for all of them in java.time, the modern Java date and time API also known as JSR-310.

And even more so because the modern API has a method for counting years between two dates built-in. Not only is it easier to write the code, more importantly it is easier to read and understand, and you can be more sure of the correctness.

```<code>private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("dd-MM-uuuu");

private static void getAge(String dob1) {
    LocalDate dob = LocalDate.parse(dob1, dateFormatter);
    LocalDate today = LocalDate.now(ZoneId.of("Asia/Dushanbe"));
    if (dob.isAfter(today)) {
        System.out.println("Future date not allowed");
    } else {
        int age = (int) ChronoUnit.YEARS.between(dob, today);

        if (age < 18) {
            System.out.println(age);
            System.out.println("Underage");
        } else {
            System.out.println(age);
            System.out.println("18 years");
            //Some logic
        }
    }
}
</code>```

With your example date of "29-12-1999" the above method prints:

```<code>17
Underage
</code>```

Since it is never the same date in all time zones, please substitute your desired time zone instead of Asia/Dushanbe.

between() returns a long. In this case we can safely cast it to an int because LocalDate only handles years in the range -999 999 999 through 999 999 999, so the difference in years will never exceed the capacity of int.

Your questions

Use of System.exit(0); is generally questionable, though at times necessary. In my code I have avoided it using an if-else construct. Another option would be return;. I guess this would more give you what you wanted in case there were two calls to getAge() after each other. Yet another option is throwing an IllegalArgumentException, that would leave for the caller to decide to catch it or not.

The line you are quoting will not be executed when running your code here in December. Imagine running your code next January, then today’s month will be January and dob2’s month will still be December, so since January is before December, the code will be executed. Which will also be necessary for your method to calculate the correct age.

The code seems convoluted, as Jim Garrison said, but appears to be correct (not even with the outdated API needed it be this complex). I have not spotted a case that would not be handled correctly.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

In Java 8 and later the new API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).

On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.

For learning to use java.time, see the Oracle tutorial or find other resoureces on the net.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to calculate the age of the person based on the date of birth and doing some logic if its over 18 years. I had my code written and it was working fine, but I stumbled upon a code I found online and I am not getting one condition in that. The code is:

public class AgeValidation {
public static void main(String[] args) {
    getAge("29-12-1999");
}

private static void getAge(String dob1) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    Date dob;
    try {
        dob = format.parse(dob1);
        Calendar dob2 = Calendar.getInstance();
        dob2.setTime(dob);
        Calendar today = Calendar.getInstance();
        int age = today.get(Calendar.YEAR) - dob2.get(Calendar.YEAR);

        if(dob2.after(today)) {
            System.out.println("Future date not allowed");
            System.exit(0);
        }

        if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH)) {
            System.out.println("First if condition");
            age--;
        } else if (today.get(Calendar.MONTH) == dob2.get(Calendar.MONTH)
                && today.get(Calendar.DAY_OF_MONTH) < dob2.get(Calendar.DAY_OF_MONTH)) {
            System.out.println("else if condition");
            age--;
        }

        if (age < 18) {
            System.out.println(age);
            System.out.println("Underage");
        } else {
            System.out.println(age);
            System.out.println("18 years");
            //Some logic
        }
    } catch (ParseException e) {

        e.printStackTrace();
    }
}
}

Need addressing on below points:

I have added a condition if DOB year is after Current year it should not proceed.

if(dob2.after(today)) {
    System.out.println("Future date not allowed");
    System.exit(0);
}

Is it correct to use System.exit(0); or is there some better approach to stop further execution.

In the code that I found online I saw a condition as

` if (today.get(Calendar.MONTH) < dob2.get(Calendar.MONTH))`

I am not getting in which scenario will this be executed.

Is there any use case in which this code will not work (I cannot think of any)

Body:
java.time

You should not (as in not) want to use the long outdated classes SimpleDateFormat, Date and Calendar. Especially the first is notoriously troublesome, but we have better replacements for all of them in java.time, the modern Java date and time API also known as JSR-310.

And even more so because the modern API has a method for counting years between two dates built-in. Not only is it easier to write the code, more importantly it is easier to read and understand, and you can be more sure of the correctness.

private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("dd-MM-uuuu");

private static void getAge(String dob1) {
    LocalDate dob = LocalDate.parse(dob1, dateFormatter);
    LocalDate today = LocalDate.now(ZoneId.of("Asia/Dushanbe"));
    if (dob.isAfter(today)) {
        System.out.println("Future date not allowed");
    } else {
        int age = (int) ChronoUnit.YEARS.between(dob, today);

        if (age < 18) {
            System.out.println(age);
            System.out.println("Underage");
        } else {
            System.out.println(age);
            System.out.println("18 years");
            //Some logic
        }
    }
}

With your example date of "29-12-1999" the above method prints:

17
Underage

Since it is never the same date in all time zones, please substitute your desired time zone instead of Asia/Dushanbe.

between() returns a long. In this case we can safely cast it to an int because LocalDate only handles years in the range -999 999 999 through 999 999 999, so the difference in years will never exceed the capacity of int.

Your questions

Use of System.exit(0); is generally questionable, though at times necessary. In my code I have avoided it using an if-else construct. Another option would be return;. I guess this would more give you what you wanted in case there were two calls to getAge() after each other. Yet another option is throwing an IllegalArgumentException, that would leave for the caller to decide to catch it or not.

The line you are quoting will not be executed when running your code here in December. Imagine running your code next January, then today’s month will be January and dob2’s month will still be December, so since January is before December, the code will be executed. Which will also be necessary for your method to calculate the correct age.

The code seems convoluted, as Jim Garrison said, but appears to be correct (not even with the outdated API needed it be this complex). I have not spotted a case that would not be handled correctly.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

In Java 8 and later the new API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).

On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.

For learning to use java.time, see the Oracle tutorial or find other resoureces on the net.


问:
Error while removing the trailing comma using javascript
```<code>var checked1 = JSON.parse(Cookies.get('checkedValues'));
</code>```

Now the checked1 contains:     ,1

I used the following code to remove the trailing comma.

```<code>var checked = checked1.replace(/(^,)|(,$)/g, "");
</code>```

But now i'm getting an error

Uncaught TypeError: checked1.replace is not a function

答:
Try this</p>

```<code>var checked1 = JSON.parse(Cookies.get('checkedValues').replace(/(^,)|(,$)/g, ""));
</code>```

Body:
var checked1 = JSON.parse(Cookies.get('checkedValues'));

Now the checked1 contains:     ,1

I used the following code to remove the trailing comma.

var checked = checked1.replace(/(^,)|(,$)/g, "");

But now i'm getting an error

Uncaught TypeError: checked1.replace is not a function

Body:
Try this

var checked1 = JSON.parse(Cookies.get('checkedValues').replace(/(^,)|(,$)/g, ""));


问:
Add Glyphicon to Every Button (bootstrap 3.5)
I'd like to add a glyphicon after the text on all my default buttons.

I found how to include the glyphicon in lists here:
Using a Glyphicon as an LI bullet point

I tried applying this to buttons, but I haven't got it right

```<code>.btn-default button:after {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    float: left;
    margin-top: 4px;
    margin-left: -17px;
    color: #0099FF;
}
</code>```

I realise I can add it like this:

```<code><a class="btn btn-default" href="testpage.aspx">
    Learn more
    <span class="glyphicon glyphicon-chevron-right"></span>
</a>
</code>```

But I'd prefer not to have to add it each time.  I'd also like to set the colour.

答:
I thing you might wants above image Output for your all the buttons.

For that you need to just write simple css :after class css to apply on all default buttons after text:

```<code>.btn-default:after {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    vertical-align: middle;
    padding: 6px 5px;
    color: #0099FF;
}
</code>```

this will work for your all buttons as shown in image.

Body:
I'd like to add a glyphicon after the text on all my default buttons.

I found how to include the glyphicon in lists here:
Using a Glyphicon as an LI bullet point

I tried applying this to buttons, but I haven't got it right

.btn-default button:after {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    float: left;
    margin-top: 4px;
    margin-left: -17px;
    color: #0099FF;
}

I realise I can add it like this:

    Learn more

But I'd prefer not to have to add it each time.  I'd also like to set the colour.

Body:
I thing you might wants above image Output for your all the buttons.

For that you need to just write simple css :after class css to apply on all default buttons after text:

.btn-default:after {
    content: "\e080";
    font-family: 'Glyphicons Halflings';
    font-size: 9px;
    vertical-align: middle;
    padding: 6px 5px;
    color: #0099FF;
}

this will work for your all buttons as shown in image.


问:
how to compile aws-sdk-cpp kinesis?

Trying to build a simple kinesis client app using aws-sdk-cpp

The problem is that no one seems (not even the AWS website nudge) to have simple examples on kinesis with simple barebones example CMakeLists.txt for kinesis. On top of that, its either that the CMakeList.txt is up to date but is too blown out of proportion OR the CMakeLists.txt is not up to date and I end up getting errors.

Could someone provide a simple barebones CMakeList.txt example for the Threadpool example on the AWS website:

https://aws.amazon.com/blogs/developer/category/cpp/?nc1=f_ls

OS: OSX Sierra 10.12.3
cmake version 3.9.4

NOTE: source code structure would be organized as ./source ./model ./build, etc.

Any help whatsoever is greatly appreciated. Thx

答: So after carefully going and siftig through different documentation I was able to piece together a working CMakeList.txt file. Disregard question</p>

Title: how to compile aws-sdk-cpp kinesis?


问:
Excel Auto Customize Status Bar not summing up
All,

I am using MS Excel 2016. While highlighting a particular column MS Excel doesn't sum up values in the toolbar. I have checked the setting and sum and other values have been check marked. My column is Text format but changing it to any other format such as Number or General doesn't help.

Any hints/ideas ?

答:
You definitely can't "add text together", so you need to get the affected cells back into a value.

Changing the cell's Number Format (to Number or General for example) sets the "data type" for new  values entered after that point, but doesn't automatically change how existing data is stored.

You said you're not getting a Sum total... what about Count?  If the feature is working but it's just an incorrect data type that can't "sum", it should still be showing a Count of cells.

This seems to happen more in complex multi-user workbooks, because one user's accidental keystroke can potentially be a pain to diagnose.

I usually just start "fresh cells" for the affected area.

For example, if yours is definitely just one column affected, I would insert a new column next-to or nearby; somewhere that the new column isn't inheriting the same (problem) formatting from the column next to it.

Then Copy the "bad column" and Paste Values on top of the "new column".

Select the column, right click, Format Cells, and set your Number format, etc.

Copy the "bad column" again and Paste Formulas on top of the "new column".

Basically you can copy everything but the formats of the "bad" column.  (You could also Copy & Paste Formatting from another area of the workbook that isn't affected by the issue, or a backup, etc.)

If this is indeed a multi-user workbook, consider setting up Data Validation and/or Protecting parts of the workbook to avoid accidental changes.


问:
Problem selecting max year, max month & max date in one query
```<code>CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);

CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
</code>```

I have this query so far,

```<code>SELECT MAX (TEMP.COSTO) COSTO,
       TEMP.M_PRODUCT_ID,
       TEMP.ANO
  FROM TEMP TEMP
       INNER JOIN
       (SELECT MAX(ANO) ANO,
               M_PRODUCT_ID
          FROM TEMP I
        GROUP BY M_PRODUCT_ID
       ) LA ON
       LA.ANO = TEMP.ANO
   AND LA.M_PRODUCT_ID = TEMP.M_PRODUCT_ID
GROUP BY TEMP.M_PRODUCT_ID,
         TEMP.ANO;
</code>```

but my intention is not to have the max cost, my intention is to query in this order

first i need to select distinct m_product_id then

for every m_product_id i need to

filter max (ano) then filter max (mes) then filter max (dia)

I need the result set like this.

```<code>C_INVOICE_ID DIA MES ANO SOCIO  PRODUCTO_NO                 M_PRODUCT_ID CATERGORIA COSTO
1015         15  2    2010 1520 ALURON 100MG X 30 TABLETAS     1530           15     2.15
5654         5   2    2010 1520 AMARYL 2MG X 15 TABLETAS       1531           15     4.2
15132        25  9    2010 1585 AMOXAL 250MG X 75ML SUSPENSION 1534           15     3.4
</code>```

please i really apritiated any help, thanks pd:i'm using oracle 9i

答:
If I am reading your requirement right, I come up with this:

```<code>select *
  from (select t.*
              ,row_number() over(partition by m_product_id
                                     order by ano desc, mes desc, dia desc) as rn
          from temp t
       )
 where rn = 1;
</code>```

But when I run the query I get another result than what you specified:

```<code>1015    15  2  2010  1520  ALURON 100MG X 30 TABLETAS       1530  15 2,15
116544   8  8  2010  1220  AMARYL 2MG X 15 TABLETAS         1531  15 4,8
15132   25  9  2010  1585  AMOXAL 250MG X 75ML SUSPENSION   1534  15 3,4
</code>```

For product_id = 1531, I picked the row with invoice_id = 116544, because that row comes up first if I sort by the order you specified:

```<code>select c_invoice_id, ano, mes, dia
  from temp t
 where m_product_id = 1531
order by ano desc, mes desc, dia desc;

C_INVOICE_ID        ANO        MES        DIA
------------ ---------- ---------- ----------
      116544       2010          8          8
       13548       2010          6          8
       15321       2010          6          4
       19456       2010          4         31
         132       2010          3          2
        5654       2010          2          5
         168       2010          1         15
</code>```

Did I missunderstand you requirements?

Body:
CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);

CREATE TABLE TEMP
(
C_INVOICE_ID NUMBER(10),
DIA NUMBER,
MES NUMBER,
ANO NUMBER,
SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
M_PRODUCT_ID NUMBER(10),
CATEGORIA NVARCHAR2(60) NOT NULL,
COSTO NUMBER
)

INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);

I have this query so far,

SELECT MAX (TEMP.COSTO) COSTO,
       TEMP.M_PRODUCT_ID,
       TEMP.ANO
  FROM TEMP TEMP
       INNER JOIN
       (SELECT MAX(ANO) ANO,
               M_PRODUCT_ID
          FROM TEMP I
        GROUP BY M_PRODUCT_ID
       ) LA ON
       LA.ANO = TEMP.ANO
   AND LA.M_PRODUCT_ID = TEMP.M_PRODUCT_ID
GROUP BY TEMP.M_PRODUCT_ID,
         TEMP.ANO;

but my intention is not to have the max cost, my intention is to query in this order

first i need to select distinct m_product_id then

for every m_product_id i need to

filter max (ano) then filter max (mes) then filter max (dia)

I need the result set like this.

C_INVOICE_ID DIA MES ANO SOCIO  PRODUCTO_NO                 M_PRODUCT_ID CATERGORIA COSTO
1015         15  2    2010 1520 ALURON 100MG X 30 TABLETAS     1530           15     2.15
5654         5   2    2010 1520 AMARYL 2MG X 15 TABLETAS       1531           15     4.2
15132        25  9    2010 1585 AMOXAL 250MG X 75ML SUSPENSION 1534           15     3.4

please i really apritiated any help, thanks pd:i'm using oracle 9i

Body:
If I am reading your requirement right, I come up with this:

select *
  from (select t.*
              ,row_number() over(partition by m_product_id
                                     order by ano desc, mes desc, dia desc) as rn
          from temp t
       )
 where rn = 1;

But when I run the query I get another result than what you specified:

1015    15  2  2010  1520  ALURON 100MG X 30 TABLETAS       1530  15 2,15
116544   8  8  2010  1220  AMARYL 2MG X 15 TABLETAS         1531  15 4,8
15132   25  9  2010  1585  AMOXAL 250MG X 75ML SUSPENSION   1534  15 3,4

For product_id = 1531, I picked the row with invoice_id = 116544, because that row comes up first if I sort by the order you specified:

select c_invoice_id, ano, mes, dia
  from temp t
 where m_product_id = 1531
order by ano desc, mes desc, dia desc;

C_INVOICE_ID        ANO        MES        DIA
------------ ---------- ---------- ----------
      116544       2010          8          8
       13548       2010          6          8
       15321       2010          6          4
       19456       2010          4         31
         132       2010          3          2
        5654       2010          2          5
         168       2010          1         15

Did I missunderstand you requirements?


问:
InvalidOperationException: An operation is already in progress
I am using Asp.net core Razor engine Entity Framework.  I keep getting the error above and it from what I have read, it refers to the the db already being used for an operation.  I am not sure why this would be happening. Is is because it is in a foreach loop?  What would the workaround be?  Here is my code</p>

```<code>[HttpGet]
[Route("currentSession")]
public IActionResult CurrentSession()
{

    var id = HttpContext.Session.GetInt32("Id");
    if(id != null)
    {
        var user = _context.User.FirstOrDefault(x => x.Id == id);
         ViewBag.User = user;
         ViewBag.User_Id = id;
         ViewBag.Auction = _context.Auction.AsEnumerable();
         foreach(var item in ViewBag.Auction)
         {
             if(item.End_Date < DateTime.Now)
             {
                 var seller_id = (int)item.Id_Of_Seller;
                 var seller = _context.User.FirstOrDefault(x => x.Id == seller_id); //this is the line that causes the error in the title
                 var bidder_id = (int)item.Id_Highest_Bid;
                 var buyer = _context.User.FirstOrDefault(x => x.Id == bidder_id); //this line also causes the same error
                 buyer.Wallet -= item.Bid;
                 seller.Wallet += item.Bid;

                _context.Auction.Remove(item);
                _context.SaveChanges();
             }
         }
         return View("Home");
    }
    return RedirectToAction("LoginPage");
}
</code>```

答:
I added MultipleActiveResultSets=True to my sql server connection strings and this fixed the exception.  No other changes were needed.

This fixed the async methods, the background tasks and IQueryable loops for me.

Body:
I am using Asp.net core Razor engine Entity Framework.  I keep getting the error above and it from what I have read, it refers to the the db already being used for an operation.  I am not sure why this would be happening. Is is because it is in a foreach loop?  What would the workaround be?  Here is my code

[HttpGet]
[Route("currentSession")]
public IActionResult CurrentSession()
{

    var id = HttpContext.Session.GetInt32("Id");
    if(id != null)
    {
        var user = _context.User.FirstOrDefault(x => x.Id == id);
         ViewBag.User = user;
         ViewBag.User_Id = id;
         ViewBag.Auction = _context.Auction.AsEnumerable();
         foreach(var item in ViewBag.Auction)
         {
             if(item.End_Date < DateTime.Now)
             {
                 var seller_id = (int)item.Id_Of_Seller;
                 var seller = _context.User.FirstOrDefault(x => x.Id == seller_id); //this is the line that causes the error in the title
                 var bidder_id = (int)item.Id_Highest_Bid;
                 var buyer = _context.User.FirstOrDefault(x => x.Id == bidder_id); //this line also causes the same error
                 buyer.Wallet -= item.Bid;
                 seller.Wallet += item.Bid;

                _context.Auction.Remove(item);
                _context.SaveChanges();
             }
         }
         return View("Home");
    }
    return RedirectToAction("LoginPage");
}


问:
Pass response of one http request to another Synchronously in Node.js
I want to Pass response of one http request to another Synchronously ,
Have three conditions to execute one by one  PreExecute(),OnExecute() and PostExecute() .

Each of the above will send http request to a URL and returns a json which should be the input to the next module .How to achieve this in Node.js

答:
If each of your three functions returns a promise that is resolved with the result of the async operation, then it's very simple to do using promise chaining:

```<code>PreExecute(...).then(OnExecute).then(PostExecute).then(result => {
    // all done here
}).catch(err => {
    // an error occurred
});
</code>```

In this sequence, the resolved result of PreExecute() will be passed as a single argument to OnExecute() and the resolved result of OnExecute() will be passed as a single argument to PostExecute() and the resolved result of PostExecute() will be passed to the final .then() handler.  If an error occurs in any of the three, that error will be passed to the .catch() handler.  This is a classic use of Promise chaining to sequence asynchronous operations and to pass data down the chain.

If your functions don't already return a promise, then we need to see exactly how one knows they are done (perhaps using a callback) and they can likely be simply wrapped in a promise to make this structure work.

If your PreExecute() function follows the node.js asynchronous calling convention and accepts a callback as its last argument that is called with (err, result) as the arguments, then you can "promisify" those functions fairly easily with util.promisify().  If they don't have any way for the caller to know when their underlying asynchronous operation is complete, then they have to be fixed in order to offer that.  There is no other way to sequence them if they don't provide a means of knowing when they are complete.

Body:
If each of your three functions returns a promise that is resolved with the result of the async operation, then it's very simple to do using promise chaining:

PreExecute(...).then(OnExecute).then(PostExecute).then(result => {
    // all done here
}).catch(err => {
    // an error occurred
});

In this sequence, the resolved result of PreExecute() will be passed as a single argument to OnExecute() and the resolved result of OnExecute() will be passed as a single argument to PostExecute() and the resolved result of PostExecute() will be passed to the final .then() handler.  If an error occurs in any of the three, that error will be passed to the .catch() handler.  This is a classic use of Promise chaining to sequence asynchronous operations and to pass data down the chain.

If your functions don't already return a promise, then we need to see exactly how one knows they are done (perhaps using a callback) and they can likely be simply wrapped in a promise to make this structure work.

If your PreExecute() function follows the node.js asynchronous calling convention and accepts a callback as its last argument that is called with (err, result) as the arguments, then you can "promisify" those functions fairly easily with util.promisify().  If they don't have any way for the caller to know when their underlying asynchronous operation is complete, then they have to be fixed in order to offer that.  There is no other way to sequence them if they don't provide a means of knowing when they are complete.


问:
How to set three different textsize in single textview in android
I want to set the three different text size in single textview as like the below image sample,

I have tried with Html as like the below,

```<code> StringBuilder fontString = new StringBuilder();

    fontString.append("<small>");
    fontString.append("1.78");
    fontString.append("</small>");
    fontString.append("<big><b>");
    fontString.append("33");
    fontString.append("</b></big>");
    fontString.append("<sup>");
    fontString.append("<small>");
    fontString .append("2");
    fontString.append("</small>");
    fontString.append("</sup>");
</code>```

Also I tried SpannableString formatting,

```<code>SpannableString  spanString = new SpannableString("1.34456");
    spanString.setSpan(new RelativeSizeSpan(1.75f), 0,spanString.length()-2-1, 0);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), spanString.length()-2-1, spanString.length()-1, 0);
    spanString.setSpan(new ForegroundColorSpan(Color.RED), spanString.length()-2-1,  spanString.length()-1, 0);
    spanString.setSpan(new RelativeSizeSpan(3f), spanString.length()-2-1, spanString.length()-1, 0);
    spanString.setSpan(new RelativeSizeSpan(1.25f), spanString.length()-1, spanString.length(), 0);
</code>```

like the below mentioned image,

Please suggest me if you know the solution,I have tried with superscript or subscript also but no luck.

答: you use method Html.fromhtml("your html formatted text") It worked for me, thanks.

Body:
I want to set the three different text size in single textview as like the below image sample,

I have tried with Html as like the below,

 StringBuilder fontString = new StringBuilder();

    fontString.append("");
    fontString.append("1.78");
    fontString.append("");
    fontString.append("<big>");
    fontString.append("33");
    fontString.append("</big>");
    fontString.append("");
    fontString.append("");
    fontString .append("2");
    fontString.append("");
    fontString.append("");

Also I tried SpannableString formatting,

SpannableString  spanString = new SpannableString("1.34456");
    spanString.setSpan(new RelativeSizeSpan(1.75f), 0,spanString.length()-2-1, 0);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), spanString.length()-2-1, spanString.length()-1, 0);
    spanString.setSpan(new ForegroundColorSpan(Color.RED), spanString.length()-2-1,  spanString.length()-1, 0);
    spanString.setSpan(new RelativeSizeSpan(3f), spanString.length()-2-1, spanString.length()-1, 0);
    spanString.setSpan(new RelativeSizeSpan(1.25f), spanString.length()-1, spanString.length(), 0);

like the below mentioned image,

Please suggest me if you know the solution,I have tried with superscript or subscript also but no luck.


问:
communication between two containers using another container

I am running a docker server container attached to the server_router network (bridge network driver) and a docker client container attached to the client_router network (bridge network driver). Router container is connected to both server_router and client_router network.

I need this network topology where server and client belong to different docker networks and router is able to connect the server and client containers (actual router which can route server and client traffic). This is needed for network simulation where i am running the simulation on docker containers instead of actual computers. (network simulator being used is TCP Experiment Automation Controlled Using Python (TEACUP) ).

commands used to create the setup:

```<code>docker network create server_router
docker network create client_router
docker run -itd --net client_router --name client ubuntu:14.04
docker run -itd --net server_router --name server ubuntu:14.04
docker run -itd --net server_router --name router ubuntu:14.04
docker network connect client_router router
docker network inspect client_router
docker network inspect server_router
</code>```

representation of the network topology

I am able to ping client container from router container and vice versa, also I am able to ping server container from router container and vice versa (as they belong to the same network).
But I am not able to ping server container from client container and vice versa.

ping command does not show any result.

Any suggestions will be of great help.

答:
It is because you forgot to add network connection from client_router to server

```<code> $ docker network connect client_router server
</code>```

I was able to run things successfully with the following commands.

```<code> $ docker network create server_router
 $ docker network create client_router
 $ docker run -itd --net client_router -h client --name client ubuntu:xenial
 $ docker run -itd --net server_router -h server --name server ubuntu:xenial
 $ docker run -itd --net server_router -h router --name router ubuntu:xenial
 $ docker network connect client_router router
 $ docker network connect client_router server
</code>```

and then able to ping successfully from client to the server

```<code> viswesn@viswesn:~$ docker exec -it client bash
 root@client:/# ping server
 PING server (172.22.0.3) 56(84) bytes of data.
 64 bytes from server.client_router (172.22.0.3): icmp_seq=1 ttl=64 time=0.072 ms
 64 bytes from server.client_router (172.22.0.3): icmp_seq=2 ttl=64 time=0.048 ms
 64 bytes from server.client_router (172.22.0.3): icmp_seq=3 ttl=64 time=0.052 ms
 ^C
</code>```

Body:
I am running a docker server container attached to the server_router network (bridge network driver) and a docker client container attached to the client_router network (bridge network driver). Router container is connected to both server_router and client_router network.

I need this network topology where server and client belong to different docker networks and router is able to connect the server and client containers (actual router which can route server and client traffic). This is needed for network simulation where i am running the simulation on docker containers instead of actual computers. (network simulator being used is TCP Experiment Automation Controlled Using Python (TEACUP) ).

commands used to create the setup:

docker network create server_router
docker network create client_router
docker run -itd --net client_router --name client ubuntu:14.04
docker run -itd --net server_router --name server ubuntu:14.04
docker run -itd --net server_router --name router ubuntu:14.04
docker network connect client_router router
docker network inspect client_router
docker network inspect server_router

representation of the network topology

I am able to ping client container from router container and vice versa, also I am able to ping server container from router container and vice versa (as they belong to the same network).
But I am not able to ping server container from client container and vice versa.

ping command does not show any result.

Any suggestions will be of great help.

Body:
It is because you forgot to add network connection from client_router to server

 $ docker network connect client_router server

I was able to run things successfully with the following commands.

 $ docker network create server_router
 $ docker network create client_router
 $ docker run -itd --net client_router -h client --name client ubuntu:xenial
 $ docker run -itd --net server_router -h server --name server ubuntu:xenial
 $ docker run -itd --net server_router -h router --name router ubuntu:xenial
 $ docker network connect client_router router
 $ docker network connect client_router server

and then able to ping successfully from client to the server

 viswesn@viswesn:~$ docker exec -it client bash
 root@client:/# ping server
 PING server (172.22.0.3) 56(84) bytes of data.
 64 bytes from server.client_router (172.22.0.3): icmp_seq=1 ttl=64 time=0.072 ms
 64 bytes from server.client_router (172.22.0.3): icmp_seq=2 ttl=64 time=0.048 ms
 64 bytes from server.client_router (172.22.0.3): icmp_seq=3 ttl=64 time=0.052 ms
 ^C


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
Apart from the original question, this code, even in it's correct forms will not work, simply due to the fact that tree::nodes (sorry for the C++ notation) as a pointer to a pointer will not point to anything usefull right after a tree as been malloced. So tree->nodes[0] which in the case of ordinary pointers is essentially the same like *(tree->nodes), can't be dereferenced. This is a very strange head for a tree anyway, but you should at least allocate a single node* to initialize that pointer to pointer:

```<code>tree *initTree() {
   /* in C code (not C++), don't have to cast malloc's return pointer, it's implicitly converted from void* */
   tree* atree = malloc(sizeof(struct tree)); /* different names for variables */

   /* ... */

   /* allocate space for numNodes node*, yet numNodes needs to be set to something beforehand */
   atree->nodes = malloc(sizeof(struct node*) * atree->numNodes);

   node* anode = malloc(sizeof(struct node));
   atree->nodes[0] = anode;
   return atree;
}
</code>```

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?

Body:
Apart from the original question, this code, even in it's correct forms will not work, simply due to the fact that tree::nodes (sorry for the C++ notation) as a pointer to a pointer will not point to anything usefull right after a tree as been malloced. So tree->nodes[0] which in the case of ordinary pointers is essentially the same like *(tree->nodes), can't be dereferenced. This is a very strange head for a tree anyway, but you should at least allocate a single node* to initialize that pointer to pointer:

tree *initTree() {
   /* in C code (not C++), don't have to cast malloc's return pointer, it's implicitly converted from void* */
   tree* atree = malloc(sizeof(struct tree)); /* different names for variables */

   /* ... */

   /* allocate space for numNodes node*, yet numNodes needs to be set to something beforehand */
   atree->nodes = malloc(sizeof(struct node*) * atree->numNodes);

   node* anode = malloc(sizeof(struct node));
   atree->nodes[0] = anode;
   return atree;
}


问:
Running Selenium Tests on different browsers using pytest
I'v got UI tests (pytest) and a Selenium grid. And I want to run my suit on differnt browsers at the same time. For example:

```<code>py.test test.py --browser "internet explorer;chrome"
</code>```

I expect two parallel sessions on different hosts in my Selenium grid.

test.py:

```<code>class TestSuit:
    def test_1(self, app):
        app.do_smth()
        assert True

    def test_2(self, app):
        app.do_smth()
        assert True
</code>```

application.py:

```<code>class Application:
    def __init__(self, browser_name):
        self.driver = webdriver.Remote(
            command_executor='http://host:port/wd/hub,
            desired_capabilities={'browserName': browser_name}
        )
</code>```

conftest.py:

```<code>def pytest_addoption(parser):
    parser.addoption("--browser", action="store")

def pytest_generate_tests(metafunc):
    metafunc.parametrize(
        'browser_name',
        metafunc.config.getoption('browser').split(';'),
        scope='session'
    )

@pytest.fixture(scope='session')
def app(browser_name):
    return Application(browser_name)
</code>```

But i get running my tests on the first host with IE and right after on the second with Chrome.

How to run two parallel sessions on each host simultaneously?

答:
You can try threading instead, as the above code will not allow parallel execution.</p>

```<code> import threading

def worker(num):
    """your required work"""
    print  num
    return

threads = []
for i in range(2):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()
</code>```

Body:
I'v got UI tests (pytest) and a Selenium grid. And I want to run my suit on differnt browsers at the same time. For example:

py.test test.py --browser "internet explorer;chrome"

I expect two parallel sessions on different hosts in my Selenium grid.

test.py:

class TestSuit:
    def test_1(self, app):
        app.do_smth()
        assert True

    def test_2(self, app):
        app.do_smth()
        assert True

application.py:

class Application:
    def __init__(self, browser_name):
        self.driver = webdriver.Remote(
            command_executor='http://host:port/wd/hub,
            desired_capabilities={'browserName': browser_name}
        )

conftest.py:

def pytest_addoption(parser):
    parser.addoption("--browser", action="store")

def pytest_generate_tests(metafunc):
    metafunc.parametrize(
        'browser_name',
        metafunc.config.getoption('browser').split(';'),
        scope='session'
    )

@pytest.fixture(scope='session')
def app(browser_name):
    return Application(browser_name)

But i get running my tests on the first host with IE and right after on the second with Chrome.

How to run two parallel sessions on each host simultaneously?

Body:
You can try threading instead, as the above code will not allow parallel execution.

 import threading

def worker(num):
    """your required work"""
    print  num
    return

threads = []
for i in range(2):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()


问:
Bind Listview to ObservableCollection
I am trying to bind a listview to an ObservableCollection.

I took a look at several topics on stack, but cannot find what I am doing wrong :

My XAML looks like that (for GridViewColumn I tried both wih Path=, and without, as I saw both of them) :

```<code><ListView x:Name="ListView1"  ItemsSource="{Binding listeAff}"  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" MouseDoubleClick="ListView_MouseDoubleClick" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" >
            <ListView.ContextMenu>
                <ContextMenu x:Name="Context1">
                    <MenuItem Header="{x:Static p:Resources.ContextSupprimer}" Click="Supprimer_Element"/>
                    <MenuItem x:Name="MenuBarNesting" Header="{x:Static p:Resources.ContextMiseEnBarre}" Click="Open_MiseEnBarre"/>
                    <MenuItem x:Name="MenuExportDSTV1" Header="{x:Static  p:Resources.ContextExport}" Click="Export_DSTV"/>
                    <MenuItem x:Name="AjouterAffaire" Header="{x:Static  p:Resources.AjouterAffaire}" Click="AjoutAffaire"/>
                    <MenuItem x:Name="ModifyAffaire" Header="{x:Static  p:Resources.Edit}" Click="ModifierAffaire"/>
                </ContextMenu>
            </ListView.ContextMenu>
            <ListView.View>

                <GridView AllowsColumnReorder="true" x:Name="GridView1">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=ID}" Header="ID" />
                    <GridViewColumn DisplayMemberBinding= "{Binding Nom}" Header="{x:Static p:Resources.Nom}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Code}" Header="{x:Static p:Resources.Code}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Comm}" Header="{x:Static p:Resources.Commentaire}"/>

                </GridView>
            </ListView.View>
        </ListView>
</code>```

Then code behind is so :

```<code>public ObservableCollection<Affaire> listeAff { get; set; }
        public MainWindow()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.Langue);
            InitializeComponent();
            Initialisation();
            listeAff = new ObservableCollection<Affaire>();
            DBConnect DataBase = new DBConnect();
            string requete = "SELECT * FROM affaire ORDER BY ID";
            List<Affaire> liste = DataBase.Select_affaire(requete);
            foreach(Affaire aff in liste)
            {
                listeAff.Add(aff);
            }
            DataContext = this;
</code>```

On that part my ListView is shown correctly, but when I want to delete(for example) some objects in list, listview is not updated :

```<code>foreach (Affaire aff in ListView1.SelectedItems)
                    {
                        listeAff.Remove(aff);
                    }
</code>```

What did I miss?

答:
you have to do as below for getting updated values </p>

```<code>public class ChangeViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged=delegate {};

    private void NotifyPropertyChanged([CallerMemberName] String
                                                  propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new
                 PropertyChangedEventArgs(propertyName));
        }
    }

    ObservableCollection<Affaire> affaireListObservable;
    public ObservableCollection<Affaire> AffaireListObservable {
      get { return affaireListObservable; }
      set {
        affaireListObservable= value;
        if(PropertyChanged!=null) {
          NotifyPropertyChanged();
        }
      }
    }
    public ChangeViewModel()
    {
        AffaireListObservable  = new ObservableCollection<Affaire>();
    }
    public void RemoveFromList()
    {
         foreach (Affaire aff in ListView1.SelectedItems)
         {
              AffaireListObservable.Remove(aff);
         }
    }
}
</code>```

<p>Double check you binding , As you are assigning DataContext to widnow, than you can go up in tree till window and use it , and bind you listview to DataContext of window </p>

```<code><ListView ItemsSource="{Binding Path=DataContext.listeAff ,
        RelativeSource={RelativeSource
   Mode=FindAncestor,AncestorType=Window}}"
  />
</code>```

Title: Bind Listview to ObservableCollection

Body:
I am trying to bind a listview to an ObservableCollection.

I took a look at several topics on stack, but cannot find what I am doing wrong :

My XAML looks like that (for GridViewColumn I tried both wih Path=, and without, as I saw both of them) :

<ListView x:Name="ListView1"  ItemsSource="{Binding listeAff}"  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" MouseDoubleClick="ListView_MouseDoubleClick" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" >
            <ListView.ContextMenu>
                <ContextMenu x:Name="Context1">
                    <MenuItem Header="{x:Static p:Resources.ContextSupprimer}" Click="Supprimer_Element"/>
                    <MenuItem x:Name="MenuBarNesting" Header="{x:Static p:Resources.ContextMiseEnBarre}" Click="Open_MiseEnBarre"/>
                    <MenuItem x:Name="MenuExportDSTV1" Header="{x:Static  p:Resources.ContextExport}" Click="Export_DSTV"/>
                    <MenuItem x:Name="AjouterAffaire" Header="{x:Static  p:Resources.AjouterAffaire}" Click="AjoutAffaire"/>
                    <MenuItem x:Name="ModifyAffaire" Header="{x:Static  p:Resources.Edit}" Click="ModifierAffaire"/>
                </ContextMenu>
            </ListView.ContextMenu>
            <ListView.View>

                <GridView AllowsColumnReorder="true" x:Name="GridView1">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=ID}" Header="ID" />
                    <GridViewColumn DisplayMemberBinding= "{Binding Nom}" Header="{x:Static p:Resources.Nom}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Code}" Header="{x:Static p:Resources.Code}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Comm}" Header="{x:Static p:Resources.Commentaire}"/>

                </GridView>
            </ListView.View>
        </ListView>

Then code behind is so :

public ObservableCollection<Affaire> listeAff { get; set; }
        public MainWindow()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.Langue);
            InitializeComponent();
            Initialisation();
            listeAff = new ObservableCollection<Affaire>();
            DBConnect DataBase = new DBConnect();
            string requete = "SELECT * FROM affaire ORDER BY ID";
            List<Affaire> liste = DataBase.Select_affaire(requete);
            foreach(Affaire aff in liste)
            {
                listeAff.Add(aff);
            }
            DataContext = this;

On that part my ListView is shown correctly, but when I want to delete(for example) some objects in list, listview is not updated :

foreach (Affaire aff in ListView1.SelectedItems)
                    {
                        listeAff.Remove(aff);
                    }

What did I miss?

Body:
you have to do as below for getting updated values

public class ChangeViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged=delegate {};

    private void NotifyPropertyChanged([CallerMemberName] String
                                                  propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new
                 PropertyChangedEventArgs(propertyName));
        }
    }

    ObservableCollection<Affaire> affaireListObservable;
    public ObservableCollection<Affaire> AffaireListObservable {
      get { return affaireListObservable; }
      set {
        affaireListObservable= value;
        if(PropertyChanged!=null) {
          NotifyPropertyChanged();
        }
      }
    }
    public ChangeViewModel()
    {
        AffaireListObservable  = new ObservableCollection<Affaire>();
    }
    public void RemoveFromList()
    {
         foreach (Affaire aff in ListView1.SelectedItems)
         {
              AffaireListObservable.Remove(aff);
         }
    }
}

Double check you binding , As you are assigning DataContext to widnow, than you can go up in tree till window and use it , and bind you listview to DataContext of window

<ListView ItemsSource="{Binding Path=DataContext.listeAff ,
        RelativeSource={RelativeSource
   Mode=FindAncestor,AncestorType=Window}}"
  />


问:
Re-organize Charts in VSTS Queries
I've created a few charts in a VSTS Query but I can't figure out how to re-organize them.  Is that possible?

For example, I want to move 'Task Person Status 2' to the right of 'Task Person Status'.

答:
For now, the order of the charts can not be changed. It’s ordered by the chart created date.

So If you want to move Task Person Status 2 to the right of the Task Person Status, you should delete the chart Task Person Status 2 and then create a new chart (method for now).

And I posted an user voice Enable to change query charts order for this feature, you can vote and follow up.

Title: Re-organize Charts in VSTS Queries


问:
key is not available as prop in the Child component in ReactJs
I have a parent component in which below component is producing dynamically in map function as below:

```<code>const renderListing = this.props.listing.map(function(list, index) {
        return (
          <Listing
            key={index}
            title={list.title}
            totalWorkers={list.totalWorkers}
          />
        );
      }, this);
</code>```

In this <Listing /> component, I have a Checkbox from react-md as below:

```<code>import { Checkbox } from "react-md";
class Listing extends React.Component {
  render() {
    return (
<Checkbox id="`listSector-${this.props.key}`" name="list-sector" />
   );
  }
}
</code>```

I wanted to give the props named key concatenated with id="listSector-0" , id="listSector-1" and so on.

I have tried string-literals but all invain.

Can anyone know that how to give dynamic this.props.key concatenated with id of the checkbox ?

Thanks

答:
'key' and 'ref' are reserved words that are not allowed to be passed as props. You can pass another prop with the same value

```<code>const renderListing = this.props.listing.map(function(list, index) {
    return (
      <Listing
        key={index}
        keyId={index}
        title={list.title}
        totalWorkers={list.totalWorkers}
      />
    );
  }, this);
</code>```

and use it like

```<code><Checkbox id="`listSector-${this.props.keyId}`" name="list-sector" />
</code>```

Body:
I have a parent component in which below component is producing dynamically in map function as below:

const renderListing = this.props.listing.map(function(list, index) {
        return (
          <Listing
            key={index}
            title={list.title}
            totalWorkers={list.totalWorkers}
          />
        );
      }, this);

In this <Listing /> component, I have a Checkbox from react-md as below:

import { Checkbox } from "react-md";
class Listing extends React.Component {
  render() {
    return (
<Checkbox id="`listSector-${this.props.key}`" name="list-sector" />
   );
  }
}

I wanted to give the props named key concatenated with id="listSector-0" , id="listSector-1" and so on.

I have tried string-literals but all invain.

Can anyone know that how to give dynamic this.props.key concatenated with id of the checkbox ?

Thanks

Body:
'key' and 'ref' are reserved words that are not allowed to be passed as props. You can pass another prop with the same value

const renderListing = this.props.listing.map(function(list, index) {
    return (
      <Listing
        key={index}
        keyId={index}
        title={list.title}
        totalWorkers={list.totalWorkers}
      />
    );
  }, this);

and use it like

<Checkbox id="`listSector-${this.props.keyId}`" name="list-sector" />


问:
XML Layouting for a textview and 2 imageviews
I need to make a layout with a single lined TextView and 2 ImageViews. They need to be in the following order: TextView | ImageView1 | [Remaining space] | ImageView2

All this with the constraint that in case of the text overflow in the TextView the 1st ImageView gets pushed and sticks to the 2nd one and the overflowing text gets trimmed and shows up with an ellipsis. Something like this: Trimmed TextView... | ImageView1 | ImageView2

For better clarity of the instances, here's an illustration:

How should the layouting be done for this particular use case?

答:
Try this :

Output1 :

Output2 :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/layout_message"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tv_message"
                style="@style/TextAppearance.AppCompat.Body1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="30dp"
                android:ellipsize="end"
                android:lines="1"
                android:text="Hello Mike bla bla bla  bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla " />

            <ImageView
                android:id="@+id/tv_msg_time"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@drawable/done_all"
                android:layout_alignRight="@+id/tv_message"
                android:textColor="@android:color/black"
                android:textSize="10sp" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.1"
            android:gravity="end">

            <ImageView
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@drawable/job_like" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</code>```

Body:
Try this :

Output1 :

Output2 :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorWhite"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/layout_message"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tv_message"
                style="@style/TextAppearance.AppCompat.Body1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingRight="30dp"
                android:ellipsize="end"
                android:lines="1"
                android:text="Hello Mike bla bla bla  bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla " />

            <ImageView
                android:id="@+id/tv_msg_time"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@drawable/done_all"
                android:layout_alignRight="@+id/tv_message"
                android:textColor="@android:color/black"
                android:textSize="10sp" />

        </RelativeLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.1"
            android:gravity="end">

            <ImageView
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:src="@drawable/job_like" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>


问:
How to make an image of the current rendered map (mapbox-android)?
Is it possible to make a png or data-url of the current view on the map?</p>

答:
You can simply save the current map as a .png, by taking a screenshot (MapboxMap#snapshot) after the map has loaded.

Ensure you've got the appropriate build.gradle dependency:

```<code>implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:5.3.0-SNAPSHOT@aar'){
    transitive = true
}
</code>```

Code for capturing the map:

```<code>private void captureScreen() {

    mMapBoxMap.snapshot(new MapboxMap.SnapshotReadyCallback() {
        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            ImageView snapshotView = (ImageView) findViewById(R.id.);
            snapshotView.setImageBitmap(snapshot);
        }
    });
}
</code>```

Hope this helps you.

Body:
You can simply save the current map as a .png, by taking a screenshot (MapboxMap#snapshot) after the map has loaded.

Ensure you've got the appropriate build.gradle dependency:

implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:5.3.0-SNAPSHOT@aar'){
    transitive = true
}

Code for capturing the map:

private void captureScreen() {

    mMapBoxMap.snapshot(new MapboxMap.SnapshotReadyCallback() {
        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            ImageView snapshotView = (ImageView) findViewById(R.id.);
            snapshotView.setImageBitmap(snapshot);
        }
    });
}

Hope this helps you.


问:
Change number of classes of MNIST Tensorflow

Hi, Im trying to adapt the beginners tutorial of Tensorflow with MNIST and softmax. In the tutorial you have 10 clases (for digits 0-9).
Now, with a different dataset (EMNIST) I have 62 classes for digits and letters.

What I have in the model of the orginal example is:

```<code>x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b`
</code>```

Where 784 stands for the total pixels of a 28x28 image and 10 is the number of classes. What I want is:

```<code>x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 62]))
b = tf.Variable(tf.zeros([62]))
y = tf.matmul(x, W) + b`
</code>```

For 62 classes.

But when I reach this part of the code, where the next batch is called for execution:

```<code>  for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
</code>```

I get this error...
    Traceback (most recent call last):

```<code>File "calligraphy.py", line 77, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\Willy Barales\Anaconda3\lib\site-packages\tensorflow\python\platform\app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "calligraphy.py", line 64, in main
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  File "C:\Users\Willy Barales\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 789, in run
    run_metadata_ptr)
  File "C:\Users\Willy Barales\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 975, in _run
    % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (100, 10) for Tensor 'Placeholder_1:0', which has shape '(?, 62)'
</code>```

Any ideas on how to change the dataset for this example?
Do I have to change something in the mnist.py file where .next_batch() is implemented?

As far as I know, EMNIST has the exact same format as MNIST.
Thanks in advance.

Info on the new dataset:
http://biometrics.nist.gov/cs_links/EMNIST/Readme.txt

答:
All I have to do was to edit in the mnist.py file the part where the one hot vectors were created from labels, since those are the ones corresponding to batch_ys, thanks to the enlightment of Neijla. </p>

```<code>def extract_labels(f, one_hot=False, num_classes=62)
</code>```

<p>Besides of course, changing the number of the classes in the model as I stated first in my question. </p>

Body:
Hi, Im trying to adapt the beginners tutorial of Tensorflow with MNIST and softmax. In the tutorial you have 10 clases (for digits 0-9).
Now, with a different dataset (EMNIST) I have 62 classes for digits and letters.

What I have in the model of the orginal example is:

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b`

Where 784 stands for the total pixels of a 28x28 image and 10 is the number of classes. What I want is:

x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 62]))
b = tf.Variable(tf.zeros([62]))
y = tf.matmul(x, W) + b`

For 62 classes.

But when I reach this part of the code, where the next batch is called for execution:

  for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

I get this error...
    Traceback (most recent call last):

File "calligraphy.py", line 77, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\Willy Barales\Anaconda3\lib\site-packages\tensorflow\python\platform\app.py", line 48, in run
    _sys.exit(main(_sys.argv[:1] + flags_passthrough))
  File "calligraphy.py", line 64, in main
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  File "C:\Users\Willy Barales\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 789, in run
    run_metadata_ptr)
  File "C:\Users\Willy Barales\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 975, in _run
    % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (100, 10) for Tensor 'Placeholder_1:0', which has shape '(?, 62)'

Any ideas on how to change the dataset for this example?
Do I have to change something in the mnist.py file where .next_batch() is implemented?

As far as I know, EMNIST has the exact same format as MNIST.
Thanks in advance.

Info on the new dataset:
http://biometrics.nist.gov/cs_links/EMNIST/Readme.txt

Body:
All I have to do was to edit in the mnist.py file the part where the one hot vectors were created from labels, since those are the ones corresponding to batch_ys, thanks to the enlightment of Neijla.

def extract_labels(f, one_hot=False, num_classes=62)

Besides of course, changing the number of the classes in the model as I stated first in my question.


问:
Get File Extension C#
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

```<code>string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
</code>```

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

```<code>string filename = ddl.SelectedItem.Text;
</code>```

2.) Path where the file is located

```<code>string path = "F:\\WorkingCopy\\files\\" + filename
</code>```

I am trying to get the file extension with these . Can any one suggest on this?

答:
You can use Directory.EnumerateFiles() like this:

```<code>string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;

string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();

if (!string.IsNullOrEmpty(existingFile))
    Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));
</code>```

Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.

In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).

Title: Get File Extension C#

Body:
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

string filename = ddl.SelectedItem.Text;

2.) Path where the file is located

string path = "F:\\WorkingCopy\\files\\" + filename

I am trying to get the file extension with these . Can any one suggest on this?

Body:
You can use Directory.EnumerateFiles() like this:

string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;

string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();

if (!string.IsNullOrEmpty(existingFile))
    Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));

Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.

In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).