问:
How to set an alarm to be scheduled at an exact time after all the newest restrictions on Android?
Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you've found works using the test I've written below.

Background

There is a requirement on the app, that the user sets a reminder to be scheduled at a specific time, so when the app gets triggered on this time, it does something tiny in the background (just some DB query operation), and shows a simple notification, to tell about the reminder.

In the past, I used a simple code to set something to be scheduled at a relatively specific time:

```<code>            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
            when {
                VERSION.SDK_INT >= VERSION_CODES.KITKAT -> alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
                else -> alarmManager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
            }
</code>```

```<code>class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("AppLog", "AlarmReceiver onReceive")
        //do something in the real app
    }
}
</code>```

Usage:

```<code>            val timeToTrigger = System.currentTimeMillis() + java.util.concurrent.TimeUnit.MINUTES.toMillis(1)
            setAlarm(this, timeToTrigger, 1)
</code>```

The problem

I've now tested this code on emulators on new Android versions and on Pixel 4 with Android 10, and it doesn't seem to trigger, or maybe it triggers after a very long time since what I provide it. I'm well aware of the terrible behavior that some OEMs added to removing apps from the recent tasks, but this one is on both emulators and Pixel 4 device (stock).

I've read on the docs about setting an alarm, that it got restricted for apps so that it won't occur too often, but this doesn't explain how to set an alarm at a specific time, and it doesn't explain how come Google's Clock app succeeds doing it.

Not only that, but according to what I understand, it says the restrictions should be applied especially for low power state of the device, but in my case, I didn't have this state, on both the device and on the emulators. I've set the alarms to be triggered in about a minute from now.

Seeing that many alarm clock apps don't work anymore as they used to, I think there is something that is missing on the docs. Example of such apps is the popular Timely app that was bought by Google but never got new updates to handle the new restrictions, and now users want it back.. However, some popular apps do work fine, such as this one.

What I've tried

To test that indeed the alarm works, I perform these tests when trying to trigger the alarm in a minute from now, after installing the app for the first time, all while the device is connected to the PC (to see the logs) :

Test when the app is in the foreground, visible to the user. - took 1-2 minutes.

Test when the app was sent to the background (using the home button, for example) - took about 1 minute

Test when app's task was removed from the recent tasks. - I waited more than 20 minutes and didn't see the alarm being triggered, writing to logs.

Like #3, but also turn off the screen. It would probably be worse...

I tried to use the next things, all don't work:

alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

combination of any of the above, with :

if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
  alarmManager.setWindow(AlarmManager.RTC_WAKEUP, 0, 60 * 1000L, pendingIntent)

Tried to use a service instead of BroadcastReceiver. Also tried on a different process.

Tried making the app be ignored from the battery optimization (didn't help), but since other apps don't need it, I shouldn't use it either.

Tried using this:

```<code>            if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
                alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
            AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
</code>```

Tried having a service that will have a trigger of onTaskRemoved , to re-schedule the alarm there, but this also didn't help (the service worked fine though).

As for Google's Clock app, I didn't see anything special about it except that it shows a notification before being triggered, and I also don't see it in the "not optimized" section of the battery-optimization settings screen.

Seeing that this seems like a bug, I reported about this here, including a sample project and video to show the issue.

I've checked on multiple versions of the emulator, and it seems that this behavior started from API 27 (Android 8.1 - Oreo). Looking at the docs, I don't see AlarmManager being mentioned, but instead, it was written about various background work.

The questions

How do we set something to be triggered at a relatively exact time nowadays?

How come the above solutions don't work anymore? Am I missing anything? Permission? Maybe I'm supposed to use a Worker instead? But then wouldn't it mean that it might not trigger on time at all?

How does Google "Clock" app overcome all of this, and triggers anyway on the exact time, always, even if it was triggered just a minute ago? Is it only because it's a system app? What if it gets installed as a user app, on a device that doesn't have it built-in?

If you say that it's because it's a system app, I've found another app that can trigger an alarm twice in 2 minutes, here, though I think it might use a foreground service sometimes.

EDIT: made a tiny Github repository to try ideas on, here.

EDIT: finally found a sample that is both open-sourced and doesn't have this issue. Sadly it's very complex and I still try to figure out what makes it so different (and what's the minimal code that I should add to my POC) that lets its alarms stay scheduled after removing the app from the recent tasks

答:
Actually what worked for me for Android 12 to schedule the exact time alarm is adding to your app's AndroidManifest file a permission:

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

And to change the Flag for your PendingIntent:

```<code>  val pendingIntent = alarmIntent.let { intent ->
    val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        PendingIntent.FLAG_MUTABLE //this is needed in Android 12
    } else {
        PendingIntent.FLAG_CANCEL_CURRENT
    }
    PendingIntent.getBroadcast(
        context,
        DailyAlarmReceiver.REQUEST_DAILY_NOTIFICATION,
        intent,
        flag
    )
}
</code>```

You can also check if the app can schedule the alarm with checking on canScheduleExactAlarms:

```<code>val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

if(alarmManager.canScheduleExactAlarms()){
  //schedule the alarm
}
</code>```

Body:
Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you've found works using the test I've written below.

Background

There is a requirement on the app, that the user sets a reminder to be scheduled at a specific time, so when the app gets triggered on this time, it does something tiny in the background (just some DB query operation), and shows a simple notification, to tell about the reminder.

In the past, I used a simple code to set something to be scheduled at a relatively specific time:

            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
            when {
                VERSION.SDK_INT >= VERSION_CODES.KITKAT -> alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
                else -> alarmManager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
            }

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("AppLog", "AlarmReceiver onReceive")
        //do something in the real app
    }
}

Usage:

            val timeToTrigger = System.currentTimeMillis() + java.util.concurrent.TimeUnit.MINUTES.toMillis(1)
            setAlarm(this, timeToTrigger, 1)

The problem

I've now tested this code on emulators on new Android versions and on Pixel 4 with Android 10, and it doesn't seem to trigger, or maybe it triggers after a very long time since what I provide it. I'm well aware of the terrible behavior that some OEMs added to removing apps from the recent tasks, but this one is on both emulators and Pixel 4 device (stock).

I've read on the docs about setting an alarm, that it got restricted for apps so that it won't occur too often, but this doesn't explain how to set an alarm at a specific time, and it doesn't explain how come Google's Clock app succeeds doing it.

Not only that, but according to what I understand, it says the restrictions should be applied especially for low power state of the device, but in my case, I didn't have this state, on both the device and on the emulators. I've set the alarms to be triggered in about a minute from now.

Seeing that many alarm clock apps don't work anymore as they used to, I think there is something that is missing on the docs. Example of such apps is the popular Timely app that was bought by Google but never got new updates to handle the new restrictions, and now users want it back.. However, some popular apps do work fine, such as this one.

What I've tried

To test that indeed the alarm works, I perform these tests when trying to trigger the alarm in a minute from now, after installing the app for the first time, all while the device is connected to the PC (to see the logs) :

Test when the app is in the foreground, visible to the user. - took 1-2 minutes.

Test when the app was sent to the background (using the home button, for example) - took about 1 minute

Test when app's task was removed from the recent tasks. - I waited more than 20 minutes and didn't see the alarm being triggered, writing to logs.

Like #3, but also turn off the screen. It would probably be worse...

I tried to use the next things, all don't work:

alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

combination of any of the above, with :

if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
  alarmManager.setWindow(AlarmManager.RTC_WAKEUP, 0, 60 * 1000L, pendingIntent)

Tried to use a service instead of BroadcastReceiver. Also tried on a different process.

