问:
php does not echo back POST data
I have the following jQuery script to post form data to php.  I'm testing the form data with a simple php file to echo back the firstname field of the input post:datastring as a test (I'm new to using php so that's why I'm testing it).

```<code><script type="text/javascript">
$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    var datastring = JSON.stringify({form_data});
    console.log("Okay, I'm starting");
    console.log(form_data);
    console.log(datastring);
    return $.ajax({
        type: "POST",
        url: "echo_test.php",
        data: {post: datastring},
        success: function (responseText) {
            console.log(responseText);
        },
        error: function (error) {
            console.log("Okay, I failed" + error);
        }
    });
});
</code>```

The simple php file:

```<code><?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
?>
</code>```

Here's what the Firefox dev console echoes back:

```<code>Okay, I'm starting
email_field=mj%40abc.com&firstname=mary&lastname=jones&comments=no+comment%0D%0A
{"form_data":"email_field=mj%40abc.com&firstname=mary&lastname=jones&comments=no+comment%0D%0A"}
</code>```

and finally it echoes back:

```<code>Hello !
</code>```

So the Hello part and the exclamation point are echoed back, but not the firstname field.  I can see that the datastring it posts to the php file does contain firstname=mary, so there is a value in that field.

Why doesn't the firstname field echo back?

答:
You are not posting your data correctly, try this :</p>

```<code>$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    console.log("Okay, I'm starting");
    console.log(form_data);
    return $.ajax({
        type: "POST",
        url: "echo_test.php",
        data: form_data,
        success: function (responseText) {
            console.log(responseText);
        },
        error: function (error) {
            console.log("Okay, I failed" + error);
        }
    });
});
</code>```

Title: php does not echo back POST data

Body:
You are not posting your data correctly, try this :

$("#btn_submit").on("click", function (event) {
    event.preventDefault();
    form_data = $('form').serialize()
    console.log("Okay, I'm starting");
    console.log(form_data);
    return $.ajax({
        type: "POST",
        url: "echo_test.php",
        data: form_data,
        success: function (responseText) {
            console.log(responseText);
        },
        error: function (error) {
            console.log("Okay, I failed" + error);
        }
    });
});


来源: stackexchange

问:
Import Python class that only has `__new__` into Robot Framework
Have a python class that is imported in Robot Framework as follows:

Python: MyClass.py

```<code>class MyClass:
    def __new__(cls, a, b):
        # implementation here
</code>```

Robot Framework: MyTest.robot

```<code>*** Settings ***
Library    MyClass.py    a=1    b=2
</code>```

Getting the error Error in file 'MyTest.robot': Test Library 'MyClass' expected 0 arguments, got 2.

I understand the error is because MyClass doesn't have __init__ defined (if it's defined, there's no import error).

My question is: How can I import MyClass.py, which has __new__ defined but not __init__?

(without going into the details of why I have __new__ and not __init__)

答:
__new__ is responsible on instance creation, and __init__ is just initializer after instance is created. First always is called __new__ and then __init__. __new__ is always @staticmethod as a default, but you can use @staticmethod decorator also (same).

```<code>class Foo:

    @staticmethod
    def __new__(cls):
        print('Foo.__new__ is called')
        obj = super().__new__(cls)
        print(obj) # <__main__.Foo object at 0x7f82c1403588> This is "f" object.
        return obj

    def __init__(self, *args, **kwargs):
        print('Foo.__init__ is called !!!')

f = Foo()
</code>```

Hope, it helps you.

ContentLicense: CC BY-SA 4.0

Body:
Have a python class that is imported in Robot Framework as follows:

Python: MyClass.py

class MyClass:
    def __new__(cls, a, b):
        # implementation here

Robot Framework: MyTest.robot

*** Settings ***
Library    MyClass.py    a=1    b=2

Getting the error Error in file 'MyTest.robot': Test Library 'MyClass' expected 0 arguments, got 2.

I understand the error is because MyClass doesn't have __init__ defined (if it's defined, there's no import error).

My question is: How can I import MyClass.py, which has __new__ defined but not __init__?

(without going into the details of why I have __new__ and not __init__)

Body:
__new__ is responsible on instance creation, and __init__ is just initializer after instance is created. First always is called __new__ and then __init__. __new__ is always @staticmethod as a default, but you can use @staticmethod decorator also (same).

class Foo:

    @staticmethod
    def __new__(cls):
        print('Foo.__new__ is called')
        obj = super().__new__(cls)
        print(obj) # <__main__.Foo object at 0x7f82c1403588> This is "f" object.
        return obj

    def __init__(self, *args, **kwargs):
        print('Foo.__init__ is called !!!')

f = Foo()

Hope, it helps you.


问:
Recaptcha issue in China
We have an issue related to the Recaptcha, it is not working in China as google is blocked.

As per the below link,
https://groups.google.com/forum/m/#!topic/recaptcha/XBhetkVgh84

We need to replace the 'www.google.com' with 'www.recaptcha.net'.

But we also have the following url given in the app.config file.

```<code><add key="GRecaptcha" value="https://www.google.com/recaptcha/api/siteverify"/>
</code>```

So, could you please let me know replacing the www.google.com in the app.config with 'www.recaptcha.net' will fix this issue? Do I need to change anything in angular-recaptcha.js file also?

Also, could you please let me know if there is any other solution to fix this issue in China?

答:
NetEase a.k.a 163 provides similar service:

https://www.163yun.com/product/captcha

The page is in Chinese so you might need google translate if you do not speak the language.

Title: Recaptcha issue in China

Body:
We have an issue related to the Recaptcha, it is not working in China as google is blocked.

As per the below link,
https://groups.google.com/forum/m/#!topic/recaptcha/XBhetkVgh84

We need to replace the 'www.google.com' with 'www.recaptcha.net'.

But we also have the following url given in the app.config file.

<add key="GRecaptcha" value="https://www.google.com/recaptcha/api/siteverify"/>

So, could you please let me know replacing the www.google.com in the app.config with 'www.recaptcha.net' will fix this issue? Do I need to change anything in angular-recaptcha.js file also?

Also, could you please let me know if there is any other solution to fix this issue in China?


问:
For loop and if for multiple conditions and change another column in the same row in pandas
I am trying to have a change a column if some strings are in the other column in the same row. I am new to Pandas.

I need to change the price of some oranges to 200 but not the price of 'Red Orange'. I cannot change the name of the "fruits". It is a much longer string and I just made it shorter for convenience here.

```<code>    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        16
    Red Orange from Costa          15
    Pink Orange from Brazil        19
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5
</code>```

so that the final result would be

```<code>    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        200
    Red Orange from Costa          15
    Pink Orange from Brazil        200
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5
</code>```

I tried

```<code>    df.loc[df['fruits'].str.lower().str.contains('orange'), 'price'] = 200
</code>```

But this produces total of 4 items to change its price instead of only 2 items.

I have used for loop once and that changed the entire column to change its price.

答:
```<code>df.loc[((df['fruits'].str.contains('orange')) & (~df['fruits'].str.contains('Red'))),'price'] = 200

</code>```

We check for oranges and ~ to confirm red is not present in the string. If both conditions are true, price change to 200

Body:
I am trying to have a change a column if some strings are in the other column in the same row. I am new to Pandas.

I need to change the price of some oranges to 200 but not the price of 'Red Orange'. I cannot change the name of the "fruits". It is a much longer string and I just made it shorter for convenience here.

    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        16
    Red Orange from Costa          15
    Pink Orange from Brazil        19
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5

so that the final result would be

    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        200
    Red Orange from Costa          15
    Pink Orange from Brazil        200
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5

I tried

    df.loc[df['fruits'].str.lower().str.contains('orange'), 'price'] = 200

But this produces total of 4 items to change its price instead of only 2 items.

I have used for loop once and that changed the entire column to change its price.

Body:
df.loc[((df['fruits'].str.contains('orange')) & (~df['fruits'].str.contains('Red'))),'price'] = 200

We check for oranges and ~ to confirm red is not present in the string. If both conditions are true, price change to 200


问:
Use awk, or sed commands to remove the letters and parenthesis from the rows of a file
I have an input file as below,

```<code>group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]
</code>```

Now, I want to use the awk/sed command, such that the output file would look as:

```<code>   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979
</code>```

Any help would be appreciated.

答:
```<code>sed  's/^.*\[\|\].*//g' input_file
</code>```

This is deleting everything from start till [ and ] till end.

Or using back referencing:

```<code> sed 's/.*\[\([^]]*\)\].*/\1/g' input_file
</code>```

This will extract the text between the two [ and ].

Body:
I have an input file as below,

group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]

Now, I want to use the awk/sed command, such that the output file would look as:

   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979

Any help would be appreciated.

Body:
sed  's/^.*\[\|\].*//g' input_file

This is deleting everything from start till [ and ] till end.

Or using back referencing:

 sed 's/.*\[\([^]]*\)\].*/\1/g' input_file

This will extract the text between the two [ and ].


问:
TTStyledText that recognizes URLs without http:// scheme
I am using TTStyledText to display text with potential markup on a TTStyledTextLabel.

If text contains something like "http://stackoverflow.com" TTStyledText autogenerates the markup and linkifies said text.

The problem is I also want "www.stackoverflow.com" to appear as valid hyperlinks, as well as anything that reasonably resembles an http URL, even if the scheme is missing.

Any way to do that with TTStyleText or do I need to recognize the URL and reformat the text myself?

答: I've always found TTStyledText to be woefully underpowered and missing a lot of functionality.  This is a good example.  I think in order to make this work you'll need to as you say pre-format the text portion before you pass it in.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Is there a way to set default tags for new cells in a jupyter notebook?
I need to add the tag 'nocell' to most of my cells and it is a bit annoying. Is there a way to setup a notebook so that tags are added by default when creating a new cell?
Thanks!</p>

答:
As far as I know, there isn't a built in way to do this. However, you can look into creating a jupyter extension which does what you need. Using this, you could build either an extension that marks any newly added cells with the tag, or you can create a new button bar action that, when clicked, would insert a cell with the tag.

Update

Here is some more detail on how exactly to do this with a button added by a custom Jupyter extension. From this tutorial, it gives the instructions on adding a custom extension. You will need to tweak the example slightly to make it do what you want. Specifically, you should tweak the main.js file. It needs to be something along these lines:

