答:
Welcome to the Wonderful World of JavaScript!

I'd suggest hitting F12 in your browser and taking advantage of your browser's console and developer tools. They'll show you any exceptions that occur when your code runs. In your case, commenting out that button will cause one: by removing entry-btn from your page's markup, the code that adds an event listener to it will fail as document.getElementById("entry-btn") will return null.

```<code>var btnEnter = document.getElementById("entry-btn"); // Uh oh! This is gone! document.getElementById returns null.
btnEnter.addEventListener("click", coverFadeOut);    // btnEnter is null. I can't add a listener to it!
</code>```

There's no need to add each function to a separate file. You just have to make sure that you're debugging while you're trying things out. (Incidentally, when it comes to grouping related files and functionality, you'd want to give the JavaScript Module Pattern or ES2015 modules a Google; they're the preferred way of keeping related pieces of code together).

Title: Is each Javascript function of a webpage supposed to be defined in its own separate .js file?

Body:
Welcome to the Wonderful World of JavaScript!

I'd suggest hitting F12 in your browser and taking advantage of your browser's console and developer tools. They'll show you any exceptions that occur when your code runs. In your case, commenting out that button will cause one: by removing entry-btn from your page's markup, the code that adds an event listener to it will fail as document.getElementById("entry-btn") will return null.

var btnEnter = document.getElementById("entry-btn"); // Uh oh! This is gone! document.getElementById returns null.
btnEnter.addEventListener("click", coverFadeOut);    // btnEnter is null. I can't add a listener to it!

There's no need to add each function to a separate file. You just have to make sure that you're debugging while you're trying things out. (Incidentally, when it comes to grouping related files and functionality, you'd want to give the JavaScript Module Pattern or ES2015 modules a Google; they're the preferred way of keeping related pieces of code together).


来源: stackexchange

问:
enum combination - vb.net
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Enum for storing and processing tasks As :

```<code>Public Enum TaskStatus
    none = 0
    completed = 2
    executing = 4
    executed = 8
    errors = 16
    uploaded = 32
    incomplete = 64
    all =-1
End Enum

Private Function Manage()
    Dim ts As TaskStatus = TaskStatus.none
    '' Task Performed with Error
    ts = TaskStatus.errors Or TaskStatus.executed
    '' Task Uploading
    ts = ts Or TaskStatus.uploaded
    ts = ts Or TaskStatus.completed
    CheckStatus(ts)
End Function

Private Function CheckStatus(ByVal ts As TaskStatus)
    '' Now i have to check for two or More Enums
    '' ts have current values := Error , Executed, Uploaded , Completed

    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' It is not working
    End If
    If ts = (TaskStatus.executed Or TaskStatus.uploaded Or TaskStatus.completed) Then
        '' It is not working
    End If
    If ts And (TaskStatus.uploaded Or TaskStatus.executed) Then
       '' Working, But Not Sure is it correct way ?
    End If
    If (ts And TaskStatus.completed) = TaskStatus.completed Then
        '' Completed
    End If
End Function
</code>```

Since ts have current values := Error Or Executed Or  Uploaded Or  Completed.

I can not use HasFlag due to framework 3.5.

How to compare If enum contains two or more specific values in it, as described in code ?

答:
If the completed bit is high, then it is completed. It doesn't matter which other bits are high.

You could complete with errors and have a value of 18 (completed + errors). It's still complete, and completed with errors.

If your program doesn't work with this logic, then you are using status bits incorrectly.

Also

I don't see why you would skip 1 in your enum

-1 to represent all is silly because all should be the sum of all your enum values

If you had defined your enum like this,

```<code>Public Enum TaskStatus
    completed = 1
    executing = 2
    executed = 4
    errors = 8
    uploaded = 16
End Enum
</code>```

all will now be 31

incomplete is when TaskStatus.Complete bit is 0

Here is how you could design it better and an effective usage example

```<code>Public Enum TaskStatus
    completed = 1
    executing = 2
    executed = 4
    errors = 8
    uploaded = 16
End Enum

Sub Main()
    CheckStatus(TaskStatus.executing + TaskStatus.uploaded)
    CheckStatus(TaskStatus.completed + TaskStatus.errors)
    CheckStatus(TaskStatus.completed)
    CheckStatus(TaskStatus.completed + TaskStatus.executing + TaskStatus.executed + TaskStatus.errors + TaskStatus.uploaded)
    Console.ReadLine()
End Sub

Private Sub CheckStatus(ByVal ts As TaskStatus)
    Console.WriteLine("TaskStatus value: {0}", ts)
    If ts And TaskStatus.completed Then
        If ts And TaskStatus.errors Then
            Console.WriteLine("completed with errors")
        Else
            Console.WriteLine("completed without errors")
        End If
    Else
        Console.WriteLine("not completed")
        If ts And TaskStatus.executing Then
            Console.WriteLine("still executing")
            If ts And TaskStatus.uploaded Then
                Console.WriteLine("finished uploading")
            Else
                Console.WriteLine("still uploading")
            End If
        End If
    End If
    If ts = 31 Then
        Console.WriteLine("you set all the status bits!")
    End If
    Console.WriteLine()
End Sub
</code>```

Output with test program:

TaskStatus value: 18

not completed

still executing

finished uploading

TaskStatus value: 9

completed with errors

TaskStatus value: completed

completed without errors

TaskStatus value: 31

completed with errors

you set all the status bits!

Think about why I removed incomplete. Each bit represents a boolean logical state i.e. it can only be one way or another. If you have a bit for completed and incomplete, then you could potentially have an illogical state where completed and incomplete are both high, a value of 66 + any or all other bits in your example (with the exception of all and none - also why I removed those). The state of complete and incomplete is undefined, so why waste the bit?

Executing and executed offer a similar conundrum, as not all combinations make sense, such as executing + executed, i.e. it is still executing but it has finished executing. But other combinations of these states make sense. Look at this:

             |executed: 0             |executed: 1                   |
----------------------------------------------------------------------
executing: 0 |not currently executing |executed, finished executing  |
executing: 1 |currently executing     |executed, still executing ??? |
```

If you fix the logic of your program, you will find that you don't need both bits. It is just a sign that there are issues elsewhere.

ContentLicense: CC BY-SA 3.0

Title: enum combination - vb.net

Body:
I have a project in Vb.net and windows form application with dotnet framework 3.5. I am using Enum for storing and processing tasks As :

Public Enum TaskStatus
    none = 0
    completed = 2
    executing = 4
    executed = 8
    errors = 16
    uploaded = 32
    incomplete = 64
    all =-1
End Enum

Private Function Manage()
    Dim ts As TaskStatus = TaskStatus.none
    '' Task Performed with Error
    ts = TaskStatus.errors Or TaskStatus.executed
    '' Task Uploading
    ts = ts Or TaskStatus.uploaded
    ts = ts Or TaskStatus.completed
    CheckStatus(ts)
End Function

Private Function CheckStatus(ByVal ts As TaskStatus)
    '' Now i have to check for two or More Enums
    '' ts have current values := Error , Executed, Uploaded , Completed

    If ts = (TaskStatus.uploaded Or TaskStatus.errors) Then
        '' It is not working
    End If
    If ts = (TaskStatus.executed Or TaskStatus.uploaded Or TaskStatus.completed) Then
        '' It is not working
    End If
    If ts And (TaskStatus.uploaded Or TaskStatus.executed) Then
       '' Working, But Not Sure is it correct way ?
    End If
    If (ts And TaskStatus.completed) = TaskStatus.completed Then
        '' Completed
    End If
End Function

Since ts have current values := Error Or Executed Or  Uploaded Or  Completed.

I can not use HasFlag due to framework 3.5.

How to compare If enum contains two or more specific values in it, as described in code ?

Body:
If the completed bit is high, then it is completed. It doesn't matter which other bits are high.

You could complete with errors and have a value of 18 (completed + errors). It's still complete, and completed with errors.

If your program doesn't work with this logic, then you are using status bits incorrectly.

Also

I don't see why you would skip 1 in your enum

-1 to represent all is silly because all should be the sum of all your enum values

If you had defined your enum like this,

Public Enum TaskStatus
    completed = 1
    executing = 2
    executed = 4
    errors = 8
    uploaded = 16
End Enum

all will now be 31

incomplete is when TaskStatus.Complete bit is 0

Here is how you could design it better and an effective usage example

Public Enum TaskStatus
    completed = 1
    executing = 2
    executed = 4
    errors = 8
    uploaded = 16
End Enum

Sub Main()
    CheckStatus(TaskStatus.executing + TaskStatus.uploaded)
    CheckStatus(TaskStatus.completed + TaskStatus.errors)
    CheckStatus(TaskStatus.completed)
    CheckStatus(TaskStatus.completed + TaskStatus.executing + TaskStatus.executed + TaskStatus.errors + TaskStatus.uploaded)
    Console.ReadLine()
End Sub

Private Sub CheckStatus(ByVal ts As TaskStatus)
    Console.WriteLine("TaskStatus value: {0}", ts)
    If ts And TaskStatus.completed Then
        If ts And TaskStatus.errors Then
            Console.WriteLine("completed with errors")
        Else
            Console.WriteLine("completed without errors")
        End If
    Else
        Console.WriteLine("not completed")
        If ts And TaskStatus.executing Then
            Console.WriteLine("still executing")
            If ts And TaskStatus.uploaded Then
                Console.WriteLine("finished uploading")
            Else
                Console.WriteLine("still uploading")
            End If
        End If
    End If
    If ts = 31 Then
        Console.WriteLine("you set all the status bits!")
    End If
    Console.WriteLine()
End Sub

Output with test program:

TaskStatus value: 18

not completed

still executing

finished uploading

TaskStatus value: 9

completed with errors

TaskStatus value: completed

completed without errors

TaskStatus value: 31

completed with errors

you set all the status bits!

Think about why I removed incomplete. Each bit represents a boolean logical state i.e. it can only be one way or another. If you have a bit for completed and incomplete, then you could potentially have an illogical state where completed and incomplete are both high, a value of 66 + any or all other bits in your example (with the exception of all and none - also why I removed those). The state of complete and incomplete is undefined, so why waste the bit?

Executing and executed offer a similar conundrum, as not all combinations make sense, such as executing + executed, i.e. it is still executing but it has finished executing. But other combinations of these states make sense. Look at this:

             |executed: 0             |executed: 1                   |
----------------------------------------------------------------------
executing: 0 |not currently executing |executed, finished executing  |
executing: 1 |currently executing     |executed, still executing ??? |

If you fix the logic of your program, you will find that you don't need both bits. It is just a sign that there are issues elsewhere.


问:
Replicating graphics in ggplot
Why do these graphics get so different using the plot and ggplot2? How to replicate the graphs made with the hist() command using the ggplot() command?

```<code>library(ggplot2)
library(ssmrob)
require(gridExtra)