Tried making the app be ignored from the battery optimization (didn't help), but since other apps don't need it, I shouldn't use it either.

Tried using this:

            if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
                alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
            AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

Tried having a service that will have a trigger of onTaskRemoved , to re-schedule the alarm there, but this also didn't help (the service worked fine though).

As for Google's Clock app, I didn't see anything special about it except that it shows a notification before being triggered, and I also don't see it in the "not optimized" section of the battery-optimization settings screen.

Seeing that this seems like a bug, I reported about this here, including a sample project and video to show the issue.

I've checked on multiple versions of the emulator, and it seems that this behavior started from API 27 (Android 8.1 - Oreo). Looking at the docs, I don't see AlarmManager being mentioned, but instead, it was written about various background work.

The questions

How do we set something to be triggered at a relatively exact time nowadays?

How come the above solutions don't work anymore? Am I missing anything? Permission? Maybe I'm supposed to use a Worker instead? But then wouldn't it mean that it might not trigger on time at all?

How does Google "Clock" app overcome all of this, and triggers anyway on the exact time, always, even if it was triggered just a minute ago? Is it only because it's a system app? What if it gets installed as a user app, on a device that doesn't have it built-in?

If you say that it's because it's a system app, I've found another app that can trigger an alarm twice in 2 minutes, here, though I think it might use a foreground service sometimes.

EDIT: made a tiny Github repository to try ideas on, here.

EDIT: finally found a sample that is both open-sourced and doesn't have this issue. Sadly it's very complex and I still try to figure out what makes it so different (and what's the minimal code that I should add to my POC) that lets its alarms stay scheduled after removing the app from the recent tasks

Body:
Actually what worked for me for Android 12 to schedule the exact time alarm is adding to your app's AndroidManifest file a permission:

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

And to change the Flag for your PendingIntent:

  val pendingIntent = alarmIntent.let { intent ->
    val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        PendingIntent.FLAG_MUTABLE //this is needed in Android 12
    } else {
        PendingIntent.FLAG_CANCEL_CURRENT
    }
    PendingIntent.getBroadcast(
        context,
        DailyAlarmReceiver.REQUEST_DAILY_NOTIFICATION,
        intent,
        flag
    )
}

You can also check if the app can schedule the alarm with checking on canScheduleExactAlarms:

val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

if(alarmManager.canScheduleExactAlarms()){
  //schedule the alarm
}


来源: stackexchange

问:
Next.js JWT authentication
Currently, my backend gives me access and a refresh token to authorize users. In a previous project, I've just saved tokens into local storage and authorized users client-side.

My current project is locked for public users, I am showing an alert with information that the app is only for registered users only.

Is there any way to authorize users SSR and get rid of tokens from local storage?

答: Not entirely sure what your setup is, but couldn't you just use cookies instead? They can be accessed server side.</p>

ContentLicense: CC BY-SA 4.0

Title: Next.js JWT authentication


问:
Attempting to scan a barcode and split the entry into 2 cells
I haven't found anything specific, so please forgive me if this has been addressed.
I have a spreadsheet set up for the user to scan a barcode (Code128).  I need the spreadsheet to automatically place the first 13 digits in the next empty cell in column A, and the remaining characters (10 characters) in the adjacent cell in column B.
I've seen the user of left and right in formulas but haven't determined how to do this in VBA.</p>

答:
Please, copy the next code in the sheet code module where the scanning is done:

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
   If Target.cells.count > 1 Then Exit Sub
   If Target.Column = 1 Then
      If Len(Target.Value) > 10 Then
        Application.EnableEvents = False
          Target.Offset(1).Value = left(Target.Value, 10) 'place first 10 digits in the next cell
          Target.Offset(1, 1).Value = Right(Target.Value, Len(Target.Value) - 10) 'and the rest on the next row, column B:B
          Target.Offset(2).Select
        Application.EnableEvents = True 'select next cell to scan in
      End If
   End If
End Sub
</code>```

Before start scanning, if the barcode content is numeric, you should format columns "A:A" and "B:B" as text, but using TextToColumns (one column at a time). Pressing Next, Next, check Text and press Finish.

Edited:

The next version keep the first 10 digits in the cell where the scan has been done, and rest of the digits in column B:B, Target row:

```<code>Private Sub Worksheet_Change_(ByVal Target As Range)
   If Target.cells.count > 1 Then Exit Sub
   If Target.Column = 1 Then
      If Len(Target.Value) > 10 Then
        Application.EnableEvents = False
          Target.Offset(1).Value = left(Target.Value, 10)
          Target.Offset(1, 1).Value = Right(Target.Value, Len(Target.Value) - 10)
          Target.Offset(2).Select
        Application.EnableEvents = True
      End If
   End If
End Sub
</code>```

Body:
Please, copy the next code in the sheet code module where the scanning is done:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
   If Target.cells.count > 1 Then Exit Sub
   If Target.Column = 1 Then
      If Len(Target.Value) > 10 Then
        Application.EnableEvents = False
          Target.Offset(1).Value = left(Target.Value, 10) 'place first 10 digits in the next cell
          Target.Offset(1, 1).Value = Right(Target.Value, Len(Target.Value) - 10) 'and the rest on the next row, column B:B
          Target.Offset(2).Select
        Application.EnableEvents = True 'select next cell to scan in
      End If
   End If
End Sub

Before start scanning, if the barcode content is numeric, you should format columns "A:A" and "B:B" as text, but using TextToColumns (one column at a time). Pressing Next, Next, check Text and press Finish.

Edited:

The next version keep the first 10 digits in the cell where the scan has been done, and rest of the digits in column B:B, Target row:

Private Sub Worksheet_Change_(ByVal Target As Range)
   If Target.cells.count > 1 Then Exit Sub
   If Target.Column = 1 Then
      If Len(Target.Value) > 10 Then
        Application.EnableEvents = False
          Target.Offset(1).Value = left(Target.Value, 10)
          Target.Offset(1, 1).Value = Right(Target.Value, Len(Target.Value) - 10)
          Target.Offset(2).Select
        Application.EnableEvents = True
      End If
   End If
End Sub


问:
CSS3 transitions not working on button
I have a relatively complex button that I'm styling with CSS3, it looks and behaves as I intended apart from the transitions are not working. It should fade on hover etc but it's just not working, tested in moz opera and chrome, no luck.

Here's a link to a fiddle http://jsfiddle.net/dsyne/DpsuN/1/

Any help would be appreciated, i've tried many different things. Re-ordering the stack for instance. I'm not sure if the ordering is important with transitions ?

edit:wrong link sorry

答: Use id to specify transition property instead of class. Worked for me!</p>

ContentLicense: CC BY-SA 3.0

Title: CSS3 transitions not working on button


问:
PHP date() with timezone?
So I've checked the list of supported time zones in PHP and I was wondering how could I include them in the date() function?
Thanks!

I don't want a default timezone, each user has their timezone stored in the database, I take that timezone of the user and use it. How? I know how to take it from the database, not how to use it, though.

答:
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.

```<code>$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");
</code>```

This returns the current local time in Jakarta, Indonesia.

Title: PHP date() with timezone?

Body:
I have tried the answers based on the DateTime class. While they are working, I found a much simpler solution that makes a DateTime object timezone aware at the time of creation.

$dt = new DateTime("now", new DateTimeZone('Asia/Jakarta'));
echo $dt->format("Y-m-d H:i:s");

This returns the current local time in Jakarta, Indonesia.


问:
Python Access the raw bytes of a Float
I have a series of float64's that represent rgb values, and I am trying to interpret this as an image using python. For each float64, bits 0-15 correspond to the data for an uint8 for the red value, bits 16-31 are for green, and 32-47 are for blue. How can I get these integer RGB values?

I know this kind of bit manipulation is very odd to be doing in python, but bear with me. Basically all I need is to interpret the underlying bits of a float as an int instead(not trying to cast). The closest thing I've found that allows me to access the bit values is python struct, but it doesn't seem to actually do what I want(and I'm sure it's very inefficient).

I've tried to accomplish it with the following code:

```<code>raw_byte_data = struct.pack('f', float_value)
data_as_int = struct.unpack('i', raw_byte_data)[0]
r = data_as_int & 0xFF
g = data_as_int >> 8 & 0xFF
b = data_as_int >> 16 & 0xFF
</code>```

I'm not sure what this does, but whatever it does it doesn't give me the output bytes I want. Hopefully it illustrates what I'm trying to do at least.

答:
After some more fiddling, I was able to get it to work using python struct thanks to this post. See below.

```<code>def float_to_rgb(f):
    s = struct.pack('>f', f)
    bits = struct.unpack('>l', s)[0]
    r = bits & 0xFF
    g = bits >> 8 & 0xFF
    b = bits >> 16 & 0xFF
    return (r,g,b)
</code>```

I think the key here was unpacking the bytes as a long int('l').

Title: Python Access the raw bytes of a Float

Body:
I have a series of float64's that represent rgb values, and I am trying to interpret this as an image using python. For each float64, bits 0-15 correspond to the data for an uint8 for the red value, bits 16-31 are for green, and 32-47 are for blue. How can I get these integer RGB values?

I know this kind of bit manipulation is very odd to be doing in python, but bear with me. Basically all I need is to interpret the underlying bits of a float as an int instead(not trying to cast). The closest thing I've found that allows me to access the bit values is python struct, but it doesn't seem to actually do what I want(and I'm sure it's very inefficient).

I've tried to accomplish it with the following code:

raw_byte_data = struct.pack('f', float_value)
data_as_int = struct.unpack('i', raw_byte_data)[0]
r = data_as_int & 0xFF
g = data_as_int >> 8 & 0xFF
b = data_as_int >> 16 & 0xFF

I'm not sure what this does, but whatever it does it doesn't give me the output bytes I want. Hopefully it illustrates what I'm trying to do at least.

Body:
After some more fiddling, I was able to get it to work using python struct thanks to this post. See below.

def float_to_rgb(f):
    s = struct.pack('>f', f)
    bits = struct.unpack('>l', s)[0]
    r = bits & 0xFF
    g = bits >> 8 & 0xFF
    b = bits >> 16 & 0xFF
    return (r,g,b)

I think the key here was unpacking the bytes as a long int('l').


问:
How to generate iTunes Connect promo codes
I cannot generate promo codes for my iOS app in iTunes Connect. Usually I select the app, and then the app version, and the link to generate is located at the bottom of the page under Additional Information. However it is gone.

答: App Store Connect has moved the location again. It is now located under the "Services" heading for your app, rather than the old "Features" heading.


问:
How to delete all the logs using gcloud command
I tried the following command:

gcloud logging logs delete
```

but it is asking log name

ERROR: (gcloud.logging.logs.delete) argument LOG_NAME: Must be specified.

I want to get all the logs to be deleted which are default.

答:
Your question would benefit from showing some attempt to solve this problem for yourself.

See gcloud logging logs delete

It requires a LOG_NAME as provided by e.g. gcloud logging logs list.

Since logs list returns a simple list of logs if you wanted to delete existing (!) log entries for all logs in a specific project, you could:

Use the following at your own risk

it will irrecoverably delete every existing log entry in every log in the current project

PROJECT="[[YOUR-PROJECT]]"

LOGS=$(\
  gcloud logging log list \
  --project=${PROJECT}

for LOG in ${LOGS}
do
  gcloud logging logs delete ${LOG} \
  --project=${PROJECT} \
  --quiet
done
```

Body:
I tried the following command:

gcloud logging logs delete

but it is asking log name

ERROR: (gcloud.logging.logs.delete) argument LOG_NAME: Must be specified.

I want to get all the logs to be deleted which are default.


问:
Why does a locally scoped variable that hasn't been defined reference the instance variable of the same name?
I came across an odd bug in my code that revealed an interesting behavior of ruby.  Hopefully someone can explain why it behaves this way.

I had a class with an instance variable @foo and a method that referenced a locally scoped variable foo.  I refactored part of the method out accidentally leaving the reference to foo; the variable no longer defined in the scope.  It ended up pointing to @foo instead.  Changing foo made changes to @foo and vice versa.

Simplified version:
EDIT : added ImOutOfNames.

```<code>class ImOutOfNames
    attr_accessor :foo # the culprit!
end

class Bar < ImOutOfNames
    def initialize
        @foo = "that is a tasty burger"
    end

    def bar_method_1
        foo = "Come on Yolanda, whats Fonzie like?"
        bar_method_2
    end

    def bar_method_2
        puts foo
    end
end
</code>```

And the output of bar_method_1 and bar_method_2 was "that is a tasty burger".  I was expecting there to be an error, for example running the above code gets

```<code>NameError: undefined local variable or method
</code>```

I even had a more senior developer come take a  look and he was somewhat baffled and confirmed the behavior.

Is this an expected behavior and I misunderstood how @variables work or is there something wrong?

答:
Do you have an attr accessor for your @foo instance variable? That's one way this could happen.

I'd recommend not using the same name for a locally scoped variable, in general, but you can find out if it's coming from some method with

```<code>self.method(:foo)
</code>```

or if it's even defined with

```<code>defined? foo
</code>```

Using the ruby runtime to your advantage definitely reduces the mysticism and magical nature of some code.

Body:
I came across an odd bug in my code that revealed an interesting behavior of ruby.  Hopefully someone can explain why it behaves this way.

I had a class with an instance variable @foo and a method that referenced a locally scoped variable foo.  I refactored part of the method out accidentally leaving the reference to foo; the variable no longer defined in the scope.  It ended up pointing to @foo instead.  Changing foo made changes to @foo and vice versa.

Simplified version:
EDIT : added ImOutOfNames.

class ImOutOfNames
    attr_accessor :foo # the culprit!
end

class Bar < ImOutOfNames
    def initialize
        @foo = "that is a tasty burger"
    end

    def bar_method_1
        foo = "Come on Yolanda, whats Fonzie like?"
        bar_method_2
    end

    def bar_method_2
        puts foo
    end
end

And the output of bar_method_1 and bar_method_2 was "that is a tasty burger".  I was expecting there to be an error, for example running the above code gets

NameError: undefined local variable or method

I even had a more senior developer come take a  look and he was somewhat baffled and confirmed the behavior.

Is this an expected behavior and I misunderstood how @variables work or is there something wrong?

Body:
Do you have an attr accessor for your @foo instance variable? That's one way this could happen.

I'd recommend not using the same name for a locally scoped variable, in general, but you can find out if it's coming from some method with

self.method(:foo)

or if it's even defined with

defined? foo

Using the ruby runtime to your advantage definitely reduces the mysticism and magical nature of some code.


问:
Apache Pulsar: Access state storage in LocalRunner not working
I'm trying to implement a simple Apache Pulsar Function and access the State API in LocalRunner mode, but it's not working.

pom.xml snippet

```<code><dependencies>
    <dependency>
    <groupId>org.apache.pulsar</groupId>
    <artifactId>pulsar-client-original</artifactId>
    <version>2.9.1</version>
  </dependency>
    <dependency>
      <groupId>org.apache.pulsar</groupId>
      <artifactId>pulsar-functions-local-runner-original</artifactId>
      <version>2.9.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.13.1</version>
    </dependency>
  </dependencies>
</code>```

Function class

```<code>public class TestFunction implements Function<String, String> {

  public String process(String input, Context context) throws Exception {
    System.out.println(">>> GOT input "+input);
    context.incrCounter("counter",1); //--> try to access state
    return input;
  }
}
</code>```

Main

```<code>public class Main {
  public static final String BROKER_URL = "pulsar://localhost:6650";
  public static final String TOPIC_IN = "test-topic-input";
  public static final String TOPIC_OUT = "test-topic-output";

  public static void main(String[] args) throws Exception {

    FunctionConfig functionConfig = FunctionConfig
        .builder()
        .className(TestFunction.class.getName())
        .inputs(Collections.singleton(TOPIC_IN))
        .name("Test Function")
        .runtime(Runtime.JAVA)
        .subName("Test Function Sub")
        .build();

    LocalRunner localRunner = LocalRunner.builder()
        .brokerServiceUrl(BROKER_URL)
        .stateStorageServiceUrl("bk://127.0.0.1:4181")
        .functionConfig(functionConfig)
        .build();
    localRunner.start(false);

    PulsarClient client = PulsarClient.builder().serviceUrl(BROKER_URL).build();
    Producer<String> producer = client.newProducer(Schema.STRING).topic(TOPIC_IN).create();

    producer.send("Hello World!");
    System.out.println(">>> PRODUCER SENT");
  }
</code>```

I'm running Pulsar in a local docker container (Docker Desktop on Win10), started like this:

Docker container

```<code>docker run -it
-p 6650:6650
-p 8080:8080
-p 4181:4181 #I added that port to expose the bookkeeper, otherwise the function will hang and don't do anything
--mount source=pulsardata,target=/pulsar/data --mount source=pulsarconf,target=/pulsar/conf
apachepulsar/pulsar:2.9.1 bin/pulsar standalone
</code>```

When I start the application the Console shows these logs:

```<code>2022-01-07T12:39:48,757+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds
2022-01-07T12:39:48,863+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds
2022-01-07T12:39:48,970+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds
2022-01-07T12:39:49,076+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds

... and it goes on an on ...
</code>```

Pulsar logging shows:

```<code>2022-01-07T12:13:48,882+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

2022-01-07T12:13:48,989+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

2022-01-07T12:13:49,097+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

2022-01-07T12:13:49,207+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

... goes on and on ...
</code>```

What am I doing wrong?

答:
The issue is with the name you chose for your function, "Test Function". Since it has a space in it, that causes issues later on inside Pulsar's state store when it uses that name for the internal storage stream.

If you remove the space and use "TestFunction" instead, it will work just fine. I have confirmed this myself just now.

```<code>2022-02-07T11:09:04,916-0800 [main] WARN  com.scurrilous.circe.checksum.Crc32cIntChecksum - Failed to load Circe JNI library. Falling back to Java based CRC32c provider
>>> PRODUCER SENT
2022-02-07T11:09:05,267-0800 [public/default/TestFunction-0] INFO  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Opening state table for function public/default/TestFunction
2022-02-07T11:09:05,279-0800 [client-scheduler-OrderedScheduler-7-0] INFO  org.apache.bookkeeper.clients.SimpleStorageClientImpl - Retrieved table properties for table public_default/TestFunction : stream_id: 1024

2022-02-07T11:09:05,527-0800 [pulsar-client-io-1-2] INFO  org.apache.pulsar.client.impl.ConsumerImpl - [test-topic-input][Test Function Sub] Subscribed to topic on localhost/127.0.0.1:6650 -- consumer: 0
>>> GOT input Hello World!
</code>```

Body:
I'm trying to implement a simple Apache Pulsar Function and access the State API in LocalRunner mode, but it's not working.

pom.xml snippet

<dependencies>
    <dependency>
    <groupId>org.apache.pulsar</groupId>
    <artifactId>pulsar-client-original</artifactId>
    <version>2.9.1</version>
  </dependency>
    <dependency>
      <groupId>org.apache.pulsar</groupId>
      <artifactId>pulsar-functions-local-runner-original</artifactId>
      <version>2.9.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.13.1</version>
    </dependency>
  </dependencies>

Function class

public class TestFunction implements Function<String, String> {

  public String process(String input, Context context) throws Exception {
    System.out.println(">>> GOT input "+input);
    context.incrCounter("counter",1); //--> try to access state
    return input;
  }
}

Main

public class Main {
  public static final String BROKER_URL = "pulsar://localhost:6650";
  public static final String TOPIC_IN = "test-topic-input";
  public static final String TOPIC_OUT = "test-topic-output";

  public static void main(String[] args) throws Exception {

    FunctionConfig functionConfig = FunctionConfig
        .builder()
        .className(TestFunction.class.getName())
        .inputs(Collections.singleton(TOPIC_IN))
        .name("Test Function")
        .runtime(Runtime.JAVA)
        .subName("Test Function Sub")
        .build();

    LocalRunner localRunner = LocalRunner.builder()
        .brokerServiceUrl(BROKER_URL)
        .stateStorageServiceUrl("bk://127.0.0.1:4181")
        .functionConfig(functionConfig)
        .build();
    localRunner.start(false);

    PulsarClient client = PulsarClient.builder().serviceUrl(BROKER_URL).build();
    Producer<String> producer = client.newProducer(Schema.STRING).topic(TOPIC_IN).create();

    producer.send("Hello World!");
    System.out.println(">>> PRODUCER SENT");
  }

I'm running Pulsar in a local docker container (Docker Desktop on Win10), started like this:

Docker container

docker run -it
-p 6650:6650
-p 8080:8080
-p 4181:4181 #I added that port to expose the bookkeeper, otherwise the function will hang and don't do anything
--mount source=pulsardata,target=/pulsar/data --mount source=pulsarconf,target=/pulsar/conf
apachepulsar/pulsar:2.9.1 bin/pulsar standalone

When I start the application the Console shows these logs:

2022-01-07T12:39:48,757+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds
2022-01-07T12:39:48,863+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds
2022-01-07T12:39:48,970+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds
2022-01-07T12:39:49,076+0100 [public/default/Test Function-0] WARN  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Encountered issue Invalid stream name : public_default on fetching state stable metadata, re-attempting in 100 milliseconds

... and it goes on an on ...

Pulsar logging shows:

2022-01-07T12:13:48,882+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

2022-01-07T12:13:48,989+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

2022-01-07T12:13:49,097+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

2022-01-07T12:13:49,207+0000 [grpc-default-executor-0] ERROR org.apache.bookkeeper.stream.storage.impl.metadata.RootRangeStoreImpl - Invalid stream name Test Function

... goes on and on ...

What am I doing wrong?

Body:
The issue is with the name you chose for your function, "Test Function". Since it has a space in it, that causes issues later on inside Pulsar's state store when it uses that name for the internal storage stream.

If you remove the space and use "TestFunction" instead, it will work just fine. I have confirmed this myself just now.

2022-02-07T11:09:04,916-0800 [main] WARN  com.scurrilous.circe.checksum.Crc32cIntChecksum - Failed to load Circe JNI library. Falling back to Java based CRC32c provider
>>> PRODUCER SENT
2022-02-07T11:09:05,267-0800 [public/default/TestFunction-0] INFO  org.apache.pulsar.functions.instance.state.BKStateStoreProviderImpl - Opening state table for function public/default/TestFunction
2022-02-07T11:09:05,279-0800 [client-scheduler-OrderedScheduler-7-0] INFO  org.apache.bookkeeper.clients.SimpleStorageClientImpl - Retrieved table properties for table public_default/TestFunction : stream_id: 1024

2022-02-07T11:09:05,527-0800 [pulsar-client-io-1-2] INFO  org.apache.pulsar.client.impl.ConsumerImpl - [test-topic-input][Test Function Sub] Subscribed to topic on localhost/127.0.0.1:6650 -- consumer: 0
>>> GOT input Hello World!


问:
Splitting text files and returning only the end in scala
I want to read a text file from scala named "c.txt" that contains

```<code>CatManC_NAA
Foranz_CSW
Foresan_SQW
</code>```

and return only the second part of the txt file as a string. Ex: NAA, CSW when entering "CatManC" or "Foranz" as a parameter while ignoring capitalization.
This is my code at the moment.

```<code>object Test {
  def getCode(fileName: String, nameInput:String): String={
  code:String=""
  for (line <- Source.fromFile(filename).getLines) {
    line.split("_")
   if (nameInput==line){
    line.takeRight(3)
     code+=line
}
   else{
   return ""
}

  }
code
}
</code>```

I'm an amateur at coding and also new to the language. Any help will be appreciated.

答:
This would be the idiomatic, safe and efficient way of doing what you want.

import scala.io.Source
import scala.util.{Try, Using}

def getCode(fileName: String, nameInput: String): Try[Option[String]] = {
  val key = nameInput.toLowerCase

  Using(Source.fromFile(fileName)) { source =>
    source.getLines().map(_.split('_').map(_.toLowerCase).toList).collectFirst {
      case `key` :: value :: Nil => value
    }
  }
}
```
<p>The <code>Try</code> is used to signal that processing the file may fail for multiple reasons; e.g. the file not existing.<br>
The <code>Option</code> is used to signal that the <code>nameInput</code> key may not be present, thus there may not be output.</p>
<p>Ideally, you would handle both kinds of errors, probably by turning everything into an <code>Either[Error, String]</code> so you don't have to deal with nesting; like this:</p>
<pre class="lang-scala prettyprint-override"><code>import scala.io.Source
import scala.util.{Failure, Success, Try, Using}

sealed abstract class GetCodeError(cause: Option[Throwable]) extends Throwable(cause.orNull)
object GetCodeError {
  final case class FileError(cause) extend GetCodeError(cause = Some(cause))
  final case object KeyNotFoundError extends GetCodeError(cause = None)
}

def getCode(fileName: String, nameInput: String): Either[GetCodeError, String] = {
  val key = nameInput.toLowerCase

  val result = Using(Source.fromFile(fileName)) { source =>
    source.getLines().map(_.split('_').map(_.toLowerCase).toList).collectFirst {
      case `key` :: value :: Nil => value
    }
  }

  result match {
    case Sucess(opt) =>
      opt.toRight(left = GetCodeError.KeyNotFoundError)

    case Failure(ex) =>
      Left(GetCodeError.FileError(cause = ex))
  }
}
</code>```

Or you may just forget about those errors and let the program crash if something wrong happens; like this:

import scala.io.Source
import scala.util.Using

def getCode(fileName: String, nameInput: String): String = {
  val key = nameInput.toLowerCase

  Using.resource(Source.fromFile(fileName)) { source =>
    source.getLines().map(_.split('_').map(_.toLowerCase).toList).collectFirst {
      case `key` :: value :: Nil => value
    }.get
  }
}
```

But please, don't do that on a real project. Although, this may be fine for a quick script.

If you have any questions about the code, please feel free to ask them!

Body:
I want to read a text file from scala named "c.txt" that contains

CatManC_NAA
Foranz_CSW
Foresan_SQW

and return only the second part of the txt file as a string. Ex: NAA, CSW when entering "CatManC" or "Foranz" as a parameter while ignoring capitalization.
This is my code at the moment.

object Test {
  def getCode(fileName: String, nameInput:String): String={
  code:String=""
  for (line <- Source.fromFile(filename).getLines) {
    line.split("_")
   if (nameInput==line){
    line.takeRight(3)
     code+=line
}
   else{
   return ""
}

  }
code
}

I'm an amateur at coding and also new to the language. Any help will be appreciated.

Body:
This would be the idiomatic, safe and efficient way of doing what you want.

import scala.io.Source
import scala.util.{Try, Using}

def getCode(fileName: String, nameInput: String): Try[Option[String]] = {
  val key = nameInput.toLowerCase

  Using(Source.fromFile(fileName)) { source =>
    source.getLines().map(_.split('_').map(_.toLowerCase).toList).collectFirst {
      case `key` :: value :: Nil => value
    }
  }
}

The Try is used to signal that processing the file may fail for multiple reasons; e.g. the file not existing.

The Option is used to signal that the nameInput key may not be present, thus there may not be output.

Ideally, you would handle both kinds of errors, probably by turning everything into an Either[Error, String] so you don't have to deal with nesting; like this:

import scala.io.Source
import scala.util.{Failure, Success, Try, Using}

sealed abstract class GetCodeError(cause: Option[Throwable]) extends Throwable(cause.orNull)
object GetCodeError {
  final case class FileError(cause) extend GetCodeError(cause = Some(cause))
  final case object KeyNotFoundError extends GetCodeError(cause = None)
}

def getCode(fileName: String, nameInput: String): Either[GetCodeError, String] = {
  val key = nameInput.toLowerCase

  val result = Using(Source.fromFile(fileName)) { source =>
    source.getLines().map(_.split('_').map(_.toLowerCase).toList).collectFirst {
      case `key` :: value :: Nil => value
    }
  }

  result match {
    case Sucess(opt) =>
      opt.toRight(left = GetCodeError.KeyNotFoundError)

    case Failure(ex) =>
      Left(GetCodeError.FileError(cause = ex))
  }
}

Or you may just forget about those errors and let the program crash if something wrong happens; like this:

import scala.io.Source
import scala.util.Using

def getCode(fileName: String, nameInput: String): String = {
  val key = nameInput.toLowerCase

  Using.resource(Source.fromFile(fileName)) { source =>
    source.getLines().map(_.split('_').map(_.toLowerCase).toList).collectFirst {
      case `key` :: value :: Nil => value
    }.get
  }
}

But please, don't do that on a real project. Although, this may be fine for a quick script.

If you have any questions about the code, please feel free to ask them!


问:
Facing Error while sending email with Multiple Excel Attachments
I am trying to send 6 x Excel Sheets as Attachment from 1 Google Sheet as Attachment, sometimes this code run's perfectly but sometime it gives the error.

The Original Code

```<code>///*** SEND 6 X ATTACHMENTS IN 1 EMAIL FROM GOOGLE SHEET USING APP SCRIPT ***///

function sendExcelAttachmentsInOneEmail() {
  var url = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getSheetId();
  var url1 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getSheetId();
  var url2 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getSheetId();
  var url3 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet4").getSheetId();
  var url4 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet5").getSheetId();
  var url5 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet6").getSheetId();

  var ss3 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet3 = ss3.getSheetByName("Sheet7");
  var value4 = sheet3.getRange("J1").getValue();

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  var blob = UrlFetchApp.fetch(url, params).getBlob().setName("Sheet1 XYZ Reports.xlsx");
  var blob1 = UrlFetchApp.fetch(url1, params).getBlob().setName("Sheet2 TXT Data.xlsx");
  var blob2 = UrlFetchApp.fetch(url2, params).getBlob().setName("Sheet3 RAW FILES.xlsx");
  var blob3 = UrlFetchApp.fetch(url3, params).getBlob().setName("Sheet4 SYS DATA.xlsx");
  var blob4 = UrlFetchApp.fetch(url4, params).getBlob().setName("Sheet5 REPORTED ISSUES.xlsx");
  var blob5 = UrlFetchApp.fetch(url5, params).getBlob().setName("Sheet6 FIXED ISSUES.xlsx");

  var message = {
    to: "email@domain.com",
    cc: "email@domain.com",
    subject: "REPORTS - "+value4,
    body: "Hi Team,\n\nPlease find attached Reprots.\n\nBest Regards!",
    name: "",
    attachments: [blob, blob1, blob2, blob3, blob4, blob5]
  }
  MailApp.sendEmail(message);
}
</code>```

Error Message from App Script

```<code>9:05:45 PM  Notice  Execution started
9:05:49 PM  Error   Exception: Request failed for https://docs.google.com returned code 429. Truncated server response: <!DOCTYPE html><html lang="en"><head><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" c... (use muteHttpExceptions option to examine full response)
sendExcelAttachmentsInOneEmail  @ Code.gs:44
</code>```

答:
I have made it work and also did an overhaul to the script due to personal reasons (I don't like repetitive lines of code). See the working script below.

Script:

```<code>function sendExcelAttachmentsInOneEmail() {
  var sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4', 'Sheet5', 'Sheet6'];
  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var spreadSheetId = spreadSheet.getId();

  var urls = sheets.map(sheet => {
    var sheetId = spreadSheet.getSheetByName(sheet).getSheetId();
    // Used this alternative url since I'm getting the error below. This other url has less traffic issues during testing:
    // "This file might be unavailable right now due to heavy traffic. Try again."
    return `https://docs.google.com/feeds/download/spreadsheets/Export?key=${spreadSheetId}&gid=${sheetId}&exportFormat=xlsx`;
  });

  var reportName = spreadSheet.getSheetByName('Sheet7').getRange(1, 10).getValue();

  var params = {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
    },
    // Add mute http exceptions to proceed
    muteHttpExceptions: true
  };

  var fileNames = ['Sheet1 XYZ Reports.xlsx',
                   'Sheet2 TXT Data.xlsx',
                   'Sheet3 RAW FILES.xlsx',
                   'Sheet4 SYS DATA.xlsx',
                   'Sheet5 REPORTED ISSUES.xlsx',
                   'Sheet6 FIXED ISSUES.xlsx'];

  var blobs = urls.map((url, index) => {
    // Added an interval due to heavy traffic error. Increase interval if needed.
    Utilities.sleep(1000);
    return UrlFetchApp.fetch(url, params).getBlob().setName(fileNames[index]);
  });

  var message = {
    to: 'user@domain.com',
    subject: 'REPORTS - ' + reportName,
    body: "Hi Team,\n\nPlease find attached Reports.\n\nBest Regards!",
    attachments: blobs
  }

  MailApp.sendEmail(message);
}
</code>```

Output:

Notes:

Important bits here are the following:

muteHttpExceptions

The alternative url for less traffic issues

Utilities.sleep(1000)

Body:
I am trying to send 6 x Excel Sheets as Attachment from 1 Google Sheet as Attachment, sometimes this code run's perfectly but sometime it gives the error.

The Original Code

///*** SEND 6 X ATTACHMENTS IN 1 EMAIL FROM GOOGLE SHEET USING APP SCRIPT ***///

function sendExcelAttachmentsInOneEmail() {
  var url = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getSheetId();
  var url1 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2").getSheetId();
  var url2 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet3").getSheetId();
  var url3 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet4").getSheetId();
  var url4 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet5").getSheetId();
  var url5 = "https://docs.google.com/spreadsheets/d/"+SpreadsheetApp.getActiveSpreadsheet().getId()+"/export"+"?format=xlsx&"+"gid="+SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet6").getSheetId();

  var ss3 = SpreadsheetApp.getActiveSpreadsheet();
  var sheet3 = ss3.getSheetByName("Sheet7");
  var value4 = sheet3.getRange("J1").getValue();

  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  var blob = UrlFetchApp.fetch(url, params).getBlob().setName("Sheet1 XYZ Reports.xlsx");
  var blob1 = UrlFetchApp.fetch(url1, params).getBlob().setName("Sheet2 TXT Data.xlsx");
  var blob2 = UrlFetchApp.fetch(url2, params).getBlob().setName("Sheet3 RAW FILES.xlsx");
  var blob3 = UrlFetchApp.fetch(url3, params).getBlob().setName("Sheet4 SYS DATA.xlsx");
  var blob4 = UrlFetchApp.fetch(url4, params).getBlob().setName("Sheet5 REPORTED ISSUES.xlsx");
  var blob5 = UrlFetchApp.fetch(url5, params).getBlob().setName("Sheet6 FIXED ISSUES.xlsx");

  var message = {
    to: "email@domain.com",
    cc: "email@domain.com",
    subject: "REPORTS - "+value4,
    body: "Hi Team,\n\nPlease find attached Reprots.\n\nBest Regards!",
    name: "",
    attachments: [blob, blob1, blob2, blob3, blob4, blob5]
  }
  MailApp.sendEmail(message);
}

Error Message from App Script

9:05:45 PM  Notice  Execution started
9:05:49 PM  Error   Exception: Request failed for https://docs.google.com returned code 429. Truncated server response: <!DOCTYPE html><meta name="description" content="Web word processing, presentations and spreadsheets"><meta name="viewport" c... (use muteHttpExceptions option to examine full response)
sendExcelAttachmentsInOneEmail  @ Code.gs:44

Body:
I have made it work and also did an overhaul to the script due to personal reasons (I don't like repetitive lines of code). See the working script below.

Script:

function sendExcelAttachmentsInOneEmail() {
  var sheets = ['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4', 'Sheet5', 'Sheet6'];
  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var spreadSheetId = spreadSheet.getId();

  var urls = sheets.map(sheet => {
    var sheetId = spreadSheet.getSheetByName(sheet).getSheetId();
    // Used this alternative url since I'm getting the error below. This other url has less traffic issues during testing:
    // "This file might be unavailable right now due to heavy traffic. Try again."
    return `https://docs.google.com/feeds/download/spreadsheets/Export?key=${spreadSheetId}&gid=${sheetId}&exportFormat=xlsx`;
  });

  var reportName = spreadSheet.getSheetByName('Sheet7').getRange(1, 10).getValue();

  var params = {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
    },
    // Add mute http exceptions to proceed
    muteHttpExceptions: true
  };

  var fileNames = ['Sheet1 XYZ Reports.xlsx',
                   'Sheet2 TXT Data.xlsx',
                   'Sheet3 RAW FILES.xlsx',
                   'Sheet4 SYS DATA.xlsx',
                   'Sheet5 REPORTED ISSUES.xlsx',
                   'Sheet6 FIXED ISSUES.xlsx'];

  var blobs = urls.map((url, index) => {
    // Added an interval due to heavy traffic error. Increase interval if needed.
    Utilities.sleep(1000);
    return UrlFetchApp.fetch(url, params).getBlob().setName(fileNames[index]);
  });

  var message = {
    to: 'user@domain.com',
    subject: 'REPORTS - ' + reportName,
    body: "Hi Team,\n\nPlease find attached Reports.\n\nBest Regards!",
    attachments: blobs
  }

  MailApp.sendEmail(message);
}

