问:
Recursive Compounding Interest
I have to rewrite this as a recursive function, and I don't understand what I'm doing wrong. I've googled and googled and seen many different ways, which just makes it even more confusing.

```<code>float Total(float ir=0, int time=0)//Savings Procedure
{
    float bal = Balance;
    for (short i = 0; i < time; i++)
    {
        bal += (Balance*((1.0+ir)/time))/100;
    }
    return bal;
};
</code>```

My attempt:

```<code>float compoundit(float balance, float ir, int time)
{
    if (time < 0)
    {
        return balance;
    }
    balance = balance * ((1.0 + ir)/time);
    return compoundit(balance, ir, --time);
}
float TotalRecursive(float ir=0, int time=0)
{
    return compoundit(Balance, ir, time);
};
</code>```

Am I even close? Sometimes I just get 'inf' as a result. Any help would be appreciated.

答:
First of all, your function to compute the total balance using compound interest is not correct.

After couple of cosmetic changes, tt should be:

```<code>float computeIterative(float Balance, float ir=0, int time=0)
{
    // The total balance is same as the initial balance if
    // time is zero.
    float bal = Balance;
    for (int i = 0; i < time; i++)
    {
       // Compute the interest for this period
       float interest = bal*ir/100;

       // Add the interest to the balance so the interest
       // for the next period is a compound interest.
       bal += interest;
    }

    // The total balance after all the interests have
    // been compounded.
    return bal;
}
</code>```

A recursive version of that function would be:

```<code>float computeRecursive(float Balance, float ir=0, int time=0)
{
   if ( time == 0 )
   {
      return Balance;
   }

   float interest = Balance * ir/100;
   return computeRecursive(Balance + interest, ir, time-1);
}
</code>```

Working code: http://ideone.com/W5ExPT

Title: Recursive Compounding Interest

Body:
I have to rewrite this as a recursive function, and I don't understand what I'm doing wrong. I've googled and googled and seen many different ways, which just makes it even more confusing.

float Total(float ir=0, int time=0)//Savings Procedure
{
    float bal = Balance;
    for (short i = 0; i < time; i++)
    {
        bal += (Balance*((1.0+ir)/time))/100;
    }
    return bal;
};

My attempt:

float compoundit(float balance, float ir, int time)
{
    if (time < 0)
    {
        return balance;
    }
    balance = balance * ((1.0 + ir)/time);
    return compoundit(balance, ir, --time);
}
float TotalRecursive(float ir=0, int time=0)
{
    return compoundit(Balance, ir, time);
};

Am I even close? Sometimes I just get 'inf' as a result. Any help would be appreciated.

Body:
First of all, your function to compute the total balance using compound interest is not correct.

After couple of cosmetic changes, tt should be:

float computeIterative(float Balance, float ir=0, int time=0)
{
    // The total balance is same as the initial balance if
    // time is zero.
    float bal = Balance;
    for (int i = 0; i < time; i++)
    {
       // Compute the interest for this period
       float interest = bal*ir/100;

       // Add the interest to the balance so the interest
       // for the next period is a compound interest.
       bal += interest;
    }

    // The total balance after all the interests have
    // been compounded.
    return bal;
}

A recursive version of that function would be:

float computeRecursive(float Balance, float ir=0, int time=0)
{
   if ( time == 0 )
   {
      return Balance;
   }

   float interest = Balance * ir/100;
   return computeRecursive(Balance + interest, ir, time-1);
}

Working code: http://ideone.com/W5ExPT


来源: stackexchange

问:
Can the Maven shade plugin fail the build when there are duplicate classes?
The Maven shade plugin coalesces your project's Java classes along with its dependencies into a single über JAR file. If there is any overlap (e.g. two dependencies contain a class with the same qualified name), it issues a warning and (if I understand correctly) uses the last version of that class that it comes across.

To me this seems a bit too lax; such an overlap could easily cause linkage or other problems at runtime, e.g. when the overlapping classes contain different bytecode.

Is it possible to configure the shade plugin to fail the build when there are overlaps, instead of just issuing a warning? This would be especially useful on a CI server where nobody is watching the log files to see if there are any warnings.

答: There doesn't seem to be any such option in the plugin. I've logged an issue requesting this (update: and submitted a patch too, which anyone can apply themselves as necessary).</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
X-Path Query won't work in Google-Sheets
I've been trying to use the following X-Path within Google-Sheets with the =ImportXML function

=importXml("http://www.managetickets.com/morecApp/ticketSearchAndStatusTicketList.jsp?msgCount=23&outputEmail=&db=nd", "/table[2]/tbody/tr@[td]")

But no matter what minor adjustments I try I continually get "#N/A" with a hover-text box that says "imported content is empty".

I know it's a valid x-path, I've cross verified it with 'X-Path Helper Wizard' chrome-extension.

Any ideas what I'm doing wrong!?

答:
No, actually it's not a valid XPath. Note that @ used to select an attributes e.g. @class, @id, etc. Also it's a bad idea to use tbody tag in your expressions as this tag is not always present in initial source code

So if you want to match table rows which contain cells from second table, you can use

```<code>/table[2]//tr[td]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
No, actually it's not a valid XPath. Note that @ used to select an attributes e.g. @class, @id, etc. Also it's a bad idea to use tbody tag in your expressions as this tag is not always present in initial source code

So if you want to match table rows which contain cells from second table, you can use

/table[2]//tr[td]


问:
Highest possible value of combinations of 5
According to https://www.heroescounters.com/teampicker a Hero has a synergy value with another hero, Heroes of the Storm have 60+ heroes each one with a synergy value for example:

```<code>HeroID  Synergy.With.HeroID      Synergy.Points
1               2                       97
1               3                       95
1               4                       94
45              1                       2
45              2                       11
</code>```

A Team in heroes of the storm have 5 heroes, and the full synergy of a team is calculated by the formula:

```<code>Team_total_synergy = Synergy_Points(Hero1 with Hero2) +
mean(Synergy_Points(Hero3 + Hero1) + Synergy_Points(Hero3 + Hero2)) +

mean(Synergy_Points(Hero4 + Hero1) + Synergy_Points(Hero4 + Hero2) + Synergy_Points(Hero4 + Hero3)

[And so on... till Hero5]
</code>```

Explaining the formula: Each Synergy Value after the synergy of Hero 1 and Hero 2 is calculated by the Mean of that Hero with the rest of the team, When Hero5 is added up i got the synergy of the team summing all the values.

My Answer is, How can I find(With Python or R) the Team with the greatest possible synergy given that formula, and how can I write the code to find it given the possibility there are 64 Heroes(approximately).

答:
The easiest way is to brute force it by counting all 64^5 combinations of heroes and calculating their total synergy score. However this would take a few minutes to an hour on most computers.

The more efficient approach is to first sort the Synergy.Points column highest to lowest. Then the problem becomes finding a 'path' of five heroes such that the highest position in the path is as low as possible on the table (ie associated with the most synergy).

A path is a list of heroes such that you jump from hero to associated hero until you have five unique heroes. In the below table, a path would be 1 -> 2 -> 5 -> 6 -> 7. The positions in the table associated with this path is 1, 4, 5, 2 where the highest point is 5.

This will guarantee that the total synergy is highest.

```<code>HeroID  Synergy.With.HeroID      Synergy.Points
1               2                       97
6               7                       95
1               4                       94
2               5                       11
5               6                       2
</code>```

As for the python code, this is a little trickier.... I tried working this out for about 20 minutes but I realize there are a lot of complications. For example, a path might have a cycle which might create an infinite loop if your program isn't careful.

If you want to do this process once to find the most efficient team for this game, I'd try the brute force method. If you want to be able to run this code over and over again, I'd pose this to the Computer Science stackoverflow and get and algorithm to do this in python.

I hope that helps : )

Body:
According to https://www.heroescounters.com/teampicker a Hero has a synergy value with another hero, Heroes of the Storm have 60+ heroes each one with a synergy value for example:

HeroID  Synergy.With.HeroID      Synergy.Points
1               2                       97
1               3                       95
1               4                       94
45              1                       2
45              2                       11

A Team in heroes of the storm have 5 heroes, and the full synergy of a team is calculated by the formula:

Team_total_synergy = Synergy_Points(Hero1 with Hero2) +
mean(Synergy_Points(Hero3 + Hero1) + Synergy_Points(Hero3 + Hero2)) +

mean(Synergy_Points(Hero4 + Hero1) + Synergy_Points(Hero4 + Hero2) + Synergy_Points(Hero4 + Hero3)

[And so on... till Hero5]

Explaining the formula: Each Synergy Value after the synergy of Hero 1 and Hero 2 is calculated by the Mean of that Hero with the rest of the team, When Hero5 is added up i got the synergy of the team summing all the values.

My Answer is, How can I find(With Python or R) the Team with the greatest possible synergy given that formula, and how can I write the code to find it given the possibility there are 64 Heroes(approximately).

Body:
The easiest way is to brute force it by counting all 64^5 combinations of heroes and calculating their total synergy score. However this would take a few minutes to an hour on most computers.

The more efficient approach is to first sort the Synergy.Points column highest to lowest. Then the problem becomes finding a 'path' of five heroes such that the highest position in the path is as low as possible on the table (ie associated with the most synergy).

A path is a list of heroes such that you jump from hero to associated hero until you have five unique heroes. In the below table, a path would be 1 -> 2 -> 5 -> 6 -> 7. The positions in the table associated with this path is 1, 4, 5, 2 where the highest point is 5.

This will guarantee that the total synergy is highest.

HeroID  Synergy.With.HeroID      Synergy.Points
1               2                       97
6               7                       95
1               4                       94
2               5                       11
5               6                       2

As for the python code, this is a little trickier.... I tried working this out for about 20 minutes but I realize there are a lot of complications. For example, a path might have a cycle which might create an infinite loop if your program isn't careful.

If you want to do this process once to find the most efficient team for this game, I'd try the brute force method. If you want to be able to run this code over and over again, I'd pose this to the Computer Science stackoverflow and get and algorithm to do this in python.

I hope that helps : )


问:
How to get only new items with addValueEventListener
When a child gets added into my firebase it Logs all the Annotation_City's in my firebase again. How can I get it to only print the new Annotation_City that got added?</p>

```<code>public void AllLocationMarkers() {
        grabMarkersFromDb = new Firebase("***");
        grabMarkersFromDb.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String city_Name = (String) locationSnapshot.child("Annotation_City").getValue();
                    Log.d("City updated", "city: " + city_Name);
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }
</code>```

答:
```<code>grabMarkersFromDb.addChildEventListener(new ChildEventListener() {
                            @Override
                            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                                //value add then it will call
                            }

                            @Override
                            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                            //value change
                            }

                            @Override
                            public void onChildRemoved(DataSnapshot dataSnapshot) {
                                // value remove
                            }

                            @Override
                            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });
