问:
Do Loop and If Statement in Excel
In the WorkSheet, I'm trying to create the following logic in Excel Macro.

Logic:

```<code>Dub Test()

Dim rws as integer
Dim counter as integer

rws = 6
counter = 2

Do while rws <> 0
    IF 'Data Sheet with Space'!J`counter` = "Sample Data Row 1 Col 10" Then
        WorkSheet!A`counter` = 'Data Sheet with Space'!A`counter`
    end IF

    counter = counter + 1
    rws = rws - 1
</code>```

The Excel sheets are:

Data Sheet with Space

```<code>---------------------------------------------
Header 1                 Header 2                 Header 3                 Header 4                 Header 5                 Header 6                 Header 7                 Header 8                 Header 9                 Header 10
Sample Data Row 1 Col 1  Sample Data Row 1 Col 2  Sample Data Row 1 Col 3  Sample Data Row 1 Col 4  Sample Data Row 1 Col 5  Sample Data Row 1 Col 6  Sample Data Row 1 Col 7  Sample Data Row 1 Col 8  Sample Data Row 1 Col 9  Sample Data Row 1 Col 10
Sample Data Row 2 Col 1  Sample Data Row 2 Col 2  Sample Data Row 2 Col 3  Sample Data Row 2 Col 4  Sample Data Row 2 Col 5  Sample Data Row 2 Col 6  Sample Data Row 2 Col 7  Sample Data Row 2 Col 8  Sample Data Row 2 Col 9  Sample Data Row 2 Col 10
Sample Data Row 3 Col 1  Sample Data Row 3 Col 2  Sample Data Row 3 Col 3  Sample Data Row 3 Col 4  Sample Data Row 3 Col 5  Sample Data Row 3 Col 6  Sample Data Row 3 Col 7  Sample Data Row 3 Col 8  Sample Data Row 3 Col 9  Sample Data Row 3 Col 10
Sample Data Row 4 Col 1  Sample Data Row 4 Col 2  Sample Data Row 4 Col 3  Sample Data Row 4 Col 4  Sample Data Row 4 Col 5  Sample Data Row 4 Col 6  Sample Data Row 4 Col 7  Sample Data Row 4 Col 8  Sample Data Row 4 Col 9  Sample Data Row 4 Col 10
Sample Data Row 5 Col 1  Sample Data Row 5 Col 2  Sample Data Row 5 Col 3  Sample Data Row 5 Col 4  Sample Data Row 5 Col 5  Sample Data Row 5 Col 6  Sample Data Row 5 Col 7  Sample Data Row 5 Col 8  Sample Data Row 5 Col 9  Sample Data Row 5 Col 10
---------------------------------------------
</code>```

and the other Excel sheet called WorkSheet

When trying to run the macro I get an error the ' in the Data Sheet with Space name causes an error.

Secondly, I an having an error when trying to change the input and output cell number dynamically using the counter variable.

Any help is appreciate it.

答:
The error comes from your ' in the code. (Easily visible already here in grey). If I understood your code correctly then you should correct it by entering real sheets and range as below (not tested):</p>

```<code>Sub Test2()

Dim rws As Integer
Dim counter As Integer

rws = 6
counter = 2

Do While rws <> 0

If Sheets("Data Sheet with Space").Range("J" & counter).Value = Cells(1, 10).Value Then

Sheets("WorkSheet").Range("A" & counter).Value = Sheets("Data Sheet with Space").Range("A" & counter).Value

End If

counter = counter + 1
rws = rws - 1
Loop

End Sub
</code>```

Title: Do Loop and If Statement in Excel

Body:
In the WorkSheet, I'm trying to create the following logic in Excel Macro.

Logic:

Dub Test()

Dim rws as integer
Dim counter as integer

rws = 6
counter = 2

Do while rws <> 0
    IF 'Data Sheet with Space'!J`counter` = "Sample Data Row 1 Col 10" Then
        WorkSheet!A`counter` = 'Data Sheet with Space'!A`counter`
    end IF

    counter = counter + 1
    rws = rws - 1

The Excel sheets are:

Data Sheet with Space

---------------------------------------------
Header 1                 Header 2                 Header 3                 Header 4                 Header 5                 Header 6                 Header 7                 Header 8                 Header 9                 Header 10
Sample Data Row 1 Col 1  Sample Data Row 1 Col 2  Sample Data Row 1 Col 3  Sample Data Row 1 Col 4  Sample Data Row 1 Col 5  Sample Data Row 1 Col 6  Sample Data Row 1 Col 7  Sample Data Row 1 Col 8  Sample Data Row 1 Col 9  Sample Data Row 1 Col 10
Sample Data Row 2 Col 1  Sample Data Row 2 Col 2  Sample Data Row 2 Col 3  Sample Data Row 2 Col 4  Sample Data Row 2 Col 5  Sample Data Row 2 Col 6  Sample Data Row 2 Col 7  Sample Data Row 2 Col 8  Sample Data Row 2 Col 9  Sample Data Row 2 Col 10
Sample Data Row 3 Col 1  Sample Data Row 3 Col 2  Sample Data Row 3 Col 3  Sample Data Row 3 Col 4  Sample Data Row 3 Col 5  Sample Data Row 3 Col 6  Sample Data Row 3 Col 7  Sample Data Row 3 Col 8  Sample Data Row 3 Col 9  Sample Data Row 3 Col 10
Sample Data Row 4 Col 1  Sample Data Row 4 Col 2  Sample Data Row 4 Col 3  Sample Data Row 4 Col 4  Sample Data Row 4 Col 5  Sample Data Row 4 Col 6  Sample Data Row 4 Col 7  Sample Data Row 4 Col 8  Sample Data Row 4 Col 9  Sample Data Row 4 Col 10
Sample Data Row 5 Col 1  Sample Data Row 5 Col 2  Sample Data Row 5 Col 3  Sample Data Row 5 Col 4  Sample Data Row 5 Col 5  Sample Data Row 5 Col 6  Sample Data Row 5 Col 7  Sample Data Row 5 Col 8  Sample Data Row 5 Col 9  Sample Data Row 5 Col 10
---------------------------------------------

and the other Excel sheet called WorkSheet

When trying to run the macro I get an error the ' in the Data Sheet with Space name causes an error.

Secondly, I an having an error when trying to change the input and output cell number dynamically using the counter variable.

Any help is appreciate it.

Body:
The error comes from your ' in the code. (Easily visible already here in grey). If I understood your code correctly then you should correct it by entering real sheets and range as below (not tested):

Sub Test2()

Dim rws As Integer
Dim counter As Integer

rws = 6
counter = 2

Do While rws <> 0

If Sheets("Data Sheet with Space").Range("J" & counter).Value = Cells(1, 10).Value Then

Sheets("WorkSheet").Range("A" & counter).Value = Sheets("Data Sheet with Space").Range("A" & counter).Value

End If

counter = counter + 1
rws = rws - 1
Loop

End Sub


来源: stackexchange

问:
Only one expression can be specified in the select list when the sub-query is not introduced with EXISTS
```<code>SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2
</code>```

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

答:
Use conditional aggregation:

```<code>SELECT
    SUM(CASE WHEN t2.EDUCATION_LEVEL = 5
             THEN 1 ELSE 0 END) AS Total_HH_Members_Primary,
    SUM(CASE WHEN t2.EDUCATION_LEVEL = 10
             THEN 1 ELSE 0 END) AS Total_HH_Members_Secondary,
    t1.SETTLEMENT_ID
FROM PScData t1
INNER JOIN PscMemberData t2
    ON t2._PARENT_AURI = t1.URI
GROUP BY
    t1.SETTLEMENT_ID
HAVING COUNT(*) > 1;
</code>```

The two subqueries in the select clause look totally unnecessary to me.  And also I think we can remove the EXISTS clause, and move the HAVING clause to the outer query.

ContentLicense: CC BY-SA 3.0

Body:
SELECT
  ( Select
COUNT(t2.ID) as Total_HH_Memebers_Primary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 5
               HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID
) col1

  , (Select
COUNT(t2.ID) as Total_HH_Memebers_Secondary,t1.SETTLEMENT_ID
from
PScData t1
INNER JOIN
PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
 WHERE  EXISTS (SELECT 1
               FROM   PScData t1
               WHERE  t1.SETTLEMENT_ID = SETTLEMENT_ID
                AND t2.EDUCATION_LEVEL = 10
              HAVING Count(*) > 1)
               Group By t1.SETTLEMENT_ID

) col2

Here is my query, i want to get two different results based on "WHERE" condition from same table in the form of columns when i do this its giving this error .can somebody how to it correctly?

Body:
Use conditional aggregation:

SELECT
    SUM(CASE WHEN t2.EDUCATION_LEVEL = 5
             THEN 1 ELSE 0 END) AS Total_HH_Members_Primary,
    SUM(CASE WHEN t2.EDUCATION_LEVEL = 10
             THEN 1 ELSE 0 END) AS Total_HH_Members_Secondary,
    t1.SETTLEMENT_ID