data(MEPS2001)
attach(MEPS2001)
par(mfrow=c(1,2))
hist(ambexp,ylim = c(0,3500),xlim=c(0,20000) ,xlab = "Ambulatory Expenses", ylab = "Freq.",main = "")
hist(lnambx,ylim = c(0,800),xlim=c(0,12), xlab = "Log Ambulatory Expenses", ylab = "Freq.",main = "")
</code>```

```<code>df <- data.frame(MEPS2001)
attach(df)

par(mfrow=c(1,2))
g1 <- ggplot(data = MEPS2001, aes(ambexp)) +
  geom_histogram(binwidth=.5, colour="black", fill="white") +
  xlab("Ambulatory Expenses") +
  ylab("Freq.") +
  xlim(c(0, 20000)) +
  ylim(c(0,3500))

g2 <- ggplot(data = MEPS2001, aes(lnambx)) +
  geom_histogram(binwidth=.5, colour="black", fill="white") +
  xlab("Log Ambulatory Expenses") +
  ylab("Freq.") +
  xlim(c(0, 12)) +
  ylim(c(0,800))

grid.arrange(g1, g2, ncol=2)
</code>```

答:
Your problem is that geom_hist naturally aligns bars so they're centered on a value. By limiting the x-axis to 0 you're cutting off bar that should be centered on 0 (ggplot will not show it because it extends into a negative x value). This behavior can be changed to what you want by setting boundary in geom_hist as below:

```<code>g1 <- ggplot(data = MEPS2001, aes(ambexp)) +
  geom_histogram(binwidth=5000, colour="black", fill="white",boundary=0) +
  xlab("Ambulatory Expenses") +
  ylab("Freq.")+
  xlim(c(0,20000)) +
  ylim(c(0,3500))

g2 <- ggplot(data = MEPS2001, aes(lnambx)) +
  geom_histogram(binwidth=1, colour="black", fill="white",boundary=0) +
  xlab("Log Ambulatory Expenses") +
  ylab("Freq.") +
  xlim(c(0, 12)) +
  ylim(c(0,800))

grid.arrange(g1, g2, ncol=2)
</code>```

yelids

Title: Replicating graphics in ggplot

Body:
Why do these graphics get so different using the plot and ggplot2? How to replicate the graphs made with the hist() command using the ggplot() command?

library(ggplot2)
library(ssmrob)
require(gridExtra)

data(MEPS2001)
attach(MEPS2001)
par(mfrow=c(1,2))
hist(ambexp,ylim = c(0,3500),xlim=c(0,20000) ,xlab = "Ambulatory Expenses", ylab = "Freq.",main = "")
hist(lnambx,ylim = c(0,800),xlim=c(0,12), xlab = "Log Ambulatory Expenses", ylab = "Freq.",main = "")

df <- data.frame(MEPS2001)
attach(df)

par(mfrow=c(1,2))
g1 <- ggplot(data = MEPS2001, aes(ambexp)) +
  geom_histogram(binwidth=.5, colour="black", fill="white") +
  xlab("Ambulatory Expenses") +
  ylab("Freq.") +
  xlim(c(0, 20000)) +
  ylim(c(0,3500))

g2 <- ggplot(data = MEPS2001, aes(lnambx)) +
  geom_histogram(binwidth=.5, colour="black", fill="white") +
  xlab("Log Ambulatory Expenses") +
  ylab("Freq.") +
  xlim(c(0, 12)) +
  ylim(c(0,800))

grid.arrange(g1, g2, ncol=2)

Body:
Your problem is that geom_hist naturally aligns bars so they're centered on a value. By limiting the x-axis to 0 you're cutting off bar that should be centered on 0 (ggplot will not show it because it extends into a negative x value). This behavior can be changed to what you want by setting boundary in geom_hist as below:

g1 <- ggplot(data = MEPS2001, aes(ambexp)) +
  geom_histogram(binwidth=5000, colour="black", fill="white",boundary=0) +
  xlab("Ambulatory Expenses") +
  ylab("Freq.")+
  xlim(c(0,20000)) +
  ylim(c(0,3500))

g2 <- ggplot(data = MEPS2001, aes(lnambx)) +
  geom_histogram(binwidth=1, colour="black", fill="white",boundary=0) +
  xlab("Log Ambulatory Expenses") +
  ylab("Freq.") +
  xlim(c(0, 12)) +
  ylim(c(0,800))

grid.arrange(g1, g2, ncol=2)

yelids


问:
Multiple user access database with Sql server
I have an access database that is stored on a network drive where all users access the one file. The database is linked to Sql server tables located in a local on site server. In my vba code my connection is to the access database.  My question is I know it's possible to just connect to sql server from vba but all my queries are stored in Access, so will my code be able to run the queries from access if it's connected to Sql server or would I need to re-write all the queries? The problem we are having is that more than one user may be on the same record pulled up and they are overwriting each other's changes. Also a user may need to take the program on their laptop instead of having to remote in to their desktop at office. I was thinking I could just give them a copy each and that would solve the problem. Does anyone have any answers? </p>

答: Just re-write the queries in SQL Server.  It may be painful now, but it shouldn't be too bad, and down the road a bit, you'll be glad you moved everything to SQL Server (much faster, more stable, you're using a real DB, etc.)</p>


问:
python executing both if and else statement together
I am not sure why, but python is executing the if statement then the else statement in the same iteration

i'm cutting out unimportant code:

```<code>from livewires import games
...
...
def update(self):
  if games.keyboard.is_pressed(games.K_s):
    if self.y == games.screen.height/3:
      self.y = games.screen.height/2
    else:
      self.y = games.screen.height
</code>```

In my mind it should go:
if 's' is pressed:
then, if the height is equal to whatever do whatever
otherwise, do whatever2

But the computer is going:
if 's' is pressed
then, make the height equal to whatever and since the height is no longer equal to whatever, make it equal to whatever2

I have tried this by using single if statements with 'and' operators and all kinds of funky ways of doing it, but everything I do, the code just seems to move to the next line regardless of if/elif/else

I even tried implementing a sort of timer that kind of works, but is unreliable.

答:
It was a pretty easy fix. I added a timer in the init and added this:

```<code>def update(self):
  self.timer -= 1
  if self.timer == 0:
    self.timer = 8
    if games.keyboard.is_pressed(games.K_s):
      if self.y == games.screen.height/3:
        self.y = games.screen.height/2
      else:
        self.y = games.screen.height
</code>```

It took the pdb.set_trace() to figure out it did, in fact, execute both individually (just really fast). It moved so fast it looked like it did both simultaneously.

Body:
I am not sure why, but python is executing the if statement then the else statement in the same iteration

i'm cutting out unimportant code:

from livewires import games
...
...
def update(self):
  if games.keyboard.is_pressed(games.K_s):
    if self.y == games.screen.height/3:
      self.y = games.screen.height/2
    else:
      self.y = games.screen.height

In my mind it should go:
if 's' is pressed:
then, if the height is equal to whatever do whatever
otherwise, do whatever2

But the computer is going:
if 's' is pressed
then, make the height equal to whatever and since the height is no longer equal to whatever, make it equal to whatever2

I have tried this by using single if statements with 'and' operators and all kinds of funky ways of doing it, but everything I do, the code just seems to move to the next line regardless of if/elif/else

I even tried implementing a sort of timer that kind of works, but is unreliable.

Body:
It was a pretty easy fix. I added a timer in the init and added this:

def update(self):
  self.timer -= 1
  if self.timer == 0:
    self.timer = 8
    if games.keyboard.is_pressed(games.K_s):
      if self.y == games.screen.height/3:
        self.y = games.screen.height/2
      else:
        self.y = games.screen.height

It took the pdb.set_trace() to figure out it did, in fact, execute both individually (just really fast). It moved so fast it looked like it did both simultaneously.


问:
Python Pandas: selecting rows based on criteria
I have a pandas DataFrame in the following format:

```<code>df.head()

        y   y_pred
599     0   0
787     9   9
47      2   2
1237    1   1
1069    6   6
</code>```

I want to find the rows / index numbers - where y != y_pred.

I am trying to do it through Select but am not able to do so. Please help.

TIA

答:
Try:

```<code>df.index[df.y != df.y_pred]
</code>```

Let's alter your sample data

```<code>df.iloc[0, 0] = 1
df.iloc[3, 1] = 0
print(df)

      y  y_pred
599   1       0
787   9       9
47    2       2
1237  1       0
1069  6       6
</code>```

Then try our code

```<code>df.index[df.y != df.y_pred]