</code>```

use  addChildEventListener for it. it will one by one value . and if value is add then its method onChildAdded will call.

read full documentation here.

Body:
When a child gets added into my firebase it Logs all the Annotation_City's in my firebase again. How can I get it to only print the new Annotation_City that got added?

public void AllLocationMarkers() {
        grabMarkersFromDb = new Firebase("***");
        grabMarkersFromDb.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String city_Name = (String) locationSnapshot.child("Annotation_City").getValue();
                    Log.d("City updated", "city: " + city_Name);
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }

Body:
grabMarkersFromDb.addChildEventListener(new ChildEventListener() {
                            @Override
                            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                                //value add then it will call
                            }

                            @Override
                            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                            //value change
                            }

                            @Override
                            public void onChildRemoved(DataSnapshot dataSnapshot) {
                                // value remove
                            }

                            @Override
                            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });

use  addChildEventListener for it. it will one by one value . and if value is add then its method onChildAdded will call.

read full documentation here.


问:
Is mysql insertion possible without the field names
To save time and space is it possible to insert into a mysql db without the use of the field names as shown below:

With the fields

```<code>INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`,`user_id`,`class_id)
values
    (1,1,1);
</code>```

Without the fields

```<code>INSERT INTO `wp_realty_listingsdb` values(1,1,1);
</code>```

答:
Yes, you can certainly omit the field names from an insert statement as you have done here:

```<code>INSERT INTO `wp_realty_listingsdb`
VALUES
    (1,1,1);
</code>```

However, the caviat is that MySQL will assume that your data is intended for the listingsdb_id, user_id, and class_id columns, in that order.  This would also assume that these columns also respectively appear in the first, second, and third positions of the table.

In general, it is probably best practice to always list the column names, for many reasons.  It makes it clear what you are actually doing.  Also, nameless inserts could break down the road if the table structure changes.

Body:
To save time and space is it possible to insert into a mysql db without the use of the field names as shown below:

With the fields

INSERT INTO `wp_realty_listingsdb` (`listingsdb_id`,`user_id`,`class_id)
values
    (1,1,1);

Without the fields

INSERT INTO `wp_realty_listingsdb` values(1,1,1);

Body:
Yes, you can certainly omit the field names from an insert statement as you have done here:

INSERT INTO `wp_realty_listingsdb`
VALUES
    (1,1,1);

However, the caviat is that MySQL will assume that your data is intended for the listingsdb_id, user_id, and class_id columns, in that order.  This would also assume that these columns also respectively appear in the first, second, and third positions of the table.

In general, it is probably best practice to always list the column names, for many reasons.  It makes it clear what you are actually doing.  Also, nameless inserts could break down the road if the table structure changes.


答:
Yes ! Its Possible To Insert Like This</p>

```<code>INSERT INTO `wp_realty_listingsdb` values(1,1,1);
</code>```

Title: Is mysql insertion possible without the field names

Body:
Yes ! Its Possible To Insert Like This

INSERT INTO `wp_realty_listingsdb` values(1,1,1);


问:
ASP.NET Web API 2 ApiController.Ok() not working, causing timeout
When request by client app, Timeout occurs.
I set breakpoints to check if the parameters were entered well in the controller method, and it looks fine.

Even after a while, an System.AccessViolationException occurs and my app crashes.

My Controller Code is here.

```<code>namespace REST_API_EX.Controllers
{
    public class DeliveriesController : ApiController
    {
        private DatabaseContext db = new DatabaseContext();

        [ResponseType(typeof(Delivery))]
        public async Task<IHttpActionResult> GetDeliveryByOrder_No(string Order_No)
        {
            Delivery delivery = await db.Deliveries
                .Where(d => d.Order_No == Order_No)
                .FirstAsync();
            if (delivery == null)
            {
                return NotFound();
            }
            return Ok(delivery);
        }
    }
}
</code>```

答:
since you're using EF6.
try

```<code>public class DeliveriesController : ApiController{
db.Configuration.LazyLoadingEnabled = false

// Your Code

}
</code>```

because EF tries to load the reference but end up looping in that.

Body:
When request by client app, Timeout occurs.
I set breakpoints to check if the parameters were entered well in the controller method, and it looks fine.

Even after a while, an System.AccessViolationException occurs and my app crashes.

My Controller Code is here.

namespace REST_API_EX.Controllers
{
    public class DeliveriesController : ApiController
    {
        private DatabaseContext db = new DatabaseContext();

        [ResponseType(typeof(Delivery))]
        public async Task<IHttpActionResult> GetDeliveryByOrder_No(string Order_No)
        {
            Delivery delivery = await db.Deliveries
                .Where(d => d.Order_No == Order_No)
                .FirstAsync();
            if (delivery == null)
            {
                return NotFound();
            }
            return Ok(delivery);
        }
    }
}

Body:
since you're using EF6.
try

public class DeliveriesController : ApiController{
db.Configuration.LazyLoadingEnabled = false

// Your Code

}

because EF tries to load the reference but end up looping in that.


问:
Using an interface as a type
I've been looking through some production code, and I'm a little confused on the concept of using an interface as a type (object)

I saw this explanation http://download.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

Here's the code below:

```<code>public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ( (obj1).isLargerThan(obj2) > 0)
      return object1;
   else
      return object2;
}
</code>```

Where Relatable is an interface, I don't understand where it gets the logic for the isLargerThan(obj2) function call.

Can somebody make this clear for me?

答: The logic comes from the class which implements the interface. This is exactly the reason why you cannot directly instantiate an interface, because the interface itself doesn't contain any implementation. The language ensures that the objects passed to your method are of a concrete class that implements the methods in the interface.</p>

Title: Using an interface as a type

Body:
I've been looking through some production code, and I'm a little confused on the concept of using an interface as a type (object)

I saw this explanation http://download.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

Here's the code below:

public Object findLargest(Object object1, Object object2) {
   Relatable obj1 = (Relatable)object1;
   Relatable obj2 = (Relatable)object2;
   if ( (obj1).isLargerThan(obj2) > 0)
      return object1;
   else
      return object2;
}

Where Relatable is an interface, I don't understand where it gets the logic for the isLargerThan(obj2) function call.

Can somebody make this clear for me?


问:
How to perform a cumulative sum but maintain zero values in MATLAB?
I need to do a cumulative sum in MATLAB, for a matrix of zeros and ones for each row, but I need to stop it when there are no more ones. Example, if I start with:

```<code>A = [0 0 0 0 0 1 1 1 1 1 0 0 0;
     0 0 0 1 1 1 1 1 1 1 0 0 0;
     0 0 0 0 0 0 0 1 1 0 0 0 0];
</code>```

I want the result:

```<code>B = [0 0 0 0 0 1 2 3 4 5 0 0 0;
     0 0 0 1 2 3 4 5 6 7 0 0 0;
     0 0 0 0 0 0 0 1 2 0 0 0 0];
</code>```

If I use cumsum, it will continue adding the values and give another result:

```<code>B = [0 0 0 0 0 1 2 3 4 5 5 5 5;
     0 0 0 1 2 3 4 5 6 7 7 7 7;
     0 0 0 0 0 0 0 1 2 2 2 2 2];
</code>```

Please, if someone has any suggestion as I can't find something similar (I have several quite large matrix).

答:
Find the cumulative sum of A and get positions of zeros in A and replace zero at these positions in the cumsum. </p>

```<code>A = [0 0 0 0 0 1 1 1 1 1 0 0 0;
     0 0 0 1 1 1 1 1 1 1 0 0 0;
     0 0 0 0 0 0 0 1 1 0 0 0 0];

B = cumsum(A,2) ;
B(A==0) = 0 ;
</code>```

OwnerDisplayName: siaskel

Body:
I need to do a cumulative sum in MATLAB, for a matrix of zeros and ones for each row, but I need to stop it when there are no more ones. Example, if I start with:

A = [0 0 0 0 0 1 1 1 1 1 0 0 0;
     0 0 0 1 1 1 1 1 1 1 0 0 0;
     0 0 0 0 0 0 0 1 1 0 0 0 0];

I want the result:

B = [0 0 0 0 0 1 2 3 4 5 0 0 0;
     0 0 0 1 2 3 4 5 6 7 0 0 0;
     0 0 0 0 0 0 0 1 2 0 0 0 0];

If I use cumsum, it will continue adding the values and give another result:

B = [0 0 0 0 0 1 2 3 4 5 5 5 5;
     0 0 0 1 2 3 4 5 6 7 7 7 7;
     0 0 0 0 0 0 0 1 2 2 2 2 2];

Please, if someone has any suggestion as I can't find something similar (I have several quite large matrix).

Body:
Find the cumulative sum of A and get positions of zeros in A and replace zero at these positions in the cumsum.

A = [0 0 0 0 0 1 1 1 1 1 0 0 0;
     0 0 0 1 1 1 1 1 1 1 0 0 0;
     0 0 0 0 0 0 0 1 1 0 0 0 0];

B = cumsum(A,2) ;
B(A==0) = 0 ;


答:
Insert NULL into the auto-increment field.

I recommend that unless this is a hack script, you use field names.  The rationale is that your code will break if you ever add a field to the table or change their order.

Instead, be explicit with field names, and it will go much better in the future.


问:
how to get rid of all trailing question marks and exclamation points in a string - ruby
How can I get rid of the trailing question marks and exclamation points in this string:

```<code> str = "Hello!!!!! World???"
</code>```

so that the final result is:

```<code>str = "Hello! World?"
</code>```

I only want the first "?" and "!" in the string.

答:
```<code>"Hello!!!!! World????".squeeze('!?')
  #=> "Hello! World?"
</code>```

See String#squeeze. Use squeeze! to modify the string in place.

Body:
How can I get rid of the trailing question marks and exclamation points in this string:

 str = "Hello!!!!! World???"

so that the final result is:

str = "Hello! World?"

I only want the first "?" and "!" in the string.

Body:
"Hello!!!!! World????".squeeze('!?')
  #=> "Hello! World?"