Output:

Notes:

Important bits here are the following:

muteHttpExceptions

The alternative url for less traffic issues

Utilities.sleep(1000)


答:
The rook criterion in pysal's Voronoi weights can do this.</p>
```<code>import os
import pandas as pd
import geopandas as gpd
import shapely
from shapely.geometry import Point
import matplotlib.pyplot as plt
import pysal
import numpy as np
from libpysal.weights import Voronoi

df = pd.DataFrame()
df['x']=[0,1,3,0,1,3,0,1,3]
df['y']=[0,0,0,1.5,1.5,1.5,2.5,2.5,2.5]
points=[]
for i in df.index:
    points.append(Point(df['x'][i],df['y'][i]))

gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.x, df.y))
f, ax=plt.subplots()
gdf.plot(color='red',ax=ax)

for idx, row in df.iterrows():
    ax.annotate(str(idx), (df['x'][idx], df['y'][idx])

points = df[['x', 'y']].to_numpy()
w = Voronoi(points, criterion='rook')
neighbors_dict = w.neighbors

df['adjacent'] = df.index.map(neighbors_dict)

print(df)

    x   y   geometry                adjacent
0   0   0.0 POINT (0.00000 0.00000) [1, 3]
1   1   0.0 POINT (1.00000 0.00000) [0, 2, 4]
2   3   0.0 POINT (3.00000 0.00000) [1, 5]
3   0   1.5 POINT (0.00000 1.50000) [0, 4, 6]
4   1   1.5 POINT (1.00000 1.50000) [1, 3, 5, 7]
5   3   1.5 POINT (3.00000 1.50000) [8, 2, 4]
6   0   2.5 POINT (0.00000 2.50000) [3, 7]
7   1   2.5 POINT (1.00000 2.50000) [8, 4, 6]
8   3   2.5 POINT (3.00000 2.50000) [5, 7]
</code>```