FROM PScData t1
INNER JOIN PscMemberData t2
    ON t2._PARENT_AURI = t1.URI
GROUP BY
    t1.SETTLEMENT_ID
HAVING COUNT(*) > 1;

The two subqueries in the select clause look totally unnecessary to me.  And also I think we can remove the EXISTS clause, and move the HAVING clause to the outer query.


问:
docker logs multiple containers
I have a requirement where data gets loaded into the system using load balanced docker containers. We have multiple images of docker running on different instances either of which picks up the job and load data. The data loading process is reflected in "docker logs -f", but I need to check all the container logs manually and then figure out which container is active and loading data to tail for logs.

Is there a way though which I check which docker is active and tail it for logs. Or may be merge all the container logs into a single and then tail it.
I have good understanding on shell so any pointers would be helpful.

Please let me know if further details needed.
Thanks

答: Assuming you use docker compose you should be able to do docker service logs to see logs from any container making up a service.

Title: docker logs multiple containers


问:
Migrate Firebase Realtime Database to Firestore
I am looking for the best way to migrate my apps database which is using firebase realtime database to the new Cloud Firestore database. I am confident for the project I am working on I don't need to make any data schema changes, so I am pretty much just trying to 1-1 map it. Firebase has suggested on their site to just write a script to do this, but I am not sure of the best way to go about that. Has anyone already made a script that accomplishes this?</p>

答:
Hi i have created a script for the same </p>

```<code>import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { AngularFireDatabase } from 'angularfire2/database';
constructor( private afs: AngularFirestore, private angularfire: AngularFireDatabase ) {}
convert() {
this.itemsCollection = this.afs.collection('requests');//ref()
this.angularfire.list('/requests/').auditTrail().subscribe((data: any) => {
_.each(data, element =>{
this.itemsCollection.doc(element.key).set(element.payload.val()) .then((result) => { }); }); });}
</code>```

Body:
Hi i have created a script for the same

import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { AngularFireDatabase } from 'angularfire2/database';
constructor( private afs: AngularFirestore, private angularfire: AngularFireDatabase ) {}
convert() {
this.itemsCollection = this.afs.collection('requests');//ref()
this.angularfire.list('/requests/').auditTrail().subscribe((data: any) => {
_.each(data, element =>{
this.itemsCollection.doc(element.key).set(element.payload.val()) .then((result) => { }); }); });}


问:
my character is not moving
I have this code and trying to move my character using jquery inside for loop. If I separate the code, it kind of works, but to me, this code still looks ok. I really don't get why it doesn't move.</p>

```<code>let currentX = $('character').css('left');
for(i=0; i<100; i++){
      setTimeout(function(){
        $('.character').css('left',currentX+=3);   //move to right

        if(i>33){
          $('.character').css('left',currentX-=3); //move to left

}else if (i >66){
          if($('.character').css({'background-image':'url(https://gameartpartners.com/wp-content/uploads/edd/2015/03/Golden_Knight_featured.png)'})){
            $('.character').css({'background-image':'url(old-man-game-character.png)'});
          }else{

          $('.character').css('left',currentX+=3);
        }
        }
      },200*i);
  }
</code>```

答:
Try changing

```<code>let currentX = $('character').css('left');
</code>```

to

```<code>let currentX = $('.character').css('left');
</code>```

You missed the class specifier.

Title: my character is not moving

Body:
I have this code and trying to move my character using jquery inside for loop. If I separate the code, it kind of works, but to me, this code still looks ok. I really don't get why it doesn't move.

let currentX = $('character').css('left');
for(i=0; i<100; i++){
      setTimeout(function(){
        $('.character').css('left',currentX+=3);   //move to right

        if(i>33){
          $('.character').css('left',currentX-=3); //move to left

}else if (i >66){
          if($('.character').css({'background-image':'url(https://gameartpartners.com/wp-content/uploads/edd/2015/03/Golden_Knight_featured.png)'})){
            $('.character').css({'background-image':'url(old-man-game-character.png)'});
          }else{

          $('.character').css('left',currentX+=3);
        }
        }
      },200*i);
  }

Body:
Try changing

let currentX = $('character').css('left');

to

let currentX = $('.character').css('left');

You missed the class specifier.


问:
Resources for TDD aimed at Python Web Development
I am a hacker not and not a full-time programmer but am looking to start my own full application development experiment. I apologize if I am missing something easy here. I am looking for recommendations for books, articles, sites, etc for learning more about test driven development specifically compatible with or aimed at Python web application programming. I understand that Python has built-in tools to assist. What would be the best way to learn about these outside of RTFM? I have searched on StackOverflow and found the Kent Beck's and David Astels book on the subject. I have also bookmarked the Wikipedia article as it has many of these types of resources.

Are there any particular ones you would recommend for this language/application?

答:
I know that Kent Beck's book (which you mentioned) covers TDD in Python to some pretty good depth.  If I remember correctly, the last half of the book takes you through development of a unit test framework in Python.  There's nothing specific to web development, though, which is a problem in many TDD resources that I've read.  It's a best practice to keep your business logic separate from your presentation in order to make your BL more testable, among other reasons.

Another good book that you might want to look into is xUnit Test Patterns.  It doesn't use Python, but it does talk a lot about designing for testability, how to use mocks and stubs (which you'll need for testing web applications), and automating testing.  It's more advanced than Beck's book, which makes it a good follow-up.

OwnerDisplayName: Null Route

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bill the Lizard


问:
architecture for high availability
I have this scenario:

You have a factory process line which runs 24/7. Downtime is extremely expensive.
The software controlling all different parts must use a shared form of database storage
The main reason for this is to know in which state the factory is in.  For example some products can be mixed when using the same set of equipement and others DEFINITELY not.

requirements:

I want to the software be able to detect that an error in one part of
the plant must result in some machine shutdown more then 1 km away. so stoing data in the plc's is not an option.

Updates and upgrades to the factory environment are frequent

load (in computer terms) will be really low.

The systems handles a few hunderd assignments a day for which calculations / checks are done followed by instructions send for the factory machines. Systems will be bored most of the time. Most important requirement is the central computer system must be correct and always working.

I was thinking to use a dynamo based database (riak or cassandra) where data gets written to multiple machines with each machine having the whole database

When one system goes down it will go down unoticed. A Traditional sql databse might be more of a pain to upgrade when tables changes and this master slave is harder to configure.

What would be your solution?

Network has been made redundant and most other single points of failure to. The database system is critical because downtime of the db means downtime for the entire plant not just one of the machines which is acceptable.

How to solve shared state problem.

complexity in the database will not be a problem. I will be more like a simple key value store to get the most current and correct data.

答:
Use an established RDBMS that supports such things natively

Do you really want to run a 24/7 mission critical system on something that may be consistent at any point in time?

Title: architecture for high availability


问:
How to count the number of comparisons happening when organizing an array?
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modiﬁed sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.

```<code>import java.util.Scanner;
public class Lab11
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        final int Size = 10;
        double [] scores = new double[Size];
        // set all the scores to a random number [0 - 99]
        for (int s = 0; s < Size; ++s)
            scores[s] = (int)(Math.random() * 100);
        // print the scores - original order
        System.out.println("Scores - Original");
        System.out.println("------------------");
        printArray(scores, Size);
        System.out.println("\n");
        // sort the scores
        System.out.println("Sorting ...\n");
        // print the scores - sorted order
        sortArray(scores, Size);
        System.out.println("Size of array = " + Size);
        System.out.println("Comparisons needed =   \n");
        System.out.println("Scores - Sorted");
        System.out.println("----------------");
        printArray(scores, Size);
        System.out.println("\n");
        stdIn.close();
    }
    public static void printArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
            System.out.println(arr[i]);
    }
    public static int findMinLoc(double [] arr, int startInd, int     endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
    public static void swapInArray(double [] arr, int ind1, int ind2)
    {
        double tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
    public static void sortArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
        {
            int ind = findMinLoc(arr, i, eSize-1);
            swapInArray(arr, i, ind);
        }
    }
}
</code>```

It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...

Size of array = 10
Comparisions needed = 55

Scores - Sorted

19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0

each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?

答:
Just define static count variable globally and add increment the count in the finfMinLoc function as below:

```<code>static int count=0;

public static int findMinLoc(double [] arr, int startInd, int endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            count++;
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
</code>```

And add the count variable in print statement:

```<code>System.out.println("Comparisons needed =   \n" +count);
</code>```

Body:
I have this java code that sorts a set of random scores. What I need to do is modify sortArray so that it returns the total number of comparisons that were made during its calls to findMinLoc and modify the main to call the modiﬁed sortArray correctly, capturing the number of comparisons total into a variable. I am very new to programming and I'm having a complete block on how to do this. I've attempted to use a counter however it always displays only the amount of scores not how many comparisons were made to put the array in order.