See String#squeeze. Use squeeze! to modify the string in place.


问:
Converting xls to csv in Python 3 using xlrd
I'm using Python 3.3 with xlrd and csv modules to convert an xls file to csv. This is my code:

```<code>import xlrd
import csv

def csv_from_excel():

    wb = xlrd.open_workbook('MySpreadsheet.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('test_output.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):

        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()
</code>```

With that I am receiving this error: TypeError: 'str' does not support the buffer interface

I tried changing the encoding and replaced the line within the loop with this:

```<code>wr.writerow(bytes(sh.row_values(rownum),'UTF-8'))
</code>```

But I get this error: TypeError: encoding or errors without a string argument

Anyone know what may be going wrong?

答:
A quicker way to do it with pandas:

```<code>import pandas as pd

xls_file = pd.read_excel('MySpreadsheet.xls', sheetname="Sheet1")
xls_file.to_csv('MySpreadsheet.csv', index = False)
#remove the index because pandas automatically indexes the first column of CSV files.
</code>```

You can read more about pandas.read_excel here.

Body:
I'm using Python 3.3 with xlrd and csv modules to convert an xls file to csv. This is my code:

import xlrd
import csv

def csv_from_excel():

    wb = xlrd.open_workbook('MySpreadsheet.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('test_output.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in range(sh.nrows):

        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

With that I am receiving this error: TypeError: 'str' does not support the buffer interface

I tried changing the encoding and replaced the line within the loop with this:

wr.writerow(bytes(sh.row_values(rownum),'UTF-8'))

But I get this error: TypeError: encoding or errors without a string argument

Anyone know what may be going wrong?

Body:
A quicker way to do it with pandas:

import pandas as pd

xls_file = pd.read_excel('MySpreadsheet.xls', sheetname="Sheet1")
xls_file.to_csv('MySpreadsheet.csv', index = False)
#remove the index because pandas automatically indexes the first column of CSV files.

You can read more about pandas.read_excel here.


问:
Why my image is different being plotted in Opencv-Python?
I am trying to take an image and convert it to grayscale, adding some gaussian blur to that image, and detecting the edges. I am having trouble displaying the image with matplotlib's pyplot.

```<code>import cv2
import matplotlib.pyplot as plt

def read_image_and_print_dims(image_path):
    """Reads and returns image.
    Helper function to examine ow an image is represented"""

    #reading an image
    image=cv2.imread(image_path)
    #printing out some stats and plottin
    print('This image is ',type(image),' with dinmesions',image.shape)
    plt.subplot(2,2,3)
    plt.imshow(image)
    return image

image_path='fall-leaves.png'

img=read_image_and_print_dims(image_path)
#Make a blurred/smoothed version
def gaussian_blur(img,kernel_size):

    """Applies a Gaussian Noise Kernel"""
    print ('Inside Gaussian')

    return cv2.GaussianBlur(img,(kernel_size,kernel_size),4)

#Gray Scale Image
def grayscale(img):
    """Applies the Grayscale transform
        This will return an image with only one color channel
        but NOTE: to see the returned image as grayscale
        you should call plimshow(gray, cmap='gray')"""
    print ('Inside gray sale')
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# gray scale it
greyscaled_image = grayscale(img)
plt.subplot(2, 2, 1)

plt.imshow(greyscaled_image, cmap='gray')

# smooth it a bit with Gaussian blur
kernal_size = 11
blur_gray = gaussian_blur(img, kernal_size)

plt.subplot(2, 2, 2)
plt.imshow(blur_gray)

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

While running above code in Pycharm it generates following message:

```<code>('This image is ', <type 'numpy.ndarray'>, ' with dinmesions', (320L, 400L, 3L))
Inside gray sale
Inside Gaussian
</code>```

But it doesn't plot the image.

EDIT

I got it to display using plt.show. However, now I'm having a different problem. I obtained this figure from pyplot, but using cv2.imshow, I got these: top two images, bottom two images

This is my code for plt.show:

```<code>#REad Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def read_image_and_print_dims(image_path):
    """Reads and returns image.
    Helper function to examine ow an image is represented"""

    #reading an image
    image=cv2.imread(image_path)
    #printing out some stats and plottin
    print('This image is ',type(image),' with dinmesions',image.shape)
    plt.subplot(2,2,1)
    #cv2.imshow('Original Image',image)
    plt.imshow(image)
    return image

image_path='fall-leaves.png'

img=read_image_and_print_dims(image_path)
#Make a blurred/smoothed version
def gaussian_blur(img,kernel_size):

    """Applies a Gaussian Noise Kernel"""
    print ('Inside Gaussian')

    return cv2.GaussianBlur(img,(kernel_size,kernel_size),4)

#Gray Scale Image
def grayscale(img):
    """Applies the Grayscale transform
        This will return an image with only one color channel
        but NOTE: to see the returned image as grayscale
        you should call plimshow(gray, cmap='gray')"""
    print ('Inside gray sale')
    gray_image=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return gray_image

def canny(img,low_threshold,high_threshold):
    """Applies the Canny Transform"""
    return  cv2.Canny(img,low_threshold,high_threshold)

# gray scale it
greyscaled_image = grayscale(img)
plt.subplot(2, 2, 2)
plt.imshow(greyscaled_image)
#cv2.imshow('grey scale',greyscaled_image)

# smooth it a bit with Gaussian blur
kernal_size = 11
blur_gray = gaussian_blur(img, kernal_size)

plt.subplot(2, 2, 3)
plt.imshow(blur_gray)
#cv2.imshow('gaussian ',blur_gray)

#Canny image detection

edges_image=canny(blur_gray,50,150)

plt.subplot(2, 2, 4)
plt.imshow(edges_image)
plt.show()
#cv2.imshow('Canny image detection',edges_image)
#
# cv2.waitKey(0)
# cv2.destroyAllWindows()
</code>```

And this is my code for using cv2.imshow:

```<code>#REad Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def read_image_and_print_dims(image_path):
    """Reads and returns image.
    Helper function to examine ow an image is represented"""

    #reading an image
    image=cv2.imread(image_path)
    #printing out some stats and plottin
    print('This image is ',type(image),' with dinmesions',image.shape)
    #plt.subplot(2,2,3)
    cv2.imshow('Original Image',image)
    return image

image_path='fall-leaves.png'

img=read_image_and_print_dims(image_path)
#Make a blurred/smoothed version
def gaussian_blur(img,kernel_size):

    """Applies a Gaussian Noise Kernel"""
    print ('Inside Gaussian')

    return cv2.GaussianBlur(img,(kernel_size,kernel_size),4)

#Gray Scale Image
def grayscale(img):
    """Applies the Grayscale transform
        This will return an image with only one color channel
        but NOTE: to see the returned image as grayscale
        you should call plimshow(gray, cmap='gray')"""
    print ('Inside gray sale')
    gray_image=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return gray_image

def canny(img,low_threshold,high_threshold):
    """Applies the Canny Transform"""
    return  cv2.Canny(img,low_threshold,high_threshold)

# gray scale it
greyscaled_image = grayscale(img)
#plt.subplot(2, 2, 1)

cv2.imshow('grey scale',greyscaled_image)

# smooth it a bit with Gaussian blur
kernal_size = 11
blur_gray = gaussian_blur(img, kernal_size)

#plt.subplot(2, 2, 2)
cv2.imshow('gaussian ',blur_gray)

#Canny image detection

edges_image=canny(blur_gray,50,150)

cv2.imshow('Canny image detection',edges_image)

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Different images are obtained using pyplot and cv2. Shouldn't the same image be obtained?

答:
You should use plt.show() to get the plot to display after you create the subplots.

Matplotlib assumes RGB order while OpenCV uses BGR ordering. To get the Matplotlib images the correct color, you need to swap the first and last channel around. You can use the built-in OpenCV method rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB) to change them before you display them.

Also the images on the right in plt.imshow() are not using a gray colormap even though they are gray images. You need to use plt.imshow(blur_gray, cmap='gray') and plt.imshow(edges_image, cmap='gray') to use the grayscale colormap. cv2.imshow() always displays grayscale when there is only one channel. Your top set of code use the correct colormaps.

Body:
I am trying to take an image and convert it to grayscale, adding some gaussian blur to that image, and detecting the edges. I am having trouble displaying the image with matplotlib's pyplot.

import cv2
import matplotlib.pyplot as plt

def read_image_and_print_dims(image_path):
    """Reads and returns image.
    Helper function to examine ow an image is represented"""

    #reading an image
    image=cv2.imread(image_path)
    #printing out some stats and plottin
    print('This image is ',type(image),' with dinmesions',image.shape)
    plt.subplot(2,2,3)
    plt.imshow(image)
    return image

image_path='fall-leaves.png'

img=read_image_and_print_dims(image_path)
#Make a blurred/smoothed version
def gaussian_blur(img,kernel_size):

    """Applies a Gaussian Noise Kernel"""
    print ('Inside Gaussian')

    return cv2.GaussianBlur(img,(kernel_size,kernel_size),4)

#Gray Scale Image
def grayscale(img):
    """Applies the Grayscale transform
        This will return an image with only one color channel
        but NOTE: to see the returned image as grayscale
        you should call plimshow(gray, cmap='gray')"""
    print ('Inside gray sale')
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# gray scale it
greyscaled_image = grayscale(img)
plt.subplot(2, 2, 1)

plt.imshow(greyscaled_image, cmap='gray')

# smooth it a bit with Gaussian blur
kernal_size = 11
blur_gray = gaussian_blur(img, kernal_size)

plt.subplot(2, 2, 2)
plt.imshow(blur_gray)

cv2.waitKey(0)
cv2.destroyAllWindows()

While running above code in Pycharm it generates following message:

('This image is ', <type 'numpy.ndarray'>, ' with dinmesions', (320L, 400L, 3L))
Inside gray sale
Inside Gaussian

But it doesn't plot the image.

EDIT

I got it to display using plt.show. However, now I'm having a different problem. I obtained this figure from pyplot, but using cv2.imshow, I got these: top two images, bottom two images

This is my code for plt.show:

#REad Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def read_image_and_print_dims(image_path):
    """Reads and returns image.
    Helper function to examine ow an image is represented"""

    #reading an image
    image=cv2.imread(image_path)
    #printing out some stats and plottin
    print('This image is ',type(image),' with dinmesions',image.shape)
    plt.subplot(2,2,1)
    #cv2.imshow('Original Image',image)
    plt.imshow(image)
    return image