Title: Python: how to detect the adjacent nodes of a point in a geopandas dataframe?

Body:
I have a geoepandas dataframe that looks like the following:

df = pd.DataFrame()
df['x']=[0,1,3,0,1,3,0,1,3]
df['y']=[0,0,0,1.5,1.5,1.5,2.5,2.5,2.5]
points=[]
for i in df.index:
    points.append(Point(df['x'][i],df['y'][i]))

gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.x, df.y))
f,ax=plt.subplots()
gdf.plot(color='red',ax=ax)

where gdf is the following

    x     y     geometry
0   0   0.0     POINT (0.00000 0.00000)
1   1   0.0     POINT (1.00000 0.00000)
2   3   0.0     POINT (3.00000 0.00000)
3   0   1.5     POINT (0.00000 1.50000)
4   1   1.5     POINT (1.00000 1.50000)
5   3   1.5     POINT (3.00000 1.50000)
6   0   2.5     POINT (0.00000 2.50000)
7   1   2.5     POINT (1.00000 2.50000)
8   3   2.5     POINT (3.00000 2.50000)

I would like to detect the adjacent nodes (only in the vertical and horizontal directions) and have a dataframe like the following:

    x     y     geometry                   adjacent
0   0   0.0     POINT (0.00000 0.00000)    [1,3]
1   1   0.0     POINT (1.00000 0.00000)    [0,2,4]
2   3   0.0     POINT (3.00000 0.00000)    [1,5]
3   0   1.5     POINT (0.00000 1.50000)    [0,4,6]
4   1   1.5     POINT (1.00000 1.50000)    [1,3,5,7]
5   3   1.5     POINT (3.00000 1.50000)    [2,4,8]
6   0   2.5     POINT (0.00000 2.50000)    [3,7]
7   1   2.5     POINT (1.00000 2.50000)    [4,6]
8   3   2.5     POINT (3.00000 2.50000)    [5,7]