Int64Index([599, 1237], dtype='int64')
</code>```

For more efficiency, use the underlying numpy arrays

```<code>df.index.values[df.y.values != df.y_pred.values]

array([ 599, 1237])
</code>```

you can return the df subset with

```<code>df.loc[(df.y != df.y_pred).values]

      y  y_pred
599   1       0
1237  1       0
</code>```

Body:
I have a pandas DataFrame in the following format:

df.head()

        y   y_pred
599     0   0
787     9   9
47      2   2
1237    1   1
1069    6   6

I want to find the rows / index numbers - where y != y_pred.

I am trying to do it through Select but am not able to do so. Please help.

TIA

Body:
Try:

df.index[df.y != df.y_pred]

Let's alter your sample data

df.iloc[0, 0] = 1
df.iloc[3, 1] = 0
print(df)

      y  y_pred
599   1       0
787   9       9
47    2       2
1237  1       0
1069  6       6

Then try our code

df.index[df.y != df.y_pred]

Int64Index([599, 1237], dtype='int64')

For more efficiency, use the underlying numpy arrays

df.index.values[df.y.values != df.y_pred.values]

array([ 599, 1237])

you can return the df subset with

df.loc[(df.y != df.y_pred).values]

      y  y_pred
599   1       0
1237  1       0


问:
Location Listener in Android Intent Service
My app has an Intent Service which keeps checking on a web server if there is "start" or "stop" word on an html page every 100000ms.

If it receives "start" it starts a locationmanager.requestUpdateLocation(..), if it receives "stop" it stops it with locationmanager.removeUpdates(..).

But I've got this problem:

When I call locationmanager.requestUpdateLocation(..) I NEVER enter in my listener's onLocationChanged (that's implemented in the same scope of service).

Then, I observe that my Intent service doesn't live forever :( I put a receiver which captures the moment when Android boots up and starts it (and this work) and a ploy in which when my Intent service is closed by user it restarts himself :P

But it never lives forever, after few hours (or maybe only 30 minutes) it dies :(

Why?

Here's the code:

```<code>@Override
protected void onHandleIntent(@Nullable Intent intent) {

  Log.i("Service", "Started");

  LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
  LocationListener  locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
    //IT NEVER ENTER HERE
    Log.i("LOC", "LAT: " + location.getLatitude() +" LONG: "+location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onProviderDisabled(String provider) {
    //NEVER ENTER ALSO HERE
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      startActivity(intent);
    }
  };

  int localizzazioneAttiva=0;
  int delay = 0;

  while (true) {
    Log.i("SERVICE_CheckSito", "Check Sito STARTED");

    String inputLine = "";
    StringBuffer stringBuffer = new StringBuffer();
    //Check Permission and SKD_INT
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED)
    {
      if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {

        URL url;
        try
        {
          url = new URL("http://www.sito.com/file.html");
          HttpURLConnection httpURLConnection;
          httpURLConnection = (HttpURLConnection) url.openConnection();
          httpURLConnection.connect();
          if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

            try {
              while ((inputLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(inputLine).append("\n");
              }
            } finally {
              bufferedReader.close();
            }
          }
        } catch (IOException e) {
        //  e.printStackTrace();
        }
      } else return;
    }

    if (stringBuffer.toString().equals("start\n") && 0==localizzazioneAttiva )
    {
      localizzazioneAttiva=1;
      delay = 1000;
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, 0, locationListener);
    }
    if(stringBuffer.toString().equals("stop\n")) {
      delay = 2000;
      locationManager.removeUpdates(locationListener);
      localizzazioneAttiva=0;
    }

    Log.i("SERVICE_CheckSito", "Message from server: " + stringBuffer.toString());
    Log.i("SERVICE_CheckSito", "Check Sito FINISHED");
    try {
      Thread.sleep(delay);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
</code>```

答:
I should not answer after 3 beers. My bad, did not see you appending /n.

Consider using a plain Service and the FusedLocationProvider.

Body:
My app has an Intent Service which keeps checking on a web server if there is "start" or "stop" word on an html page every 100000ms.

If it receives "start" it starts a locationmanager.requestUpdateLocation(..), if it receives "stop" it stops it with locationmanager.removeUpdates(..).

But I've got this problem:

When I call locationmanager.requestUpdateLocation(..) I NEVER enter in my listener's onLocationChanged (that's implemented in the same scope of service).

Then, I observe that my Intent service doesn't live forever :( I put a receiver which captures the moment when Android boots up and starts it (and this work) and a ploy in which when my Intent service is closed by user it restarts himself :P

But it never lives forever, after few hours (or maybe only 30 minutes) it dies :(

Why?

Here's the code:

@Override
protected void onHandleIntent(@Nullable Intent intent) {

  Log.i("Service", "Started");

  LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
  LocationListener  locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
    //IT NEVER ENTER HERE
    Log.i("LOC", "LAT: " + location.getLatitude() +" LONG: "+location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onProviderDisabled(String provider) {
    //NEVER ENTER ALSO HERE
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
      startActivity(intent);
    }
  };

  int localizzazioneAttiva=0;
  int delay = 0;

  while (true) {
    Log.i("SERVICE_CheckSito", "Check Sito STARTED");

    String inputLine = "";
    StringBuffer stringBuffer = new StringBuffer();
    //Check Permission and SKD_INT
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED)
    {
      if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {

        URL url;
        try
        {
          url = new URL("http://www.sito.com/file.html");
          HttpURLConnection httpURLConnection;
          httpURLConnection = (HttpURLConnection) url.openConnection();
          httpURLConnection.connect();
          if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

            try {
              while ((inputLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(inputLine).append("\n");
              }
            } finally {
              bufferedReader.close();
            }
          }
        } catch (IOException e) {
        //  e.printStackTrace();
        }
      } else return;
    }

    if (stringBuffer.toString().equals("start\n") && 0==localizzazioneAttiva )
    {
      localizzazioneAttiva=1;
      delay = 1000;
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,2000, 0, locationListener);
    }
    if(stringBuffer.toString().equals("stop\n")) {
      delay = 2000;
      locationManager.removeUpdates(locationListener);
      localizzazioneAttiva=0;
    }

    Log.i("SERVICE_CheckSito", "Message from server: " + stringBuffer.toString());
    Log.i("SERVICE_CheckSito", "Check Sito FINISHED");
    try {
      Thread.sleep(delay);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}


问:
Image segmentation based on mouse click
Using python framework we are able to create image segments as shown in attachment. Now, based on the mouse click in the image segment we need to highlight the segment with specific color.

Based on the mouse click I am able to get x/y coordinates of the specific location. Please suggest me how can I check on which image segment the coordinates belongs to?

The following is the code snippet:

```<code>from skimage.segmentation import felzenszwalb, slic,quickshift
from skimage.segmentation import mark_boundaries
from skimage.segmentation import find_boundaries
from skimage.util import img_as_float
from skimage import io

import matplotlib.pyplot as plt

from skimage import measure
from skimage import restoration
from skimage import img_as_float

import numpy as np

coords = []

def find_nearest(array,value):

    idx = (np.abs(array-value)).argmin()

    return array[idx]

def onclick(event):

    global ix, iy

    ix, iy = event.xdata, event.ydata

    print ('ix ',ix)

    print ("iy ",iy)

    color = np.float64([1,0,1]) # red color

    image[segments == 14] = color

    mark_boundaries(image, segments)

    ax.imshow(mark_boundaries(image, segments))

    coords.append((ix, iy))

    return

image=img_as_float(io.imread("amazon.jpg"))

segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,
           return_tree=False, sigma=0, convert2lab=True, random_seed=42)

fig = plt.figure("Superpixels -- %d segments" % (500))

ax = fig.add_subplot(1, 1, 1)

fig,ax = plt.subplots()

color = np.float64([1,0,0])

image[segments == 14] = color  # desired segment to be colored

fig.canvas.mpl_connect('button_press_event', onclick)

ax.imshow(mark_boundaries(image, segments))

plt.axis("off")