image_path='fall-leaves.png'

img=read_image_and_print_dims(image_path)
#Make a blurred/smoothed version
def gaussian_blur(img,kernel_size):

    """Applies a Gaussian Noise Kernel"""
    print ('Inside Gaussian')

    return cv2.GaussianBlur(img,(kernel_size,kernel_size),4)

#Gray Scale Image
def grayscale(img):
    """Applies the Grayscale transform
        This will return an image with only one color channel
        but NOTE: to see the returned image as grayscale
        you should call plimshow(gray, cmap='gray')"""
    print ('Inside gray sale')
    gray_image=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return gray_image

def canny(img,low_threshold,high_threshold):
    """Applies the Canny Transform"""
    return  cv2.Canny(img,low_threshold,high_threshold)

# gray scale it
greyscaled_image = grayscale(img)
plt.subplot(2, 2, 2)
plt.imshow(greyscaled_image)
#cv2.imshow('grey scale',greyscaled_image)

# smooth it a bit with Gaussian blur
kernal_size = 11
blur_gray = gaussian_blur(img, kernal_size)

plt.subplot(2, 2, 3)
plt.imshow(blur_gray)
#cv2.imshow('gaussian ',blur_gray)

#Canny image detection

edges_image=canny(blur_gray,50,150)

plt.subplot(2, 2, 4)
plt.imshow(edges_image)
plt.show()
#cv2.imshow('Canny image detection',edges_image)
#
# cv2.waitKey(0)
# cv2.destroyAllWindows()

And this is my code for using cv2.imshow:

#REad Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def read_image_and_print_dims(image_path):
    """Reads and returns image.
    Helper function to examine ow an image is represented"""

    #reading an image
    image=cv2.imread(image_path)
    #printing out some stats and plottin
    print('This image is ',type(image),' with dinmesions',image.shape)
    #plt.subplot(2,2,3)
    cv2.imshow('Original Image',image)
    return image

image_path='fall-leaves.png'

img=read_image_and_print_dims(image_path)
#Make a blurred/smoothed version
def gaussian_blur(img,kernel_size):

    """Applies a Gaussian Noise Kernel"""
    print ('Inside Gaussian')

    return cv2.GaussianBlur(img,(kernel_size,kernel_size),4)

#Gray Scale Image
def grayscale(img):
    """Applies the Grayscale transform
        This will return an image with only one color channel
        but NOTE: to see the returned image as grayscale
        you should call plimshow(gray, cmap='gray')"""
    print ('Inside gray sale')
    gray_image=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return gray_image

def canny(img,low_threshold,high_threshold):
    """Applies the Canny Transform"""
    return  cv2.Canny(img,low_threshold,high_threshold)

# gray scale it
greyscaled_image = grayscale(img)
#plt.subplot(2, 2, 1)

cv2.imshow('grey scale',greyscaled_image)

# smooth it a bit with Gaussian blur
kernal_size = 11
blur_gray = gaussian_blur(img, kernal_size)

#plt.subplot(2, 2, 2)
cv2.imshow('gaussian ',blur_gray)

#Canny image detection

edges_image=canny(blur_gray,50,150)

cv2.imshow('Canny image detection',edges_image)

cv2.waitKey(0)
cv2.destroyAllWindows()

Different images are obtained using pyplot and cv2. Shouldn't the same image be obtained?


问:
ionic: Starter app with -v1
I am getting started with Ionic. I want to use ionic 1. I am using following command to create ionic v1 app as explained here.

ionic start -v1 myapp blank

But it's creating ionic v2 app using angular 2. I don't know why it is doing so. I also tried commands below but no luck.

ionic -v1 start myapp blank

ionic start myapp -v1 blank

ionic start myapp blank -v1

It's not showing any error or warning either. Can anyone please help? Thanks.

答: You need to downgrade your ionic version. Then run "ionic start myproject blank" without --v</p>

Title: ionic: Starter app with -v1


答:
When you change the dtype the way you do it, you do not change the data, but the interpretation of it. That means that for each int64 (your standard int type) you get 8 int8 values. And with the LSB order of bytes in memory, the lowest 8 bits (i.e., the lowest byte) are first, giving you your number (as long as it is smaller than 256) followed by 7 zeros.

What you probably want to do, is to convert the data, and generate a new memory layout, generating a new array from the old one, this can be done e.g. by:

```<code>x=np.array(x, dtype=np.int8)
</code>```

or simpler:

```<code>x.astype(np.int8)
</code>```

Title: changing the dtype of numpy array affects the data

Body:
While I'm playing around with numpy,

x = np.arange(9).reshape((3,3))
x

it returns array([[0, 1, 2],[3, 4, 5],[6, 7, 8]])

but once I change the datatype by

x.dtype=np.int8
x

now x becomes array([[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0,0, 0],[3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0,0, 0],[6, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0,0, 0]], dtype=int8), and x.shape returns (3, 24).

Why is this happening?

Thanks in advance!

Body:
When you change the dtype the way you do it, you do not change the data, but the interpretation of it. That means that for each int64 (your standard int type) you get 8 int8 values. And with the LSB order of bytes in memory, the lowest 8 bits (i.e., the lowest byte) are first, giving you your number (as long as it is smaller than 256) followed by 7 zeros.

What you probably want to do, is to convert the data, and generate a new memory layout, generating a new array from the old one, this can be done e.g. by:

x=np.array(x, dtype=np.int8)

or simpler:

x.astype(np.int8)


问:
MYSQL Query Error
I'm trying to use this query

```<code>$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject["id"]}", $connection);
</code>```

but i keep getting this error when loading my page .

Database query failed: You have an
  error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '' at line 1

答:
Try it without the complex syntax:

```<code>$query = 'SELECT * FROM pages WHERE subject_id = ' . $subject['id'];
$page_set = mysql_query($query, $connection);
</code>```

Incidentally, I loathe variable parsing in strings, and prefer concatenation.

Title: MYSQL Query Error

Body:
I'm trying to use this query

$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject["id"]}", $connection);

but i keep getting this error when loading my page .

Database query failed: You have an
  error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '' at line 1

Body:
Try it without the complex syntax:

$query = 'SELECT * FROM pages WHERE subject_id = ' . $subject['id'];
$page_set = mysql_query($query, $connection);

Incidentally, I loathe variable parsing in strings, and prefer concatenation.


问:
Real-time streaming using Python
I wish to develop a video encoder system using Raspberry Pi and I am using Python in order to do the encoding. Now I have to push this encoded video to a remote server live so that the server serves the video to the connected clients live. I have searched for a solution but didn't get a proper way to implement the same.</p>

答: You can do this with sockets. Check out this question. The top answer has pretty good client/server code that might suit your needs. </p>

Title: Real-time streaming using Python


问:
doinbackground() method is not called in aync task
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

```<code>private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}
</code>```

Any help is appreciated.
Thank you

答:
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

You cannot update UI as well as perform any UI operation on the background thread. doInBackground() is invoked on the background thread.

onPreExecute(),onPostExecute(Result), are invoked on the UI thread. So you can display toast here.

Body:
I am trying to upload post from my app to my database. To show the progress dialog when uploading is in progress I am using async task. The doinbackground() method is not executed. :

private ProgressDialog mProgress;
public void startPosting() {
//uploading posts
}

post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Task task=new Task();
             if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            else
                task.execute();
        }
    });

}

class Task extends AsyncTask<Void,Void,Void>{

        @Override
        protected void onPreExecute() {
            mProgress = new ProgressDialog(PostActivity.this);

            mProgress.setMessage("Posting Alert");
            mProgress.show();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                startPosting();
            }catch (Exception e){

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mProgress.dismiss();
            Toast.makeText(PostActivity.this, "Alert Posted", Toast.LENGTH_LONG).show();

        }
    }

}

Any help is appreciated.
Thank you


问:
Css positioning button at center of Overlay with image in background

.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="msg-ex msg-ex-box">
  <div class="msg-ex-overlay">
    <button class="msg-ex-cta">Show</button>
  </div>
</div></code>```

I am positioning my "Show" button at the center using transform: translateX(-48%) translateY(-47%); but ideally it should be transform: translateX(50%) translateY(50%); which centers it - cannot figure out what I am doing wrong. Please help.

答:
use following css for button which you want to make center

```<code>position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
</code>```

or

```<code>display:flex;
align-items:center;
justify-content:center;
</code>```

Body:
.msg-ex {
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
}

.msg-ex .msg-ex-overlay {
  position: relative;
  background-color: rgba(0, 0, 0, 0.4);
  width: 100%;
  height: 100%;
  opacity: 0;
  z-index: 2;
}

.msg-ex .msg-ex-overlay .msg-ex-cta {
  position: absolute;
  color: red;
  background-color: #DCE0E3;
  font-size: 1.1em;
  font-weight: 700;
  border-radius: 18px;
  height: 38px;
  width: 100px;
  cursor: pointer;
  top: 50%;
  left: 50%;
  transform: translateX(-48%) translateY(-47%);
}

.msg-ex .msg-ex-overlay:hover {
  opacity: 1;
}

.msg-ex-box {
  position: relative;
  background-color: $voiceColor;
}

.msg-ex-box::after {
  content: '';
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background-image: url(../pics/data/img1.png);
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  z-index: 1;
}

}
.msg-ex-voice:hover {
  background-color: rgba(0, 0, 0, 0.4);
}

    <button class="msg-ex-cta">Show</button>

I am positioning my "Show" button at the center using transform: translateX(-48%) translateY(-47%); but ideally it should be transform: translateX(50%) translateY(50%); which centers it - cannot figure out what I am doing wrong. Please help.

Body:
use following css for button which you want to make center

position:absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);

or

display:flex;
align-items:center;
justify-content:center;


问:
Autocomplete Ajax on cakephp 2
I want to know, how to create autocomplete in cakephp 2. I read on internet, but i can't find relevant info about my part.

Currently I load all data first at controller, assign to view then start the autocomplete from all datas. but this not efficient and takes time since the data could be alot. how can i filter the controller function to load only keyword i type on input? I am able to do this on PHP level, but i dunt know how on cakephp 2.

here my current codes on cakephp 2:

productcontroller this load all product on the stores:

```<code>$storeproducts = $this->get_storeproduct_autocomplete($sale['Sale']['store_id']);
</code>```

this is the input at my view:

```<code><input type="text" class="form-control" placeholder="Barcode/Nama barang..." name="search_keyword" id="searchProduct" />
</code>```

and at the bottom of the view i put script:

```<code>$(function() {
        var availableProduct = [
        <?php
        foreach ($products as $spro):
            $label = addslashes($spro['Product']['barcode'].' '.$spro['Product']['product_name']);

            ?>
            { label:"<?php echo $label;?>", value:"<?php echo $spro['Product']['barcode'];?>" },
            <?php
        endforeach;
        unset($spro);
        ?>
        ];
        $( "#searchProduct" ).autocomplete({
            source: availableProduct,
            delay: 200,
            minLength: 2
        });
    });