Body:
The rook criterion in pysal's Voronoi weights can do this.

import os
import pandas as pd
import geopandas as gpd
import shapely
from shapely.geometry import Point
import matplotlib.pyplot as plt
import pysal
import numpy as np
from libpysal.weights import Voronoi

df = pd.DataFrame()
df['x']=[0,1,3,0,1,3,0,1,3]
df['y']=[0,0,0,1.5,1.5,1.5,2.5,2.5,2.5]
points=[]
for i in df.index:
    points.append(Point(df['x'][i],df['y'][i]))

gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.x, df.y))
f, ax=plt.subplots()
gdf.plot(color='red',ax=ax)

for idx, row in df.iterrows():
    ax.annotate(str(idx), (df['x'][idx], df['y'][idx])

points = df[['x', 'y']].to_numpy()
w = Voronoi(points, criterion='rook')
neighbors_dict = w.neighbors

df['adjacent'] = df.index.map(neighbors_dict)

print(df)

    x   y   geometry                adjacent
0   0   0.0 POINT (0.00000 0.00000) [1, 3]
1   1   0.0 POINT (1.00000 0.00000) [0, 2, 4]
2   3   0.0 POINT (3.00000 0.00000) [1, 5]
3   0   1.5 POINT (0.00000 1.50000) [0, 4, 6]
4   1   1.5 POINT (1.00000 1.50000) [1, 3, 5, 7]
5   3   1.5 POINT (3.00000 1.50000) [8, 2, 4]
6   0   2.5 POINT (0.00000 2.50000) [3, 7]
7   1   2.5 POINT (1.00000 2.50000) [8, 4, 6]
8   3   2.5 POINT (3.00000 2.50000) [5, 7]


问:
What is the other way to get result without using MYSQL ROW_NUMBER Function with PARTITION and multiple group by to reset row count
```<code>select
   Id,request_id,key_skill_id,
   ROW_NUMBER() OVER (PARTITION BY skill_id
                      ORDER BY request_id,skill_id) sequence
from report
where id= x
GROUP by request_id, skill_id
order by  request_id,skill_id ;
</code>```

I tried to write something like the following, but the result is not the same:

select
id,
request_id,
@skill_id :=skill_id as skill_id,
@row_number :=
CASE
WHEN  @skill_id = skill_id THEN @row_number+1
ELSE 1
END AS row_number
from report,
(SELECT @row_number := 0, @skill_id := '') as t
where id =x

GROUP by request_id, skill_id
order by request_id, skill_id;

答:
The original window function strikes me as a bit odd but I confess that I don't use these functions too frequently being confined to MySQL 5.7 myself. The PARTITION BY clause specifies the key_skill_id column so re-numbering 1, 2, 3, etc. will be done on those rows with identical key_skill_id column values. But then there is a final ORDER clause at the very end of the SQL that re-sorts the results so that rows with the same key_skill_id will not in general be together (unless, for example, there was only a single value of feedback_request_id being selected).

To do the initial numbering the rows, however, the table must first be sorted by key_skill_id and then feedback_request_id. The purpose of the GROUP BY clause in the original SQL is to function as an equivalent of a SELECT DISTINCT query, which can't be used because the added row number column guarantees that each row is distinct. The reason why the GROUP BY works is that it is applied before the ROW_NUMBER window function is performed whereas the SELECT DISTINCT implied filtering would be applied after the ROW_NUMBER function is performed.

Given you have provided no table definitions, data, expected output, etc. I was unable to test the following. This is my best guess:

select
    x.*,
    @row_number :=
      CASE
         WHEN  @key_skill_id = x.key_skill_id THEN @row_number+1
         ELSE 1
      END AS sequence,
    @key_skill_id = x.key_skill_id
from (
    select distinct /* to emulate group by */
       candidateId,
       feedback_id,
       key_skill_id
       from newFeedbackReport
       where candidate_id = 2501
       order by key_skill_id, feedback_request /* this is not a mistake */
) x,
(SELECT @row_number := 0, @key_skill_id := '') as t
order by feedback_request_id, key_skill_id;
```

Body:
select
   Id,request_id,key_skill_id,
   ROW_NUMBER() OVER (PARTITION BY skill_id
                      ORDER BY request_id,skill_id) sequence
from report
where id= x
GROUP by request_id, skill_id
order by  request_id,skill_id ;

I tried to write something like the following, but the result is not the same:

select
id,
request_id,
@skill_id :=skill_id as skill_id,
@row_number :=
CASE
WHEN  @skill_id = skill_id THEN @row_number+1
ELSE 1
END AS row_number
from report,
(SELECT @row_number := 0, @skill_id := '') as t
where id =x

GROUP by request_id, skill_id
order by request_id, skill_id;


问:
HTML JavaScript not playing sound?
I am trying to get sound to work for the following HTML-JavaScript code... but no sound and and the program doesn't say "No sound support".  Not sure what the problem is ??

```<code><html>
<head>
<title>Sound Test</title>
<script type="text/javascript">
function PlaySound(){
    var sound = document.getElementById("note_c1");
    try{
        //RealPlayer
        sound.DoPlay();
    }catch (e){
        try{
            //Windows Media / Quicktime
            sound.Play();
            alert("should hear sound");
        }catch(e){
            alert("No sound support.");
        }
    }
}
</script>
</head>
<body>
<h1>Sound Test</h1>
<embed id="note_c1" src="c1.au" width="0" height="0" autostart="false" enablejavascript="true"/>
<input type = "button" value="Play the Sound" onClick="PlaySound()">
</body>
</code>```

答:
Use http://www.jplayer.org/.

I have no affiliation - It's simple, highly configurable, will work on a larger set of clients and far more future proof (and no forking code).

Happy Coding :)

Title: HTML JavaScript not playing sound?

Body:
I am trying to get sound to work for the following HTML-JavaScript code... but no sound and and the program doesn't say "No sound support".  Not sure what the problem is ??

<title>Sound Test</title>

Sound Test

<embed id="note_c1" src="c1.au" width="0" height="0" autostart="false" enablejavascript="true"/>
<input type = "button" value="Play the Sound" onClick="PlaySound()">


问:
How can I get tree-like indentation for Flutter code in VS Code?
How do I make VS Code do scaffolding guides like in the picture below?:

答: I suggest you go in the settings and enable the Dart:Preview Flutter Ui Guides option. That will make it really easy to spot the parent-child relationships in your code, which is particularly useful when you have many nested widgets in your UI files.


问:
Where do I find the project ID for the GitLab API?
I use GitLab on their servers. I would like to download my latest built artifacts (build via GitLab CI) via the API like this:

```<code>curl --header "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" "https://gitlab.com/api/v3/projects/1/builds/8/artifacts"
</code>```

Where do I find this project ID? Or is this way of using the API not intended for hosted GitLab projects?

答:
You can search for the project path

```<code>curl -s  'https://gitlab.com/api/v4/projects?search=my/path/to/my/project&search_namespaces=true' --header "PRIVATE-TOKEN: $GITLAB_TOKEN" |python -mjson.tool |grep \"id\"
</code>```

https://docs.gitlab.com/ee/api/projects.html

Which will only match your project and will not find other unnecessary projects

Body:
I use GitLab on their servers. I would like to download my latest built artifacts (build via GitLab CI) via the API like this:

curl --header "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" "https://gitlab.com/api/v3/projects/1/builds/8/artifacts"

Where do I find this project ID? Or is this way of using the API not intended for hosted GitLab projects?

Body:
You can search for the project path

curl -s  'https://gitlab.com/api/v4/projects?search=my/path/to/my/project&search_namespaces=true' --header "PRIVATE-TOKEN: $GITLAB_TOKEN" |python -mjson.tool |grep \"id\"

https://docs.gitlab.com/ee/api/projects.html

Which will only match your project and will not find other unnecessary projects


问:
Error: Member not found: 'packageRoot', how to solve ignore: deprecated_member_use in Flutter?
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

```<code>    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1
</code>```

So, I need a suggestion that how can I solve this issue?

答:
firstly, run

flutter pub outdated

then

flutter pub upgrade --major-versions

Body:
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1

So, I need a suggestion that how can I solve this issue?


问:
Sklearn online prediction, batch vs one by one
As stated in many places, for input data with size 10000, it's much more faster to predict the whole data in batch than predict each line one by one (in both cases, model.n_jobs=1).

I know there're many overheads in the one by one solution. But in a online service, requests are coming one by one, it's hard to aggregate them first and then predict in batch.

An alternative solution is use scikit-learn for train/validation only, and develop a project to load the model file and optimize the one-by-one prediction.

The problem is that the prediction project need to know the detail of every kind of model (we may use Random Forests, LR, etc.).

So my question is there any solutions to reduce the one-by-one prediction overhead for sklearn?

scikit-learn version: 0.20.0 (You can propose any other versions can solve this problem)

答:
You can try playing with optimized libraries such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex
There are optimizations for single row inference particularly for RF and kNN algorithms

First install package

pip install scikit-learn-intelex
```
<p>And then add in your python script</p>
<pre class="lang-py prettyprint-override"><code>from sklearnex import patch_sklearn
patch_sklearn()
</code>```

This would accelerate your code with no additional changes on your side

Body:
You can try playing with optimized libraries such as scikit-learn-intelex - https://github.com/intel/scikit-learn-intelex
There are optimizations for single row inference particularly for RF and kNN algorithms

First install package

pip install scikit-learn-intelex

And then add in your python script

from sklearnex import patch_sklearn
patch_sklearn()

This would accelerate your code with no additional changes on your side


问:
Regex for parsing url PHP
I need to find whether a given url is valid or not, the scenario is it should be allowed if it contains urls haviing

1.Generic top-level domains
2.Country code top-level domains
refer below url
http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

I need to do this in PHP, this is currently what I am doing

```
    $regexUrl = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regexUrl .= "([a-zA-Z0-9+!*(),;?&=\$_.-]+(\:[a-zA-Z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regexUrl .= "([a-zA-Z0-9-]+)\.([a-zA-Z]{2,3})";  // Host or IP
    $regexUrl .= "(\:[0-9]{2,5})?"; // Port
    $regexUrl .= "(\/([a-zA-Z0-9+\$_-]\.?)+)*\/?"; // Path
    $regexUrl .= "(\?[a-zA-Z+&\$_.-][a-zA-Z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regexUrl .= "(#[a-zA-Z_.-][a-zA-Z0-9+\$_.-]*)?"; // Anchor
    //if(preg_match_all("#\bhttps?://[^\s()]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#", $message, $matches1, PREG_PATTERN_ORDER))
    //$pattern = '/((https?|ftp)\:(\/\/)|(file\:\/{2,3}))?(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(((([a-zA-Z0-9]+)(\.)?)+)(\.)(com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|[a-z]{2}))([\/][\/a-zA-Z0-9\.]*)*([\/]?(([\?][a-zA-Z0-9]+[\=][a-zA-Z0-9\%\(\)]*)([\&][a-zA-Z0-9]+[\=][a-zA-Z0-9\%\(\)]*)*))?/';
    if(preg_match_all("/$regexUrl/", $urlMessage, $matches1, PREG_PATTERN_ORDER))
    {
      try
        {
            foreach($matches1[0] as $urlToTrim1)
            {
                $url= $urlToTrim1;
                echo $url;
            }
        }
        catch(Exception $e)
        {
            $url="-1";
        }
    }
```

答:
To figure out if it's generally a valid URL:

```<code>filter_var($url, FILTER_VALIDATE_URL)
</code>```

http://www.php.net/manual/en/function.filter-var.php

If you want to confirm that the TLD is in your approved list (I don't know if filter_var goes so far as to check whether a TLD actually exists):

```<code>$host = parse_url($url, PHP_URL_HOST);
$tld = substr($host, strrpos($host, '.') + 1);

// check if $tld is in a list of allowed TLDs
</code>```

Or simply try to look up the DNS record of the domain using gethostbyname. If one exists, it's a valid domain.*

* Unless you're being DNS spoofed, if that case is important to you...

Title: Regex for parsing url PHP

Body:
I need to find whether a given url is valid or not, the scenario is it should be allowed if it contains urls haviing

1.Generic top-level domains
2.Country code top-level domains
refer below url
http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

I need to do this in PHP, this is currently what I am doing

    $regexUrl = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regexUrl .= "([a-zA-Z0-9+!*(),;?&=\$_.-]+(\:[a-zA-Z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regexUrl .= "([a-zA-Z0-9-]+)\.([a-zA-Z]{2,3})";  // Host or IP
    $regexUrl .= "(\:[0-9]{2,5})?"; // Port
    $regexUrl .= "(\/([a-zA-Z0-9+\$_-]\.?)+)*\/?"; // Path
    $regexUrl .= "(\?[a-zA-Z+&\$_.-][a-zA-Z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regexUrl .= "(#[a-zA-Z_.-][a-zA-Z0-9+\$_.-]*)?"; // Anchor
    //if(preg_match_all("#\bhttps?://[^\s()]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#", $message, $matches1, PREG_PATTERN_ORDER))
    //$pattern = '/((https?|ftp)\:(\/\/)|(file\:\/{2,3}))?(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(((([a-zA-Z0-9]+)(\.)?)+)(\.)(com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|[a-z]{2}))([\/][\/a-zA-Z0-9\.]*)*([\/]?(([\?][a-zA-Z0-9]+[\=][a-zA-Z0-9\%\(\)]*)([\&][a-zA-Z0-9]+[\=][a-zA-Z0-9\%\(\)]*)*))?/';
    if(preg_match_all("/$regexUrl/", $urlMessage, $matches1, PREG_PATTERN_ORDER))
    {
      try
        {
            foreach($matches1[0] as $urlToTrim1)
            {
                $url= $urlToTrim1;
                echo $url;
            }
        }
        catch(Exception $e)
        {
            $url="-1";
        }
    }

Body:
To figure out if it's generally a valid URL:

filter_var($url, FILTER_VALIDATE_URL)

http://www.php.net/manual/en/function.filter-var.php

If you want to confirm that the TLD is in your approved list (I don't know if filter_var goes so far as to check whether a TLD actually exists):

$host = parse_url($url, PHP_URL_HOST);
$tld = substr($host, strrpos($host, '.') + 1);

// check if $tld is in a list of allowed TLDs

Or simply try to look up the DNS record of the domain using gethostbyname. If one exists, it's a valid domain.*

* Unless you're being DNS spoofed, if that case is important to you...


问:
What is the difference between private and protected members of C++ classes?
What is the difference between private and protected members in C++ classes?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.

What's the difference and which should I use?

答:
The protected keyword specifies access to class members in the
member-list up to the next access specifier (public or private) or the
end of the class definition. Class members declared as protected can
be used only by the following:

Member functions of the class that originally declared these members.

Friends of the class that originally declared these members.

Classes derived with public or protected access from the class that originally declared these members.

Direct privately derived classes that also have private access to protected members.

When preceding the name of a base class, the protected keyword
specifies that the public and protected members of the base class are
protected members of its derived classes.

Protected members are not as private as private members, which are
accessible only to members of the class in which they are declared,
but they are not as public as public members, which are accessible in
any function.

Protected members that are also declared as static are accessible to
any friend or member function of a derived class. Protected members
that are not declared as static are accessible to friends and member
functions in a derived class only through a pointer to, reference to,
or object of the derived class.

protected (C++)

OwnerDisplayName: Whyamistilltyping

LastEditorDisplayName: Don Kirkby


问:
How to implement associative array (not dictionary) in Python?
I trying to print out a dictionary in Python:

```<code>Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
  print Key,"=",Value
</code>```

Although the item "Forename" is listed first, but dictionaries in Python seem to be sorted by values, so the result is like this:

```<code>Surname = Dinh
Forename = Paul
</code>```

How to print out these with the same order in code or the order when items are appended in (not sorted by values nor by keys)?

答:
As of Python 3.7, regular dicts are guaranteed to be ordered, so you can just do

Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.items():
  print(Key,"=",Value)
```

Body:
I trying to print out a dictionary in Python:

Dictionary = {"Forename":"Paul","Surname":"Dinh"}
for Key,Value in Dictionary.iteritems():
  print Key,"=",Value

Although the item "Forename" is listed first, but dictionaries in Python seem to be sorted by values, so the result is like this:

Surname = Dinh
Forename = Paul

How to print out these with the same order in code or the order when items are appended in (not sorted by values nor by keys)?


问:
flutter ink well on tap not working in list wheel scroll view
I am trying to add ink well to List Wheel Scroll View in flutter but it is not working. Can you help me to add on tap in list wheel Scroll View</p>

答:
check out this package https://pub.dev/packages/clickable_list_wheel_view

Behavior:

When you click on the selected item, onItemTapCallback is called on the ClickableListWheelScrollView

When you click on another item, onItemTapCallback is called on the ClickableListWheelScrollView, immediately followed by a call to onSelectedItemChanged on the ListWheelScrollView

```<code>import 'package:flutter/material.dart';
import 'package:clickable_list_wheel_view/clickable_list_wheel_widget.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            'List Wheel',
          ),
        ),
        body: MyListWheel(),
      ),
    ),
  );
}

class MyListWheel extends StatelessWidget {
  final _scrollController = FixedExtentScrollController();
  final double _itemHeight = 100.0;
  final data = List.generate(20, (index) => 'Item $index');

  @override
  Widget build(BuildContext context) {
    return ClickableListWheelScrollView(
      scrollController: _scrollController,
      itemHeight: _itemHeight,
      itemCount: data.length,
      onItemTapCallback: (index) {
        print("onItemTapCallback index: $index");
      },
      child: ListWheelScrollView.useDelegate(
        controller: _scrollController,
        itemExtent: _itemHeight,
        physics: FixedExtentScrollPhysics(),
        overAndUnderCenterOpacity: 0.5,
        perspective: 0.002,
        onSelectedItemChanged: (index) {
          print("onSelectedItemChanged index: $index");
        },
        childDelegate: ListWheelChildBuilderDelegate(
          builder: (context, index) => ListTile(title: Text(data[index])),
          childCount: data.length,
        ),
      ),
    );
  }
}
</code>```

Body:
check out this package https://pub.dev/packages/clickable_list_wheel_view

Behavior:

When you click on the selected item, onItemTapCallback is called on the ClickableListWheelScrollView

When you click on another item, onItemTapCallback is called on the ClickableListWheelScrollView, immediately followed by a call to onSelectedItemChanged on the ListWheelScrollView

import 'package:flutter/material.dart';
import 'package:clickable_list_wheel_view/clickable_list_wheel_widget.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            'List Wheel',
          ),
        ),
        body: MyListWheel(),
      ),
    ),
  );
}