plt.show()
</code>```

答:
According to the documentation, quickshift returns an integer mask indicating segment labels. If you know what pixel the user clicked on, you can check the value of that pixel in your variable segments to get the segment number.

In you click handler, you can use
clicked_segment = segments[event.xdata, event.ydata]

Title: Image segmentation based on mouse click

Body:
Using python framework we are able to create image segments as shown in attachment. Now, based on the mouse click in the image segment we need to highlight the segment with specific color.

Based on the mouse click I am able to get x/y coordinates of the specific location. Please suggest me how can I check on which image segment the coordinates belongs to?

The following is the code snippet:

from skimage.segmentation import felzenszwalb, slic,quickshift
from skimage.segmentation import mark_boundaries
from skimage.segmentation import find_boundaries
from skimage.util import img_as_float
from skimage import io

import matplotlib.pyplot as plt

from skimage import measure
from skimage import restoration
from skimage import img_as_float

import numpy as np

coords = []

def find_nearest(array,value):

    idx = (np.abs(array-value)).argmin()

    return array[idx]

def onclick(event):

    global ix, iy

    ix, iy = event.xdata, event.ydata

    print ('ix ',ix)

    print ("iy ",iy)

    color = np.float64([1,0,1]) # red color

    image[segments == 14] = color

    mark_boundaries(image, segments)

    ax.imshow(mark_boundaries(image, segments))

    coords.append((ix, iy))

    return

image=img_as_float(io.imread("amazon.jpg"))

segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,
           return_tree=False, sigma=0, convert2lab=True, random_seed=42)

fig = plt.figure("Superpixels -- %d segments" % (500))

ax = fig.add_subplot(1, 1, 1)

fig,ax = plt.subplots()

color = np.float64([1,0,0])

image[segments == 14] = color  # desired segment to be colored

fig.canvas.mpl_connect('button_press_event', onclick)

ax.imshow(mark_boundaries(image, segments))

plt.axis("off")

plt.show()


问:
Convert long number as string in the serialization
I have a custom made class that use a long as ID. However, when I call my action using ajax, my ID is truncated and it loses the last 2 numbers because javascript loses precision when dealing with large numbers. My solution would be to give a string to my javascript, but the ID have to stay as a long on the server side.

Is there a way to serialize the property as a string? I'm looking for some kind of attribute.

Controller

```<code>public class CustomersController : ApiController
{
   public IEnumerable<CustomerEntity> Get()
   {
      yield return new CustomerEntity() { ID = 1306270928525862486, Name = "Test" };
   }
}
</code>```

Model

```<code>public class CustomerEntity
{
   public long ID { get; set; }
   public string Name { get; set; }
}
</code>```

JSON Result

```<code>[{"Name":"Test","ID":1306270928525862400}]
</code>```

答:
Depending on your case, you could potentially use getters and setters to masquerade the property as a string during JSON serialization.</p>

```<code>public class Money
{
    [JsonIgnore]
    public decimal Money { get; set; }

    [JsonProperty("money")]
    public string MoneyAsString
    {
        get { return Money.ToString("0.00"); }
        set { Money = decimal.Parse(value); }
    }
}
</code>```

Body:
I have a custom made class that use a long as ID. However, when I call my action using ajax, my ID is truncated and it loses the last 2 numbers because javascript loses precision when dealing with large numbers. My solution would be to give a string to my javascript, but the ID have to stay as a long on the server side.

Is there a way to serialize the property as a string? I'm looking for some kind of attribute.

Controller

public class CustomersController : ApiController
{
   public IEnumerable<CustomerEntity> Get()
   {
      yield return new CustomerEntity() { ID = 1306270928525862486, Name = "Test" };
   }
}

Model

public class CustomerEntity
{
   public long ID { get; set; }
   public string Name { get; set; }
}

JSON Result

[{"Name":"Test","ID":1306270928525862400}]

Body:
Depending on your case, you could potentially use getters and setters to masquerade the property as a string during JSON serialization.

public class Money
{
    [JsonIgnore]
    public decimal Money { get; set; }

    [JsonProperty("money")]
    public string MoneyAsString
    {
        get { return Money.ToString("0.00"); }
        set { Money = decimal.Parse(value); }
    }
}


答:
Use query:

```<code>df = df.query('y != y_pred').index
</code>```

Sample:

```<code>print (df)
      y  y_pred
599   0       1 <-values changed for match
787   9       9
47    2       2
1237  1       1
1069  6       3 <-values changed for match

df = df.query('y != y_pred').index
print (df)
Int64Index([599, 1069], dtype='int64')
</code>```

Solutions with boolean indexing are:

```<code>df1 = df[df.y != df.y_pred].index
print (df1)
Int64Index([599, 1069], dtype='int64')
</code>```

Or another answer.

For check different values:

```<code>print (df.query('y != y_pred'))
      y  y_pred
599   0       1
1069  6       3

print (df[df.y != df.y_pred])
      y  y_pred