</code>```

By Using Those code, the autocomplete is working, but it load whole record first, not as the filter i type. and the input field is filled with barcode, or whatever value i set, but i want it show the product name, and when i submit, it got product id, can we do that?

Edit 1:
Update my controller, create new function to do the data filter that called via ajax:

```<code>public function ajax_get_autocomplete_storeproduct($keyword, $store_id)
    {
        $result = array();

        $storeproducts = $this->StoreProduct->find('all', array(
            'fields'=>array('StoreProduct.id', 'StoreProduct.stok'),
            'conditions'=>array('Product.deleted'=>0,
                                'StoreProduct.stok >'=>0,
                                'StoreProduct.store_id'=>$store_id,
                                'OR'=>array(
                                    'Product.barcode LIKE' => "%$keyword%",
                                    'Product.product_name LIKE' => "%$keyword%",
                                )
                               )));

        //how to set the value to view ?

        return new CakeResponse(array('body'=>json_encode($result)));
    }
</code>```

How to set the key:value from controller to data response at ajax?

答:
What you can do is, you can call ajax function in autocomplete. So on page load, you dont have to do anything. But on key type, ajax function will be called.

```<code>$("#searchProduct").autocomplete({
     source: function (request, response) {
          $.ajax({
              url: "add url for function call in ajax",
              dataType: "json",
              type: "post",
              data: {key: value},// if you want to send any values to ajax call, you can do it here.
              success: function (data) {
                   response(data);
              }
          });
      },
      minLength: 2,
      delay: 200// im not sure why u need delay.
 });
</code>```

In that function for which ajax call goes, populate the array there and echo the array in json format using echo json_encode($array);. It will work.

Edit

Your controller function should look like this

```<code>function products() {
    $array[0]['name'] = "Product - 1";
    $array[0]['price'] = 100;
    $array[1]['name'] = "Product - 2";
    $array[1]['price'] = 200;
    // like above populate all your products in to an array.

    // at last add this line
    echo json_encode($array);// this will generate key: value what you asked.
}
</code>```

Title: Autocomplete Ajax on cakephp 2

Body:
I want to know, how to create autocomplete in cakephp 2. I read on internet, but i can't find relevant info about my part.

Currently I load all data first at controller, assign to view then start the autocomplete from all datas. but this not efficient and takes time since the data could be alot. how can i filter the controller function to load only keyword i type on input? I am able to do this on PHP level, but i dunt know how on cakephp 2.

here my current codes on cakephp 2:

productcontroller this load all product on the stores:

$storeproducts = $this->get_storeproduct_autocomplete($sale['Sale']['store_id']);

this is the input at my view:

<input type="text" class="form-control" placeholder="Barcode/Nama barang..." name="search_keyword" id="searchProduct" />

and at the bottom of the view i put script:

$(function() {
        var availableProduct = [
        <?php
        foreach ($products as $spro):
            $label = addslashes($spro['Product']['barcode'].' '.$spro['Product']['product_name']);

            ?>
            { label:"<?php echo $label;?>", value:"<?php echo $spro['Product']['barcode'];?>" },
            <?php
        endforeach;
        unset($spro);
        ?>
        ];
        $( "#searchProduct" ).autocomplete({
            source: availableProduct,
            delay: 200,
            minLength: 2
        });
    });

By Using Those code, the autocomplete is working, but it load whole record first, not as the filter i type. and the input field is filled with barcode, or whatever value i set, but i want it show the product name, and when i submit, it got product id, can we do that?

Edit 1:
Update my controller, create new function to do the data filter that called via ajax:

public function ajax_get_autocomplete_storeproduct($keyword, $store_id)
    {
        $result = array();

        $storeproducts = $this->StoreProduct->find('all', array(
            'fields'=>array('StoreProduct.id', 'StoreProduct.stok'),
            'conditions'=>array('Product.deleted'=>0,
                                'StoreProduct.stok >'=>0,
                                'StoreProduct.store_id'=>$store_id,
                                'OR'=>array(
                                    'Product.barcode LIKE' => "%$keyword%",
                                    'Product.product_name LIKE' => "%$keyword%",
                                )
                               )));

        //how to set the value to view ?

        return new CakeResponse(array('body'=>json_encode($result)));
    }

How to set the key:value from controller to data response at ajax?

Body:
What you can do is, you can call ajax function in autocomplete. So on page load, you dont have to do anything. But on key type, ajax function will be called.

$("#searchProduct").autocomplete({
     source: function (request, response) {
          $.ajax({
              url: "add url for function call in ajax",
              dataType: "json",
              type: "post",
              data: {key: value},// if you want to send any values to ajax call, you can do it here.
              success: function (data) {
                   response(data);
              }
          });
      },
      minLength: 2,
      delay: 200// im not sure why u need delay.
 });

In that function for which ajax call goes, populate the array there and echo the array in json format using echo json_encode($array);. It will work.

Edit

Your controller function should look like this

function products() {
    $array[0]['name'] = "Product - 1";
    $array[0]['price'] = 100;
    $array[1]['name'] = "Product - 2";
    $array[1]['price'] = 200;
    // like above populate all your products in to an array.

    // at last add this line
    echo json_encode($array);// this will generate key: value what you asked.
}


问:
ASP.NET WEB API 2 Works Locally But Not On Production Web Server
I've developed a new WEB API 2 that works great locally, however when I upload the same code to my production server (Arvixe in this case) all I get is a 404 when I call it. I've spent HOURS searching the web, reading forums, etc.. and have been able to find no resolution, so I'm asking here as my last effort.

I'm currently only testing with the default project that gets created when you do New Project > ASP.NET Web API 2 Empty Project in Visual Studio. This creates an empty project with a single ValuesController. You should be able the JSON response by called /api/values, but this doesn't even work.

I'm using Fiddler to test the API locally and on the web server.

```<code>http://localhost:1993/api/values    <--- works great
</code>```

but

```<code>http://api.mydomain.com/api/values   <--- returns 404
</code>```

Note: I created a subdomain "api" in this case, but everything for the code for the API is unchanged from when it was created.

Why in the world does this work locally but not on the production web server?

答:
Please verify the .net framework on you hosted domain that may be old one.

Web api 2 is supposed on 4.5 framework.

Body:
I've developed a new WEB API 2 that works great locally, however when I upload the same code to my production server (Arvixe in this case) all I get is a 404 when I call it. I've spent HOURS searching the web, reading forums, etc.. and have been able to find no resolution, so I'm asking here as my last effort.

I'm currently only testing with the default project that gets created when you do New Project > ASP.NET Web API 2 Empty Project in Visual Studio. This creates an empty project with a single ValuesController. You should be able the JSON response by called /api/values, but this doesn't even work.

I'm using Fiddler to test the API locally and on the web server.

http://localhost:1993/api/values    <--- works great

but

http://api.mydomain.com/api/values   <--- returns 404

Note: I created a subdomain "api" in this case, but everything for the code for the API is unchanged from when it was created.

Why in the world does this work locally but not on the production web server?


问:
Why an immutable class is mutable in Groovy?
Reading the "The Well-Grounded Java Developer" book by Benjamin J. Evans and Martijn Verburg I've encountered the following example in Groovy:

```<code>class Character {
    private int strength
    private int wisdom
}

def pc = new Character(strength: 10, wisdom: 15)
pc.strength = 18
println "STR [" + pc.strength + "] WIS [" + pc.wisdom + "]"
</code>```

The output of the snippet is the following:

```<code>STR [18] WIS [15]
</code>```

Till now there is no questions. The code above have been slightly modified with the @Immutable annotation, as the book suggests:

```<code>import groovy.transform.*

@Immutable
class Character {
    private int strength
    private int wisdom
}

def pc = new Character(strength: 10, wisdom: 15)

pc.strength = 18

println "STR [" + pc.strength + "] WIS [" + pc.wisdom + "]"
</code>```

The output of the last snippet is still the same:

```<code>STR [18] WIS [15]
</code>```

The expected result is anything but not like the one above...

Why does an object of an immutable class seem to act like a mutable one? Does conception of immutability in Groovy permit modification to class fields?

答:
In order to fix the issue that you reported is simple which is removing access modifier to fields. That should fix the issue.

```<code>import groovy.transform.Immutable
@Immutable
class Character {
    int strength
    int wisdom
}

def pc = new Character(strength: 10, wisdom: 15)

pc.strength = 18