class MyListWheel extends StatelessWidget {
  final _scrollController = FixedExtentScrollController();
  final double _itemHeight = 100.0;
  final data = List.generate(20, (index) => 'Item $index');

  @override
  Widget build(BuildContext context) {
    return ClickableListWheelScrollView(
      scrollController: _scrollController,
      itemHeight: _itemHeight,
      itemCount: data.length,
      onItemTapCallback: (index) {
        print("onItemTapCallback index: $index");
      },
      child: ListWheelScrollView.useDelegate(
        controller: _scrollController,
        itemExtent: _itemHeight,
        physics: FixedExtentScrollPhysics(),
        overAndUnderCenterOpacity: 0.5,
        perspective: 0.002,
        onSelectedItemChanged: (index) {
          print("onSelectedItemChanged index: $index");
        },
        childDelegate: ListWheelChildBuilderDelegate(
          builder: (context, index) => ListTile(title: Text(data[index])),
          childCount: data.length,
        ),
      ),
    );
  }
}


问:
How to pass the latitude and longitude values to the ns url as a arguments?
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

```<code> NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];
</code>```

I write this one in below method for get and pass the latitude and longitude values.

```<code>   - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}
</code>```

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method.

With others suggestions i changed the code like below.

```<code>    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
    NSURL *url = [NSURL URLFromString:address];
}
</code>```