import java.util.Scanner;
public class Lab11
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        final int Size = 10;
        double [] scores = new double[Size];
        // set all the scores to a random number [0 - 99]
        for (int s = 0; s < Size; ++s)
            scores[s] = (int)(Math.random() * 100);
        // print the scores - original order
        System.out.println("Scores - Original");
        System.out.println("------------------");
        printArray(scores, Size);
        System.out.println("\n");
        // sort the scores
        System.out.println("Sorting ...\n");
        // print the scores - sorted order
        sortArray(scores, Size);
        System.out.println("Size of array = " + Size);
        System.out.println("Comparisons needed =   \n");
        System.out.println("Scores - Sorted");
        System.out.println("----------------");
        printArray(scores, Size);
        System.out.println("\n");
        stdIn.close();
    }
    public static void printArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
            System.out.println(arr[i]);
    }
    public static int findMinLoc(double [] arr, int startInd, int     endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }
    public static void swapInArray(double [] arr, int ind1, int ind2)
    {
        double tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
    public static void sortArray(double [] arr, int eSize)
    {
        for (int i = 0; i < eSize; ++i)
        {
            int ind = findMinLoc(arr, i, eSize-1);
            swapInArray(arr, i, ind);
        }
    }
}

It should look something like..
Scores - Original -----------------
69.0
56.0
19.0
70.0
88.0
86.0
56.0
19.0
79.0
20.0
Sorting ...

Size of array = 10
Comparisions needed = 55

Scores - Sorted

19.0
19.0
20.0
56.0
56.0
69.0
70.0
79.0
86.0
88.0

each method I tried always came up with the caparisons needed being 10 and I don't understand why. Any suggestions on how to solve this?

Body:
Just define static count variable globally and add increment the count in the finfMinLoc function as below:

static int count=0;

public static int findMinLoc(double [] arr, int startInd, int endInd)
    {
        int minLoc = startInd;
        for (int i = startInd; i <= endInd; ++i)
        {
            count++;
            if (arr[i] < arr[minLoc])
                minLoc = i;
        }
        return minLoc;
    }

And add the count variable in print statement:

System.out.println("Comparisons needed =   \n" +count);


问:
Use of undeclared identifier 'NSButtonCell'
I am trying to implement some radio button functionality. I found this page but when I try to use the classes NSButtonCell, NSRect and NSMatrix I get the error:

Use of undeclared identifier 'NSButtonCell'

Use of undeclared identifier 'NSRect'

Use of undeclared identifier 'NSMatrix'

I tried to import AppKit/AppKit.h but I get file not found. After reading this I changed it to UIKit/UIKit.h but the problem remains.

How can I solve this?

答:
NSButton is only for mac applications, i think.

Create uibutton with background image. It will be easier and simple.


问:
How to ignore the fail case and continues to next value
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

```<code>open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================
</code>```

答:
The way I understood your question was that you cycle through items fetched from Excel. Sometimes the item in Excel does not exist in the application. If that is the case, then skip the checks for that item and fetch the next item from excel.

As correctly referenced by @pankaj mishra, the keyword Run Keyword and Ignore Error should be used. This keyword outputs 2 values (this is why you see 2 variables before it). The first one contains the status and the second one the actual value.

This is then used by the keyword Continue For Loop which breaks off this cycle when the keyword returned an error (FAIL). All the checks that followed (represented by the logging step) are then skipped.

```<code>*** Test Cases ***
TC
    @{list}    Create List    ${3}    ${6}    ${15}   ${21}
    Log To Console  \n
    :FOR    ${id}    IN    @{list}
    \    ${status}    ${result}
    \    ...    Run Keyword And Ignore Error    Mock Element Exists    ${id}
    \
    \    Continue For Loop If    '${status}' == 'FAIL'
    \    Log To Console   No Failure for ${id}

*** Keywords ***
Mock Element Exists
    [Arguments]    ${id}
    &{dic}    Create Dictionary    3=1    6=2    18=6    21=7
    [Return]   ${dic['${id}']}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================

Body:
The way I understood your question was that you cycle through items fetched from Excel. Sometimes the item in Excel does not exist in the application. If that is the case, then skip the checks for that item and fetch the next item from excel.

As correctly referenced by @pankaj mishra, the keyword Run Keyword and Ignore Error should be used. This keyword outputs 2 values (this is why you see 2 variables before it). The first one contains the status and the second one the actual value.

This is then used by the keyword Continue For Loop which breaks off this cycle when the keyword returned an error (FAIL). All the checks that followed (represented by the logging step) are then skipped.

*** Test Cases ***
TC
    @{list}    Create List    ${3}    ${6}    ${15}   ${21}
    Log To Console  \n
    :FOR    ${id}    IN    @{list}
    \    ${status}    ${result}
    \    ...    Run Keyword And Ignore Error    Mock Element Exists    ${id}
    \
    \    Continue For Loop If    '${status}' == 'FAIL'
    \    Log To Console   No Failure for ${id}

*** Keywords ***
Mock Element Exists
    [Arguments]    ${id}
    &{dic}    Create Dictionary    3=1    6=2    18=6    21=7
    [Return]   ${dic['${id}']}


问:
Installing R with Homebrew
I'm trying to install R using Homebrew. I ran these commands which are recommended elsewhere on SO:

```<code>brew tap homebrew/science
brew install R
</code>```

For brew tap homebrew/science, I'm receiving this error:

```<code>Error: Already tapped!
</code>```

For the second command, I receive this:

```<code>Error: No available formula for r
</code>```

Any suggestions?

答:
```<code>If you meant "r" specifically:
It was migrated from homebrew/science to homebrew/core.
</code>```

For r 3.4.3 Mac High Sierra:

```<code>brew tap homebrew/core
brew install Caskroom/cask/xquartz
brew install r
</code>```

Title: Installing R with Homebrew

Body:
I'm trying to install R using Homebrew. I ran these commands which are recommended elsewhere on SO:

brew tap homebrew/science
brew install R

For brew tap homebrew/science, I'm receiving this error:

Error: Already tapped!

For the second command, I receive this:

Error: No available formula for r

Any suggestions?

Body:
If you meant "r" specifically:
It was migrated from homebrew/science to homebrew/core.

For r 3.4.3 Mac High Sierra:

brew tap homebrew/core
brew install Caskroom/cask/xquartz
brew install r


问:
How to traverse a particular node's descendant node based on some other descendant's value
I have an example xml as below:

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
            <topic>
        <table>...</table>
        <p>...</p>
        <ul>

              <li>there is a tag
        <b>
    <u>HERE an XREF tag </u>
    </b>has to be added after the fn tag that point to the fn id
    <fn id="id-523">this is a second fn with id-523</fn>
    </li>
      <li>there is another third
    <fn id="id-524">this is a third  fn  id-524</fn>
        </li>
              <li>there is another fourth
 <fn id="id-525">this is a fourth  fn  id-525</fn>
    <xref href="#topic_gtc_yn2_bcb/id-525" format="dita" type="fn"/>
    </li>
              <li>there is a xref  tag that points to the fn id-523
    <xref href="#topic_gtc_yn2_bcb/id-523" format="dita" type="fn"/>
    </li>
            </ul>
        </topic>
</code>```

Now here I have to check the id attribute present inside the fn tag.
If corresponding to that id I have an xref tag inside the same ul (it can be for a table or ol element as well)then remove the id attribute else I=if I have an xref tag with same id(here for eg id=523).
Then I have to introduce xref tag just after that particular fn tag.

Expected output therefore will be:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
        <topic>
    <table>...</table>
    <p>...</p>
    <ul>

          <li>there is another tag
    <b>
<u>HERE an XREF tag </u>
</b>has to be added after the fn tag that point to the fn id
       <fn id="id-523">this is a second fn with id-523</fn>
<xref href="#topic_gtc_yn2_bcb/id-523" format="dita" type="fn"/>
    </li>
      <li>there is another third
<fn>this is a third  fn  id-524</fn>
    </li>
          <li>there is another fourth <fn id="id-525">this is a fourth  fn  id-525</fn>
<xref href="#topic_gtc_yn2_bcb/id-525" format="dita" type="fn"/>
</li>
          <li>there is a xref  tag that points to the fn id-523
<xref href="#topic_gtc_yn2_bcb/id-523" format="dita" type="fn"/>
</li>
        </ul>
    </topic>
</code>```

答:
You can try this</p>

```<code><xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="fn[@id]">
    <xsl:variable name="id" select="concat('#topic_gtc_yn2_bcb/', @id)"/>
    <xsl:copy>
        <xsl:if test="ancestor::*[matches(name(), '^(ul|table|ol)$')]//xref/@href  = $id">
            <xsl:copy-of select="@*"></xsl:copy-of>
        </xsl:if>
        <xsl:apply-templates/>
    </xsl:copy>
    <xsl:if test="ancestor::*[matches(name(), '^(ul|table|ol)$')]//xref/@href  = $id">
        <xsl:if test="not(following-sibling::*[1][self::xref/@href = $id])">
            <xsl:copy-of select="ancestor::*[matches(name(), '^(ul|table|ol)$')]//xref[@href  = $id]"></xsl:copy-of>
        </xsl:if>
    </xsl:if>