println "STR [" + pc.strength + "] WIS [" + pc.wisdom + "]"
</code>```

Now, it will raise an exception, saying below :

groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: strength for class: Character

      at Character.setProperty(Script1.groovy)

      at Script1.run(Script1.groovy:10)

If you want more details on why the behavior is different, please refer here

Body:
Reading the "The Well-Grounded Java Developer" book by Benjamin J. Evans and Martijn Verburg I've encountered the following example in Groovy:

class Character {
    private int strength
    private int wisdom
}

def pc = new Character(strength: 10, wisdom: 15)
pc.strength = 18
println "STR [" + pc.strength + "] WIS [" + pc.wisdom + "]"

The output of the snippet is the following:

STR [18] WIS [15]

Till now there is no questions. The code above have been slightly modified with the @Immutable annotation, as the book suggests:

import groovy.transform.*

@Immutable
class Character {
    private int strength
    private int wisdom
}

def pc = new Character(strength: 10, wisdom: 15)

pc.strength = 18

println "STR [" + pc.strength + "] WIS [" + pc.wisdom + "]"

The output of the last snippet is still the same:

STR [18] WIS [15]

The expected result is anything but not like the one above...

Why does an object of an immutable class seem to act like a mutable one? Does conception of immutability in Groovy permit modification to class fields?

Body:
In order to fix the issue that you reported is simple which is removing access modifier to fields. That should fix the issue.

import groovy.transform.Immutable
@Immutable
class Character {
    int strength
    int wisdom
}

def pc = new Character(strength: 10, wisdom: 15)

pc.strength = 18

println "STR [" + pc.strength + "] WIS [" + pc.wisdom + "]"

Now, it will raise an exception, saying below :

groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: strength for class: Character

      at Character.setProperty(Script1.groovy)

      at Script1.run(Script1.groovy:10)

If you want more details on why the behavior is different, please refer here


问:
Cannot view website (running in glassfish home server / router ports are forwarded)
I would like to show the website I have made to a friend. But I just can't seem to get the website available to the rest of the web.

Ok, so the details are:

I created a jsp website

It is hosted on GlassFish v3

I forwarded port 8080 to the pc hosting GlassFish (Tested with this)

With all this as is, I don't know what else to do. I am 'n newbie web developer and I have tried the internet for answers but no luck. If anyone can assist, it would be greatly appreciated!

EDIT: I have a dyndns.org ddns that I am using. I also tried using my external IP, but to no avail.

答:
Make sure Glassfish is listening on the PC's real IP address, i.e. not on 127.0.0.1 (localhost). If it's running on localhost, then you'll be able to see it from the same machine, but not from anywhere else.

I'm not a glassfish user, though, so I can't tell you how to go about changing it.


问:
modify scala map values
I has learn scala recently,but I found a question when modify map values.

```<code>    def exercise1():Map[String, Int]={
      val map = createMap()
      var newMap = map
     for((k,v) <-  map){
       newMap(k) = 2 * v;
     }
      newMap
    }
</code>```

the function exercise1 can running. But when I change a line like next

```<code>newMap(k) = v * 2;
</code>```

I found it failed, why?

答:
I'm not sure what createMap() function returns, but my guess is that it returns a Map[String, Int].

If this is true, then your code fails because Map[String, Int] is immutable, and you can't reassign value to immutable map with this code newMap(k) = 2 * v. You must use mutable.Map[String, Int] here.

Example code (in scala REPL):

```<code>scala> val x = Map("foo" -> 1, "bar" -> 2)
x: scala.collection.immutable.Map[String,Int] = Map(foo -> 1, bar -> 2)

scala> var y: scala.collection.mutable.Map[String, Int] = scala.collection.mutable.Map(x.toSeq: _*)
y: scala.collection.mutable.Map[String,Int] = Map(foo -> 1, bar -> 2)

scala> y("foo") = 3

scala> y
res2: scala.collection.mutable.Map[String,Int] = Map(foo -> 3, bar -> 2)
</code>```

However, what you need here is just a new map with all the values being doubled, you can simply do:

```<code>x.map { case (k, v) => k -> 2 * v }
</code>```

Title: modify scala map values

Body:
I has learn scala recently,but I found a question when modify map values.

    def exercise1():Map[String, Int]={
      val map = createMap()
      var newMap = map
     for((k,v) <-  map){
       newMap(k) = 2 * v;
     }
      newMap
    }

the function exercise1 can running. But when I change a line like next

newMap(k) = v * 2;

I found it failed, why?

Body:
I'm not sure what createMap() function returns, but my guess is that it returns a Map[String, Int].

If this is true, then your code fails because Map[String, Int] is immutable, and you can't reassign value to immutable map with this code newMap(k) = 2 * v. You must use mutable.Map[String, Int] here.

Example code (in scala REPL):

scala> val x = Map("foo" -> 1, "bar" -> 2)
x: scala.collection.immutable.Map[String,Int] = Map(foo -> 1, bar -> 2)

scala> var y: scala.collection.mutable.Map[String, Int] = scala.collection.mutable.Map(x.toSeq: _*)
y: scala.collection.mutable.Map[String,Int] = Map(foo -> 1, bar -> 2)

scala> y("foo") = 3

scala> y
res2: scala.collection.mutable.Map[String,Int] = Map(foo -> 3, bar -> 2)

However, what you need here is just a new map with all the values being doubled, you can simply do:

x.map { case (k, v) => k -> 2 * v }


问:
Pandas read_excel: only read first few lines
Using pandas read_excel on about 100 excel files - some are large - I want to read the first few lines of each (header and first few rows of data).

This doesn't work but illustrates the goal (example reading 10 data rows):

```<code>workbook_dataframe = pd.read_excel(workbook_filename, nrows = 10)
</code>```

This is my current workaround:

```<code>workbook_dataframe = pd.read_excel(workbook_filename).head(10)
</code>```

Problem with the workaround is it has to read the entire excel file before taking the head.  I've also tried experimenting with skiprows and skip_footer, giving it negative numbers which just produces errors.

答: This isn't currently supported although looking at the code it doesn't look like it should be too hard. You can open an issue on the Github project page at https://github.com/pandas-dev/pandas/issues.</p>

Body:
Using pandas read_excel on about 100 excel files - some are large - I want to read the first few lines of each (header and first few rows of data).

This doesn't work but illustrates the goal (example reading 10 data rows):

workbook_dataframe = pd.read_excel(workbook_filename, nrows = 10)

This is my current workaround:

workbook_dataframe = pd.read_excel(workbook_filename).head(10)

Problem with the workaround is it has to read the entire excel file before taking the head.  I've also tried experimenting with skiprows and skip_footer, giving it negative numbers which just produces errors.


问:
How to trigger another controller on AngularJS?
I don't want to share data between controller. I just want to trigger controller C when i click either tab A or tab B.

```<code><body ng-controller="MainController">
   <div class="div1" ng-controller="ControllerA" ng-click="changeTab('tab1')">
    ...
   </div>
   <div class="div2" ng-controller="ControllerB" ng-click="changeTab('tab2')">
    ...
   </div>
   <div class="div3" ng-controller="ControllerC">
    ...
   </div>
</body>
</code>```

How this can be done ? Any idea ?

答:
$emit is way better that $broadcast : You can call controllers like following code. You can send data as well. Try this .

```<code>        <div ng-app="myApp" ng-controller="myCtrl">

            <button ng-click="sendData();"></button>

        </div>

        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope, $rootScope) {
                function sendData($scope) {
                    var arrayData = [1,2,3];
                    $rootScope.$emit('someEvent', arrayData);
                }

            });
            app.controller('yourCtrl', function($scope, $rootScope) {
                $rootScope.$on('someEvent', function(event, data) {
                    console.log(data);
                });
            });
        </script>
</code>```

or the simplest but not recommended way :

```<code><div ng-app="myApp">
    <div class="div1" ng-controller="ControllerA"  ng-show="tab1" ng-click="changeTab('tab1')">
        ...
    </div>
    <div class="div2" ng-controller="ControllerB" ng-show="tab2" ng-click="changeTab('tab2')">
        ...
    </div>
    <div class="div3" ng-controller="ControllerC">
        ...
    </div>
</div>

<script>
    var app = angular.module('myApp', []);
    app.run(function($rootScope) {
        $rootScope.tab1 = true;
        $rootScope.tab2 = false;
    });

    app.controller('ControllerA', function($scope, $rootScope) {
        $scope.changeTab = function (tab) {
            $rootScope.tab1 = true;
            $rootScope.tab2 = false;
        }
    });
    app.controller('ControllerB', function($scope, $rootScope) {
        $scope.changeTab = function (tab) {
            $rootScope.tab1 = false;
            $rootScope.tab2 = true;
        }
    });
    app.controller('ControllerC', function($scope, $rootScope) {

    });
</script>
</code>```

Body:
I don't want to share data between controller. I just want to trigger controller C when i click either tab A or tab B.

    ...

    ...

    ...

How this can be done ? Any idea ?

Body:
$emit is way better that $broadcast : You can call controllers like following code. You can send data as well. Try this .

        <div ng-app="myApp" ng-controller="myCtrl">

            <button ng-click="sendData();"></button>

        </div>

        <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope, $rootScope) {
                function sendData($scope) {
                    var arrayData = [1,2,3];
                    $rootScope.$emit('someEvent', arrayData);
                }

            });
            app.controller('yourCtrl', function($scope, $rootScope) {
                $rootScope.$on('someEvent', function(event, data) {
                    console.log(data);
                });
            });
        </script>

or the simplest but not recommended way :

<div ng-app="myApp">
    <div class="div1" ng-controller="ControllerA"  ng-show="tab1" ng-click="changeTab('tab1')">
        ...
    </div>
    <div class="div2" ng-controller="ControllerB" ng-show="tab2" ng-click="changeTab('tab2')">
        ...
    </div>
    <div class="div3" ng-controller="ControllerC">
        ...
    </div>
</div>

<script>
    var app = angular.module('myApp', []);
    app.run(function($rootScope) {
        $rootScope.tab1 = true;
        $rootScope.tab2 = false;
    });

    app.controller('ControllerA', function($scope, $rootScope) {
        $scope.changeTab = function (tab) {
            $rootScope.tab1 = true;
            $rootScope.tab2 = false;
        }
    });
    app.controller('ControllerB', function($scope, $rootScope) {
        $scope.changeTab = function (tab) {
            $rootScope.tab1 = false;
            $rootScope.tab2 = true;
        }
    });
    app.controller('ControllerC', function($scope, $rootScope) {

    });
</script>


问:
Get Filename Without Extension in Python
If I have a filename like one of these:

```<code>1.1.1.1.1.jpg

1.1.jpg

1.jpg
</code>```

How could I get only the filename, without the extension? Would a regex be appropriate?

答:
In most cases, you shouldn't use a regex for that.

```<code>os.path.splitext(filename)[0]
</code>```

This will also handle a filename like .bashrc correctly by keeping the whole name.

Body:
If I have a filename like one of these:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension? Would a regex be appropriate?

Body:
In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.


问:
Squeeze blank lines into one blank line in C
Hello to refer to the  same question but different code.

Replacing multiple new lines in a file with just one

```<code>int main(void){

    format();
    printf("\n");
    return 0;
}