This also gives the error like Exe_Bad_Access when the first line executed.SO please tell me how to write that one.

答:
Try This ,</p>

```<code>NSURL *addressUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%@,%@&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM",newLocation.latitude, newLocation.longitude, nil]];
</code>```

Body:
Iam developing one application.In that i use the google api for getting the location information.For that i use the CLLocationManager for getting the location latitude and longitude values.And my pblm is how to pass these latitude and longitude values to nsurl .ANd iam directly given the one location values to the url like below.

 NSURL *URL = [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search           /json?location=40.7143528,-74.0059731&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM"];

I write this one in below method for get and pass the latitude and longitude values.

   - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
}

So please tell me how to pass the newlocation.Coordinates.latitude and newlocation.Coordinates.longitude to that url in that method.

With others suggestions i changed the code like below.

    - (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{

    NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f, %f&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM", newLocation.lattitude, newLocation.longitude];
    NSURL *url = [NSURL URLFromString:address];
}

This also gives the error like Exe_Bad_Access when the first line executed.SO please tell me how to write that one.

Body:
Try This ,

NSURL *addressUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%@,%@&radius=10000&types=school&sensor=false&key=AIzaSyDbiWWIOmc08YSb9DAkdyTWXh_PirVuXpM",newLocation.latitude, newLocation.longitude, nil]];


问:
I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong
I'm trying to allow a user to enter data into a textbox that will be added to the web.config file. I've added the relevent lines to the web.config file but when I make this class all goes wrong.

I keep getting the are you missing a using directive or assembly refenrence error whenever I try to run my app. I have looked at the other times this question has been asked and can't seem to figure out where I'm going wrong. The thing is that I am extremely new to Visual Studio and am just left blank at what could be the answer.

Below here is the class file that's generating the error. I hope I've included everything you need to assist me. Thank you.

```<code> using System.Collections.Generic;
 using System.Linq;
 using System.Configuration;

namespace WebConfigDemo
{
public class CompanyConfigSection : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    public CompanyConfigCollection Companies
    {
        get
        {
        return (CompanyConfigCollection)this[""];
        }
        set
        {
            this[""] = value;
        }
    }
}
public class CompanyConfigElement : ConfigurationElement
{
                [ConfigurationProperty("id", IsKey = true, IsRequired = true)]
    public int Id
                {
                    get
                {
                        return (int)this["id"];
                    }
                    set
                    {
                        this["id"] = value;
                }
                }
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
                    return this["name"].ToString();
        }
        set
        {
            this["name"] = value;
        }

    }
} '
public class CompanyConfigCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
{
    return new CompanyConfigElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((CompanyConfigElement)element).Id;
    }
}
public class CompaniesConfig
{
            private static readonly Dictionary<int, CompanyConfigElement>
                Elements;
    static CompaniesConfig()
    {
                Elements = new Dictionary<int, CompanyConfigElement>();
                var section = (CompanyConfigSection)ConfigurationManager.GetSection          ("companies");
                foreach (CompanyConfigElement system in section.Companies)
                    Elements.Add(system.Id, system);
    }
    public static CompanyConfigElement GetCompany(int companyId)
    {
                        return Elements[companyId];
    }
            public static List<CompanyConfigElement> Companies
            {
                get
                {
                    return Elements.Values.ToList();
                }
            }
}
}  '
</code>```

Any help is appreciated

答:
If you've tried the above solutions and haven't found the answer, make sure that the .NET versions of all projects are the same.

I ran into this problem when importing a .NET version 4.6.1 into a .NET version 4.6.2 project. Without any warnings from Visual Basic!

More Info: The type or namespace name could not be found

Body:
I'm trying to allow a user to enter data into a textbox that will be added to the web.config file. I've added the relevent lines to the web.config file but when I make this class all goes wrong.

I keep getting the are you missing a using directive or assembly refenrence error whenever I try to run my app. I have looked at the other times this question has been asked and can't seem to figure out where I'm going wrong. The thing is that I am extremely new to Visual Studio and am just left blank at what could be the answer.

Below here is the class file that's generating the error. I hope I've included everything you need to assist me. Thank you.

 using System.Collections.Generic;
 using System.Linq;
 using System.Configuration;

namespace WebConfigDemo
{
public class CompanyConfigSection : ConfigurationSection
{
    [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)]
    public CompanyConfigCollection Companies
    {
        get
        {
        return (CompanyConfigCollection)this[""];
        }
        set
        {
            this[""] = value;
        }
    }
}
public class CompanyConfigElement : ConfigurationElement
{
                [ConfigurationProperty("id", IsKey = true, IsRequired = true)]
    public int Id
                {
                    get
                {
                        return (int)this["id"];
                    }
                    set
                    {
                        this["id"] = value;
                }
                }
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
                    return this["name"].ToString();
        }
        set
        {
            this["name"] = value;
        }

    }
} '
public class CompanyConfigCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
{
    return new CompanyConfigElement();
    }
    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((CompanyConfigElement)element).Id;
    }
}
public class CompaniesConfig
{
            private static readonly Dictionary<int, CompanyConfigElement>
                Elements;
    static CompaniesConfig()
    {
                Elements = new Dictionary<int, CompanyConfigElement>();
                var section = (CompanyConfigSection)ConfigurationManager.GetSection          ("companies");
                foreach (CompanyConfigElement system in section.Companies)
                    Elements.Add(system.Id, system);
    }
    public static CompanyConfigElement GetCompany(int companyId)
    {
                        return Elements[companyId];
    }
            public static List<CompanyConfigElement> Companies
            {
                get
                {
                    return Elements.Values.ToList();
                }
            }
}
}  '