599   0       1
1069  6       3
</code>```

Title: Python Pandas: selecting rows based on criteria

Body:
Use query:

df = df.query('y != y_pred').index

Sample:

print (df)
      y  y_pred
599   0       1 <-values changed for match
787   9       9
47    2       2
1237  1       1
1069  6       3 <-values changed for match

df = df.query('y != y_pred').index
print (df)
Int64Index([599, 1069], dtype='int64')

Solutions with boolean indexing are:

df1 = df[df.y != df.y_pred].index
print (df1)
Int64Index([599, 1069], dtype='int64')

Or another answer.

For check different values:

print (df.query('y != y_pred'))
      y  y_pred
599   0       1
1069  6       3

print (df[df.y != df.y_pred])
      y  y_pred
599   0       1
1069  6       3


问:
Spring rabbit message consumption, payload wrong format
I am consuming messages from a queue in rabbitmq like that

```<code> @RabbitListener(queues = "#{'${rabbitmq.queues}'.split(',')}" )
public void processOrder(@Payload String data, @Header(AmqpHeaders.CONSUMER_QUEUE) String queue) {
</code>```

The data I am printing in my logger seems to be bytes, it is printing values like that: 116,104,114,116,104,114,116,104,114
What am I supposed to do and how please? Deserialization?

答:
The default SimpleMessageConverter can only handle String and serialized Java objects. Any content type it doesn't understand is returned as a byte[].

The content_type for a String should be text/plain.

What is the content of your message? Does the message have a content_type property? If so, what value?

If it's JSON (and application/json) you need a Jackson2JsonMessageConverter, but I see you expecting String, so I suspect it's just the missing content_type property.

Body:
I am consuming messages from a queue in rabbitmq like that

 @RabbitListener(queues = "#{'${rabbitmq.queues}'.split(',')}" )
public void processOrder(@Payload String data, @Header(AmqpHeaders.CONSUMER_QUEUE) String queue) {

The data I am printing in my logger seems to be bytes, it is printing values like that: 116,104,114,116,104,114,116,104,114
What am I supposed to do and how please? Deserialization?


问:
Base Class __init__ being called automatically from derived class
I am having a little hard time understanding why this is happening.
So far from what I have read about python is that the initializer of a base class needs to be explicitly called by the derived class.This is one of the source that confirms my understanding. However the following example baffles me

```<code>class foo(object) :
  def __init__(self,par):
    print "Inside foo constructor"

class bar(foo):
  status_code = 302

b = bar(23)
</code>```

In the above case the derived class does not have an initializer. So will it be correct for me to assume that the reason why the initializer of the base class is being called is because its being inherited by the derived class.

答: I believe that you have to explicitly call the base class's __init__ only if you define __init__ of the derived class. Otherwise it will be called automatically. This is actually exactly what the answer you link says.

Body:
I am having a little hard time understanding why this is happening.
So far from what I have read about python is that the initializer of a base class needs to be explicitly called by the derived class.This is one of the source that confirms my understanding. However the following example baffles me

class foo(object) :
  def __init__(self,par):
    print "Inside foo constructor"

class bar(foo):
  status_code = 302

b = bar(23)

In the above case the derived class does not have an initializer. So will it be correct for me to assume that the reason why the initializer of the base class is being called is because its being inherited by the derived class.


问:
Flex Builder Tween Library
There are missing tween libraries in my Flex Builder how to add them?

Sultan

答:
http://livedocs.adobe.com/flex/3/html/help.html?content=projects_7.html#157949

Add it to Library path.

ContentLicense: CC BY-SA 2.5

Title: Flex Builder Tween Library


问:
DataTable JQuery How to remove a row from a table based on an ID?
I have a web application where you can drag and drop pictures into boxes. If you drop it in the one it will add the picture's information to the datatable, if you drop in the left it will remove the data from the datatable. I was wondering If there was a way I could remove the row based on the id?

```<code>$('#pictures')
    .dataTable({
        "columnDefs": [{
                "orderable": false,
                "targets": 1
            },
            {
                "orderable": false,
                "targets": 3
            }
        ]
    });
var t = $('#pictures')
    .DataTable();

$("#left")
    .droppable({
        accept: ".draggable",
        drop: function (event, ui) {
            console.log("drop");
            $(this)
                .removeClass("border")
                .removeClass("over");
            var dropped = ui.draggable;
            var droppedOn = $(this);
            $(dropped)
                .detach()
                .css({
                    top: 0,
                    left: 0
                })
                .appendTo(droppedOn);

            var $id = $(this)
                .children()
                .last()
                .attr('id');
            var rowId = pictures[id].id;
            t.row(pictures[$id].id)
                .remove()
                .draw(false);
        }
    });
</code>```

This obviously isn't the entire thing; however, I think this is enough to identify any problems.

答:
You can use DataTable's API to remove the corresponding row:

```<code>t.row("your selector here").remove().draw();
</code>```

in row() you could use several kind of selectors. If you saved the row's id in a variable, simply use

```<code>t.row("#"+rowId).remove().draw();
</code>```

Note that you have to call draw() after a remove, since datatables doesn't redraw itself after a remove due to performance reasons.

Body:
I have a web application where you can drag and drop pictures into boxes. If you drop it in the one it will add the picture's information to the datatable, if you drop in the left it will remove the data from the datatable. I was wondering If there was a way I could remove the row based on the id?

$('#pictures')
    .dataTable({
        "columnDefs": [{
                "orderable": false,
                "targets": 1
            },
            {
                "orderable": false,
                "targets": 3
            }
        ]
    });
var t = $('#pictures')
    .DataTable();

$("#left")
    .droppable({
        accept: ".draggable",
        drop: function (event, ui) {
            console.log("drop");
            $(this)
                .removeClass("border")
                .removeClass("over");
            var dropped = ui.draggable;
            var droppedOn = $(this);
            $(dropped)
                .detach()
                .css({
                    top: 0,
                    left: 0
                })
                .appendTo(droppedOn);

            var $id = $(this)
                .children()
                .last()
                .attr('id');
            var rowId = pictures[id].id;
            t.row(pictures[$id].id)
                .remove()
                .draw(false);
        }
    });

This obviously isn't the entire thing; however, I think this is enough to identify any problems.

Body:
You can use DataTable's API to remove the corresponding row:

t.row("your selector here").remove().draw();

in row() you could use several kind of selectors. If you saved the row's id in a variable, simply use

t.row("#"+rowId).remove().draw();

Note that you have to call draw() after a remove, since datatables doesn't redraw itself after a remove due to performance reasons.


问:
Webkit support for gradient transitions
Im wondering if anyone know when will webkit support transitions of gradients?

for example, the following code doesnt work in Chrome 6 (assuming grad-transition is a link):

```<code>.grad-transition {
     background-image: -webkit-gradient(linear, 0 0, 0 100%, from(white), to(black));
     -webkit-transition: background-image .5s;
}
.grad-transition:hover {
     background-image: -webkit-gradient(linear, 0 0, 0 100%, from(black), to(white));
}
</code>```

答:
I'm working on JS lib which makes a transition for gradients possible:
It already can be used for linear gradients.
Usage:

```<code>    var button = $('#button');
    var targetGradientString = 'linear-gradient(rgb(247, 91, 52) 0%, rgb(240, 233, 93) 25%, rgb(43, 245, 12) 50%, rgb(24, 85, 240) 75%, rgb(166, 39, 230) 100%)';
    var targetElement = $('#target');

    button.click( function() {
        targetElement.gradientTransition(targetGradientString, 1500, 60);
    });
</code>```

github
Demo

Title: Webkit support for gradient transitions

Body:
Im wondering if anyone know when will webkit support transitions of gradients?

for example, the following code doesnt work in Chrome 6 (assuming grad-transition is a link):

.grad-transition {
     background-image: -webkit-gradient(linear, 0 0, 0 100%, from(white), to(black));
     -webkit-transition: background-image .5s;
}
.grad-transition:hover {
     background-image: -webkit-gradient(linear, 0 0, 0 100%, from(black), to(white));
}

Body:
I'm working on JS lib which makes a transition for gradients possible:
It already can be used for linear gradients.
Usage:

    var button = $('#button');
    var targetGradientString = 'linear-gradient(rgb(247, 91, 52) 0%, rgb(240, 233, 93) 25%, rgb(43, 245, 12) 50%, rgb(24, 85, 240) 75%, rgb(166, 39, 230) 100%)';
    var targetElement = $('#target');

    button.click( function() {
        targetElement.gradientTransition(targetGradientString, 1500, 60);
    });

github
Demo


问:
How to trigger search through this form?
So, I am working on this simple problem where I have a search form and I want the user to enter the search term. After clicking enter, the user should go to a google appliance page to see the search results. Everything works fine, but the search does not work in one specific instance and I don't know how to take care of this issue. Basically, the search works https://www.efg.ijk/?# if I have '?#' in my URL. Therefore, it does not work the very first time I try because my URL looks like https://www.efg.ijk/. However, after sending first search request, the URL becomes https://www.efg.ijk/?# and subsequent searches work fine.

Here is the code that I have written:

```<code><form id="search-nav" action="#">
                    <input class="search-field" placeholder="Search…" value="" title="Search:">
                    <button class="search-submit">
                            <span class="fa fa-search">
                                <span class="sr-only">Search</span>
                            </span>
                    </button>
                </form>
</code>```

To redirect, AJAX:

```<code>$(document).ready(function() {
  $( ".search-submit" ).on( "click", function()  {
    $.ajax({
        success: function(){
            var value= $(".search-field").val();
            $(".search-field").val("");
            window.location.href =URL + value;
            //URL is the address and I am appending the query using value.
        },
        error: function() {
            alert("error");
        }
    });
  });
});
</code>```

答:
Although even after so much of explanation, I am unable to understand the exact requirement, still I will suggest you little changes, Please try if it works for you

HTML Part

```<code>                    <input class="search-field" placeholder="Search…" title="Search:">
                    <button class="search-submit">
                            <span class="fa fa-search">
                                <span class="sr-only">Search</span>
                            </span>
                    </button>
</code>```

JQUERY Part

```<code>  $( ".search-submit" ).on( "click", function()  {

            var value= $(".search-field").val();
            $(".search-field").val("");
            window.location.href =URL +'#'+ value;
            //URL is the address and I am appending the query using value.
    });
</code>```

Body:
So, I am working on this simple problem where I have a search form and I want the user to enter the search term. After clicking enter, the user should go to a google appliance page to see the search results. Everything works fine, but the search does not work in one specific instance and I don't know how to take care of this issue. Basically, the search works https://www.efg.ijk/?# if I have '?#' in my URL. Therefore, it does not work the very first time I try because my URL looks like https://www.efg.ijk/. However, after sending first search request, the URL becomes https://www.efg.ijk/?# and subsequent searches work fine.

Here is the code that I have written:

<form id="search-nav" action="#">
                    <input class="search-field" placeholder="Search…" value="" title="Search:">
                    <button class="search-submit">

                                Search

                    </button>
                </form>

To redirect, AJAX:

$(document).ready(function() {
  $( ".search-submit" ).on( "click", function()  {
    $.ajax({
        success: function(){
            var value= $(".search-field").val();
            $(".search-field").val("");
            window.location.href =URL + value;
            //URL is the address and I am appending the query using value.
        },
        error: function() {
            alert("error");
        }
    });
  });
});

Body:
Although even after so much of explanation, I am unable to understand the exact requirement, still I will suggest you little changes, Please try if it works for you

HTML Part

                    <input class="search-field" placeholder="Search…" title="Search:">
                    <button class="search-submit">
                            <span class="fa fa-search">
                                <span class="sr-only">Search</span>
                            </span>
                    </button>

JQUERY Part

  $( ".search-submit" ).on( "click", function()  {

            var value= $(".search-field").val();
            $(".search-field").val("");
            window.location.href =URL +'#'+ value;
            //URL is the address and I am appending the query using value.
    });


问:
Pandas: KeyError when using column names which are included in an index
I have text files that I'm parsing which contain fixed width fields with lines that look like this:

```<code>USC00142401201703TMAX  211  H  133  H  161  H  194  H  206  H  161  H  244  H  178  H-9999     250  H   78  H   44  H   67  H   50  H   39  H  106  H  239  H  239  H  217  H  317  H  311  H  178  H  139  H-9999     228  H-9999   -9999   -9999   -9999   -9999   -9999
</code>```

I'm parsing these into a pandas DataFrame like so:

```<code>from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np

def read_into_dataframe(station_filepath):

    # specify the fixed-width fields
    column_specs = [(0, 11),   # ID
                    (11, 15),  # year
                    (15, 17),  # month
                    (17, 21),  # variable (referred to as element in the GHCND readme.txt)
                    (21, 26),  # day 1
                    (29, 34),  # day 2
                    (37, 42),  # day 3
                    (45, 50),  # day 4
                    (53, 58),  # day 5
                    (61, 66),  # day 6
                    (69, 74),  # day 7
                    (77, 82),  # day 8
                    (85, 90),  # day 9
                    (93, 98),  # day 10
                    (101, 106),  # day 11
                    (109, 114),  # day 12
                    (117, 122),  # day 13
                    (125, 130),  # day 14
                    (133, 138),  # day 15
                    (141, 146),  # day 16
                    (149, 154),  # day 17
                    (157, 162),  # day 18
                    (165, 170),  # day 19
                    (173, 178),  # day 20
                    (181, 186),  # day 21
                    (189, 194),  # day 22
                    (197, 202),  # day 23
                    (205, 210),  # day 24
                    (213, 218),  # day 25
                    (221, 226),  # day 26
                    (229, 234),  # day 27
                    (237, 242),  # day 28
                    (245, 250),  # day 29
                    (253, 258),  # day 30
                    (261, 266)]  # day 31

    # create column names to correspond with the fields specified above
    column_names = ['station_id', 'year', 'month', 'variable',
                    '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                    '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
                    '21', '22', '23', '24', '25', '26', '27', '28', '29', '30',  '31']

    # read the fixed width file into a DataFrame columns with the widths and names specified above
    df = pd.read_fwf(station_filepath,
                     header=None,
                     colspecs=column_specs,
                     names=column_names,
                     na_values=-9999)

    # convert the variable column to string data type, all others as integer data type
    df.dropna()  #REVISIT do we really want to do this?
    df['variable'] = df['variable'].astype(str)

    # keep only the rows where the variable value is 'PRCP', 'TMIN', or 'TMAX'
    df = df[df['variable'].isin(['PRCP', 'TMAX', 'TMIN'])]

    # melt the individual day columns into a single day column
    df = pd.melt(df,
                 id_vars=['station_id', 'year', 'month', 'variable'],
                 value_vars=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                             '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
                             '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
                 var_name='day',
                 value_name='value')

    # pivot the DataFrame on the variable type (PRCP, TMIN, TMAX), so each
    # type has a separate column with the day's value for the type
    df = df.pivot_table(index=['year',
                               'month',
                               'day'],
                        columns='variable',
                        values='value')

    return df
</code>```

I now get the DataFrame in the shape I want it, except that there are rows for days that don't exist (i.e. February 31st, etc.), and which I'd like to remove.

I've tried to do this using masks, but when I've done so I get a KeyError when I try to use what I think are valid column names. For example if I include the following code in the above function before returning the DataFrame I will get a KeyError:

```<code>months_with_31days = [1, 3, 7, 8, 10, 12]
df = df[((df['day'] == 31) & (df['month'] in months_with_31days))
        |
       ((df['day'] == 30) & (df['month'] != 2))
        |
       ((df['day'] == 29) & (df['month'] != 2))
        |
       ((df['day'] == 29) & (df['month'] == 2) & calendar.isleap(df['year']))
        |
        df['day'] < 29]
</code>```

The above will result in a KeyError:

```<code>KeyError: 'day'
</code>```

The day variable was created by the melt() call, then used within the index in the call to pivot_table(). How this affects the indexing of the DataFrame and why it goobers up the ability to use the previous column names is not clear to me. [EDIT]I assume that I now have a MultiIndex on the DatFrame, created as a result of the call to pivot_table() via using an index argument.

Initial lines displayed when printing the DataFrame:

```<code>variable         PRCP   TMAX   TMIN
year month day
1893 1     01     NaN   61.0   33.0
           02     NaN   33.0    6.0
           03     NaN   44.0   17.0
           04     NaN   78.0   22.0
           05     NaN   17.0  -94.0
           06     NaN   33.0    0.0
           07     NaN    0.0  -67.0
</code>```

I've tried referencing the DataFrame's columns using dot notation instead of brackets with quoted column names, but I get similar errors. It seems like the year, month, and day columns have been merged into a single index column and can no longer be referenced individually. Or not, maybe something else is going on here? I'm stumped, maybe not even approaching this in the best way, any help or suggestions will be very appreciated. Thanks.

答:
Yes, you've created a multi-index DataFrame.  From looking at your output (without having access to your data), you should be able to access the days by typing:</p>

```<code>df['variable']['day']
</code>```

Body:
I have text files that I'm parsing which contain fixed width fields with lines that look like this:

USC00142401201703TMAX  211  H  133  H  161  H  194  H  206  H  161  H  244  H  178  H-9999     250  H   78  H   44  H   67  H   50  H   39  H  106  H  239  H  239  H  217  H  317  H  311  H  178  H  139  H-9999     228  H-9999   -9999   -9999   -9999   -9999   -9999

I'm parsing these into a pandas DataFrame like so:

from collections import OrderedDict
from pandas import DataFrame
import pandas as pd
import numpy as np

def read_into_dataframe(station_filepath):

    # specify the fixed-width fields
    column_specs = [(0, 11),   # ID
                    (11, 15),  # year
                    (15, 17),  # month
                    (17, 21),  # variable (referred to as element in the GHCND readme.txt)
                    (21, 26),  # day 1
                    (29, 34),  # day 2
                    (37, 42),  # day 3
                    (45, 50),  # day 4
                    (53, 58),  # day 5
                    (61, 66),  # day 6
                    (69, 74),  # day 7
                    (77, 82),  # day 8
                    (85, 90),  # day 9
                    (93, 98),  # day 10
                    (101, 106),  # day 11
                    (109, 114),  # day 12
                    (117, 122),  # day 13
                    (125, 130),  # day 14
                    (133, 138),  # day 15
                    (141, 146),  # day 16
                    (149, 154),  # day 17
                    (157, 162),  # day 18
                    (165, 170),  # day 19
                    (173, 178),  # day 20
                    (181, 186),  # day 21
                    (189, 194),  # day 22
                    (197, 202),  # day 23
                    (205, 210),  # day 24
                    (213, 218),  # day 25
                    (221, 226),  # day 26
                    (229, 234),  # day 27
                    (237, 242),  # day 28
                    (245, 250),  # day 29
                    (253, 258),  # day 30
                    (261, 266)]  # day 31

    # create column names to correspond with the fields specified above
    column_names = ['station_id', 'year', 'month', 'variable',
                    '01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                    '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
                    '21', '22', '23', '24', '25', '26', '27', '28', '29', '30',  '31']

    # read the fixed width file into a DataFrame columns with the widths and names specified above
    df = pd.read_fwf(station_filepath,
                     header=None,
                     colspecs=column_specs,
                     names=column_names,
                     na_values=-9999)

    # convert the variable column to string data type, all others as integer data type
    df.dropna()  #REVISIT do we really want to do this?
    df['variable'] = df['variable'].astype(str)

    # keep only the rows where the variable value is 'PRCP', 'TMIN', or 'TMAX'
    df = df[df['variable'].isin(['PRCP', 'TMAX', 'TMIN'])]

    # melt the individual day columns into a single day column
    df = pd.melt(df,
                 id_vars=['station_id', 'year', 'month', 'variable'],
                 value_vars=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                             '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
                             '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
                 var_name='day',
                 value_name='value')

    # pivot the DataFrame on the variable type (PRCP, TMIN, TMAX), so each
    # type has a separate column with the day's value for the type
    df = df.pivot_table(index=['year',
                               'month',
                               'day'],
                        columns='variable',
                        values='value')

    return df

I now get the DataFrame in the shape I want it, except that there are rows for days that don't exist (i.e. February 31st, etc.), and which I'd like to remove.

I've tried to do this using masks, but when I've done so I get a KeyError when I try to use what I think are valid column names. For example if I include the following code in the above function before returning the DataFrame I will get a KeyError:

months_with_31days = [1, 3, 7, 8, 10, 12]
df = df[((df['day'] == 31) & (df['month'] in months_with_31days))
        |
       ((df['day'] == 30) & (df['month'] != 2))
        |
       ((df['day'] == 29) & (df['month'] != 2))
        |
       ((df['day'] == 29) & (df['month'] == 2) & calendar.isleap(df['year']))
        |
        df['day'] < 29]

The above will result in a KeyError:

KeyError: 'day'

The day variable was created by the melt() call, then used within the index in the call to pivot_table(). How this affects the indexing of the DataFrame and why it goobers up the ability to use the previous column names is not clear to me. [EDIT]I assume that I now have a MultiIndex on the DatFrame, created as a result of the call to pivot_table() via using an index argument.

Initial lines displayed when printing the DataFrame:

variable         PRCP   TMAX   TMIN
year month day
1893 1     01     NaN   61.0   33.0
           02     NaN   33.0    6.0
           03     NaN   44.0   17.0
           04     NaN   78.0   22.0
           05     NaN   17.0  -94.0
           06     NaN   33.0    0.0
           07     NaN    0.0  -67.0

I've tried referencing the DataFrame's columns using dot notation instead of brackets with quoted column names, but I get similar errors. It seems like the year, month, and day columns have been merged into a single index column and can no longer be referenced individually. Or not, maybe something else is going on here? I'm stumped, maybe not even approaching this in the best way, any help or suggestions will be very appreciated. Thanks.

Body:
Yes, you've created a multi-index DataFrame.  From looking at your output (without having access to your data), you should be able to access the days by typing:

df['variable']['day']


问:
Android OrmLite Foreign Key / Foreign Collection
On my recent project on Android Im using OrmLite to model one-to-many relations as well as simple one-to-one relations.
Ive noticed that with one-to-many relations,  the child holds the foreign key reference to the parent in the database. Still when loading the parent object OrmLite knows what to do and loads the collection of child elements which is, of course, the desired behavior.

However, with simple one-to-one relationships, the parent object seems to be required holding the foreign key column in order to achieve the same behavior.

So the actual question: Is it possible to have OrmLite loading the child objects in one-to-one relations when the foreign key is only set in the child, as it is the standard behavior with one-to-many relations?

Here is some example code:

```<code>@DatabaseTable
public class Parent
{

@DatabaseField(foreign = true)
private Child1 child1;

@ForeignCollectionField
private Collection<Child2> children2;

}
</code>```

So in child 1 and 2 I need to have the reference to the Parent like this:

```<code> public class Child1 / Child2
{

    @DatabaseField(foreign = true)
    private Parent parent;
}
</code>```

So when saving a child2 I simply set

```<code>child2.setParent(parent);
child2Dao.create(child2)
</code>```

But in order to arrive at the same behavior when querying the parent including the child1 and child2 I would have to save the relationship the other way around:

```<code>parent.setChild1(child1)
parentDao.create(parent)
</code>```

This is very inconvenient as I want either child1/child2 both holding the foreign key of the parent or the other way around. But a mixture seems somewhat ugly!

Any ideas how to achieve that?

Ive searched for answers to that question here but couldnt find one. In case it is a duplicate, Im sorry!

Thank you very much!

Edit:

To be more precisely:
Is it possible to set the Foreign Key in my child1 table and still be able to obtain child1 when querying for the Parent. ORMLite does it automagically for the foreign collection of child2. I want the same behavior for child1.
But when I set

```<code>child1.setParent(parent);
child1Dao.create(child1);
</code>```

and then make a query

```<code>Parent parent = parentDao.queryForId(1)
</code>```

only child2 is obtained since the Parent Table does not have a reference (foreign key) to the child1. Only child1 has a reference to the parent.

So: I want either have OrmLite automatically update the parent foreign key column or tell Ormlite to still obtain child1 even though no foreign key is set in the parent (as this is exactly the case with the collection of child2).
Is this somehow possible? Or not?

I hope this is not too confusing :) Im totally aware that it would be simpler to just set the foreign key in the parent. But I really dislike that approach as I will end up with some children having a foreign key of the parent and some that do not.

Thank you very much

答:
ORMLite supports the concept of "foreign" objects where one or more of the fields correspond to an object are persisted in another table in the same database. For example, if you had an Order objects in your database and each Order had a corresponding Account object, then the Order object would have foreign Account field. With foreign objects, just the id field from the Account is persisted to the Order table as the column "account_id". For example, the Order class might look something like:

```<code>@DatabaseTable(tableName = "orders")
public class Order {

    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(canBeNull = false, foreign = true)
    private Account account;
    …
}
</code>```

When the Order table was created, something like the following SQL would be generated:

```<code>CREATE TABLE `orders`
   (`id` INTEGER AUTO_INCREMENT , `account_id` INTEGER,
    PRIMARY KEY (`id`));
</code>```

When you are creating a field with a foreign object, please note that the foreign object will not automatically be created for you. If your foreign object has a generated-id which is provided by the database then you need to create it before you create any objects that reference it. For example:

```<code>Account account = new Account("Jim Coakley");
accountDao.create(account);
// this will create the account object and set any generated ids

// now we can set the account on the order and create it
Order order = new Order("Jim Sanders", 12.34);
order.setAccount(account);
…
orderDao.create(order);
</code>```

A foreign collection allows you to add a collection of orders on the account table. Whenever an Account object is returned by a query or refreshed by the DAO, a separate query is made over the order table and a collection of orders is set on the account. All of the orders in the collection have a corresponding foreign object that matches the account. For example:

```<code>public class Account {
    …
    @ForeignCollectionField(eager = false)
    ForeignCollection<Order> orders;
    …
}
</code>```

In the above example, the @ForeignCollectionField annotation marks that the orders field is a collection of the orders that match the account. The field type of orders must be either ForeignCollection or Collection – no other collections are supported because they are much heavier with many methods to support.

Source: http://ormlite.com/

Body:
On my recent project on Android Im using OrmLite to model one-to-many relations as well as simple one-to-one relations.
Ive noticed that with one-to-many relations,  the child holds the foreign key reference to the parent in the database. Still when loading the parent object OrmLite knows what to do and loads the collection of child elements which is, of course, the desired behavior.

However, with simple one-to-one relationships, the parent object seems to be required holding the foreign key column in order to achieve the same behavior.

So the actual question: Is it possible to have OrmLite loading the child objects in one-to-one relations when the foreign key is only set in the child, as it is the standard behavior with one-to-many relations?

Here is some example code:

@DatabaseTable
public class Parent
{

@DatabaseField(foreign = true)
private Child1 child1;

@ForeignCollectionField
private Collection<Child2> children2;

}

So in child 1 and 2 I need to have the reference to the Parent like this:

 public class Child1 / Child2
{

    @DatabaseField(foreign = true)
    private Parent parent;
}

So when saving a child2 I simply set

child2.setParent(parent);
child2Dao.create(child2)

But in order to arrive at the same behavior when querying the parent including the child1 and child2 I would have to save the relationship the other way around:

parent.setChild1(child1)
parentDao.create(parent)

This is very inconvenient as I want either child1/child2 both holding the foreign key of the parent or the other way around. But a mixture seems somewhat ugly!

Any ideas how to achieve that?

Ive searched for answers to that question here but couldnt find one. In case it is a duplicate, Im sorry!

Thank you very much!

Edit:

To be more precisely:
Is it possible to set the Foreign Key in my child1 table and still be able to obtain child1 when querying for the Parent. ORMLite does it automagically for the foreign collection of child2. I want the same behavior for child1.
But when I set

child1.setParent(parent);
child1Dao.create(child1);

and then make a query

Parent parent = parentDao.queryForId(1)

only child2 is obtained since the Parent Table does not have a reference (foreign key) to the child1. Only child1 has a reference to the parent.

So: I want either have OrmLite automatically update the parent foreign key column or tell Ormlite to still obtain child1 even though no foreign key is set in the parent (as this is exactly the case with the collection of child2).
Is this somehow possible? Or not?

I hope this is not too confusing :) Im totally aware that it would be simpler to just set the foreign key in the parent. But I really dislike that approach as I will end up with some children having a foreign key of the parent and some that do not.

Thank you very much

Body:
ORMLite supports the concept of "foreign" objects where one or more of the fields correspond to an object are persisted in another table in the same database. For example, if you had an Order objects in your database and each Order had a corresponding Account object, then the Order object would have foreign Account field. With foreign objects, just the id field from the Account is persisted to the Order table as the column "account_id". For example, the Order class might look something like:

@DatabaseTable(tableName = "orders")
public class Order {

    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(canBeNull = false, foreign = true)
    private Account account;
    …
}

When the Order table was created, something like the following SQL would be generated:

CREATE TABLE `orders`
   (`id` INTEGER AUTO_INCREMENT , `account_id` INTEGER,
    PRIMARY KEY (`id`));

When you are creating a field with a foreign object, please note that the foreign object will not automatically be created for you. If your foreign object has a generated-id which is provided by the database then you need to create it before you create any objects that reference it. For example:

Account account = new Account("Jim Coakley");
accountDao.create(account);
// this will create the account object and set any generated ids

// now we can set the account on the order and create it
Order order = new Order("Jim Sanders", 12.34);
order.setAccount(account);
…
orderDao.create(order);

A foreign collection allows you to add a collection of orders on the account table. Whenever an Account object is returned by a query or refreshed by the DAO, a separate query is made over the order table and a collection of orders is set on the account. All of the orders in the collection have a corresponding foreign object that matches the account. For example:

public class Account {
    …
    @ForeignCollectionField(eager = false)
    ForeignCollection<Order> orders;
    …
}

In the above example, the @ForeignCollectionField annotation marks that the orders field is a collection of the orders that match the account. The field type of orders must be either ForeignCollection or Collection – no other collections are supported because they are much heavier with many methods to support.

Source: http://ormlite.com/


问:
How to filter by space in filter as you type list?
I want to filter a list by typing a space (just like any other character).

The current code is:

```<code>var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));
</code>```

If I have vege tables in my list and I type a space, or letter e and space, or space and letter t, the list should filter to show vege tables.

I have tried to add \s to the code but it is not working as I had hoped:

```<code>var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|\s]/g, "\\$&"));
</code>```

Am I missing something?

答:
Here's an example of how to filter a list of stings based on a pattern.</p>

```<code>function filter(list, pattern) {
  return list.filter(function(item) {
    return pattern.test(item);
  });
}
const list = ['vege tables', 'man eater', 'word'];
console.log('Current list: ', list);