void format(){
    int c;
    size_t nlines = 1;
    size_t nspace = 0;

    while (( c= getchar()) != EOF ){

        /*TABS*/
        if(c == '\t'){
            c = ' ';
        }
        /*SPACES*/
        if (c ==' '){
            if(nspace > 0){
                continue;
            }
            else{
                putchar(c);
                nspace++;
                nlines = 0;
            }
        }

        /*NEW LINE*/
        else if(c == '\n'){
            if(++nlines >2){
                continue;
            }
            else {
                nlines++;
                nspace = 0;
            }
            putchar(c);
        }
        else{
            putchar(c);
            nspace = 0;
            nlines = 0;
        }
    }
}
</code>```

I want to squeeze multiple blank lines into one blank line but it doesn't seem to work and on Cygwin terminal at the stdout, last line gives me extra blank line although the input doesn't have the blank line at the end.

For example

INPUT

```<code>Hello   Hi\n
\n
\n
Hey\t\tHola\n
</code>```

DESIRED OUTPUT

```<code>Hello Hi\n
\n
Hey Hola\n
</code>```

ACTUAL OUTPUT

```<code>Hello Hi\n
Hey Hola\n
</code>```

Please explain!

答:
You're incrementing nlines twice:

```<code>else if(c == '\n'){
    if(++nlines >2){  /* incremented here */
        continue;
    }
    else {
        nlines++;     /* incremented here */
        nspace = 0;
    }
    putchar(c);
}
</code>```

You just want to do it once.  I'd suggest just incrementing the counter until it hits 2 and then not incrementing it any more.  That just means  a small change:

```<code>    if(nlines >= 2){
        continue;
    }
</code>```

Body:
Hello to refer to the  same question but different code.

Replacing multiple new lines in a file with just one

int main(void){

    format();
    printf("\n");
    return 0;
}

void format(){
    int c;
    size_t nlines = 1;
    size_t nspace = 0;

    while (( c= getchar()) != EOF ){

        /*TABS*/
        if(c == '\t'){
            c = ' ';
        }
        /*SPACES*/
        if (c ==' '){
            if(nspace > 0){
                continue;
            }
            else{
                putchar(c);
                nspace++;
                nlines = 0;
            }
        }

        /*NEW LINE*/
        else if(c == '\n'){
            if(++nlines >2){
                continue;
            }
            else {
                nlines++;
                nspace = 0;
            }
            putchar(c);
        }
        else{
            putchar(c);
            nspace = 0;
            nlines = 0;
        }
    }
}

I want to squeeze multiple blank lines into one blank line but it doesn't seem to work and on Cygwin terminal at the stdout, last line gives me extra blank line although the input doesn't have the blank line at the end.

For example

INPUT

Hello   Hi\n
\n
\n
Hey\t\tHola\n

DESIRED OUTPUT

Hello Hi\n
\n
Hey Hola\n

ACTUAL OUTPUT

Hello Hi\n
Hey Hola\n

Please explain!

Body:
You're incrementing nlines twice:

else if(c == '\n'){
    if(++nlines >2){  /* incremented here */
        continue;
    }
    else {
        nlines++;     /* incremented here */
        nspace = 0;
    }
    putchar(c);
}

You just want to do it once.  I'd suggest just incrementing the counter until it hits 2 and then not incrementing it any more.  That just means  a small change:

    if(nlines >= 2){
        continue;
    }


问:
canOpenURL is getting failed but the open works for outlook iOS
I too saw many stack overflow question related to my question , I have implemented all the things they have mentioned and still it doesn't work. Before flagging duplicate please kind go through my complete question and I have implemented all of the required changes.

I am trying to open the outlook mail client app from my app. Please find the below code

```<code>let url = URL(string: "ms-outlook://compose?to=Feedback@myDomain.com&subject=Mobile%20App%20Feedback")
     if UIApplication.shared.canOpenURL(url!) {
        UIApplication.shared.open(url!)
    }
    else
    {
          AppDelegate.sharedDelegate().getRootViewController().showAlert(title: "Cannot send email", message: "There is no Outlook app installed on your device device.")
    }
</code>```

I have also added ms-outlook in my plist too.

```<code><key>LSApplicationQueriesSchemes</key>
<array>
    <string>ms-outlook</string>
</array>
</code>```

I am getting the below error

```<code>"This app is not allowed to query for scheme ms-outlook"
</code>```

I am testing in real device too. If I remove the canOpenURL check and directly open the url is working fine. I have no clue what I have been missing. Thanks in advance.

答:
I came out with alternate option.</p>

```<code>  let scheme : String = "ms-outlook://compose?to=Feedback@myDomain.com&subject=Mobile%20App%20Feedback"

    if let url = URL(string: scheme) {
        UIApplication.shared.open(url, options: [:], completionHandler: {
            (success) in
            if (success)
            {
                print("Open \(scheme): \(success)")
            }
            else
            {
                AppDelegate.sharedDelegate().getRootViewController().showAlert(title: "Cannot send email", message: "There is no Outlook app installed on your device.")
            }
        })
    }
</code>```

Body:
I too saw many stack overflow question related to my question , I have implemented all the things they have mentioned and still it doesn't work. Before flagging duplicate please kind go through my complete question and I have implemented all of the required changes.

I am trying to open the outlook mail client app from my app. Please find the below code

let url = URL(string: "ms-outlook://compose?to=Feedback@myDomain.com&subject=Mobile%20App%20Feedback")
     if UIApplication.shared.canOpenURL(url!) {
        UIApplication.shared.open(url!)
    }
    else
    {
          AppDelegate.sharedDelegate().getRootViewController().showAlert(title: "Cannot send email", message: "There is no Outlook app installed on your device device.")
    }

I have also added ms-outlook in my plist too.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>ms-outlook</string>
</array>

I am getting the below error

"This app is not allowed to query for scheme ms-outlook"

I am testing in real device too. If I remove the canOpenURL check and directly open the url is working fine. I have no clue what I have been missing. Thanks in advance.

Body:
I came out with alternate option.

  let scheme : String = "ms-outlook://compose?to=Feedback@myDomain.com&subject=Mobile%20App%20Feedback"

    if let url = URL(string: scheme) {
        UIApplication.shared.open(url, options: [:], completionHandler: {
            (success) in
            if (success)
            {
                print("Open \(scheme): \(success)")
            }
            else
            {
                AppDelegate.sharedDelegate().getRootViewController().showAlert(title: "Cannot send email", message: "There is no Outlook app installed on your device.")
            }
        })
    }


问:
How to highlight the day in datepicker on click of text box
Here is my code

```<code> <input type="text" name="date" class="datepicker" value="20-Jun-2017" readonly="">

$(".datepicker").each(function() {

    var date_val = $(this).val();

    $(this).datepicker({

        'setDate':  date_val,

        'pickDate': true,

        'dateFormat': 'd-M-y'
    });
});
</code>```

datepicker is highlighting only today's date, but not default textbox value.

Thanks in advance :)

答:
DatePicker highlights the selected date automatically, but there is a problem with your format of year. If you set it as 17 rather 2017, it will work.

Else try setting the date after initialization like below.

```<code>$(".datepicker").each(function() {

var date_val = $(this).val();

$(this).datepicker({

    'pickDate': true,

    'dateFormat': 'd-M-y'
});

$(this).datepicker( "setDate", new Date(date_val) );
});
</code>```

Body:
Here is my code

 <input type="text" name="date" class="datepicker" value="20-Jun-2017" readonly="">

$(".datepicker").each(function() {

    var date_val = $(this).val();

    $(this).datepicker({

        'setDate':  date_val,

        'pickDate': true,

        'dateFormat': 'd-M-y'
    });
});

datepicker is highlighting only today's date, but not default textbox value.

Thanks in advance :)

Body:
DatePicker highlights the selected date automatically, but there is a problem with your format of year. If you set it as 17 rather 2017, it will work.

Else try setting the date after initialization like below.

$(".datepicker").each(function() {

var date_val = $(this).val();

$(this).datepicker({

    'pickDate': true,

    'dateFormat': 'd-M-y'
});

$(this).datepicker( "setDate", new Date(date_val) );
});


问:
In Batch, using FIND or FINDSTR and saving its output to a variable with SET
I have a file that contains a lot of lines, e.g.

```<code>foo=1
foobar=2
bar=3
</code>```

I want to use FIND (or FINDSTR) to read this file and use SET to set a variable foobar to 2, etc.

I would much prefer to only use Batch and tools that come with Windows - no third-party tools. But if it's impossible without any, then I'm open to using them.

答:
What do you need find or findstr for?

If your file is structured as you suggest, then

```<code>for /f "delims=" %%a in (filename) do set "%%a"
</code>```

will set those variables to the values.

Body:
I have a file that contains a lot of lines, e.g.

foo=1
foobar=2
bar=3

I want to use FIND (or FINDSTR) to read this file and use SET to set a variable foobar to 2, etc.

I would much prefer to only use Batch and tools that come with Windows - no third-party tools. But if it's impossible without any, then I'm open to using them.

Body:
What do you need find or findstr for?

If your file is structured as you suggest, then

for /f "delims=" %%a in (filename) do set "%%a"

will set those variables to the values.


问:
Why do we need a return address?
On a call stack, we have a frame pointer which gives us the location of the arguments to a procedure and the address of a pointer to the previous frame. We also have a return address. Why it the return address necessary? Could we not just follow the frame pointers back up the stack, popping off the stack frames as we went? Is the return address just an optimisation?</p>

答: return address refers to address of the code segment or instruction whose function call has created that stack.It is very important data as per vulnerabilities, as in case of buffer overrun,attackers get address space which can lead to compromising state </p>

Title: Why do we need a return address?


答:
Try something like this:

```<code><input type="text" id="datepicker" value="1-Jun-17" />

$('#datepicker').datepicker({
    'dateFormat': 'd-M-y'
});
</code>```

Working Fiddle

Title: How to highlight the day in datepicker on click of text box

Body:
Try something like this:

<input type="text" id="datepicker" value="1-Jun-17" />

$('#datepicker').datepicker({
    'dateFormat': 'd-M-y'
});

Working Fiddle


问:
java.io.FileNotFoundException: class path resource can't be opened
I work on Spring web MVC project and try to write some test for the database operations. The test class is provided below,

```<code>@ActiveProfiles("dev")
@ContextConfiguration(locations = {
        "classpath:com/puut/bitcoin/config/dao-context.xml",
//        "classpath:com/puut/bitcoin/config/security-context.xml",
        "classpath:com/puut/bitcoin/dao/test/config/datasource.xml"
})

@RunWith(SpringJUnit4ClassRunner.class)
public class OfferDaoTests {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private OffersDao offersDao;

    @Before
    public void init() {
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);