```<code>define([
    'base/js/namespace',
    'base/js/events'
], function (Jupyter, events) {

    var add_cell_tagged_nocell = function () {
        Jupyter.notebook.insert_cell_below();
        Jupyter.notebook.select_next();
        var cell = Jupyter.notebook.get_selected_cell();
        cell.metadata.tags = ["nocell"];
    };

    function load_ipython_extension() {
        // Button to add tagged cell
        Jupyter.toolbar.add_buttons_group([
            Jupyter.keyboard_manager.actions.register({
                'help': 'Add cell tagged nocell',
                'icon': 'fa-play-circle',
                'handler': add_cell_tagged_nocell
            }, 'add-tagged-cell', 'Tagged cell')
        ])
    }
    return {
        load_ipython_extension: load_ipython_extension
    };
});
</code>```

Then when the extension is loaded, you will get an additional button in the button bar to click. When clicked, a new cell will be inserted below the current cell and have the tag "nocell".

There is a known issue where the cell toolbar does not refresh if you have the tags showing, but the metadata is there and the tags toolbar will be correct if you hide and show it again.

Cheers!

Body:
As far as I know, there isn't a built in way to do this. However, you can look into creating a jupyter extension which does what you need. Using this, you could build either an extension that marks any newly added cells with the tag, or you can create a new button bar action that, when clicked, would insert a cell with the tag.

Update

Here is some more detail on how exactly to do this with a button added by a custom Jupyter extension. From this tutorial, it gives the instructions on adding a custom extension. You will need to tweak the example slightly to make it do what you want. Specifically, you should tweak the main.js file. It needs to be something along these lines:

define([
    'base/js/namespace',
    'base/js/events'
], function (Jupyter, events) {

    var add_cell_tagged_nocell = function () {
        Jupyter.notebook.insert_cell_below();
        Jupyter.notebook.select_next();
        var cell = Jupyter.notebook.get_selected_cell();
        cell.metadata.tags = ["nocell"];
    };

    function load_ipython_extension() {
        // Button to add tagged cell
        Jupyter.toolbar.add_buttons_group([
            Jupyter.keyboard_manager.actions.register({
                'help': 'Add cell tagged nocell',
                'icon': 'fa-play-circle',
                'handler': add_cell_tagged_nocell
            }, 'add-tagged-cell', 'Tagged cell')
        ])
    }
    return {
        load_ipython_extension: load_ipython_extension
    };
});

Then when the extension is loaded, you will get an additional button in the button bar to click. When clicked, a new cell will be inserted below the current cell and have the tag "nocell".

There is a known issue where the cell toolbar does not refresh if you have the tags showing, but the metadata is there and the tags toolbar will be correct if you hide and show it again.

Cheers!


问:
Transform: Translate Animation not working
I am wanting to achieve a "blind effect" where clicking on a button will cause an overlay div to animate up so only a small portion shows at the top of the screen and it reveals a div below.

I am using gatsby, with react spring and styled components. I have set the "blind"  up as a component as follows:-

```<code>const HeroWrapper = styled(animated.div)`
  background-color: blue;
  height: 100vh;
  width: 100vw;
  text-align: center;
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: column;
  z-index: 15;
`
const HeroTitle = styled.h1`
  margin: auto;
  color: whitesmoke;
`

const Hero = () => {
  const [isHeroOpen, setHeroOpen] = useState(true)
  const heroAnimation = useSpring({
    transform: isHeroOpen ? `translate3d(0,0,0)` : `translate3d(0, -85%, 0)`,
  })

  return (
    <HeroWrapper style={heroAnimation} onClick={() => setHeroOpen(!isHeroOpen)}>
      <HeroTitle>I am a Hero Blind</HeroTitle>
      <div style={{ paddingBottom: '40px' }}>
        <button type="button" onClick={() => setHeroOpen(!isHeroOpen)}>
          Click
        </button>
      </div>
    </HeroWrapper>
  )
}
</code>```

However the animation does not work with the transform:translate.
If I replace this with an animation on the background color...

```<code>    backgroundColor: isHeroOpen ? `#66666666` : `green`,
</code>```

...it works fine so all is working with the state toggle.

Also if I amend the transform:translate in the developer tools it also works -  so what am I doing wrong?

Many thanks

答:
It was a hard one. Apparently you have to include the percent sign for the first translate too for react-spring to interpolate it properly.

```<code>const heroAnimation = useSpring({
  transform: isHeroOpen ? `translate3d(0,0%,0)` : `translate3d(0,-85%,0)`
});
</code>```

Here is a sandbox for it: https://codesandbox.io/s/focused-maxwell-1m8vq

Body:
I am wanting to achieve a "blind effect" where clicking on a button will cause an overlay div to animate up so only a small portion shows at the top of the screen and it reveals a div below.

I am using gatsby, with react spring and styled components. I have set the "blind"  up as a component as follows:-

const HeroWrapper = styled(animated.div)`
  background-color: blue;
  height: 100vh;
  width: 100vw;
  text-align: center;
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: column;
  z-index: 15;
`
const HeroTitle = styled.h1`
  margin: auto;
  color: whitesmoke;
`

const Hero = () => {
  const [isHeroOpen, setHeroOpen] = useState(true)
  const heroAnimation = useSpring({
    transform: isHeroOpen ? `translate3d(0,0,0)` : `translate3d(0, -85%, 0)`,
  })

  return (
    <HeroWrapper style={heroAnimation} onClick={() => setHeroOpen(!isHeroOpen)}>
      <HeroTitle>I am a Hero Blind</HeroTitle>

        <button type="button" onClick={() => setHeroOpen(!isHeroOpen)}>
          Click
        </button>

    </HeroWrapper>
  )
}

However the animation does not work with the transform:translate.
If I replace this with an animation on the background color...

    backgroundColor: isHeroOpen ? `#66666666` : `green`,

...it works fine so all is working with the state toggle.

Also if I amend the transform:translate in the developer tools it also works -  so what am I doing wrong?

Many thanks

Body:
It was a hard one. Apparently you have to include the percent sign for the first translate too for react-spring to interpolate it properly.

const heroAnimation = useSpring({
  transform: isHeroOpen ? `translate3d(0,0%,0)` : `translate3d(0,-85%,0)`
});

Here is a sandbox for it: https://codesandbox.io/s/focused-maxwell-1m8vq


问:
Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'
When I try to launch my AndEngine Activity, I get this error:

```<code>ERROR/InputDispatcher(21374): channel '4122e148 my.package.AcGame (server)' ~ Channel is unrecoverably broken and will be disposed!
</code>```

The app doesn't crash, but there's a black screen and the device doesn't react to pressing the 'back' or 'home' buttons.

Does anyone know what the problem is?

答:
This error occurred in case of memory leak. For example if you have any static context of an Android component (Activity/service/etc) and its gets killed by system.

Example: Music player controls in notification area. Use a foreground service and set actions in the notification channel via PendingIntent like below.

```<code>Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(AppConstants.ACTION.MAIN_ACTION);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        Intent previousIntent = new Intent(this, ForegroundService.class);
        previousIntent.setAction(AppConstants.ACTION.PREV_ACTION);
        PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                previousIntent, 0);

        Intent playIntent = new Intent(this, ForegroundService.class);
        playIntent.setAction(AppConstants.ACTION.PLAY_ACTION);
        PendingIntent pplayIntent = PendingIntent.getService(this, 0,
                playIntent, 0);

        Intent nextIntent = new Intent(this, ForegroundService.class);
        nextIntent.setAction(AppConstants.ACTION.NEXT_ACTION);

        Bitmap icon = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder
                .setOngoing(true)
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("Foreground Service")
                .setContentText("Foreground Service Running")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setContentIntent(pendingIntent)
                .setPriority(NotificationManager.IMPORTANCE_MAX)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setTicker("Hearty365")
                .build();
        startForeground(AppConstants.NOTIFICATION_ID.FOREGROUND_SERVICE,
                notification);
</code>```

And if this notification channel get broken abruptly (may be by system, like in Xiomi devices when we clean out the background apps), then due to memory leaks this error is thrown by system.

Body:
When I try to launch my AndEngine Activity, I get this error:

ERROR/InputDispatcher(21374): channel '4122e148 my.package.AcGame (server)' ~ Channel is unrecoverably broken and will be disposed!

The app doesn't crash, but there's a black screen and the device doesn't react to pressing the 'back' or 'home' buttons.

Does anyone know what the problem is?

Body:
This error occurred in case of memory leak. For example if you have any static context of an Android component (Activity/service/etc) and its gets killed by system.

Example: Music player controls in notification area. Use a foreground service and set actions in the notification channel via PendingIntent like below.

Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setAction(AppConstants.ACTION.MAIN_ACTION);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

        Intent previousIntent = new Intent(this, ForegroundService.class);
        previousIntent.setAction(AppConstants.ACTION.PREV_ACTION);
        PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
                previousIntent, 0);

        Intent playIntent = new Intent(this, ForegroundService.class);
        playIntent.setAction(AppConstants.ACTION.PLAY_ACTION);
        PendingIntent pplayIntent = PendingIntent.getService(this, 0,
                playIntent, 0);

        Intent nextIntent = new Intent(this, ForegroundService.class);
        nextIntent.setAction(AppConstants.ACTION.NEXT_ACTION);

        Bitmap icon = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder
                .setOngoing(true)
                .setAutoCancel(true)
                .setWhen(System.currentTimeMillis())
                .setContentTitle("Foreground Service")
                .setContentText("Foreground Service Running")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setContentIntent(pendingIntent)
                .setPriority(NotificationManager.IMPORTANCE_MAX)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setTicker("Hearty365")
                .build();
        startForeground(AppConstants.NOTIFICATION_ID.FOREGROUND_SERVICE,
                notification);

And if this notification channel get broken abruptly (may be by system, like in Xiomi devices when we clean out the background apps), then due to memory leaks this error is thrown by system.


问:
Collecting the value which have the same name in column and row from data frame
```<code>This is a small example:
a <- c("a", "b", "f", "c", "e")
b <- c("a", "c", "e", "d", "b")
p <- matrix(1:25, nrow = 5, dimnames = list(a, b))
p <- as.data.frame(p)

#data.frame would be like that
    a    c    e    d    b
a   1    6    11   16   21
b   2    7    12   17   22
f   3    8    13   18   23
c   4    9    14   19   24
e   5   10    15   20   25
</code>```