var pattern = ' e';
console.log('Filter by: "' + pattern + '"');

pattern = new RegExp(pattern, 'gi'); // convert the pattern to regex
console.log(filter(list, pattern)); // get filtered list, ['man eater']
</code>```

Body:
I want to filter a list by typing a space (just like any other character).

The current code is:

var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"));

If I have vege tables in my list and I type a space, or letter e and space, or space and letter t, the list should filter to show vege tables.

I have tried to add \s to the code but it is not working as I had hoped:

var search = $.trim($(this).val().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|\s]/g, "\\$&"));

Am I missing something?

Body:
Here's an example of how to filter a list of stings based on a pattern.

function filter(list, pattern) {
  return list.filter(function(item) {
    return pattern.test(item);
  });
}
const list = ['vege tables', 'man eater', 'word'];
console.log('Current list: ', list);

var pattern = ' e';
console.log('Filter by: "' + pattern + '"');

pattern = new RegExp(pattern, 'gi'); // convert the pattern to regex
console.log(filter(list, pattern)); // get filtered list, ['man eater']


问:
java.lang.RuntimeException: Cannot initialize Visualizer engine, error: -4
I am getting below error when running app on API  16.

```<code> java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.RuntimeException: Cannot initialize Visualizer engine, error: -4
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                      at android.app.ActivityThread.access$600(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.RuntimeException: Cannot initialize Visualizer engine, error: -4
                      at android.media.audiofx.Visualizer.<init>(Visualizer.java:199)
                      at xyz.activity.AudioPreviewActivity.setupVisualizerFxAndUI(AudioPreviewActivity.java:83)
                      at xyz.activity.AudioPreviewActivity.initAudio(AudioPreviewActivity.java:60)
                      at xyz.activity.AudioPreviewActivity.onCreate(AudioPreviewActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:5008)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                      at android.app.ActivityThread.access$600(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)
</code>```

Error line-

```<code>mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
</code>```

Code

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

    mMediaPlayer = MediaPlayer.create(this, Uri.parse(filePath));
    mMediaPlayer
            .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mVisualizer.setEnabled(false);
                }
            });

    mMediaPlayer.start();
    mMediaPlayer.setLooping(true);
    mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    mVisualizer.setDataCaptureListener(
                    new Visualizer.OnDataCaptureListener() {
                        public void onWaveFormDataCapture(Visualizer visualizer,
                                                          byte[] bytes, int samplingRate) {
                            mVisualizerView.updateVisualizer(bytes);
                        }

                        public void onFftDataCapture(Visualizer visualizer,
                                                     byte[] bytes, int samplingRate) {
                        }
                    }, Visualizer.getMaxCaptureRate() / 2, true, false);
        }
</code>```

I already have added below permissions in manifest-

```<code><uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
</code>```

答:
Add a runtime permission for api 23 and above.</p>

```<code>if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {

            int hasAudioPermission = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
            int hasInternetPermission = checkSelfPermission(Manifest.permission.INTERNET);

            List<String> permissions = new ArrayList<>();

      if (hasAudioPermission != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }

            if (hasInternetPermission != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.INTERNET);
            }

            if (!permissions.isEmpty()) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), PERMISSION);
            }
        }
</code>```

Body:
I am getting below error when running app on API  16.

 java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.RuntimeException: Cannot initialize Visualizer engine, error: -4
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                      at android.app.ActivityThread.access$600(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.RuntimeException: Cannot initialize Visualizer engine, error: -4
                      at android.media.audiofx.Visualizer.<init>(Visualizer.java:199)
                      at xyz.activity.AudioPreviewActivity.setupVisualizerFxAndUI(AudioPreviewActivity.java:83)
                      at xyz.activity.AudioPreviewActivity.initAudio(AudioPreviewActivity.java:60)
                      at xyz.activity.AudioPreviewActivity.onCreate(AudioPreviewActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:5008)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                      at android.app.ActivityThread.access$600(ActivityThread.java:130)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                      at android.os.Handler.dispatchMessage(Handler.java:99)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:4745)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:511)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                      at dalvik.system.NativeStart.main(Native Method)