        jdbc.execute("delete from offers");
        jdbc.execute("delete from users");
        jdbc.execute("delete from authorities");
    }

    @Test
    public void testCreateUser() {

        Offer offer = new Offer("johnwpurcell", "john@caveofprogramming.com", "This is a test offer.");

        assertTrue("Offer creation should return true", offersDao.create(offer));

        List<Offer> offers = offersDao.getOffers();

        assertEquals("Should be one offer in database.", 1, offers.size());

        assertEquals("Retrieved offer should match created offer.", offer, offers.get(0));

        // Get the offer with ID filled in.
        offer = offers.get(0);

        offer.setText("Updated offer text.");
        assertTrue("Offer update should return true", offersDao.update(offer));

        Offer updated = offersDao.getOffer(offer.getId());

        assertEquals("Updated offer should match retrieved updated offer", offer, updated);

        offersDao.delete(offer.getId());

        List<Offer> empty = offersDao.getOffers();

        assertEquals("Offers lists should be empty.", 0, empty.size());
    }
}
</code>```

The project structure is provided below,

I get the error informing that the datasource.xml can't be opened, because, it doesn't exist. Its indeed exist and the path is correct as well.

```<code>Caused by: java.io.FileNotFoundException: class path resource [com/puut/bitcoin/dao/test/config/datasource.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
</code>```

In the datasource.xml file, I see that the Application context is not configured for this file and IntelliJ is literally provided some option to do so.

This is not very clear to me as I have defined this file in the OfferDaoTests as following,

```<code>@ContextConfiguration(locations = {
            "classpath:com/puut/bitcoin/config/dao-context.xml",
    //        "classpath:com/puut/bitcoin/config/security-context.xml",
            "classpath:com/puut/bitcoin/dao/test/config/datasource.xml"
    })
</code>```

I don't see the point to define the file in the web.xml as well. Because, this is only to test the database operations. Also, suddenly gets some error in the web.xml which was not here a while ago.

Any thoughts?

答:
As per the Spring documentation, the @ContextConfiguration lookup the resources. So, you could create a resource folder, preferably under /test folder, with the structure com/puut/bitcoin/dao/test/config/datasource.xml. This way the spring configuration should be able to read the resources for your test. So, your folder structure should look like:

```<code>/test/java - contains your test cases
/test/resources - contains your XML/configuration files
</code>```

Body:
I work on Spring web MVC project and try to write some test for the database operations. The test class is provided below,

@ActiveProfiles("dev")
@ContextConfiguration(locations = {
        "classpath:com/puut/bitcoin/config/dao-context.xml",
//        "classpath:com/puut/bitcoin/config/security-context.xml",
        "classpath:com/puut/bitcoin/dao/test/config/datasource.xml"
})

@RunWith(SpringJUnit4ClassRunner.class)
public class OfferDaoTests {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private OffersDao offersDao;

    @Before
    public void init() {
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);

        jdbc.execute("delete from offers");
        jdbc.execute("delete from users");
        jdbc.execute("delete from authorities");
    }

    @Test
    public void testCreateUser() {

        Offer offer = new Offer("johnwpurcell", "john@caveofprogramming.com", "This is a test offer.");

        assertTrue("Offer creation should return true", offersDao.create(offer));

        List<Offer> offers = offersDao.getOffers();

        assertEquals("Should be one offer in database.", 1, offers.size());

        assertEquals("Retrieved offer should match created offer.", offer, offers.get(0));

        // Get the offer with ID filled in.
        offer = offers.get(0);

        offer.setText("Updated offer text.");
        assertTrue("Offer update should return true", offersDao.update(offer));

        Offer updated = offersDao.getOffer(offer.getId());

        assertEquals("Updated offer should match retrieved updated offer", offer, updated);

        offersDao.delete(offer.getId());

        List<Offer> empty = offersDao.getOffers();

        assertEquals("Offers lists should be empty.", 0, empty.size());
    }
}

The project structure is provided below,

I get the error informing that the datasource.xml can't be opened, because, it doesn't exist. Its indeed exist and the path is correct as well.

Caused by: java.io.FileNotFoundException: class path resource [com/puut/bitcoin/dao/test/config/datasource.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)

In the datasource.xml file, I see that the Application context is not configured for this file and IntelliJ is literally provided some option to do so.

This is not very clear to me as I have defined this file in the OfferDaoTests as following,

@ContextConfiguration(locations = {
            "classpath:com/puut/bitcoin/config/dao-context.xml",
    //        "classpath:com/puut/bitcoin/config/security-context.xml",
            "classpath:com/puut/bitcoin/dao/test/config/datasource.xml"
    })

I don't see the point to define the file in the web.xml as well. Because, this is only to test the database operations. Also, suddenly gets some error in the web.xml which was not here a while ago.

Any thoughts?

Body:
As per the Spring documentation, the @ContextConfiguration lookup the resources. So, you could create a resource folder, preferably under /test folder, with the structure com/puut/bitcoin/dao/test/config/datasource.xml. This way the spring configuration should be able to read the resources for your test. So, your folder structure should look like:

/test/java - contains your test cases
/test/resources - contains your XML/configuration files


问:
MYSQL Query Error
I'm trying to use this query

```<code>$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject["id"]}", $connection);
</code>```

but i keep getting this error when loading my page .

Database query failed: You have an
  error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '' at line 1

答:
```<code>$sql = "SELECT * FROM pages WHERE subject_id = '".$subject["id"]."'";
$page_set = mysql_query($sql, $connection);
</code>```

Make sure you escape the subject_id also.

Title: MYSQL Query Error

Body:
I'm trying to use this query

$page_set = mysql_query("SELECT * FROM pages WHERE subject_id =
            {$subject["id"]}", $connection);

but i keep getting this error when loading my page .

Database query failed: You have an
  error in your SQL syntax; check the
  manual that corresponds to your MySQL
  server version for the right syntax to
  use near '' at line 1

Body:
$sql = "SELECT * FROM pages WHERE subject_id = '".$subject["id"]."'";
$page_set = mysql_query($sql, $connection);

Make sure you escape the subject_id also.


问:
Unable to get an result with only an simple if not null with MySql
```<code>SELECT `a`.`id`   AS `id`,
       `a`.`info` AS `info`,
       `a`.`type` AS `type`,
       `a`.`disp` AS `disp`,
       `a`.`emp`  AS `emp`,
       `a`.`tel`  AS `tel`,
       `a`.`img`  AS `img`,
       `a`.`job`  AS `job`
FROM ((`my_shop` `a`
       LEFT JOIN `my_shop2` `b`
           ON(( `a`.`id` = `b`.`my_shop_id` )))
       JOIN `my_shop3` `c`
           ON(( Ifnull(`b`.`my_shop_id`, `a`.`id`) = `c`.`id` )))
</code>```

<p>I've added a field in my_shop table called "personal_id". And what I want to do is to  get the above information if the personal_id field contains an id. How will I achieve this ? Some example or tips would be great! I would love to hear from you! </p>

答:
Try this

If you want JOIN personal_id with my_shop3, use below

```<code>SELECT a.id AS id,
       a.info AS info,
       a.type AS type,
       a.disp AS disp,
       a.emp  AS emp,
       a.tel  AS tel,
       a.img  AS img,
       a.job  AS job
FROM my_shop a  LEFT JOIN my_shop2 b ON a.id = b.my_shop_id
       JOIN my_shop3 c ON Ifnull(b.my_shop_id, a.id) = c.id  AND a.personal_id = C.id
</code>```

If you want use personal_id with WHERE clause, use below

```<code>SELECT a.id AS id,
       a.info AS info,
       a.type AS type,
       a.disp AS disp,
       a.emp  AS emp,
       a.tel  AS tel,
       a.img  AS img,
       a.job  AS job
FROM my_shop a  LEFT JOIN my_shop2 b ON a.id = b.my_shop_id
       JOIN my_shop3 c ON Ifnull(b.my_shop_id, a.id) = c.id
WHERE a.personal_id = <id value>
</code>```

Body:
SELECT `a`.`id`   AS `id`,
       `a`.`info` AS `info`,
       `a`.`type` AS `type`,
       `a`.`disp` AS `disp`,
       `a`.`emp`  AS `emp`,
       `a`.`tel`  AS `tel`,
       `a`.`img`  AS `img`,
       `a`.`job`  AS `job`
FROM ((`my_shop` `a`
       LEFT JOIN `my_shop2` `b`
           ON(( `a`.`id` = `b`.`my_shop_id` )))
       JOIN `my_shop3` `c`
           ON(( Ifnull(`b`.`my_shop_id`, `a`.`id`) = `c`.`id` )))

I've added a field in my_shop table called "personal_id". And what I want to do is to  get the above information if the personal_id field contains an id. How will I achieve this ? Some example or tips would be great! I would love to hear from you!

Body:
Try this

If you want JOIN personal_id with my_shop3, use below

SELECT a.id AS id,
       a.info AS info,
       a.type AS type,
       a.disp AS disp,
       a.emp  AS emp,
       a.tel  AS tel,
       a.img  AS img,
       a.job  AS job
FROM my_shop a  LEFT JOIN my_shop2 b ON a.id = b.my_shop_id
       JOIN my_shop3 c ON Ifnull(b.my_shop_id, a.id) = c.id  AND a.personal_id = C.id

If you want use personal_id with WHERE clause, use below

SELECT a.id AS id,
       a.info AS info,
       a.type AS type,
       a.disp AS disp,
       a.emp  AS emp,
       a.tel  AS tel,
       a.img  AS img,
       a.job  AS job
FROM my_shop a  LEFT JOIN my_shop2 b ON a.id = b.my_shop_id
       JOIN my_shop3 c ON Ifnull(b.my_shop_id, a.id) = c.id
WHERE a.personal_id = <id value>


问:
Is uninstall/reinstall the best way to update PyCharm on Windows 7?
When I open PyCharm I get a nag that I need to update.  So I followed the link and found that it lead to a download of a new version.  Fine.  I downloaded it and started the installation wizard expecting to find an "Update" option.  But it goes right to asking me if I want to uninstall my old version.  I hesitate because I don't want to hose what is a good working system.

Looking for the voice of experience ... Are there any gotchas connected with uninstall/reinstall for PyCharm?

答:
Probably unnecessary by now, but in case anyone sees this in the future, what this does is uninstalls the previous version of PyCharm (or any Jetbrains IDE for that matter), but keeps for config and settings files intact. Once you uninstall the last version and install the newer one, you'll be able to import your settings from past versions.

EDIT:
Shortly after this, I discovered Jetbrains Toolbox which basically lets you update your IDEs dynamically, without having to uninstall/install manually.