The output what I want:

```<code>  score
a   1
b   22
c   9
e   15
</code>```

This is the code I wrote:

```<code>L <- rownames(p)
output <- NULL
t <- 1
for (i in L) {
  tar_column <- p[i]
  score <- tar_column[t, ]
  tar_score <- matrix(score, nrow = 1, dimnames = list(i, "score"))
  output <- rbind(output, tar_score)
  t <- t+1
}
</code>```

The output I got:

```<code>score
a   1
b   22

Error in `[.data.frame`(p, i) : undefined columns selected
</code>```

The problem is that column name and rowname are not matched perfectly. I think that the if statement can help to skip the variable when it can't be matched to the column name. Could someone help me fix this problem?

答:
Here is another option: </p>

```<code>library(tidyverse)

p %>%
  rownames_to_column("row") %>%
  gather(col, score, -row) %>%
  filter(row == col) %>%
  select(-row)
#>   col score
#> 1   a     1
#> 2   c     9
#> 3   e    15
#> 4   b    22
</code>```

<p>First we make the row name into a variable, then we gather from wide to long format, lastly we filter only matching pairs of row and col. </p>

Body:
This is a small example:
a <- c("a", "b", "f", "c", "e")
b <- c("a", "c", "e", "d", "b")
p <- matrix(1:25, nrow = 5, dimnames = list(a, b))
p <- as.data.frame(p)

#data.frame would be like that
    a    c    e    d    b
a   1    6    11   16   21
b   2    7    12   17   22
f   3    8    13   18   23
c   4    9    14   19   24
e   5   10    15   20   25

The output what I want:

  score
a   1
b   22
c   9
e   15

This is the code I wrote:

L <- rownames(p)
output <- NULL
t <- 1
for (i in L) {
  tar_column <- p[i]
  score <- tar_column[t, ]
  tar_score <- matrix(score, nrow = 1, dimnames = list(i, "score"))
  output <- rbind(output, tar_score)
  t <- t+1
}

The output I got:

score
a   1
b   22

Error in `[.data.frame`(p, i) : undefined columns selected

The problem is that column name and rowname are not matched perfectly. I think that the if statement can help to skip the variable when it can't be matched to the column name. Could someone help me fix this problem?

Body:
Here is another option:

library(tidyverse)

p %>%
  rownames_to_column("row") %>%
  gather(col, score, -row) %>%
  filter(row == col) %>%
  select(-row)
#>   col score
#> 1   a     1
#> 2   c     9
#> 3   e    15
#> 4   b    22

First we make the row name into a variable, then we gather from wide to long format, lastly we filter only matching pairs of row and col.


问:
Rewriting java if statements in clojure syntax
I have a set of recursive if statements written in Java and I tried taking it to clojure syntax but got the ArrayOutOfBound error. The functions accepts row = 0, col = 0 and a multidimensional array of characters.

This is the Java Code:

```<code>public static boolean solveMaze(int r, int c, char[][] maze) {

    //check for boundaries
    if(r < 0 || c < 0 || r >= maze.length || c >= maze[0].length)
        return false;
    //base case, did i reach the finish?
    if(maze[r][c] == '@')
        return true;
    //check if I'm at a valid point
    if(maze[r][c] != '-')
    //I have hit a wall, not a valid solution
        return false;
    //must be on a path, may be the right path
    //leave a bread crumb
    maze[r][c] = '!';
    //check above
    if(solveMaze(r-1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check below
    if(solveMaze(r+1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check left
    if(solveMaze(r,c-1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check right
    if(solveMaze(r,c+1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //if I reach this point...
    return false;
}
</code>```

This is my code in clojure that provides the Index out of bound error:

```<code>    (defn solveMaze [r c m]
    (def tt true)
    ;(def che false)

    ;check to verify boundaries
    (if (or (or (or (< r 0) (< c 0)) (>= r (count m))) (>= c (count (str (m 0)))))
        false
        true
    )
    ;Check to know if the @ symbol has been found
    (if (= (get-in m[r c]) "@")
        true
        false
    )
    ;Checking if current index is a valid one
    (if (not= (get-in m[r c]) "-")
        ;Wall hit
        false
        true
    )
    ;found a path, leave a breadcrumb
    (def temp_map (assoc-in m[r c] "!"))
    ;Check North
    (if (= (solveMaze (dec r) c m) true)
        (def temp_map (assoc-in m [r c] "+"))
        true
        ;false
    )
    ;Check South
    (if (= (solveMaze (inc r) c m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check East
    (if (= (solveMaze r (dec c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check West
    (if (= (solveMaze r (inc c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;If code gets here
    (= tt false)
</code>```

)

Please is there something I am doing wrongly??? I have tried several if constructs using clojure but it doesn't work.

答:
Use a cond to solve this instead of if. The way the code executes now is that first if is evaluated and then it goes to the next line to execute rest of code. With cond, if an expression is evaluated to be true, it returns the value and won't evaluate other expressions.

Refer :https://clojuredocs.org/clojure.core/cond

Body:
I have a set of recursive if statements written in Java and I tried taking it to clojure syntax but got the ArrayOutOfBound error. The functions accepts row = 0, col = 0 and a multidimensional array of characters.

This is the Java Code:

public static boolean solveMaze(int r, int c, char[][] maze) {

    //check for boundaries
    if(r < 0 || c < 0 || r >= maze.length || c >= maze[0].length)
        return false;
    //base case, did i reach the finish?
    if(maze[r][c] == '@')
        return true;
    //check if I'm at a valid point
    if(maze[r][c] != '-')
    //I have hit a wall, not a valid solution
        return false;
    //must be on a path, may be the right path
    //leave a bread crumb
    maze[r][c] = '!';
    //check above
    if(solveMaze(r-1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check below
    if(solveMaze(r+1,c, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check left
    if(solveMaze(r,c-1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //check right
    if(solveMaze(r,c+1, maze)) {

        maze[r][c] = '+';
        return true;
    }
    //if I reach this point...
    return false;
}

This is my code in clojure that provides the Index out of bound error:

    (defn solveMaze [r c m]
    (def tt true)
    ;(def che false)

    ;check to verify boundaries
    (if (or (or (or (< r 0) (< c 0)) (>= r (count m))) (>= c (count (str (m 0)))))
        false
        true
    )
    ;Check to know if the @ symbol has been found
    (if (= (get-in m[r c]) "@")
        true
        false
    )
    ;Checking if current index is a valid one
    (if (not= (get-in m[r c]) "-")
        ;Wall hit
        false
        true
    )
    ;found a path, leave a breadcrumb
    (def temp_map (assoc-in m[r c] "!"))
    ;Check North
    (if (= (solveMaze (dec r) c m) true)
        (def temp_map (assoc-in m [r c] "+"))
        true
        ;false
    )
    ;Check South
    (if (= (solveMaze (inc r) c m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check East
    (if (= (solveMaze r (dec c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;Check West
    (if (= (solveMaze r (inc c) m) true)
        (def temp_map (assoc-in m[r c] "+"))
        true
        ;false
    )
    ;If code gets here
    (= tt false)

)

Please is there something I am doing wrongly??? I have tried several if constructs using clojure but it doesn't work.


问:
Getting odbc drivers to work with windows subsystem for linux
I am trying to configure the Teradata 16.20.00.54 ODBC drivers to work on Ubuntu (under the windows subsystem for linux). I've been encountering a lot of esoteric errors, so I'm wondering whether it's possible to get this working with the WSL.

(1) I downloaded the teradata driver for ubuntu here

(2)Then I followed the instructions to configure the ODBC drivers here

This is my setup:

```<code>$ odbcinst -j
unixODBC 2.3.4
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/myusername/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

$ odbcinst -q -d
odbcinst: SQLGetPrivateProfileString failed with .

$ odbcinst -q -s
[<DSN_name>]

$ cat ~/.odbc.ini
[ODBC Data Sources]

Teradata ODBC DSN = Teradata Database ODBC Driver 16.20
<DSN_name> = DEVDB

[<DSN_name>]
Driver=/opt/teradata/client/ODBC_64/lib/tdataodbc_sb64.so
Description=Teradatadatabase
DBCName=DEVDB.mycompany.com
UID=XXXXXXX
PWD=XXXXXXX

$ cat /etc/odbcinst.ini

$ echo $ODBCINI
/home/myusername/.odbc.ini
</code>```

I'm very inexperienced with teradata so there is likely some issue with my configuration somewhere.

This is the error message that I get:

```<code>$ isql DEVDB -v
[IM002][unixODBC][Driver Manager]Data source name not found, and no default driver specified
[ISQL]ERROR: Could not SQLConnect
</code>```

答:
I think you interpreted the configuration example a bit too literally. For a DSN named DEVDB your .odbc.ini would look more like this:</p>

```<code>[ODBC Data Sources]
DEVDB=Teradata Database ODBC Driver

[DEVDB]
Driver=/opt/teradata/client/ODBC_64/lib/tdataodbc_sb64.so
Description=Teradatadatabase
DBCName=DEVDB.mycompany.com
UID=XXXXXXX
PWD=XXXXXXX
</code>```

Body:
I am trying to configure the Teradata 16.20.00.54 ODBC drivers to work on Ubuntu (under the windows subsystem for linux). I've been encountering a lot of esoteric errors, so I'm wondering whether it's possible to get this working with the WSL.

(1) I downloaded the teradata driver for ubuntu here

(2)Then I followed the instructions to configure the ODBC drivers here

This is my setup:

$ odbcinst -j
unixODBC 2.3.4
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/myusername/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8

$ odbcinst -q -d
odbcinst: SQLGetPrivateProfileString failed with .

$ odbcinst -q -s
[<DSN_name>]

$ cat ~/.odbc.ini
[ODBC Data Sources]

Teradata ODBC DSN = Teradata Database ODBC Driver 16.20
<DSN_name> = DEVDB

[<DSN_name>]
Driver=/opt/teradata/client/ODBC_64/lib/tdataodbc_sb64.so
Description=Teradatadatabase
DBCName=DEVDB.mycompany.com
UID=XXXXXXX
PWD=XXXXXXX

$ cat /etc/odbcinst.ini

$ echo $ODBCINI
/home/myusername/.odbc.ini

I'm very inexperienced with teradata so there is likely some issue with my configuration somewhere.

This is the error message that I get:

$ isql DEVDB -v
[IM002][unixODBC][Driver Manager]Data source name not found, and no default driver specified
[ISQL]ERROR: Could not SQLConnect

Body:
I think you interpreted the configuration example a bit too literally. For a DSN named DEVDB your .odbc.ini would look more like this:

[ODBC Data Sources]
DEVDB=Teradata Database ODBC Driver

[DEVDB]
Driver=/opt/teradata/client/ODBC_64/lib/tdataodbc_sb64.so
Description=Teradatadatabase
DBCName=DEVDB.mycompany.com
UID=XXXXXXX
PWD=XXXXXXX


问:
How do you get git bisect to ignore merged branches?
I'm aware that git bisect is branch-aware by design, so that if between good commit, G, and bad commit, B, you merged in a branch, it needs to take those changes into consideration as well, as the bug may be contained in the branch.

In my case I have a dependency as a side branch and I merge in changes to my main project from time to time. The dependency can be considered a library that has a different way of running, different build-system etc. from my main project, but I still want recent changes from it via merges to the main branch.

The problem is then that while bisecting in this scenario, you end up on non-compilable commits in the commits from the dependency.

I would really just want to consider each branch merge as a single commit while doing the bisection.

A workaround I've found so far is making a list of valid commits G..B with git log --first-parent, and then while bisecting, do git bisect skip if the current commit isn't in that list. That takes a lot of time though (lots of files to checkout/change for each skip).

So the question is: Is there any way of doing --first-parent with git bisect or providing a list of commits i feel are valid to be able to avoid checking out branches I know already are not compilable? How do we only check the commits marked o in the diagram?

```
G---o---o---o---o---o---o---B  main project branch
   /       /       /
  x---x---x---x---x            dependency
           \ /
            x'                 dependency project taskbranch
```

Edit: added diagram for clarity

答:
I don't see a one-step method, however, based on your current solution:
git bisect skip can take a list of commits to skip.
git log branchname will list commits on branch branchname.
So this should let you specify the list of commits.

If your dependency and your main code live in different filesystem spaces, you can specify the paths to include with git bisect start. Depending on your code layout, that may be the best option. (Almost certainly is if you have a list of files that may contain the bug!)

The man page has details; the see also there is interesting reading, too.

Body:
I'm aware that git bisect is branch-aware by design, so that if between good commit, G, and bad commit, B, you merged in a branch, it needs to take those changes into consideration as well, as the bug may be contained in the branch.

In my case I have a dependency as a side branch and I merge in changes to my main project from time to time. The dependency can be considered a library that has a different way of running, different build-system etc. from my main project, but I still want recent changes from it via merges to the main branch.

The problem is then that while bisecting in this scenario, you end up on non-compilable commits in the commits from the dependency.

I would really just want to consider each branch merge as a single commit while doing the bisection.

A workaround I've found so far is making a list of valid commits G..B with git log --first-parent, and then while bisecting, do git bisect skip if the current commit isn't in that list. That takes a lot of time though (lots of files to checkout/change for each skip).

So the question is: Is there any way of doing --first-parent with git bisect or providing a list of commits i feel are valid to be able to avoid checking out branches I know already are not compilable? How do we only check the commits marked o in the diagram?

G---o---o---o---o---o---o---B  main project branch
   /       /       /
  x---x---x---x---x            dependency
           \ /
            x'                 dependency project taskbranch

Edit: added diagram for clarity


问:
HardFault when running code from RAM in CortexM0
I'm currently developing firmware for an Arm Cortex-M0+ microcontroller and I'm facing a rather interesting issue. I'm not looking for any answers but rather would like to share the problem with other developers so I can (hopefully) shed some light on the issue I'm facing. I will describe it below:

I have a program that dynamically loads (properly compiled and linked) code from an external Flash Chip, to be executed straight out of the MCU RAM. The interesting is that I can perfectly execute the RAM-loaded code when running in step-by-step (via debugger), but it will always crash [formally HardFault] when freely running. I've tried to disable all interrupts, I've double checked the instructions, memory addresses, byte alignments, everything, but I still cannot pinpoint a reason for the exception.

Have some of you any hint of what could be happening? I'm very interested to know more about your experiences! Thanks,

Update 1 (30/05)

Free run in this case, means not setting a breakpoint right before the branch to RAM. Whenever I step into the branch and execute the instructions in RAM it will run correctly and return. Wherever the breakpoint is not there (and thus the MCU goes zooming thought the branch) the HardFault is observed. Notice that it will crash even when booting up with the debugger engaged but not having the breakpoint set.

Update 2 (30/05)

I'm using a Cypress S6E1C3 Series Arm Cortex M0+ FM0+ Microcontroller.

Update 3 (30/05)

After digging around and playing with the code, I could get it to work properly! It however brought up more questions than answers for me. Reading the official ARM documentation about the BLX instruction (BLX) I found out that the LSBit of the branch address determines the CPU instruction mode (1 causes it to run in Thumb mode). By explicitly setting this bit, I get the code to always work, even in free-run mode. The thing is, the code in RAM has not been compiled in Thumb mode, and there is not apparent reason why running the code step-by-step with the debugger would cause the instruction mode to change... Any ideas?

K.

答:
Cortex-M only supports Thumb mode, not ARM mode, so telling your compiler to compiler for Cortex-M0+ guarantees that it will create Thumb2 code.

That's why you need to set the low bit of your target address.

https://en.wikipedia.org/wiki/ARM_Cortex-M#Instruction_sets

Only Thumb-1 and Thumb-2 instruction sets are supported in Cortex-M architectures; the legacy 32-bit ARM instruction set isn't supported.

If you actually look at the code bytes in memory, you'll see they're Thumb2 instructions.

The only question is how your debugger managed to make it not fault.  Perhaps it has to handle BLX specially anyway, and doesn't emulate the fault-if-switching-to-ARM-mode on Thumb-only microarchitectures behaviour.  Or maybe just handling the single-step interrupt ends up returning properly in Thumb mode.

"legacy" is a bit of an overstatement for ARM mode in general, I think; I thought high-performance ARM chips (with large instruction caches) could still benefit from ARM mode getting more done with fewer instructions and easier access to more registers.  Anyway, that's just Wikipedia's phrasing.


问:
How to override the message of the custom validation rule in Laravel?
I am developing a Laravel application. What I am doing in my application is that I am trying to override the custom validation rule message.

I have validation rules like this in the request class:

```<code>[
    'name'=> [ 'required' ],
    'age' => [ 'required', new OverAge() ],
];
</code>```

Normally, we override the error message of the rules like this:

```<code>return [
    'title.required' => 'A title is required',
    'body.required'  => 'A message is required',
];
</code>```

But how can I do that to the custom validation rule class?

答:
You cannot simply overwrite it with the custom messages of the request. If you take a look at the Validator class:

```<code>/**
 * Validate an attribute using a custom rule object.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @param  \Illuminate\Contracts\Validation\Rule  $rule
 * @return void
 */
protected function validateUsingCustomRule($attribute, $value, $rule)
{
    if (! $rule->passes($attribute, $value)) {
        $this->failedRules[$attribute][get_class($rule)] = [];

        $this->messages->add($attribute, $this->makeReplacements(
            $rule->message(), $attribute, get_class($rule), []
        ));
    }
}
</code>```

As you can see, it's simply adding the $rule->message() directly to the message bag.

However, you can add a parameter for the message in your custom rule's class:

```<code>public function __construct(string $message = null)
{
    $this->message = $message;
}
</code>```

Then in your message function:

```<code>public function message()
{
    return $this->message ?: 'Default message';
}
</code>```

And finally in your rules:

```<code>'age' => ['required', new OverAge('Overwritten message')];
</code>```

Body:
I am developing a Laravel application. What I am doing in my application is that I am trying to override the custom validation rule message.

I have validation rules like this in the request class:

[
    'name'=> [ 'required' ],
    'age' => [ 'required', new OverAge() ],
];

Normally, we override the error message of the rules like this:

return [
    'title.required' => 'A title is required',
    'body.required'  => 'A message is required',
];

But how can I do that to the custom validation rule class?

Body:
You cannot simply overwrite it with the custom messages of the request. If you take a look at the Validator class:

/**
 * Validate an attribute using a custom rule object.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @param  \Illuminate\Contracts\Validation\Rule  $rule
 * @return void
 */
protected function validateUsingCustomRule($attribute, $value, $rule)
{
    if (! $rule->passes($attribute, $value)) {
        $this->failedRules[$attribute][get_class($rule)] = [];

        $this->messages->add($attribute, $this->makeReplacements(
            $rule->message(), $attribute, get_class($rule), []
        ));
    }
}

As you can see, it's simply adding the $rule->message() directly to the message bag.

However, you can add a parameter for the message in your custom rule's class:

public function __construct(string $message = null)
{
    $this->message = $message;
}

Then in your message function:

public function message()
{
    return $this->message ?: 'Default message';
}

And finally in your rules:

'age' => ['required', new OverAge('Overwritten message')];


问:
How to speed up accessing a list of dicts inside a pandas dataframe column?
This may sound like a crazy way of storing data, but I am working with data that is sparse, and in an attempt to save space I have created dataframe where one column is a variable length list of dicts (from 1 to over a dozen dicts with three elements each).  I am trying to access the second element in each dict and make a new column with just a list of those second elements.  I can't actually paste my data, however I can provide an example that closely approximates it.

Imagine I have a dataframe of the attributes of my cats, dogs, and hamsters, and I had 3 cats, 1 dog, and 1 hamster, each with color and fur length data.  I'm basically trying to access a list of specific attributes for each animal type.  Now the code below works just fine.  However if you expand it to over 22,000 rows, it is VERY impossibly slow.  This is probably due to the for loop.

```<code>df = pd.DataFrame({'name':['cats','dogs','hamsters'],'attributes':[[{'color':'white','fur':'short'},{'color':'black','fur':'long'},{'color':'gray','fur':'long'}],[{'color':'brown','fur':'short'}],[{'color':'brown','fur':'short'}]]})

df['colors']=''
for i in range(len(df)):
  attributes = df.attributes.iloc[i]
  df.loc[i,['colors']] = [list(map(lambda x: x['color'],attributes))]
</code>```

df before:

```<code>       name                                         attributes
0      cats  [{'color': 'white', 'fur': 'short'}, {'color':...
1      dogs               [{'color': 'brown', 'fur': 'short'}]
2  hamsters               [{'color': 'brown', 'fur': 'short'}]
</code>```

df after:

```<code>       name  ...                colors
0      cats  ...  [white, black, gray]
1      dogs  ...               [brown]
2  hamsters  ...               [brown]
</code>```

I'm looking for a way to speed up this process, possibly with a lambda function?  Not sure, but there is almost always a way to ditch a for loop, however I'm just not able to see it.

答:
Try with </p>

```<code>l=[[y['color'] for y in x] for x in df.attributes]
l
Out[321]: [['white', 'black', 'gray'], ['brown'], ['brown']]
df['color']=l
</code>```

Body:
This may sound like a crazy way of storing data, but I am working with data that is sparse, and in an attempt to save space I have created dataframe where one column is a variable length list of dicts (from 1 to over a dozen dicts with three elements each).  I am trying to access the second element in each dict and make a new column with just a list of those second elements.  I can't actually paste my data, however I can provide an example that closely approximates it.

Imagine I have a dataframe of the attributes of my cats, dogs, and hamsters, and I had 3 cats, 1 dog, and 1 hamster, each with color and fur length data.  I'm basically trying to access a list of specific attributes for each animal type.  Now the code below works just fine.  However if you expand it to over 22,000 rows, it is VERY impossibly slow.  This is probably due to the for loop.

df = pd.DataFrame({'name':['cats','dogs','hamsters'],'attributes':[[{'color':'white','fur':'short'},{'color':'black','fur':'long'},{'color':'gray','fur':'long'}],[{'color':'brown','fur':'short'}],[{'color':'brown','fur':'short'}]]})

df['colors']=''
for i in range(len(df)):
  attributes = df.attributes.iloc[i]
  df.loc[i,['colors']] = [list(map(lambda x: x['color'],attributes))]

df before:

       name                                         attributes
0      cats  [{'color': 'white', 'fur': 'short'}, {'color':...
1      dogs               [{'color': 'brown', 'fur': 'short'}]
2  hamsters               [{'color': 'brown', 'fur': 'short'}]

df after:

       name  ...                colors
0      cats  ...  [white, black, gray]
1      dogs  ...               [brown]
2  hamsters  ...               [brown]

I'm looking for a way to speed up this process, possibly with a lambda function?  Not sure, but there is almost always a way to ditch a for loop, however I'm just not able to see it.

Body:
Try with

l=[[y['color'] for y in x] for x in df.attributes]
l
Out[321]: [['white', 'black', 'gray'], ['brown'], ['brown']]
df['color']=l


问:
How to identify all weights of all fonts used on page/site
I'm using Google webfonts. Initially, I include all the weights of a given family so I can choose all the ones I want. So for example:

```<code>  <link href='http://fonts.googleapis.com/css?family=Roboto:300,300italic,400,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet'>
</code>```

Once I'm done, I only want the weights I ended up using to be fetched on page load to minimize size. My finished link looks something like

```<code><link href='http://fonts.googleapis.com/css?family=Roboto:400,400italic,900,900italic' rel='stylesheet'>
</code>```

I suppose I can scroll thru my entire CSS directory and eyeball all the pages to find all the weights I used, but that's error-prone. At a glance, how can I know exactly, which weights I ended up using?

PS: A few things I tried:

Firebug's Net panel lets you see whether the google fonts script was called but does not specify which weights were used.

Chengyin Liu's very nice WhatFont tool (http://chengyinliu.com/whatfont.html) but that only lets you hover over a single element.

Update April 2020

For what it's worth, I no longer use any of the solutions below, I've been using a Chrome plugin called FontsNinja for a few years and it does an amazing job of pinpointing fonts and weights used on pages.

答:
Here is a quick script for pages using Jquery to run in the console which will log all fonts / styles /  weights:</p>

```<code>var ret={};
$('*').each(function () {
    var str = $(this).css('font-family');
    str = str  + ':' + $(this).css('font-weight');
    str = str + ':' + $(this).css('font-style');
    if (ret[str] ) {
      ret[str] = ret[str] + 1;
    } else {
      ret[str] = 1;
    }

});
console.log(ret);
</code>```

Body:
I'm using Google webfonts. Initially, I include all the weights of a given family so I can choose all the ones I want. So for example:

  <link href='http://fonts.googleapis.com/css?family=Roboto:300,300italic,400,400italic,500,500italic,700,700italic,900,900italic' rel='stylesheet'>

Once I'm done, I only want the weights I ended up using to be fetched on page load to minimize size. My finished link looks something like

<link href='http://fonts.googleapis.com/css?family=Roboto:400,400italic,900,900italic' rel='stylesheet'>

I suppose I can scroll thru my entire CSS directory and eyeball all the pages to find all the weights I used, but that's error-prone. At a glance, how can I know exactly, which weights I ended up using?

PS: A few things I tried:

Firebug's Net panel lets you see whether the google fonts script was called but does not specify which weights were used.

Chengyin Liu's very nice WhatFont tool (http://chengyinliu.com/whatfont.html) but that only lets you hover over a single element.

Update April 2020

For what it's worth, I no longer use any of the solutions below, I've been using a Chrome plugin called FontsNinja for a few years and it does an amazing job of pinpointing fonts and weights used on pages.

Body:
Here is a quick script for pages using Jquery to run in the console which will log all fonts / styles /  weights:

var ret={};
$('*').each(function () {
    var str = $(this).css('font-family');
    str = str  + ':' + $(this).css('font-weight');
    str = str + ':' + $(this).css('font-style');
    if (ret[str] ) {
      ret[str] = ret[str] + 1;
    } else {
      ret[str] = 1;
    }

});
console.log(ret);


问:
Why do I get an CS1056 Unexpected character '' on this code
I'm getting this unexpected character '' error and I don't understand why.</p>

```<code>var list = new List<MyModel>();
list.Add(new MyModel() {
    variable1 = 942,
    variable2 = 2001,
    variable3 = "my text",
    variable4   = 123
}); // CS1056 Unexpected character ''  on this line
</code>```

答:
Just reporting my direct experience.
As Daneau wrote, I had a character (ASCII DLE, I copied while messing up a zebra printer) hiding in the text. I could not afford to rewrite everything, so I used notepad++ "View->Show Symbol->Show All Characters" feature.
I apologize for not commenting Daneau entry, but I don't have enough reputation.</p>

Body:
I'm getting this unexpected character '' error and I don't understand why.

var list = new List<MyModel>();
list.Add(new MyModel() {
    variable1 = 942,
    variable2 = 2001,
    variable3 = "my text",
    variable4   = 123
}); // CS1056 Unexpected character ''  on this line


问:
How do I provision throughput on a container?
I created a Cosmos Db account, database, and containers using this ARM template. Deployment via Azure DevOps Release pipeline is working.

I used this ARM template to adjust the database throughput. It is also in a Release pipeline and is working.

Currently the throughput is provisioned at the database level and shared across all containers. How do I provision throughput at the container level? I tried running this ARM template to update throughput at the container level. It appears that once shared throughput is provisioned at the database level there's no way to provision throughput at the container level.

I found this reference document but throughput is not listed. Am I missing something super obvious or is the desired functionality not implemented yet?

UPDATE:
When attempting to update the container with the above template I get the following:

```<code>2019-05-29T20:25:10.5166366Z There were errors in your deployment. Error code: DeploymentFailed.
2019-05-29T20:25:10.5236514Z ##[error]At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.
2019-05-29T20:25:10.5246027Z ##[error]Details:
2019-05-29T20:25:10.5246412Z ##[error]NotFound: {
  "code": "NotFound",
  "message": "Entity with the specified id does not exist in the system.\r\nActivityId: 7ba84...b52b2, Microsoft.Azure.Documents.Common/2.4.0.0"
} undefined
2019-05-29T20:25:10.5246730Z ##[error]Task failed while creating or updating the template deployment.
</code>```

答:
I believe you have to create the container with a dedicated throughput, first. I have not seen any documentation for changing a container from shared to dedicated throughput. In the Microsoft documentation, the example is creating containers with both shared and dedicated throughput.

Set throughput on a database and a container

You can combine the two models. Provisioning throughput on both the database and the container is allowed. The following example shows how to provision throughput on an Azure Cosmos database and a container:

You can create an Azure Cosmos database named Z with provisioned throughput of "K" RUs.

Next, create five containers named A, B, C, D, and E within the database. When creating container B, make sure to enable Provision dedicated throughput for this container option and explicitly configure "P" RUs of provisioned throughput on this container. Note that you can configure shared and dedicated throughput only when creating the database and container.

The "K" RUs throughput is shared across the four containers A, C, D, and E. The exact amount of throughput available to A, C, D, or E varies. There are no SLAs for each individual container’s throughput.

The container named B is guaranteed to get the "P" RUs throughput all the time. It's backed by SLAs.

There is a prereq ARM template in a subfolder for the 101-cosmosdb-sql-container-ru-update. In the prereq version, the container has the throughput property set when the container is created. After the container is created with dedicated throughput, the update template works without error. I have tried it out and verified that it works.

```<code>        {
            "type": "Microsoft.DocumentDB/databaseAccounts/apis/databases",
            "name": "[concat(variables('accountName'), '/sql/', variables('databaseName'))]",
            "apiVersion": "2016-03-31",
            "dependsOn": [ "[resourceId('Microsoft.DocumentDB/databaseAccounts/', variables('accountName'))]" ],
            "properties":{
                "resource":{
                    "id": "[variables('databaseName')]"
                },
                "options": { "throughput": "[variables('databaseThroughput')]" }
            }
        },
        {
            "type": "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers",
            "name": "[concat(variables('accountName'), '/sql/', variables('databaseName'), '/', variables('containerName'))]",
            "apiVersion": "2016-03-31",
            "dependsOn": [ "[resourceId('Microsoft.DocumentDB/databaseAccounts/apis/databases', variables('accountName'), 'sql', variables('databaseName'))]" ],
            "properties":
            {
                "resource":{
                    "id":  "[variables('containerName')]",
                    "partitionKey": {
                        "paths": [
                        "/MyPartitionKey1"
                        ],
                        "kind": "Hash"
                    }
                },
                "options": { "throughput": "[variables('containerThroughput')]" }
            }
        }

</code>```

Body:
I created a Cosmos Db account, database, and containers using this ARM template. Deployment via Azure DevOps Release pipeline is working.

I used this ARM template to adjust the database throughput. It is also in a Release pipeline and is working.

Currently the throughput is provisioned at the database level and shared across all containers. How do I provision throughput at the container level? I tried running this ARM template to update throughput at the container level. It appears that once shared throughput is provisioned at the database level there's no way to provision throughput at the container level.

I found this reference document but throughput is not listed. Am I missing something super obvious or is the desired functionality not implemented yet?

UPDATE:
When attempting to update the container with the above template I get the following:

2019-05-29T20:25:10.5166366Z There were errors in your deployment. Error code: DeploymentFailed.
2019-05-29T20:25:10.5236514Z ##[error]At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-debug for usage details.
2019-05-29T20:25:10.5246027Z ##[error]Details:
2019-05-29T20:25:10.5246412Z ##[error]NotFound: {
  "code": "NotFound",
  "message": "Entity with the specified id does not exist in the system.\r\nActivityId: 7ba84...b52b2, Microsoft.Azure.Documents.Common/2.4.0.0"
} undefined
2019-05-29T20:25:10.5246730Z ##[error]Task failed while creating or updating the template deployment.

Body:
I believe you have to create the container with a dedicated throughput, first. I have not seen any documentation for changing a container from shared to dedicated throughput. In the Microsoft documentation, the example is creating containers with both shared and dedicated throughput.

Set throughput on a database and a container

You can combine the two models. Provisioning throughput on both the database and the container is allowed. The following example shows how to provision throughput on an Azure Cosmos database and a container:

You can create an Azure Cosmos database named Z with provisioned throughput of "K" RUs.

Next, create five containers named A, B, C, D, and E within the database. When creating container B, make sure to enable Provision dedicated throughput for this container option and explicitly configure "P" RUs of provisioned throughput on this container. Note that you can configure shared and dedicated throughput only when creating the database and container.

The "K" RUs throughput is shared across the four containers A, C, D, and E. The exact amount of throughput available to A, C, D, or E varies. There are no SLAs for each individual container’s throughput.

The container named B is guaranteed to get the "P" RUs throughput all the time. It's backed by SLAs.

There is a prereq ARM template in a subfolder for the 101-cosmosdb-sql-container-ru-update. In the prereq version, the container has the throughput property set when the container is created. After the container is created with dedicated throughput, the update template works without error. I have tried it out and verified that it works.

        {
            "type": "Microsoft.DocumentDB/databaseAccounts/apis/databases",
            "name": "[concat(variables('accountName'), '/sql/', variables('databaseName'))]",
            "apiVersion": "2016-03-31",
            "dependsOn": [ "[resourceId('Microsoft.DocumentDB/databaseAccounts/', variables('accountName'))]" ],
            "properties":{
                "resource":{
                    "id": "[variables('databaseName')]"
                },
                "options": { "throughput": "[variables('databaseThroughput')]" }
            }
        },
        {
            "type": "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers",
            "name": "[concat(variables('accountName'), '/sql/', variables('databaseName'), '/', variables('containerName'))]",
            "apiVersion": "2016-03-31",
            "dependsOn": [ "[resourceId('Microsoft.DocumentDB/databaseAccounts/apis/databases', variables('accountName'), 'sql', variables('databaseName'))]" ],
            "properties":
            {
                "resource":{
                    "id":  "[variables('containerName')]",
                    "partitionKey": {
                        "paths": [
                        "/MyPartitionKey1"
                        ],
                        "kind": "Hash"
                    }
                },
                "options": { "throughput": "[variables('containerThroughput')]" }
            }
        }


问:
How to check if a dynamic object is an array in c#?
I have a dynamic object that sometimes is an object and sometimes is an object[].

How can I check if the dynamic object is an array?

答:
To complement Rango's original response, a more generic way to determine is to use the type's IsSerializable property. Because if the object is a List or any other collection, the IsArray returns false.

```<code>int [] array = {1,2,3,4};
Type t1 = array.GetType();
// t1.IsArray == true
List<int> list = new List();
list.AddRange(array);
Type t2 = list.GetType();
//t2.IsArray = false;
//t2.IsSerializable = true;

foreach(var i in list) {
        // do stuff
}
</code>```

Body:
To complement Rango's original response, a more generic way to determine is to use the type's IsSerializable property. Because if the object is a List or any other collection, the IsArray returns false.

int [] array = {1,2,3,4};
Type t1 = array.GetType();
// t1.IsArray == true
List<int> list = new List();
list.AddRange(array);
Type t2 = list.GetType();
//t2.IsArray = false;
//t2.IsSerializable = true;

foreach(var i in list) {
        // do stuff
}


问:
My function won't return the proper value
I am currently doing problem 3 on project Euler and I have run into a problem while writing a function that returns the max prime factor of a number.

I made two functions, isprime(number) and maxprime(number). The first function works just fine, returning true if a number is prime, but the ladder function gives me the problem.

function maxprime(number)
    maximum = 0
    for i = 2, number - 1 do
        if(number % i == 0 and isprime(i)) then
            if(maximum < i) then
                maximum = i
            end
        end
    end
    return maximum end
end
```

It returns 0 everytime and the for loop seems to only run once. What am I doing wrong here?

答:
Are you certain that your isPrime function is returning true on prime numbers? You didn't post what your isPrime function is, so it's hard to tell if it's the culprit or not.

However, I will point out that you do not need to count up to n-1, and instead, as mentioned in comments by tonypdmtr, you can start with n and count down. It's actually better that way, as you'll return the first prime number that meets your criteria. See the code below:

```<code>function isPrime(n)
    for i = 2, n^(1/2) do
        if (n % i) == 0 then
            return false
        end
    end
    return true
end

function maxPrime(n)
    for i = n, 2, -1 do
        if isPrime(i) and (n % i) == 0 then
            return i
        end
    end
end

> print(maxPrime(1449))
> 23
> print(maxPrime(7))
> 7
> print(maxPrime(13))
> 13
</code>```

Hopefully this helps you, but if you have any questions, feel free to ask.

Body:
I am currently doing problem 3 on project Euler and I have run into a problem while writing a function that returns the max prime factor of a number.

I made two functions, isprime(number) and maxprime(number). The first function works just fine, returning true if a number is prime, but the ladder function gives me the problem.

function maxprime(number)
    maximum = 0
    for i = 2, number - 1 do
        if(number % i == 0 and isprime(i)) then
            if(maximum < i) then
                maximum = i
            end
        end
    end
    return maximum end
end

It returns 0 everytime and the for loop seems to only run once. What am I doing wrong here?

Body:
Are you certain that your isPrime function is returning true on prime numbers? You didn't post what your isPrime function is, so it's hard to tell if it's the culprit or not.

However, I will point out that you do not need to count up to n-1, and instead, as mentioned in comments by tonypdmtr, you can start with n and count down. It's actually better that way, as you'll return the first prime number that meets your criteria. See the code below:

function isPrime(n)
    for i = 2, n^(1/2) do
        if (n % i) == 0 then
            return false
        end
    end
    return true
end

function maxPrime(n)
    for i = n, 2, -1 do
        if isPrime(i) and (n % i) == 0 then
            return i
        end
    end
end

> print(maxPrime(1449))
> 23
> print(maxPrime(7))
> 7
> print(maxPrime(13))
> 13

Hopefully this helps you, but if you have any questions, feel free to ask.


问:
WordPress add_action bug?
When a single array of objects is passed as an array to do_action, add_action will see it as an object, not as an array. Is it a bug?

```<code>/* Correct if $order is not object*/
$orders = array();
$orders[] = 'abc';

add_action('action123', 'func123');
function func123($orders){
    //$orders will be array here (CORRECT)
}

do_action( 'action123', $orders);

/* BUG: if $orders is an object */
$orders = array();
$orders[]=new stdClass();

add_action('action123', 'func123');
function func123($orders){
    //$orders will be non-array here (BUG?)
}

do_action( 'action123', $orders);
</code>```

答:
Great question, I didn't realize this myself until I tried it out, but this is expected and intentional behavior (only for an array that has an object as the only item), as documented in the comments at https://developer.wordpress.org/reference/functions/do_action/
And if you look at the code for do_action(), you'll see the same.

Incidentally, your example code throws an error when you try to set a property on the array:

```<code>PHP Warning:  Attempt to assign property 'name' of non-object in object-test.php
</code>```

Additionally, make sure you always add_action prior to do_action for the "hooked" function to have any effect.

Title: WordPress add_action bug?

Body:
When a single array of objects is passed as an array to do_action, add_action will see it as an object, not as an array. Is it a bug?

/* Correct if $order is not object*/
$orders = array();
$orders[] = 'abc';

add_action('action123', 'func123');
function func123($orders){
    //$orders will be array here (CORRECT)
}

do_action( 'action123', $orders);

/* BUG: if $orders is an object */
$orders = array();
$orders[]=new stdClass();

add_action('action123', 'func123');
function func123($orders){
    //$orders will be non-array here (BUG?)
}

do_action( 'action123', $orders);

Body:
Great question, I didn't realize this myself until I tried it out, but this is expected and intentional behavior (only for an array that has an object as the only item), as documented in the comments at https://developer.wordpress.org/reference/functions/do_action/
And if you look at the code for do_action(), you'll see the same.

Incidentally, your example code throws an error when you try to set a property on the array:

PHP Warning:  Attempt to assign property 'name' of non-object in object-test.php

Additionally, make sure you always add_action prior to do_action for the "hooked" function to have any effect.


问:
why doesn't make -C change $PWD as seen through a scripting language such as Perl?
Here is temp/Makefile:

```<code>all:
    echo $$PWD
    echo $(CURDIR)
    perl -e 'print $$ENV{"PWD"}'
</code>```

and now

```<code>$make -C temp
make: Entering directory `/home/mgaleck/temp'
/home/mgaleck/temp
/home/mgaleck/temp
/home/mgaleck
make: Leaving directory `/home/mgaleck/temp'
</code>```

Why is the third value without temp?

According to Make manual, -C option causes to "change the directory" (working directory?) first.

Same thing happens with Python.

答: Because the PWD environment variable doesn't hold the current working directory; it holds whatever the current working directory was the last time sh set it. Anything other than a shell starting up, or a shell executing the cd builtin (or a similar builtin like pushd, in shells that have it), has no effect on PWD, and relying on PWD anywhere except in the shell is probably a silly idea. Use getcwd (C), Cwd::getcwd (Perl), os.getcwd (Python), etc. instead.

Body:
Here is temp/Makefile:

all:
    echo $$PWD
    echo $(CURDIR)
    perl -e 'print $$ENV{"PWD"}'

and now

$make -C temp
make: Entering directory `/home/mgaleck/temp'
/home/mgaleck/temp
/home/mgaleck/temp
/home/mgaleck
make: Leaving directory `/home/mgaleck/temp'

Why is the third value without temp?

According to Make manual, -C option causes to "change the directory" (working directory?) first.

Same thing happens with Python.


问:
how is it possible to display continuously calculated values of functions from a class?
I want the program to run continuously and output the values from the methods (func1 - func4) as soon as a signal gradient is detected on the pins.

This is just a test code to understand how I can access the values, because I have written a "program" with a surface that shows uninterrupted values from a machine where I use ONLY global variables and I don't want to post that here because it's embarrassing...
and i want to get rid of all the global variables

A raspberry pi is connected to the machine with which I intercept 4 signals over the gpio.

```<code>cavity = 2
count = 0
scrap = 0
uptime = datetime.timedelta(0)
downtime = datetime.timedelta(0)

def func1(channel):
    if GPIO.input(7) == 0:
        while True:
            uptime = uptime + datetime.timedelta(0,1)
            time.sleep(1)
            if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                break

def func2(channel):
    scrap = scrap + cavity

def func3(channel):
    count = count + cavity

def func4(channel):
    if GPIO.input(37) == 0:
        while True:
            downtime = downtime + datetime.timedelta(0,1)
            if GPIO.inpu(37) == 1:
                break

GPIO.add_event_detect(7, GPIO.RISING, callback = func1, bouncetime = 100)           #Run
GPIO.add_event_detect(29, GPIO.RISING, callback = func2, bouncetime = 100)          #Scrap
GPIO.add_event_detect(13, GPIO.RISING, callback = func3, bouncetime = 100)          #Count
GPIO.add_event_detect(37, GPIO.RISING, callback = func4, bouncetime = 100)          #Alarm

class Output(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.show()

    def show(self):
        print('ich werde aufgerufen')
        while True:
            print(uptime)
            print(scrap)
            print(count)
            print(downtime)
            print('############################')
            time.sleep(5)

thread2 = Output()
thread2.start()
</code>```

only zeros are output this was to be expected but how do i get access to the variables so that on signal detection the values increase

答:
Your functions are just creating their own local variables, so the global ones don't change.

Try this:

```<code>def func1(channel):
    global uptime
    if GPIO.input(7) == 0:
        while True:
            uptime = uptime + datetime.timedelta(0,1)
            time.sleep(1)
            if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                break

def func2(channel):
    global scrap
    scrap = scrap + cavity

def func3(channel):
    global count
    count = count + cavity

def func4(channel):
    global downtime
    if GPIO.input(37) == 0:
        while True:
            downtime = downtime + datetime.timedelta(0,1)
            if GPIO.inpu(37) == 1:
                break
</code>```

Body:
I want the program to run continuously and output the values from the methods (func1 - func4) as soon as a signal gradient is detected on the pins.

This is just a test code to understand how I can access the values, because I have written a "program" with a surface that shows uninterrupted values from a machine where I use ONLY global variables and I don't want to post that here because it's embarrassing...
and i want to get rid of all the global variables

A raspberry pi is connected to the machine with which I intercept 4 signals over the gpio.

cavity = 2
count = 0
scrap = 0
uptime = datetime.timedelta(0)
downtime = datetime.timedelta(0)

def func1(channel):
    if GPIO.input(7) == 0:
        while True:
            uptime = uptime + datetime.timedelta(0,1)
            time.sleep(1)
            if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                break

def func2(channel):
    scrap = scrap + cavity

def func3(channel):
    count = count + cavity

def func4(channel):
    if GPIO.input(37) == 0:
        while True:
            downtime = downtime + datetime.timedelta(0,1)
            if GPIO.inpu(37) == 1:
                break

GPIO.add_event_detect(7, GPIO.RISING, callback = func1, bouncetime = 100)           #Run
GPIO.add_event_detect(29, GPIO.RISING, callback = func2, bouncetime = 100)          #Scrap
GPIO.add_event_detect(13, GPIO.RISING, callback = func3, bouncetime = 100)          #Count
GPIO.add_event_detect(37, GPIO.RISING, callback = func4, bouncetime = 100)          #Alarm

class Output(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.show()

    def show(self):
        print('ich werde aufgerufen')
        while True:
            print(uptime)
            print(scrap)
            print(count)
            print(downtime)
            print('############################')
            time.sleep(5)

thread2 = Output()
thread2.start()

only zeros are output this was to be expected but how do i get access to the variables so that on signal detection the values increase

Body:
Your functions are just creating their own local variables, so the global ones don't change.

Try this:

def func1(channel):
    global uptime
    if GPIO.input(7) == 0:
        while True:
            uptime = uptime + datetime.timedelta(0,1)
            time.sleep(1)
            if GPIO.input(7) == 1 or GPIO.input(37) == 0:
                break

def func2(channel):
    global scrap
    scrap = scrap + cavity

def func3(channel):
    global count
    count = count + cavity

def func4(channel):
    global downtime
    if GPIO.input(37) == 0:
        while True:
            downtime = downtime + datetime.timedelta(0,1)
            if GPIO.inpu(37) == 1:
                break


问:
ffmpeg m4a/m4b/mp4 output file's "Time" value is incorrect when read into iTunes
I'm using ffmpeg to convert audiobooks to m4a/m4b/mp4. All seems to work until trying to play them in iTunes. It plays in VLC, QuickTime, and MacOS's Quicklook without issue.

"So why are you posting here? This isn't an iTunes forum."

I'm hoping this is iTunes being picky about file formats and that I can add some magic argument to my ffmpeg command and have it spit out something that iTunes can read.

Below is the bash function I'm using to do the conversion. I've tried m4a/mp4/m4b as values for TEMP_FILE_EXTENSION and tried opening the intermediate file as well. It's always the same corrupted "Time" value when you put it in iTunes.

dedrm_audible () {
  # Check for AtomicParsley, ffmpeg, and 3 args
  if (! type AtomicParsley >/dev/null 2>/dev/null) || (! type ffmpeg >/dev/null 2>/dev/null) || [ ! $# -eq 3 ]; then
    echo "Usage:"
    echo "    dedrm_audible <path to .aax> <activation bytes> <path to output file>"
    echo "    Note: AtomicParsley and ffmpeg must be in PATH variable"
    return
  fi
  local ORIGINAL_PWD="$(pwd)"
  local TEMP_DIR="/tmp/audible"
  local AUDIOBOOK_FILE="$1"
  local ACTIVATION_BYTES="$2"
  local OUTPUT_FILE="$3"
  local FULL_AUDIOBOOK_PATH="$(realpath "${AUDIOBOOK_FILE}")"
  local OUTPUT_PATH="$(realpath "${OUTPUT_FILE}")"
  local TEMP_FILE_EXTENSION="m4a"

  mkdir -p "${TEMP_DIR}"
  cd "${TEMP_DIR}"

  # Extract the book cover
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${FULL_AUDIOBOOK_PATH}" -vcodec copy artwork.png
  # Convert the audio
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${FULL_AUDIOBOOK_PATH}" -vn -c:a copy -v debug output.${TEMP_FILE_EXTENSION}
  # Add the cover to the new file
  AtomicParsley output.${TEMP_FILE_EXTENSION} --artwork artwork.png --overWrite

  # Put it where you want it and clean up
  cp output.${TEMP_FILE_EXTENSION} "${OUTPUT_PATH}"
  rm artwork.png
  rm output.${TEMP_FILE_EXTENSION}
  cd "${ORIGINAL_PWD}"
}
```

<p>It goes off without a hitch. The new file is there waiting for me, with all the metadata including the cover when I do a "Get Info" or "Quick look" on it (I'm on MacOS). But when opening it and trying to play it in iTunes, the "time" field is <em>way</em> off and it immediately skips to the next song/audiobook in the queue.</p>

<p>Attempts to convert it within iTunes fail immediately - too quickly to see what's happening. The errors in the console simply say "Assert failure:" (with nothing after the colon).</p>

<p>edit: Tommy answered the question. Here's a working bash function:</p>

<pre class="lang-sh prettyprint-override"><code>dedrm_audible () {
  # Check for AtomicParsley, ffmpeg, and 3 args
  if (! type AtomicParsley >/dev/null 2>/dev/null) || (! type ffmpeg >/dev/null 2>/dev/null) || [ ! $# -eq 3 ]; then
    echo "Usage:"
    echo "    dedrm_audible <path to .aax> <activation bytes> <path to output file>"
    echo "    Note: AtomicParsley and ffmpeg must be in PATH variable"
    return
  fi
  local ORIGINAL_PWD="$(pwd)"
  local TEMP_DIR="/tmp/audible"
  local AUDIOBOOK_FILE="$1"
  local ACTIVATION_BYTES="$2"
  local OUTPUT_FILE="$3"
  # Alternative to realpath (since I read somewhere that it's not there by default on some systems): OUTPUT_PATH="$( cd "$( dirname "$OUTPUT_FILE" )" && pwd )"
  local FULL_AUDIOBOOK_PATH="$(realpath "${AUDIOBOOK_FILE}")"
  local AUDIOBOOK_NAME="${$(basename "${FULL_AUDIOBOOK_PATH}")%.aax}.m4a"
  local OUTPUT_PATH="$(realpath "${OUTPUT_FILE}")"
  local TEMP_FILE_EXTENSION="m4a"

  mkdir -p "${TEMP_DIR}"
  cd "${TEMP_DIR}"

  cp "${FULL_AUDIOBOOK_PATH}" "${AUDIOBOOK_NAME}"

  # Extract the book cover
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${AUDIOBOOK_NAME}" -vcodec copy artwork.png
  # Convert the audio
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${AUDIOBOOK_NAME}" -vn -c:a copy -v debug output.${TEMP_FILE_EXTENSION}
  # Add the cover to the new file
  AtomicParsley output.${TEMP_FILE_EXTENSION} --artwork artwork.png --overWrite

  # Put it where you want it and clean up
  mv output.${TEMP_FILE_EXTENSION} "${OUTPUT_PATH}"
  rm artwork.png
  rm "${AUDIOBOOK_NAME}"
  cd "${ORIGINAL_PWD}"
}
</code>```

答:
They stopped working for me too, but if you just change the file extension to .m4a it will import fine, then you just have to change type from music to audiobook and tell it to remember location and it works fine on mac or iPhone. </p>

<p>The other approach is I went back and reran ffmpeg on the .aax with output to .m4b and iTunes handled it fine. I didn’t use.m4b before but I frankly don’t recall why. </p>

Body:
I'm using ffmpeg to convert audiobooks to m4a/m4b/mp4. All seems to work until trying to play them in iTunes. It plays in VLC, QuickTime, and MacOS's Quicklook without issue.

"So why are you posting here? This isn't an iTunes forum."

I'm hoping this is iTunes being picky about file formats and that I can add some magic argument to my ffmpeg command and have it spit out something that iTunes can read.

Below is the bash function I'm using to do the conversion. I've tried m4a/mp4/m4b as values for TEMP_FILE_EXTENSION and tried opening the intermediate file as well. It's always the same corrupted "Time" value when you put it in iTunes.

dedrm_audible () {
  # Check for AtomicParsley, ffmpeg, and 3 args
  if (! type AtomicParsley >/dev/null 2>/dev/null) || (! type ffmpeg >/dev/null 2>/dev/null) || [ ! $# -eq 3 ]; then
    echo "Usage:"
    echo "    dedrm_audible <path to .aax> <activation bytes> <path to output file>"
    echo "    Note: AtomicParsley and ffmpeg must be in PATH variable"
    return
  fi
  local ORIGINAL_PWD="$(pwd)"
  local TEMP_DIR="/tmp/audible"
  local AUDIOBOOK_FILE="$1"
  local ACTIVATION_BYTES="$2"
  local OUTPUT_FILE="$3"
  local FULL_AUDIOBOOK_PATH="$(realpath "${AUDIOBOOK_FILE}")"
  local OUTPUT_PATH="$(realpath "${OUTPUT_FILE}")"
  local TEMP_FILE_EXTENSION="m4a"

  mkdir -p "${TEMP_DIR}"
  cd "${TEMP_DIR}"

  # Extract the book cover
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${FULL_AUDIOBOOK_PATH}" -vcodec copy artwork.png
  # Convert the audio
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${FULL_AUDIOBOOK_PATH}" -vn -c:a copy -v debug output.${TEMP_FILE_EXTENSION}
  # Add the cover to the new file
  AtomicParsley output.${TEMP_FILE_EXTENSION} --artwork artwork.png --overWrite

  # Put it where you want it and clean up
  cp output.${TEMP_FILE_EXTENSION} "${OUTPUT_PATH}"
  rm artwork.png
  rm output.${TEMP_FILE_EXTENSION}
  cd "${ORIGINAL_PWD}"
}

It goes off without a hitch. The new file is there waiting for me, with all the metadata including the cover when I do a "Get Info" or "Quick look" on it (I'm on MacOS). But when opening it and trying to play it in iTunes, the "time" field is way off and it immediately skips to the next song/audiobook in the queue.

Attempts to convert it within iTunes fail immediately - too quickly to see what's happening. The errors in the console simply say "Assert failure:" (with nothing after the colon).

edit: Tommy answered the question. Here's a working bash function:

dedrm_audible () {
  # Check for AtomicParsley, ffmpeg, and 3 args
  if (! type AtomicParsley >/dev/null 2>/dev/null) || (! type ffmpeg >/dev/null 2>/dev/null) || [ ! $# -eq 3 ]; then
    echo "Usage:"
    echo "    dedrm_audible <path to .aax> <activation bytes> <path to output file>"
    echo "    Note: AtomicParsley and ffmpeg must be in PATH variable"
    return
  fi
  local ORIGINAL_PWD="$(pwd)"
  local TEMP_DIR="/tmp/audible"
  local AUDIOBOOK_FILE="$1"
  local ACTIVATION_BYTES="$2"
  local OUTPUT_FILE="$3"
  # Alternative to realpath (since I read somewhere that it's not there by default on some systems): OUTPUT_PATH="$( cd "$( dirname "$OUTPUT_FILE" )" && pwd )"
  local FULL_AUDIOBOOK_PATH="$(realpath "${AUDIOBOOK_FILE}")"
  local AUDIOBOOK_NAME="${$(basename "${FULL_AUDIOBOOK_PATH}")%.aax}.m4a"
  local OUTPUT_PATH="$(realpath "${OUTPUT_FILE}")"
  local TEMP_FILE_EXTENSION="m4a"

  mkdir -p "${TEMP_DIR}"
  cd "${TEMP_DIR}"

  cp "${FULL_AUDIOBOOK_PATH}" "${AUDIOBOOK_NAME}"

  # Extract the book cover
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${AUDIOBOOK_NAME}" -vcodec copy artwork.png
  # Convert the audio
  ffmpeg -activation_bytes "${ACTIVATION_BYTES}" -i "${AUDIOBOOK_NAME}" -vn -c:a copy -v debug output.${TEMP_FILE_EXTENSION}
  # Add the cover to the new file
  AtomicParsley output.${TEMP_FILE_EXTENSION} --artwork artwork.png --overWrite

  # Put it where you want it and clean up
  mv output.${TEMP_FILE_EXTENSION} "${OUTPUT_PATH}"
  rm artwork.png
  rm "${AUDIOBOOK_NAME}"
  cd "${ORIGINAL_PWD}"
}

Body:
They stopped working for me too, but if you just change the file extension to .m4a it will import fine, then you just have to change type from music to audiobook and tell it to remember location and it works fine on mac or iPhone.

The other approach is I went back and reran ffmpeg on the .aax with output to .m4b and iTunes handled it fine. I didn’t use.m4b before but I frankly don’t recall why.


问:
Use AngularJS in China
I got a small angularJS based website that is supposed to run internationally. One important location is China. While the website works fine here (Germany), I cannot get it to work in China.
I am currently using proxys to confirm that, but I also have had friends in China confirm it is not working.

Research has shown that googleapis is blocked in China. So I've tried to use it locally which also did not work. I've also tried other CDNs.

Now I just randomly checked angularJs-Demo pages (e.g. for various plugins on github). None of them works with a chinese proxy.

What Am I missing here? How can this be fixed?

答:
Here are two CDNs that are not blocked in China:

https://www.jsdelivr.com/

https://www.bootcdn.cn/

The second one is located in China so I would recommend it if you want to have lower load time.

Title: Use AngularJS in China


问:
dateFromString always returns null with dateformatter
I have the following code:

```<code> NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [df setTimeZone:[NSTimeZone systemTimeZone]];
    [df setFormatterBehavior:NSDateFormatterBehaviorDefault];

    [df dateFromString:@"2011-04-12 10:00:00"];
</code>```

In which it always generates a null date. Why is this?

答:
I just ran this code and it worked for me.

```<code>NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setFormatterBehavior:NSDateFormatterBehaviorDefault];

NSDate *theDate = [df dateFromString:@"2011-04-12 10:00:00"];
NSLog(@"date: %@", theDate);
</code>```

The output was: date: 2011-04-12 17:00:00 +0000

Body:
I have the following code:

 NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [df setTimeZone:[NSTimeZone systemTimeZone]];
    [df setFormatterBehavior:NSDateFormatterBehaviorDefault];

    [df dateFromString:@"2011-04-12 10:00:00"];

In which it always generates a null date. Why is this?

Body:
I just ran this code and it worked for me.

NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
[df setFormatterBehavior:NSDateFormatterBehaviorDefault];

NSDate *theDate = [df dateFromString:@"2011-04-12 10:00:00"];
NSLog(@"date: %@", theDate);

The output was: date: 2011-04-12 17:00:00 +0000


问:
Increasing timeout on channel originate
Using ARI (C#, AsterNET), I'm creating a channel via the Originate command:

```<code>   var channel = client.Channels.Originate($"SIP/{number}@{destination}", app: appName, callerId: CLI, timeout: timeout);
</code>```

This works fine; however,timeout starts from when the channel is created, and in reality I'd like to timeout to only be enforced once the channel starts ringing.

Is there any way (via ARI) to manipulate the timeout setting once the channel is created - so I could, for example, create the channel with an arbitrary timeout, and then (re)set the timeout once the channel state has changed to RINGING?

答:
Instead of using originate:

```<code>POST /channels
</code>```

you could use:

```<code>POST /channels/create
</code>```

to create a channel without dialing immediately. This allows your Stasis Application to gain control of the channel before it is answered.

Before /channels/create, you should now be setting a StasisStart event handler that does /channels/dial and sets the timeout in this request.

This won't be for exactly when the channel starts ringing (since that is not possible to set), but it will be exactly when the channel is dialed, which is hopefully pretty close to what you're looking for.

Note: when using this method, you will likely want to be setting the Caller ID in the StasisStart event handler as well, since it cannot be set in the /channels/create request.

Title: Increasing timeout on channel originate

Body:
Using ARI (C#, AsterNET), I'm creating a channel via the Originate command:

   var channel = client.Channels.Originate($"SIP/{number}@{destination}", app: appName, callerId: CLI, timeout: timeout);

This works fine; however,timeout starts from when the channel is created, and in reality I'd like to timeout to only be enforced once the channel starts ringing.

Is there any way (via ARI) to manipulate the timeout setting once the channel is created - so I could, for example, create the channel with an arbitrary timeout, and then (re)set the timeout once the channel state has changed to RINGING?

Body:
Instead of using originate:

POST /channels

you could use:

POST /channels/create

to create a channel without dialing immediately. This allows your Stasis Application to gain control of the channel before it is answered.

Before /channels/create, you should now be setting a StasisStart event handler that does /channels/dial and sets the timeout in this request.

This won't be for exactly when the channel starts ringing (since that is not possible to set), but it will be exactly when the channel is dialed, which is hopefully pretty close to what you're looking for.

Note: when using this method, you will likely want to be setting the Caller ID in the StasisStart event handler as well, since it cannot be set in the /channels/create request.