</xsl:template>
</code>```

Body:
I have an example xml as below:

 <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
            <topic>

...

...

there is a tag

    HERE an XREF tag
    has to be added after the fn tag that point to the fn id
    <fn id="id-523">this is a second fn with id-523</fn>

there is another third
    <fn id="id-524">this is a third  fn  id-524</fn>

there is another fourth
 <fn id="id-525">this is a fourth  fn  id-525</fn>
    <xref href="#topic_gtc_yn2_bcb/id-525" format="dita" type="fn"/>

there is a xref  tag that points to the fn id-523
    <xref href="#topic_gtc_yn2_bcb/id-523" format="dita" type="fn"/>

        </topic>

Now here I have to check the id attribute present inside the fn tag.
If corresponding to that id I have an xref tag inside the same ul (it can be for a table or ol element as well)then remove the id attribute else I=if I have an xref tag with same id(here for eg id=523).
Then I have to introduce xref tag just after that particular fn tag.

Expected output therefore will be:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN" "topic.dtd">
        <topic>

...

...

there is another tag

HERE an XREF tag
has to be added after the fn tag that point to the fn id
       <fn id="id-523">this is a second fn with id-523</fn>
<xref href="#topic_gtc_yn2_bcb/id-523" format="dita" type="fn"/>

there is another third
<fn>this is a third  fn  id-524</fn>

there is another fourth <fn id="id-525">this is a fourth  fn  id-525</fn>
<xref href="#topic_gtc_yn2_bcb/id-525" format="dita" type="fn"/>

there is a xref  tag that points to the fn id-523
<xref href="#topic_gtc_yn2_bcb/id-523" format="dita" type="fn"/>

    </topic>

Body:
You can try this

<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="fn[@id]">
    <xsl:variable name="id" select="concat('#topic_gtc_yn2_bcb/', @id)"/>
    <xsl:copy>
        <xsl:if test="ancestor::*[matches(name(), '^(ul|table|ol)$')]//xref/@href  = $id">
            <xsl:copy-of select="@*"></xsl:copy-of>
        </xsl:if>
        <xsl:apply-templates/>
    </xsl:copy>
    <xsl:if test="ancestor::*[matches(name(), '^(ul|table|ol)$')]//xref/@href  = $id">
        <xsl:if test="not(following-sibling::*[1][self::xref/@href = $id])">
            <xsl:copy-of select="ancestor::*[matches(name(), '^(ul|table|ol)$')]//xref[@href  = $id]"></xsl:copy-of>
        </xsl:if>
    </xsl:if>
</xsl:template>


问:
Regex in jmeter to not match string containing substring
My Response data is -

MyString=01015400007715243552T2867X01051005012447/3/1207/7\u0026index=2

MyString=014274X9000010152435500000MT2867X0154992365418/3/1207/7\u0026index=3

where i want to write a regex to match first string and ignore second string,below is my requirement.

As i highlighted in second string if the value contains X9 i should not match that string.

I tried many regex ,but dint help me much.
i tried MyString=(.*[^X9].+?)u0026
Please can someone help me

答:
The regex you may use is

```<code>MyString=((?:(?!X9).)*?)u0026
</code>```

Or, to avoid matching in the backslash,

```<code>MyString=((?:(?!X9).)*?)\\u0026
</code>```

Or, if \\u0026 is actually just a representation of & (and you have & in fact), use

```<code>MyString=((?:(?!X9)[^&])*)
</code>```

The (?:(?!X9).)*? is a tempered greedy token that matches any char, any 0+ times, as few as possible, that does not start a X9 sequence.

Details

MyString= - a literal substring

((?:(?!X9).)*?) - any char, 0+ repetitions, as few as possible (since *? is a lazy quantifier that forces the regex engine to skip the quantifyable pattern first and try all subsequent ones, and only if they fail to match this one is "expanded"), up to the first occurrence of X9

u0026 - a literal substring

Body:
The regex you may use is

MyString=((?:(?!X9).)*?)u0026

Or, to avoid matching in the backslash,

MyString=((?:(?!X9).)*?)\\u0026

Or, if \\u0026 is actually just a representation of & (and you have & in fact), use

MyString=((?:(?!X9)[^&])*)

The (?:(?!X9).)*? is a tempered greedy token that matches any char, any 0+ times, as few as possible, that does not start a X9 sequence.

Details

MyString= - a literal substring

((?:(?!X9).)*?) - any char, 0+ repetitions, as few as possible (since *? is a lazy quantifier that forces the regex engine to skip the quantifyable pattern first and try all subsequent ones, and only if they fail to match this one is "expanded"), up to the first occurrence of X9

u0026 - a literal substring


问:
String variable value as a property in a type
i try to create a type which has a variable value as a property

For example:

```<code>const myProp: string = 'my prop';
type Foo ={
    [myProp]: string
};
</code>```

i expected that i can do:

```<code>const test: Foo = {
   [myProp] = myProp
}
</code>```

But get error of:

[ts] A computed property name in a type literal must directly refer to
  a built-in symbol.

答:
If you want to declare a type that has the same property name as a string constant you could use the following syntax (lookup type syntax)

```<code>const myProp = 'my prop';
type Foo = {
    [P in typeof myProp]: string
};
const test: Foo = {
    [myProp]: myProp
}
</code>```

If you want to have several of these keys you can use a union type :

```<code>const myProp = 'my prop';
const otherProp = "otherProp"
type Foo = {
    [P in (typeof myProp | typeof otherProp)]: string
};
const test: Foo = {
    [myProp]: myProp,
    [otherProp]: otherProp
}
</code>```

The typescript default libraries, actually provides a type that is equivalent to the above lookup type declaration, named Record. Using this you could write your type as:

```<code>type Foo2 = Record<typeof myProp, string>;
</code>```

Body:
i try to create a type which has a variable value as a property

For example:

const myProp: string = 'my prop';
type Foo ={
    [myProp]: string
};

i expected that i can do:

const test: Foo = {
   [myProp] = myProp
}

But get error of:

[ts] A computed property name in a type literal must directly refer to
  a built-in symbol.

Body:
If you want to declare a type that has the same property name as a string constant you could use the following syntax (lookup type syntax)

const myProp = 'my prop';
type Foo = {
    [P in typeof myProp]: string
};
const test: Foo = {
    [myProp]: myProp
}

If you want to have several of these keys you can use a union type :

const myProp = 'my prop';
const otherProp = "otherProp"
type Foo = {
    [P in (typeof myProp | typeof otherProp)]: string
};
const test: Foo = {
    [myProp]: myProp,
    [otherProp]: otherProp
}

The typescript default libraries, actually provides a type that is equivalent to the above lookup type declaration, named Record. Using this you could write your type as:

type Foo2 = Record<typeof myProp, string>;


问:
Regex match the words from a string without the start and end space
I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

```<code>"word , word , two words, word"
</code>```

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

```<code>["word","word","two words","word"]
</code>```

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

```<code>match(/[^(,)]+/g)
</code>```

and using map to remove all the spaces from the resulting array:

```<code>map(value => value.trim());
</code>```

But would like to do it only through regular expression and have no idea how to do it.

答:
```<code>\w[\w ]*?(?:(?=\s*,)|$)
</code>```

Explanation:

```<code>\w[\w ]*?
</code>```

Matches word characters with 0 or more spaces in between, but never at the start. (lazy)

```<code>(?:(?=\s*,)|$)
</code>```

This non-capturing group looks ahead for spaces followed by ,, or the end of string.

Try it here.

Body:
I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

"word , word , two words, word"

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

["word","word","two words","word"]

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

match(/[^(,)]+/g)

and using map to remove all the spaces from the resulting array:

map(value => value.trim());

But would like to do it only through regular expression and have no idea how to do it.

Body:
\w[\w ]*?(?:(?=\s*,)|$)

Explanation:

\w[\w ]*?

Matches word characters with 0 or more spaces in between, but never at the start. (lazy)

(?:(?=\s*,)|$)

This non-capturing group looks ahead for spaces followed by ,, or the end of string.

Try it here.


问:
How to add language mutation to url by Helicon ISAPI Rewrite
we have web with nice url by Helicon ISAPI Rewrite and now we adding 3 language mutations (/en, /de, /ru) and I need to know how to create rewrite rule (redirect) which will add default lang mutation (/en) to the URL, when it does not exists in incoming URL

www.mydomain.com/de/gallery/ -> nothing happend

but

www.mydomain.com/gallery/ -> I need redirect to www.mydomain.com/en/gallery/

Can you help me, please? THX

答:
Try this:</p>

```<code>RewriteCond %{REQUEST_URI} !^(/de/)|(/en/)|(/ru/) [NC]
RewriteRule (.*) en/$1 [R]
</code>```

Body:
Try this:

RewriteCond %{REQUEST_URI} !^(/de/)|(/en/)|(/ru/) [NC]
RewriteRule (.*) en/$1 [R]


问:
how to fire findoneandupdate query in mongo db to update array of object
I want to update a field of the array object.
I want to update field of    _idWorksInRestaurant for experience[0].

here is my json object:

```<code>{
    "_id" : NumberInt(0),
    "_idUserProfile" : NumberInt(1),
    "experience" : [
    {
        "fromDate" : "06/2017",
        "zip" : "95014",
        "restaurantType" : "Family Style",
        "_idWorksInRestaurant" : "8020",

    },
    {
        "fromDate" : "11/2017",
        "restaurantType" : "Ethnic",
        "_idWorksInRestaurant" : "-1",

    }],

"__v" : NumberInt(0)
</code>```

Here is my code: In bari variable I am passing index no

```<code>var t = "experience." + bari + ".$._idWorksInRestaurant";
var z = "experience."+bari+"._idWorksInRestaurant";
ModelBarTender.findOneAndUpdate({ _idUserProfile: user._id, z: req.body.experience[bari]._idWorksInRestaurant },
    {
         $set: { t: restoid },
         $new: true, upsert: true
    },
    function (err, bartender) {
        if (!err) {
             bari++;
             bartenderexp(exp, req, imageURL, i9form, bari, callback);
        }
    }
);
</code>```

答:
```<code>var updateObj = {$set:{}};
updateObj.$set["experience." + bari + "._idWorksInRestaurant"] = restoid;
ModelBarTender.findOneAndUpdate({
    _idUserProfile: user._id
}, updateObj, {
    new: true, upsert: false
}, function (err, bartender) {
    if (!err) {
        bari++;
        bartenderexp(exp, req, imageURL, i9form, bari, callback);
    }
});
</code>```

Body:
I want to update a field of the array object.
I want to update field of    _idWorksInRestaurant for experience[0].

here is my json object:

{
    "_id" : NumberInt(0),
    "_idUserProfile" : NumberInt(1),
    "experience" : [
    {
        "fromDate" : "06/2017",
        "zip" : "95014",
        "restaurantType" : "Family Style",
        "_idWorksInRestaurant" : "8020",

    },
    {
        "fromDate" : "11/2017",
        "restaurantType" : "Ethnic",
        "_idWorksInRestaurant" : "-1",

    }],

"__v" : NumberInt(0)

Here is my code: In bari variable I am passing index no

var t = "experience." + bari + ".$._idWorksInRestaurant";
var z = "experience."+bari+"._idWorksInRestaurant";
ModelBarTender.findOneAndUpdate({ _idUserProfile: user._id, z: req.body.experience[bari]._idWorksInRestaurant },
    {
         $set: { t: restoid },
         $new: true, upsert: true
    },
    function (err, bartender) {
        if (!err) {
             bari++;
             bartenderexp(exp, req, imageURL, i9form, bari, callback);
        }
    }
);


问:
HLSL Geometry Shader Thick Lines DirectX

I try to draw a thick lined Sinus curve using this approach : https://forum.libcinder.org/topic/smooth-thick-lines-using-geometry-shader

I tried to port it to HLSL geometry shader:

Setting the dimension to fix 500/500 atm

THICKNESS seems not to change the issue

```<code>struct PSInput
{
    float4 Position : SV_POSITION;
};

float2 toScreenSpace(float4 vertex)
{
    float2 WIN_SCALE = { 500.0f, 500.0f };
    return float2(vertex.xy / vertex.w) * WIN_SCALE;
}

[maxvertexcount(7)]
void main(lineadj float4 vertices[4] : SV_POSITION, inout TriangleStream<PSInput> triStream)
{
    float2 WIN_SCALE = { 500.0f, 500.0f };

    float2 p0 = toScreenSpace(vertices[0]); // start of previous segment
    float2 p1 = toScreenSpace(vertices[1]); // end of previous segment, start of current segment
    float2 p2 = toScreenSpace(vertices[2]); // end of current segment, start of next segment
    float2 p3 = toScreenSpace(vertices[3]); // end of next segment

    // perform naive culling
    float2 area = WIN_SCALE * 1.2;
    if (p1.x < -area.x || p1.x > area.x)
        return;
    if (p1.y < -area.y || p1.y > area.y)
        return;
    if (p2.x < -area.x || p2.x > area.x)
        return;
    if (p2.y < -area.y || p2.y > area.y)
        return;

    float2 v0 = normalize(p1 - p0);
    float2 v1 = normalize(p2 - p1);
    float2 v2 = normalize(p3 - p2);

    // determine the normal of each of the 3 segments (previous, current, next)
    float2 n0 = { -v0.y, v0.x};
    float2 n1 = { -v1.y, v1.x};
    float2 n2 = { -v2.y, v2.x};

    // determine miter lines by averaging the normals of the 2 segments
    float2 miter_a = normalize(n0 + n1); // miter at start of current segment
    float2 miter_b = normalize(n1 + n2); // miter at end of current segment

    // determine the length of the miter by projecting it onto normal and then inverse it
    float THICKNESS = 1;
    float length_a = THICKNESS / dot(miter_a, n1);
    float length_b = THICKNESS / dot(miter_b, n1);

    float MITER_LIMIT = 0.75;
    //float MITER_LIMIT = -1;
    //float MITER_LIMIT = 0.1;

    PSInput v;
    float2 temp;

    //// prevent excessively long miters at sharp corners
    if (dot(v0, v1) < -MITER_LIMIT)
    {
        miter_a = n1;
        length_a = THICKNESS;

        // close the gap
        if (dot(v0, n1) > 0)
        {
            temp = (p1 + THICKNESS * n0) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            temp = (p1 + THICKNESS * n1) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            v.Position = float4(p1 / WIN_SCALE, 1.0, 1.0);
            triStream.Append(v);

            //triStream.RestartStrip();

        }
        else
        {
            temp = (p1 - THICKNESS * n1) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            temp = (p1 - THICKNESS * n0) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            v.Position = float4(p1 / WIN_SCALE, 1.0, 1.0);
            triStream.Append(v);

            //triStream.RestartStrip();
        }
    }

    if (dot(v1, v2) < -MITER_LIMIT)
    {
        miter_b = n1;
        length_b = THICKNESS;
    }

    // generate the triangle strip
    temp = (p1 + length_a * miter_a) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    temp = (p1 - length_a * miter_a) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    temp = (p2 + length_b * miter_b) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    temp = (p2 - length_b * miter_b) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    //triStream.RestartStrip();

}
</code>```

The thing is, that it won't output anything of the curve I give as points to it. It already works very well without thick lines, but I want to have that. I can add Noise to my Sinus signal and if I do that, (y-values increase by a little random %) suddenly the curve shows up and is thicker and seems to work, but I want it to be thick and showing without noise too.

If I up the frequency, without noise, point appear scattered-plot style, but not as a connected Sinus.

If I debug with the VS Graphics Debugger, I can see that in the frame with no Noise it says the Pixel-Shader-Stage is not run (?).
The frame with noise shows it run and working.

Maybe my porting is incorrect and I forget something, I am very new to programming shaders. Maybe I missunderstand the approach at all.

Any help appreciated.

答: I needed to set the default behavior of the culling to CullMode.None to get all the triangle drawn.</p>

Body:
I try to draw a thick lined Sinus curve using this approach : https://forum.libcinder.org/topic/smooth-thick-lines-using-geometry-shader

I tried to port it to HLSL geometry shader:

Setting the dimension to fix 500/500 atm

THICKNESS seems not to change the issue

struct PSInput
{
    float4 Position : SV_POSITION;
};

float2 toScreenSpace(float4 vertex)
{
    float2 WIN_SCALE = { 500.0f, 500.0f };
    return float2(vertex.xy / vertex.w) * WIN_SCALE;
}

[maxvertexcount(7)]
void main(lineadj float4 vertices[4] : SV_POSITION, inout TriangleStream<PSInput> triStream)
{
    float2 WIN_SCALE = { 500.0f, 500.0f };

    float2 p0 = toScreenSpace(vertices[0]); // start of previous segment
    float2 p1 = toScreenSpace(vertices[1]); // end of previous segment, start of current segment
    float2 p2 = toScreenSpace(vertices[2]); // end of current segment, start of next segment
    float2 p3 = toScreenSpace(vertices[3]); // end of next segment

    // perform naive culling
    float2 area = WIN_SCALE * 1.2;
    if (p1.x < -area.x || p1.x > area.x)
        return;
    if (p1.y < -area.y || p1.y > area.y)
        return;
    if (p2.x < -area.x || p2.x > area.x)
        return;
    if (p2.y < -area.y || p2.y > area.y)
        return;

    float2 v0 = normalize(p1 - p0);
    float2 v1 = normalize(p2 - p1);
    float2 v2 = normalize(p3 - p2);

    // determine the normal of each of the 3 segments (previous, current, next)
    float2 n0 = { -v0.y, v0.x};
    float2 n1 = { -v1.y, v1.x};
    float2 n2 = { -v2.y, v2.x};

    // determine miter lines by averaging the normals of the 2 segments
    float2 miter_a = normalize(n0 + n1); // miter at start of current segment
    float2 miter_b = normalize(n1 + n2); // miter at end of current segment

    // determine the length of the miter by projecting it onto normal and then inverse it
    float THICKNESS = 1;
    float length_a = THICKNESS / dot(miter_a, n1);
    float length_b = THICKNESS / dot(miter_b, n1);

    float MITER_LIMIT = 0.75;
    //float MITER_LIMIT = -1;
    //float MITER_LIMIT = 0.1;

    PSInput v;
    float2 temp;

    //// prevent excessively long miters at sharp corners
    if (dot(v0, v1) < -MITER_LIMIT)
    {
        miter_a = n1;
        length_a = THICKNESS;

        // close the gap
        if (dot(v0, n1) > 0)
        {
            temp = (p1 + THICKNESS * n0) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            temp = (p1 + THICKNESS * n1) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            v.Position = float4(p1 / WIN_SCALE, 1.0, 1.0);
            triStream.Append(v);

            //triStream.RestartStrip();

        }
        else
        {
            temp = (p1 - THICKNESS * n1) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            temp = (p1 - THICKNESS * n0) / WIN_SCALE;
            v.Position = float4(temp, 1.0, 1.0);
            triStream.Append(v);

            v.Position = float4(p1 / WIN_SCALE, 1.0, 1.0);
            triStream.Append(v);

            //triStream.RestartStrip();
        }
    }

    if (dot(v1, v2) < -MITER_LIMIT)
    {
        miter_b = n1;
        length_b = THICKNESS;
    }

    // generate the triangle strip
    temp = (p1 + length_a * miter_a) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    temp = (p1 - length_a * miter_a) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    temp = (p2 + length_b * miter_b) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    temp = (p2 - length_b * miter_b) / WIN_SCALE;
    v.Position = float4(temp, 1.0, 1.0);
    triStream.Append(v);

    //triStream.RestartStrip();

}

The thing is, that it won't output anything of the curve I give as points to it. It already works very well without thick lines, but I want to have that. I can add Noise to my Sinus signal and if I do that, (y-values increase by a little random %) suddenly the curve shows up and is thicker and seems to work, but I want it to be thick and showing without noise too.

If I up the frequency, without noise, point appear scattered-plot style, but not as a connected Sinus.

If I debug with the VS Graphics Debugger, I can see that in the frame with no Noise it says the Pixel-Shader-Stage is not run (?).
The frame with noise shows it run and working.

Maybe my porting is incorrect and I forget something, I am very new to programming shaders. Maybe I missunderstand the approach at all.

Any help appreciated.


问:
How to make picker view to display from a particular row in swift 3?
How to make picker view to display from default country but it is displaying from first but I need it from default country that is united states but here it is showing from first country but I need it to display from United States can anyone help me how to implement this ?

here are the images shown below here picker view displaying from first country but I need it to display from United States because it is my default selected country

```<code>func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for item in jsonObj! {
                    let dict = Country(dict: item)
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                     self.countryPickerView.selectRow(self.i, inComponent: 0, animated: true)
                     self.countryPickerView.reloadAllComponents()
                     self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int{
        if pickerView.tag == 1 {
            return 1
        }else {
            return 1
        }
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView.tag == 1 {
            return countryArray.count
        }
        else {
            return countryArray[countrySelectedIndex!].state.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 1 {
            return countryArray[row].country
        }
        else {
            return countryArray[countrySelectedIndex!].state[row].state
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView.tag == 1 {
            countryTextField.text = countryArray[row].country
            for item in countryArray {
                print(item.country)
                print(countryArray[row].country)
                if item.country == countryArray[row].country {
                    self.countryId = item.countryId
                    if item.state.count == 0 {
                        self.stateTextfield.isHidden = false
                        self.stateLabel.isHidden = true
                        self.selectedCountryTextField.isHidden = true
                        self.imageArrow.isHidden = true
                        break
                    }
                    else {
                        if let i = countryArray.index(where: { $0.country == countryArray[row].country }) {
                            countrySelectedIndex = i
                        }
                        self.countryId = item.countryId
                        if self.countryId?.isEmpty == true {
                            self.countryId = countryTextField.text
                        }
                        UserDefaults.standard.set(self.countryId, forKey: "guestCountryId")
                        self.statePickerView.delegate = self
                        self.statePickerView.dataSource = self
                        selectedCountryTextField.inputView = statePickerView
                        self.statePickerView.reloadAllComponents()
                        selectedCountryTextField.text = "Select state/province"
                        self.stateLabel.isHidden = false
                        self.stateTextfield.isHidden = true
                        self.selectedCountryTextField.isHidden = false
                        self.imageArrow.isHidden = false
                        break
                    }
                }
                else {
                    self.stateTextfield.isHidden = false
                    self.stateLabel.isHidden = true
                    self.selectedCountryTextField.isHidden = true
                    self.imageArrow.isHidden = true
                }
            }
        }
        else {
            self.selectedCountryTextField.text = countryArray[countrySelectedIndex!].state[row].state
            self.stateCode = countryArray[countrySelectedIndex!].state[row].stateValue as! Int
            print(self.stateCode)
            UserDefaults.standard.set(self.stateCode, forKey: "statecode")
        }
    }
</code>```

答:
First thing you need to know what is the index of United States. So store it's index in variable selectedCountry when you are calling the api. After that call the pickers delegate method selectedRow.

```<code>var selectedCountry:Int = 0

func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for itemNumber in 0..<jsonObj!.count {
                    let dict = Country(dict:jsonObj![itemNumber])
                    if dict.countryName == "United States" {
                        self.selectedCountry = itemNumber
                        self.countryPickerView.selectRow(self.selectedCountry, inComponent: 0, animated: true)
                    }
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                    self.countryPickerView.reloadAllComponents()
                    self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }
</code>```

Hope this will be help.

Body:
How to make picker view to display from default country but it is displaying from first but I need it from default country that is united states but here it is showing from first country but I need it to display from United States can anyone help me how to implement this ?

here are the images shown below here picker view displaying from first country but I need it to display from United States because it is my default selected country

func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for item in jsonObj! {
                    let dict = Country(dict: item)
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                     self.countryPickerView.selectRow(self.i, inComponent: 0, animated: true)
                     self.countryPickerView.reloadAllComponents()
                     self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int{
        if pickerView.tag == 1 {
            return 1
        }else {
            return 1
        }
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
        if pickerView.tag == 1 {
            return countryArray.count
        }
        else {
            return countryArray[countrySelectedIndex!].state.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == 1 {
            return countryArray[row].country
        }
        else {
            return countryArray[countrySelectedIndex!].state[row].state
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if pickerView.tag == 1 {
            countryTextField.text = countryArray[row].country
            for item in countryArray {
                print(item.country)
                print(countryArray[row].country)
                if item.country == countryArray[row].country {
                    self.countryId = item.countryId
                    if item.state.count == 0 {
                        self.stateTextfield.isHidden = false
                        self.stateLabel.isHidden = true
                        self.selectedCountryTextField.isHidden = true
                        self.imageArrow.isHidden = true
                        break
                    }
                    else {
                        if let i = countryArray.index(where: { $0.country == countryArray[row].country }) {
                            countrySelectedIndex = i
                        }
                        self.countryId = item.countryId
                        if self.countryId?.isEmpty == true {
                            self.countryId = countryTextField.text
                        }
                        UserDefaults.standard.set(self.countryId, forKey: "guestCountryId")
                        self.statePickerView.delegate = self
                        self.statePickerView.dataSource = self
                        selectedCountryTextField.inputView = statePickerView
                        self.statePickerView.reloadAllComponents()
                        selectedCountryTextField.text = "Select state/province"
                        self.stateLabel.isHidden = false
                        self.stateTextfield.isHidden = true
                        self.selectedCountryTextField.isHidden = false
                        self.imageArrow.isHidden = false
                        break
                    }
                }
                else {
                    self.stateTextfield.isHidden = false
                    self.stateLabel.isHidden = true
                    self.selectedCountryTextField.isHidden = true
                    self.imageArrow.isHidden = true
                }
            }
        }
        else {
            self.selectedCountryTextField.text = countryArray[countrySelectedIndex!].state[row].state
            self.stateCode = countryArray[countrySelectedIndex!].state[row].stateValue as! Int
            print(self.stateCode)
            UserDefaults.standard.set(self.stateCode, forKey: "statecode")
        }
    }

Body:
First thing you need to know what is the index of United States. So store it's index in variable selectedCountry when you are calling the api. After that call the pickers delegate method selectedRow.

var selectedCountry:Int = 0

func countryListDownloadJsonwithURL(countryAPI: String) {
        let url = NSURL(string: countryAPI)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String:Any]] {
                for itemNumber in 0..<jsonObj!.count {
                    let dict = Country(dict:jsonObj![itemNumber])
                    if dict.countryName == "United States" {
                        self.selectedCountry = itemNumber
                        self.countryPickerView.selectRow(self.selectedCountry, inComponent: 0, animated: true)
                    }
                    self.countryArray.append(dict)
                }
                print(self.countryArray)
                OperationQueue.main.addOperation({
                    self.countryPickerView.reloadAllComponents()
                    self.statePickerView.reloadAllComponents()
                })
            }
        }).resume()
    }

Hope this will be help.


问:
SQL Performance: Using Union and Subqueries
Hi stackoverflow(My first question!),

We're doing something like an SNS, and got a question about optimizing queries.

Using mysql 5.1, the current table was created with:

```<code>CREATE TABLE friends(
 user_id BIGINT NOT NULL,
 friend_id BIGINT NOT NULL,
 PRIMARY KEY (user_id, friend_id)
) ENGINE INNODB;
</code>```

Sample data is populated like:

```<code>INSERT INTO friends VALUES
(1,2),
(1,3),
(1,4),
(1,5),
(2,1),
(2,3),
(2,4),
(3,1),
(3,2),
(4,1),
(4,2),
(5,1),
(5,6),
(6,5),
(7,8),
(8,7);
</code>```

The business logic: we need to figure out which users are friends or friends of friends for a given user.
The current query for this for a user with user_id=1 is:

```<code>SELECT friend_id FROM friends WHERE user_id = 1
 UNION
 SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
 SELECT friend_id FROM friends WHERE user_id = 1
);
</code>```

The expected result is(order doesn't matter):

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

As you can see, the above query performs the subquery "SELECT friend_id FROM friends WHERE user_id = 1" twice.

So, here is the question. If performance is your primary concern, how would you change the above query or schema?

Thanks in advance.

答:
No need for the UNION. Just include an OR with the user_id of the beginning user:

```<code>SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
    SELECT friend_id FROM friends WHERE user_id = 1
) OR user_id = 1;

+-----------+
| friend_id |
+-----------+
|         2 |
|         3 |
|         4 |
|         5 |
|         1 |
|         6 |
+-----------+
</code>```

Body:
Hi stackoverflow(My first question!),

We're doing something like an SNS, and got a question about optimizing queries.

Using mysql 5.1, the current table was created with:

CREATE TABLE friends(
 user_id BIGINT NOT NULL,
 friend_id BIGINT NOT NULL,
 PRIMARY KEY (user_id, friend_id)
) ENGINE INNODB;

Sample data is populated like:

INSERT INTO friends VALUES
(1,2),
(1,3),
(1,4),
(1,5),
(2,1),
(2,3),
(2,4),
(3,1),
(3,2),
(4,1),
(4,2),
(5,1),
(5,6),
(6,5),
(7,8),
(8,7);

The business logic: we need to figure out which users are friends or friends of friends for a given user.
The current query for this for a user with user_id=1 is:

SELECT friend_id FROM friends WHERE user_id = 1
 UNION
 SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
 SELECT friend_id FROM friends WHERE user_id = 1
);

The expected result is(order doesn't matter):

2
3
4
5
1
6

As you can see, the above query performs the subquery "SELECT friend_id FROM friends WHERE user_id = 1" twice.

So, here is the question. If performance is your primary concern, how would you change the above query or schema?

Thanks in advance.

Body:
No need for the UNION. Just include an OR with the user_id of the beginning user:

SELECT DISTINCT friend_id FROM friends WHERE user_id IN (
    SELECT friend_id FROM friends WHERE user_id = 1
) OR user_id = 1;

+-----------+
| friend_id |
+-----------+
|         2 |
|         3 |
|         4 |
|         5 |
|         1 |
|         6 |
+-----------+


问:
C++ Runtime Error: free(): invalid next size (fast)
I have seen mutliple posts about this error, however I have not been able to find a solution. In my code I have a vector of "Gene"s and each gene contains a source and destination in the form of an int.

I want to create a vector of ints that contains all of the different possible values of the source and destination in the vector of genes. I begin by going through each gene and identify the source and destination and then check if that ID already exists in the vector. If it does, then ignore it, but if its a new value then add it to the vector.

```<code>void addMutations(vector<Gene*>* genome){
    vector<int> nodeIDs;

    for(int i = 0; i < genome->size(); i++){
        int src = genome->at(i)->sourceNeuronID;
        int dst = genome->at(i)->destinationNeuronID;

        if(find(nodeIDs.begin(), nodeIDs.end(), src) == nodeIDs.end()){
            nodeIDs.push_back(src);// <-- Issue is here
        }

        if(find(nodeIDs.begin(), nodeIDs.end(), dst) == nodeIDs.end()){
            nodeIDs.push_back(dst);// <-- Probably here too
        }
}
</code>```

Does the issue come from the fact that src and dst go out of scope at the end of iteration of the for loop?

答:
Does the issue come from the fact that src and dst go out of scope at the end of iteration of the for loop?

No, these valuea are pushed into the vector, before going out of scope, so this is fine.

C++ Runtime Error: free(): invalid next size (fast)

This means that heap is corrupted. Valgrind can be helpful in this cases.

That memory error is not coming from std::vector, but from your pointers. Somewhere, you free something you shouldn't? That may be caused by bad memory allocation on your behalf (something has not been allocated as you desire it to). Who knows with the code you posted.

In any, case, you should really use Valgrind to track that error down.

PS: Do you really need to use that many pointers? I mean in your functions, you could just have passed your vector by reference, like this:

```<code>void addMutations(vector<Gene*>& genome) {
</code>```

and then do:

```<code>genome.at(i)->sourceNeuronID;
</code>```

and so on.

Pointers are great (e.g. in polymorphism), but you should use them with caution and of course, use them when needed (Pan Metron Ariston).

Body:
I have seen mutliple posts about this error, however I have not been able to find a solution. In my code I have a vector of "Gene"s and each gene contains a source and destination in the form of an int.

I want to create a vector of ints that contains all of the different possible values of the source and destination in the vector of genes. I begin by going through each gene and identify the source and destination and then check if that ID already exists in the vector. If it does, then ignore it, but if its a new value then add it to the vector.

void addMutations(vector<Gene*>* genome){
    vector<int> nodeIDs;

    for(int i = 0; i < genome->size(); i++){
        int src = genome->at(i)->sourceNeuronID;
        int dst = genome->at(i)->destinationNeuronID;

        if(find(nodeIDs.begin(), nodeIDs.end(), src) == nodeIDs.end()){
            nodeIDs.push_back(src);// <-- Issue is here
        }

        if(find(nodeIDs.begin(), nodeIDs.end(), dst) == nodeIDs.end()){
            nodeIDs.push_back(dst);// <-- Probably here too
        }
}

Does the issue come from the fact that src and dst go out of scope at the end of iteration of the for loop?

Body:
Does the issue come from the fact that src and dst go out of scope at the end of iteration of the for loop?

No, these valuea are pushed into the vector, before going out of scope, so this is fine.

C++ Runtime Error: free(): invalid next size (fast)

This means that heap is corrupted. Valgrind can be helpful in this cases.

That memory error is not coming from std::vector, but from your pointers. Somewhere, you free something you shouldn't? That may be caused by bad memory allocation on your behalf (something has not been allocated as you desire it to). Who knows with the code you posted.

In any, case, you should really use Valgrind to track that error down.

PS: Do you really need to use that many pointers? I mean in your functions, you could just have passed your vector by reference, like this:

void addMutations(vector<Gene*>& genome) {

and then do:

genome.at(i)->sourceNeuronID;

and so on.

Pointers are great (e.g. in polymorphism), but you should use them with caution and of course, use them when needed (Pan Metron Ariston).


问:
Sinch client wont start?
I am trying to use sinch an i am having erros i dont know why an i seem to have set it well.

and it is pointing me to this part of the code which

```<code>public void that(final String name) {
    call.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if ((getSinchServiceInterface() == null) || (!getSinchServiceInterface().isStarted())) {
                getSinchServiceInterface().startClient(name);
            }
        }
    });
}
</code>```

the "getSinchServiceInterface().startClient(name);"

this is my error

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void com.obi.thinker.logins.call.SinchService$SinchServiceInterface.startClient(java.lang.String)' on a null object reference
                                                                                at com.obi.thinker.logins.tabs.Chatting$caller$1.onClick(Chatting.java:386)
                                                                                at android.view.View.performClick(View.java:5265)
                                                                                at android.view.View$PerformClick.run(View.java:21534)
                                                                                at android.os.Handler.handleCallback(Handler.java:815)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                                at android.os.Looper.loop(Looper.java:207)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5683)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

I dont understand

答:
I was facing this issue for weeks. I literally rewrote my SinchService from scratch, removed Sinch altogether and tried starting fresh but all to no avail. It turns out I was simply initialising my call too early.

I recommend you move the code block:

```<code>if ((getSinchServiceInterface() != null || !getSinchServiceInterface().isStarted())) {
            getSinchServiceInterface().startClient(name);
        }
</code>```

I moved mine to the very end of my onResume method and it seems to all work fine now. The reason this doesn't continually keep starting the client is because we are adding the 'if' statement to make sure it isn't already initialised.

If you find that the issue is still thrown, which was the case for me at one point, try calling it at the very end of the launch of your activity. It simply comes down to being called before your BaseActivity has a chance to initialise mSinchServiceInterface

Title: Sinch client wont start?

Body:
I am trying to use sinch an i am having erros i dont know why an i seem to have set it well.

and it is pointing me to this part of the code which

public void that(final String name) {
    call.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if ((getSinchServiceInterface() == null) || (!getSinchServiceInterface().isStarted())) {
                getSinchServiceInterface().startClient(name);
            }
        }
    });
}

the "getSinchServiceInterface().startClient(name);"

this is my error

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.obi.thinker.logins.call.SinchService$SinchServiceInterface.startClient(java.lang.String)' on a null object reference
                                                                                at com.obi.thinker.logins.tabs.Chatting$caller$1.onClick(Chatting.java:386)
                                                                                at android.view.View.performClick(View.java:5265)
                                                                                at android.view.View$PerformClick.run(View.java:21534)
                                                                                at android.os.Handler.handleCallback(Handler.java:815)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                                at android.os.Looper.loop(Looper.java:207)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5683)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

I dont understand

Body:
I was facing this issue for weeks. I literally rewrote my SinchService from scratch, removed Sinch altogether and tried starting fresh but all to no avail. It turns out I was simply initialising my call too early.

I recommend you move the code block:

if ((getSinchServiceInterface() != null || !getSinchServiceInterface().isStarted())) {
            getSinchServiceInterface().startClient(name);
        }

I moved mine to the very end of my onResume method and it seems to all work fine now. The reason this doesn't continually keep starting the client is because we are adding the 'if' statement to make sure it isn't already initialised.

If you find that the issue is still thrown, which was the case for me at one point, try calling it at the very end of the launch of your activity. It simply comes down to being called before your BaseActivity has a chance to initialise mSinchServiceInterface


问:
Is there any way to hide AWS lambda code?
I want to publish my application and provide lambdas to other so that I want that on exporting the lambda package no one can get the lambda code.</p>

答: You should create an API Gateway which will connect the application to your Lambda code. Give that API endpoint URL to the others and they will call your Lambda function through that. This way they cannot know what's going on in your Lambda code.</p>


问:
Trap Subroutine LC3 Assembly
Hi I have a problem for a cs class

```<code>       The puts TRAP routine has been disabled for some reason. Write an LC-3
      subroutine called puts that
  implements its behaviour. In other words when the subroutine is called
 register R0 will contain the
 address of a null-delimited string and the subroutine will simply print the
string and return. You will of
course need to utilize the TRAP routine out that prints a character.
</code>```

do
  NOT have to write a main
  program.

So my approach to this was this I'm not sure if this is correct or if my logic is right

```<code>    PUTS:
    ADD R2, R0, #0;
    AND R0, R0, #0;
    ADD R0, R2, #0;

    Out(trapx21) ; print first char in r0;

    BRp PUTS ; repeat loop
</code>```

I'm not sure if i'm doing this correctly any help?

答:
There's a couple of things off about your TRAP.

The biggest mistake, you are making use of the OUT trap within your trap service routine.  When traps are called the return address is put in R7.  When you make a call to the OUT trap, R7 is clobbered  Now you have no way of getting back to whatever code called the trap in the first place.

You will need a RET instruction at the end to get back to whoever called you

Your code is not actually getting the characters from the string that is contained in R0. So if you read from the address contained in R0 (via LDR) you should get the first character, read from address contained in R0+1 and you should get the second character, you have to continually read characters from the address in R0 until you receive a 0 which is the NUL terminator.

And contrary to the instructions in your problem, you should write a MAIN to test it.

Title: Trap Subroutine LC3 Assembly

Body:
Hi I have a problem for a cs class

       The puts TRAP routine has been disabled for some reason. Write an LC-3
      subroutine called puts that
  implements its behaviour. In other words when the subroutine is called
 register R0 will contain the
 address of a null-delimited string and the subroutine will simply print the
string and return. You will of
course need to utilize the TRAP routine out that prints a character.

do
  NOT have to write a main
  program.

So my approach to this was this I'm not sure if this is correct or if my logic is right

    PUTS:
    ADD R2, R0, #0;
    AND R0, R0, #0;
    ADD R0, R2, #0;

    Out(trapx21) ; print first char in r0;

    BRp PUTS ; repeat loop

I'm not sure if i'm doing this correctly any help?


问:
How to display jquery datepicker on link click?
I need to show jQuery UI datepicker on link click, also when a date is picked change link text to this date, how can I do it?

答:
This worked for me. Needs jquery-ui .ls and .css.</p>

```<code> $( function() {
            $( "#from" ).datepicker({
                changeMonth: true,
                changeYear: true
            });
            $( "#to" ).datepicker({
                changeMonth: true,
                changeYear: true
            });
</code>```

Body:
This worked for me. Needs jquery-ui .ls and .css.

 $( function() {
            $( "#from" ).datepicker({
                changeMonth: true,
                changeYear: true
            });
            $( "#to" ).datepicker({
                changeMonth: true,
                changeYear: true
            });


问:
How to redisplay mysql records without reloading/refresing the current page using php?
So here's the scenario:

The code below display all the user accounts.

```<code><table border="3px" align="center" cellspacing="3px" cellpadding="3px">
<tr>
<td>Username</td>
<td>Password</td>
<td><a href="" onclick='return popup_link()'>Add</a></td>
</tr>
<?php
include("connection.php");
$query=mysql_query("select * from tbl_users");
while($row=mysql_fetch_array($query)){
?>
<tr>
<td><?php echo $row['username']; ?></td>
<td><?php echo $row['password']; ?></td>
<td></td>
</tr>
<?php
}
?>
</table>
</code>```

Then I have a popup page wherein it can add user account into the database table user account without reloading the page itself.

```<code><form id="form">
<h3>Add Record</h3>
<label>Username:</label>
<br/>
<input type="text" id="username" placeholder="Userusername"/>
<br/>
<br/>
<label>Password:</label>
<br/>
<input type="password" id="password" placeholder="Password"/>
<br/>
<br/>
<input type="button" id="submit" value="Submit"/>
</form>

<?php
// Establishing connection with server by passing "server_name", "user_id", "password"
$connection = mysql_connect("localhost", "root", "");
// Selecting Database by passing "database_name" and above connection variable
$db = mysql_select_db("smsi_inventory", $connection);

//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];

//Insert query
$query = mysql_query("insert into tbl_users(username, password) values ('$username2','$password2')");
if($query){
echo "Record Saved succesfully";
}

//connection closed
mysql_close($connection);
?>
</code>```

However, I'm having a hard time displaying the records of the newly added accounts without reloading/refreshing the page. Is there a way I can display the newly added accounts using php?

Your help is highly appreciated. Thank you!

答:
Try to Perform an asynchronous HTTP (Ajax) request.

```<code>$.ajax({
    type:'POST',
    url:'YOUR UPDATE DATA URL',
    data:{your:data},
    success:function(data){
      //WHATEVER YOU SHOW ON SUCCESS
    },
    error: function (jqXHR, exception) {
      alert("Parse Errore");
    }
});
</code>```

For More Read http://api.jquery.com/jquery.ajax/

Body:
So here's the scenario:

The code below display all the user accounts.

Username
Password
Add

<?php
include("connection.php");
$query=mysql_query("select * from tbl_users");
while($row=mysql_fetch_array($query)){
?>

<?php echo $row['username']; ?>
<?php echo $row['password']; ?>

<?php
}
?>

Then I have a popup page wherein it can add user account into the database table user account without reloading the page itself.

<form id="form">

Add Record

Username:

<input type="text" id="username" placeholder="Userusername"/>

Password:

<input type="password" id="password" placeholder="Password"/>

<input type="button" id="submit" value="Submit"/>
</form>

<?php
// Establishing connection with server by passing "server_name", "user_id", "password"
$connection = mysql_connect("localhost", "root", "");
// Selecting Database by passing "database_name" and above connection variable
$db = mysql_select_db("smsi_inventory", $connection);

//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];

//Insert query
$query = mysql_query("insert into tbl_users(username, password) values ('$username2','$password2')");
if($query){
echo "Record Saved succesfully";
}

//connection closed
mysql_close($connection);
?>

However, I'm having a hard time displaying the records of the newly added accounts without reloading/refreshing the page. Is there a way I can display the newly added accounts using php?

Your help is highly appreciated. Thank you!

Body:
Try to Perform an asynchronous HTTP (Ajax) request.

$.ajax({
    type:'POST',
    url:'YOUR UPDATE DATA URL',
    data:{your:data},
    success:function(data){
      //WHATEVER YOU SHOW ON SUCCESS
    },
    error: function (jqXHR, exception) {
      alert("Parse Errore");
    }
});

For More Read http://api.jquery.com/jquery.ajax/


问:
How to move a project up/down in eclipse?
I am having a long list of projects up in project explorer. And would like to move certain project up.
Is there a short cut for this in eclipse??</p>

答:
1>You can filter your projects according to working sets.
working sets explained

2>On the drop down menu of Package Explorer, you can select Filters and choose Closed Projects. This will automatically hide all the projects that are closed which can help you to do sorting