Error line-

mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());

Code

private void setupVisualizerFxAndUI() {

    mMediaPlayer = MediaPlayer.create(this, Uri.parse(filePath));
    mMediaPlayer
            .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mVisualizer.setEnabled(false);
                }
            });

    mMediaPlayer.start();
    mMediaPlayer.setLooping(true);
    mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    mVisualizer.setDataCaptureListener(
                    new Visualizer.OnDataCaptureListener() {
                        public void onWaveFormDataCapture(Visualizer visualizer,
                                                          byte[] bytes, int samplingRate) {
                            mVisualizerView.updateVisualizer(bytes);
                        }

                        public void onFftDataCapture(Visualizer visualizer,
                                                     byte[] bytes, int samplingRate) {
                        }
                    }, Visualizer.getMaxCaptureRate() / 2, true, false);
        }

I already have added below permissions in manifest-

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

Body:
Add a runtime permission for api 23 and above.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {

            int hasAudioPermission = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
            int hasInternetPermission = checkSelfPermission(Manifest.permission.INTERNET);

            List<String> permissions = new ArrayList<>();

      if (hasAudioPermission != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }

            if (hasInternetPermission != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.INTERNET);
            }

            if (!permissions.isEmpty()) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), PERMISSION);
            }
        }


问:
Apache Commons Crypto - Getting IllegalBlockSizeException
I am trying to use the following method to handle both encryption and decryption of AES data using Apache Commons Crypto. Encryption is working fine. But when I try to decrypt the data I just encrypted, I am getting this block size error, which I don't totally understand since I'm setting the blocksize to 1024, which of course is a multiple of 16.  </p>