Any help is appreciated


问:
How can I use json response from php in jquery?
I'm trying to do a website. I need to get all the reviews in the database. My initial guess was to use php like this:

```<code>function get_all_reviews(){
    $db = dbConnection();
    $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
    $statement = $db -> prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    foreach ($result as $row) {
        $name = $row["Nome"];
        $title = $row["Title"];
        $review = $row["Review"];
        $email = $row["Email"];
        ?>
    <div class="box" id="<?= $email ?>">
    <div class="nome"><?= $name ?>  dice:</div>
    <div class="titolo"><?= $title ?> </div>
    <div class="recensione"><?= $review ?> </div>
    <button class="admin_bottom">X</button>
  </div>
    <?php
}
</code>```

But since it's a project for the university, I need to not use it (it's mandatory). I need to send the request with jquery, then with php I should send the response with json, but I don't get how to recall the reviews and list them.
I try with this with php:

```<code>function gett_all_reviews(){
        $db = dbConnection();
        $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
        $statement = $db -> prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();
        $resultSet = '{ ';
        foreach ($result as $row) {
            $resultSet .= '{"name": "'.$row["Nome"].'",';
            $resultSet .= '"title": "'.$row["Title"].'",';
            $resultSet .= '"review": "'.$row["Review"].'",';
            $resultSet .= '"email": "'.$row["Email"].'"},';

        }
        $resultSet .= '}';
        $db = null;

        return $resultSet;
    }
    $s = get_all_reviews();

    echo $s;
</code>```

and with jquery:

```<code>$.getJSON( "../php/get_reviews.php", function( json ) {

        for (let index = 0; index < json.length; index++) {
            $("#conteiner_reviews").append(
                "<div class=\"box\" id= \""+ json[index].email+ "\">"+
                    "<div class=\"nome\">"+json[index].name +" dice:</div>" +
                    "<div class=\"titolo\"><"+json[index].title+"</div>"+
                    "<div class=\"recensione\">"+json[index].review +"</div></div>");
        }
    });
</code>```

But doesn't work.

答:
function gett_all_reviews(){
    $db = dbConnection();
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = "SELECT Nome as name, Title as title, reviews.Review as review, users.Email as email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
    $statement = $db -> prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $db = null;
    return $result;
}

echo json_encode(get_all_reviews());
```

<pre class="lang-js prettyprint-override"><code>$.getJSON('../php/get_reviews.php', function (data) {
  $.each(data, function (item) {
    $('#conteiner_reviews').append(
      '<div class="box" id="' + item.email+ '">' +
      '<div class="nome">' + item.name + 'dice:</div>' +
      '<div class="titolo">' + item.title + '</div>' +
      '<div class="recensione">' + item.review + '</div>'
    );
  });
});
</code>```

Body:
I'm trying to do a website. I need to get all the reviews in the database. My initial guess was to use php like this:

function get_all_reviews(){
    $db = dbConnection();
    $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
    $statement = $db -> prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    foreach ($result as $row) {
        $name = $row["Nome"];
        $title = $row["Title"];
        $review = $row["Review"];
        $email = $row["Email"];
        ?>
    <div class="box" id="<?= $email ?>">

<?= $name ?>  dice:

<?= $title ?>

<?= $review ?>

    <button class="admin_bottom">X</button>

    <?php
}

But since it's a project for the university, I need to not use it (it's mandatory). I need to send the request with jquery, then with php I should send the response with json, but I don't get how to recall the reviews and list them.
I try with this with php:

function gett_all_reviews(){
        $db = dbConnection();
        $db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
        $statement = $db -> prepare($query);
        $statement->execute();
        $result = $statement->fetchAll();
        $resultSet = '{ ';
        foreach ($result as $row) {
            $resultSet .= '{"name": "'.$row["Nome"].'",';
            $resultSet .= '"title": "'.$row["Title"].'",';
            $resultSet .= '"review": "'.$row["Review"].'",';
            $resultSet .= '"email": "'.$row["Email"].'"},';

        }
        $resultSet .= '}';
        $db = null;

        return $resultSet;
    }
    $s = get_all_reviews();

    echo $s;

and with jquery:

$.getJSON( "../php/get_reviews.php", function( json ) {

        for (let index = 0; index < json.length; index++) {
            $("#conteiner_reviews").append(
                "
"+
                    "
"+json[index].name +" dice:
" +
                    "
<"+json[index].title+"
"+
                    "
"+json[index].review +"

");
        }
    });

But doesn't work.

Body:
function gett_all_reviews(){
    $db = dbConnection();
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = "SELECT Nome as name, Title as title, reviews.Review as review, users.Email as email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
    $statement = $db -> prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $db = null;
    return $result;
}

echo json_encode(get_all_reviews());

$.getJSON('../php/get_reviews.php', function (data) {
  $.each(data, function (item) {
    $('#conteiner_reviews').append(
      '<div class="box" id="' + item.email+ '">' +
      '<div class="nome">' + item.name + 'dice:</div>' +
      '<div class="titolo">' + item.title + '</div>' +
      '<div class="recensione">' + item.review + '</div>'
    );
  });
});


问:
How to impute missing values with mean from row above and below python?
I have a pandas df looking like this:
df image

The row I want to impute values for has "-" instead of values and I want these to be replaced with the mean of the values in the row above and below.

Does anyone know how to do that?

Thank you all!

答:
You can replace "-" to NaN and use interpolate which by default fills missing values linearly. If there is only one missing value, then it would be akin to taking the mean of the top and bottom value of the missing value:

```<code>df = df.replace('-', np.nan)
df = df.interpolate()
</code>```

Body:
You can replace "-" to NaN and use interpolate which by default fills missing values linearly. If there is only one missing value, then it would be akin to taking the mean of the top and bottom value of the missing value:

df = df.replace('-', np.nan)
df = df.interpolate()