```<code>javax.crypto.IllegalBlockSizeException: Input length (with padding) not multiple of 16 bytes
</code>```

<p>Here is my code:  </p>

```<code>        final int bufferSize = 1024;
    try {
      this.cryptoCipher.init(cipherMode, this.secretKeySpec, this.ivParameterSpec);
        ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
        ByteBuffer outBuffer = ByteBuffer.allocateDirect(bufferSize);
        inBuffer.put(getUTF8Bytes(dataToBeEncrypted));
        inBuffer.flip();
        int updateBytes = this.cryptoCipher.update(inBuffer, outBuffer);
        int finalBytes = this.cryptoCipher.doFinal(inBuffer, outBuffer);   <<<< EXCEPTION HAPPENS HERE!!!
        byte[] encoded = new byte[updateBytes + finalBytes];
        outBuffer.flip();
        outBuffer.duplicate().get(encoded);
        encryptedDecryptedData = DatatypeConverter.printBase64Binary(encoded);
    } catch (Exception exc) {
        LOGGER.logp(Level.SEVERE, MODULE_NAME, methodName, "encountered exception: {0}", exc);
    }
</code>```

答:
AES has one block size: 16-bytes so setting the block size to another value is an error. But you are not setting the block size, just creating a buffer of (in this case) 1024 bytes.

Most implementations accept an array and will internally process the input a block at a time. But the input must be an exact multiple of the block size and that is accomplished with padding, usually PKCS#7 padding, and by an option handles this automatically by adding on encryption and removing on decryption.

Body:
I am trying to use the following method to handle both encryption and decryption of AES data using Apache Commons Crypto. Encryption is working fine. But when I try to decrypt the data I just encrypted, I am getting this block size error, which I don't totally understand since I'm setting the blocksize to 1024, which of course is a multiple of 16.

javax.crypto.IllegalBlockSizeException: Input length (with padding) not multiple of 16 bytes

Here is my code:

        final int bufferSize = 1024;
    try {
      this.cryptoCipher.init(cipherMode, this.secretKeySpec, this.ivParameterSpec);
        ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
        ByteBuffer outBuffer = ByteBuffer.allocateDirect(bufferSize);
        inBuffer.put(getUTF8Bytes(dataToBeEncrypted));
        inBuffer.flip();
        int updateBytes = this.cryptoCipher.update(inBuffer, outBuffer);
        int finalBytes = this.cryptoCipher.doFinal(inBuffer, outBuffer);   <<<< EXCEPTION HAPPENS HERE!!!
        byte[] encoded = new byte[updateBytes + finalBytes];
        outBuffer.flip();
        outBuffer.duplicate().get(encoded);
        encryptedDecryptedData = DatatypeConverter.printBase64Binary(encoded);
    } catch (Exception exc) {
        LOGGER.logp(Level.SEVERE, MODULE_NAME, methodName, "encountered exception: {0}", exc);
    }


问:
Will F# perform well when writing math functions for a C# program?
Does anyone know how well F# measures with regards to performance, compared to C#. I have a C# raytracer with a lot of vector manipulations, ray-collission algorithms etc. and thought they might be more easily expressed in F#. I'm not asking for how well F# is at expressing math problems, something which has been answered here, but rather if I should expect better or worse performance? As raytracing is very performance intensive, even small cases of poor performance can be a problem in the wrong places.

Edit:

It seems that there are already a lot of questions on the subject that I couldn't find (there are no results if you actually search for anything with the term 'F#'). One good point here was the following answer:

F# provides some performance-related
  features that can make a difference.

Firstly, the implementation of
  delegates on .NET is currently quite
  inefficient and, consequently, F# uses
  its own FastFunc type for
  high-performance first-class
  functions.

Secondly, F# uses .NET metadata to
  convey inline functions so that they
  can be exported across APIs and, of
  course, that can dramatically improve
  performance in certain circumstances.

Finally, pattern matching can be
  extremely laborious to express in C#
  because the language lacks pattern
  matching but it is almost impossible
  to maintain optimized C# code
  equivalent to many non-trivial pattern
  matches. In contrast, the F# compiler
  aggressively optimizes pattern matches
  during compilation.

Conversely, the C# compiler is better
  at optimizing loops using IEnumerables
  and is better at optimizing
  computations over value types (e.g.
  complex arithmetic).

Cheers, Jon Harrop.

答:
F#'s performance is about the same as C#'s they are both compiled to IL which is the important factor (unlike IronPython and IronRuby which are interpreted and therefore much slower). The performance of an algorithm depends much more on it's implementation than on the choice of F# or C#, as F# would help implement it in few lines of code you have much better chance of spotting optimisations in F# than in C#.

Also this article has a similar take on the perf issue:
http://diditwith.net/2008/04/03/ApplesAndOranges.aspx

OwnerDisplayName: Morten Christiansen

LastEditorDisplayName: Norman Ramsey

OwnerDisplayName: Robert


问:
Load html without refresh
Im unsure of how to approach this, should I have the html to be loaded hidden or load it from somewhere? I want to load a form in one page, and dynamic content on other pages.

The form can be saved to mongo db, and when the page loads should load the data into that form from mongo db.

Where does the html live for all the pages? I want to have a clean html5 document with lets say a content div. all content goes into that block.

Server running Django
Im want to use backbone.js for the app

any help would be appreciated

答:
The initial page should include the basic layout of the application (header, content, sidebar, different placeholder for your views, etc.)

Then you load the application (usually with a controller) and render the different view that will replace the placeholders you had in your layout.

To render the views, I suggest to use a templating engine. With backbone.js there is already underscore.js on the page, so you can use the templating engine included (http://documentcloud.github.com/underscore/#template). You then have to load the template on the page. The easiest way is to create include a script element on the page with your template inside:

```<code><script type="text/template" name="template1">
your template here...
</script>
</code>```

And you can load it using this:

```<code>var template = _.template( jQuery("script[name=template1]").text() )
</code>```

and execute with your data

```<code>var html = template(model)
</code>```

You build your page with different backbone views using different template.

I hope that help!

Title: Load html without refresh

Body:
The initial page should include the basic layout of the application (header, content, sidebar, different placeholder for your views, etc.)

Then you load the application (usually with a controller) and render the different view that will replace the placeholders you had in your layout.

To render the views, I suggest to use a templating engine. With backbone.js there is already underscore.js on the page, so you can use the templating engine included (http://documentcloud.github.com/underscore/#template). You then have to load the template on the page. The easiest way is to create include a script element on the page with your template inside:

<script type="text/template" name="template1">
your template here...
</script>

And you can load it using this:

var template = _.template( jQuery("script[name=template1]").text() )

and execute with your data

var html = template(model)

You build your page with different backbone views using different template.

I hope that help!


问:
bootstrap modal does not come up
I am trying http://bootstrap-confirmation.js.org

my html has

```<code><html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Log Analyzer</title>

    <!-- Bootstrap Core CSS -->
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- MetisMenu CSS -->
    <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <!-- DataTables CSS -->
    <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">

    <!-- DataTables Responsive CSS -->
    <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="dist/css/sb-admin-2.css" rel="stylesheet">

    <!-- Custom Fonts -->
    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <style>
    td.details-control {
        background: url('images/details_open.png') no-repeat center center;
        cursor: pointer;
    }

    tr.details td.details-control {
            background: url('images/details_close.png') no-repeat center center;
    }

    td.flag-control {
        background: url('images/ban_circle.png') no-repeat center center;
        cursor: pointer;
    }

      table {
            table-layout:fixed;
        }

            .word-break-all{
                word-break:break-all;
            }
        </style>

</head>

<body>

    <div id="wrapper">

        <!-- Navigation -->

        <div id="page-wrapper">
            <div class="row">
                <div class="col-lg-12">
                       <h4></h4>
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                          <button class="btn btn-default" data-toggle="confirmation">Confirmation</button>
</code>```

and toward bottom:

```<code><script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="js/bootstrap-confirmation.js"></script>
</code>```

my javascript has:

$(document).ready(function() {

```<code>     $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
        });
});
</code>```

clicking the button nothing happens

答: Your javascript is missing the closing });. This fixed it for me. (made my own HTML from their example, you should include yours)

Title: bootstrap modal does not come up

Body:
I am trying http://bootstrap-confirmation.js.org

my html has

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Log Analyzer</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <link href="vendor/datatables-plugins/dataTables.bootstrap.css" rel="stylesheet">

    <link href="vendor/datatables-responsive/dataTables.responsive.css" rel="stylesheet">

    <link href="dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                          <button class="btn btn-default" data-toggle="confirmation">Confirmation</button>

and toward bottom:

my javascript has:

$(document).ready(function() {

     $('[data-toggle=confirmation]').confirmation({
        rootSelector: '[data-toggle=confirmation]'
        // other options
        });
});

clicking the button nothing happens