问:
Open specific Activity when notification clicked in FCM
I am working on App in which I am required to show notification.
For notification, i am using FireBase Cloud Messaging (FCM).
I am able to get Notification when app is in background.

But when I click on notification, it redirect to home.java page. I want it to redirect to Notification.java page.

So,please tell me how to specify Activity in on Click of notification.
I am using two services:

1.)MyFirebaseMessagingService

2.)MyFirebaseInstanceIDService

This is my code sample for onMessageReceived() method in MyFirebaseMessagingService class.

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;

public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
/**
 * Create and show a simple notification containing the received FCM message.
 */

private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
    Intent intent = new Intent(this, Notification.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("Notification", TrueOrFalse);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setLargeIcon(image)/*Notification icon image*/
            .setContentTitle(messageBody)
            .setStyle(new NotificationCompat.BigPictureStyle()
             .bigPicture(image))/*Notification with Image*/
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

/*
*To get a Bitmap image from the URL received
* */
public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}
</code>```

答:
Here is the easiest way to understand this.

When you send a data payload with the notification payload as

```<code> notification: {
            title: "Your order status.",
            body: orderStatusDetail,
            clickAction: "ShopFragment"
        },
        data: {
            ORDER_ID: orderId
        }
</code>```

The notification clickAction will be the filter you will use to pass data into your Activity, what data? The data sent by the data: { } object appended to the payload.

So, the clickAction will trigger the intent filter in your Manifest, so first we need to create it

```<code> <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="ShopFragment"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>

        </activity>
</code>```

Now we set the intent filter with the same name as our clickAction, doing this we trigger that whenever we press the notification at our notification tab, this intent filter will launch and so on the activity associated with this intent filter.

And then, just use intent.getStringExtra("ORDER_ID") at your MainActivity to get your String extra sent at your data payload.

Make sure that ORDER_ID in this case is the key we send from the data { } object and needs to be the same in the client to get this data.

Body:
I am working on App in which I am required to show notification.
For notification, i am using FireBase Cloud Messaging (FCM).
I am able to get Notification when app is in background.

But when I click on notification, it redirect to home.java page. I want it to redirect to Notification.java page.

So,please tell me how to specify Activity in on Click of notification.
I am using two services:

1.)MyFirebaseMessagingService

2.)MyFirebaseInstanceIDService

This is my code sample for onMessageReceived() method in MyFirebaseMessagingService class.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;

public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
/**
 * Create and show a simple notification containing the received FCM message.
 */

private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
    Intent intent = new Intent(this, Notification.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    intent.putExtra("Notification", TrueOrFalse);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setLargeIcon(image)/*Notification icon image*/
            .setContentTitle(messageBody)
            .setStyle(new NotificationCompat.BigPictureStyle()
             .bigPicture(image))/*Notification with Image*/
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

/*
*To get a Bitmap image from the URL received
* */
public Bitmap getBitmapfromUrl(String imageUrl) {
    try {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    }
}

Body:
Here is the easiest way to understand this.

When you send a data payload with the notification payload as

 notification: {
            title: "Your order status.",
            body: orderStatusDetail,
            clickAction: "ShopFragment"
        },
        data: {
            ORDER_ID: orderId
        }

The notification clickAction will be the filter you will use to pass data into your Activity, what data? The data sent by the data: { } object appended to the payload.

So, the clickAction will trigger the intent filter in your Manifest, so first we need to create it

 <activity
            android:name=".activity.MainActivity"
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="ShopFragment"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>

        </activity>

Now we set the intent filter with the same name as our clickAction, doing this we trigger that whenever we press the notification at our notification tab, this intent filter will launch and so on the activity associated with this intent filter.

And then, just use intent.getStringExtra("ORDER_ID") at your MainActivity to get your String extra sent at your data payload.

Make sure that ORDER_ID in this case is the key we send from the data { } object and needs to be the same in the client to get this data.


来源: stackexchange

问:
Replace an Object by another type of Object in a Main[JAVA]
i try to to change a Object to another type of Object in my main. Here is some code to see what i actually mean.

Main.java

```<code>public class Main {
    public static void main(String[] args) {
        Controller newcontroller = Controller.create();
        newcontroller.change();
    }
}
</code>```

Controler.java:

```<code>public class Controller{

    public static Controller create() {
        return new North(0,0);
    }

    public void change() {
    }

}
</code>```

North.java:

```<code>public class North extends Controller{
    int x;
    int y;

    public North(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void change() {
        super.change();
        //Now i have to replace the newcontroller North(x,y) by South(x,y)
        super.newcontroller = new South(this.x, this.y)
    }
}
</code>```

South.java is just like the North one but it changes to North again.
How can i do that? Or am i doing it completly on a false way?
its not allowed to use if, switch, for, while, ... Only linear programming

答:
An easy way to do this is to have a boolean flag inside the Controller class and check the flag to change, but this should not be done because it doesn't follow OOP principles. In your code above it looks like you are creating a Factory that returns a controller.

```<code>public class ControllerFactory {

    public static CreateController(boolean isNorth) {
        return isNorth ? new North() : new South();
    }
}
</code>```

And wherever you instantiate Controller have a boolean that holds the current state of the controller.

```<code>boolean isNorth = true;

isNorth = !isNorth;
controller = ControllerFactory.CreateController(isNorth);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i try to to change a Object to another type of Object in my main. Here is some code to see what i actually mean.

Main.java

public class Main {
    public static void main(String[] args) {
        Controller newcontroller = Controller.create();
        newcontroller.change();
    }
}

Controler.java:

public class Controller{

    public static Controller create() {
        return new North(0,0);
    }

    public void change() {
    }

}

North.java:

public class North extends Controller{
    int x;
    int y;

    public North(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public void change() {
        super.change();
        //Now i have to replace the newcontroller North(x,y) by South(x,y)
        super.newcontroller = new South(this.x, this.y)
    }
}

South.java is just like the North one but it changes to North again.
How can i do that? Or am i doing it completly on a false way?
its not allowed to use if, switch, for, while, ... Only linear programming

Body:
An easy way to do this is to have a boolean flag inside the Controller class and check the flag to change, but this should not be done because it doesn't follow OOP principles. In your code above it looks like you are creating a Factory that returns a controller.

public class ControllerFactory {

    public static CreateController(boolean isNorth) {
        return isNorth ? new North() : new South();
    }
}

And wherever you instantiate Controller have a boolean that holds the current state of the controller.

boolean isNorth = true;

isNorth = !isNorth;
controller = ControllerFactory.CreateController(isNorth);


问:
scilab sending java main-class error and doesn't wanna work
scilab was working just fine 2 weeks ago but now after i updated software ubuntu if i try to open it nothing happens and if i try to open it using Terminal i get this error

```<code>WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.scilab.modules.jvm.LibraryPath (file:/usr/share/scilab/modules/jvm/jar/org.scilab.modules.jvm.jar) to field java.lang.ClassLoader.sys_paths
WARNING: Please consider reporting this to the maintainers of org.scilab.modules.jvm.LibraryPath
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Could not access to the Main Scilab Class:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.scilab.modules.localization.Messages.gettext(Unknown Source)
    at org.scilab.modules.commons.xml.XConfiguration.<clinit>(Unknown Source)
    at org.scilab.modules.core.Scilab.<clinit>(Unknown Source)
Caused by: java.lang.NullPointerException
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2646)
    at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:830)
    at java.base/java.lang.System.loadLibrary(System.java:1870)
    at org.scilab.modules.localization.MessagesJNI.<clinit>(Unknown Source)
    ... 3 more

Scilab cannot create Scilab Java Main-Class (we have not been able to find the main Scilab class. Check if the Scilab and thirdparty packages are available).
</code>```

i tried reinstalling it and reinstalling java but still doesn't work

答:
I have encountered the same problem. After googling I found out that this bug was fixed in Scilab 6.0.2.

You can download it here:

https://www.scilab.org/download/6.0.2

Current version of Scilab, that you can get from

```<code>sudo apt-get scilab
</code>```

is 6.0.1 (for me scilab-cli was working, but GUI was not)

Currently Scilab 6.0.2 works in GUI mode and CLI under Ubuntu 18.04.4 LTS. XCOS works too.

It is a little bit laggy after start, but it might be my setup.

Body:
scilab was working just fine 2 weeks ago but now after i updated software ubuntu if i try to open it nothing happens and if i try to open it using Terminal i get this error

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.scilab.modules.jvm.LibraryPath (file:/usr/share/scilab/modules/jvm/jar/org.scilab.modules.jvm.jar) to field java.lang.ClassLoader.sys_paths
WARNING: Please consider reporting this to the maintainers of org.scilab.modules.jvm.LibraryPath
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Could not access to the Main Scilab Class:
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.scilab.modules.localization.Messages.gettext(Unknown Source)
    at org.scilab.modules.commons.xml.XConfiguration.<clinit>(Unknown Source)
    at org.scilab.modules.core.Scilab.<clinit>(Unknown Source)
Caused by: java.lang.NullPointerException
    at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2646)
    at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:830)
    at java.base/java.lang.System.loadLibrary(System.java:1870)
    at org.scilab.modules.localization.MessagesJNI.<clinit>(Unknown Source)
    ... 3 more

Scilab cannot create Scilab Java Main-Class (we have not been able to find the main Scilab class. Check if the Scilab and thirdparty packages are available).

i tried reinstalling it and reinstalling java but still doesn't work

Body:
I have encountered the same problem. After googling I found out that this bug was fixed in Scilab 6.0.2.

You can download it here:

https://www.scilab.org/download/6.0.2

Current version of Scilab, that you can get from

sudo apt-get scilab

is 6.0.1 (for me scilab-cli was working, but GUI was not)

Currently Scilab 6.0.2 works in GUI mode and CLI under Ubuntu 18.04.4 LTS. XCOS works too.

It is a little bit laggy after start, but it might be my setup.


问:
want to display positive and negative values in different columns thru a single query
I have one column table with negative and positive values and want to display positive and negative values in different columns thru a single query.

```<code>Column
-10000
-17000
 16000
 25000
</code>```

output should be like

```<code>A        B
-----------------
-10000   16000
-17000   25000
</code>```

I am using oracle and pl sql developer.

答:
```<code>select decode(sign(col),1,col) positive_value
      , decode(sign(col),-1,col) negative_value
      , decode(sign(col),0,col) zero_value
from tbl_name
</code>```

i dont know whether this will work or not but once try it..

ContentLicense: CC BY-SA 3.0

Body:
I have one column table with negative and positive values and want to display positive and negative values in different columns thru a single query.

Column
-10000
-17000
 16000
 25000

output should be like

A        B
-----------------
-10000   16000
-17000   25000

I am using oracle and pl sql developer.

Body:
select decode(sign(col),1,col) positive_value
      , decode(sign(col),-1,col) negative_value
      , decode(sign(col),0,col) zero_value
from tbl_name

i dont know whether this will work or not but once try it..


问:
Struct trait error: Wrong number of type arguments: Expected 1, found 0
I'm kinda new to the concept of how Rust works even after experimenting with it for a couple months. I'm writing a webserver with R2D2 (0.8.0) and Rocket (0.4.4) + Rocket_cors (0.5.2)

Rocket allows you to feed it structs into a state pool, so I don't have to initialize my Postgres server every time somebody sends a request. Here's the code:

```<code>struct ConnectionPool<M: r2d2::ManageConnection> {
    val: r2d2::Pool<M>
}

#[post("/upload", format = "application/json", data = "<data>")]
fn upload(data: Data, state: rocket::State<ConnectionPool>) {
    if data.peek_complete() {
        println!("All of the data: {:?}", str::from_utf8(data.peek()).unwrap());
    }
    //data.stream_to_file(env::temp_dir().join("upload.txt"))
    //    .map(|n| n.to_string())
    //    .map_err(Debug)
}
</code>```

Obviously, this is just a snippet of the code, but r2d2::ConnectionPool requires one type identifier: giving me this error if I ignore the requirement (on line 4 in the code snippet above):

```<code>wrong number of type arguments: expected 1, found 0

expected 1 type argumentrustc(E0107)
main.rs(45, 44): expected 1 type argument
</code>```

But when I try my best-ish to solve the problem by updating the code:

```<code>fn upload(data: Data, state: rocket::State<ConnectionPool>) {

    |
    v

fn upload(data: Data, state: rocket::State<ConnectionPool<r2d2::ManageConnection>>) {
</code>```

I get this error:

```<code>the size for values of type `(dyn r2d2::ManageConnection + 'static)` cannot be known at compilation time

doesn't have a size known at compile-time

help: the trait `std::marker::Sized` is not implemented for `(dyn r2d2::ManageConnection + 'static)`
</code>```

答:
r2d2::ManageConnection is a trait. Rather than repeating the trait name you need to pass it a concrete type that implements the trait. Since you're using Postgres you probably want:

```<code>fn upload(data: Data, state: rocket::State<ConnectionPool<PostgresConnectionManager>>)
</code>```

Alternatively, if you want to keep your code database agnostic you can make the method generic over the connection type and let the caller decide:

```<code>fn upload<M: r2d2::ManageConnection>(data: Data, state: rocket::State<ConnectionPool<M>>)
</code>```

Body:
I'm kinda new to the concept of how Rust works even after experimenting with it for a couple months. I'm writing a webserver with R2D2 (0.8.0) and Rocket (0.4.4) + Rocket_cors (0.5.2)

Rocket allows you to feed it structs into a state pool, so I don't have to initialize my Postgres server every time somebody sends a request. Here's the code:

struct ConnectionPool<M: r2d2::ManageConnection> {
    val: r2d2::Pool<M>
}

#[post("/upload", format = "application/json", data = "<data>")]
fn upload(data: Data, state: rocket::State<ConnectionPool>) {
    if data.peek_complete() {
        println!("All of the data: {:?}", str::from_utf8(data.peek()).unwrap());
    }
    //data.stream_to_file(env::temp_dir().join("upload.txt"))
    //    .map(|n| n.to_string())
    //    .map_err(Debug)
}

Obviously, this is just a snippet of the code, but r2d2::ConnectionPool requires one type identifier: giving me this error if I ignore the requirement (on line 4 in the code snippet above):

wrong number of type arguments: expected 1, found 0

expected 1 type argumentrustc(E0107)
main.rs(45, 44): expected 1 type argument

But when I try my best-ish to solve the problem by updating the code:

fn upload(data: Data, state: rocket::State<ConnectionPool>) {

    |
    v

fn upload(data: Data, state: rocket::State<ConnectionPool<r2d2::ManageConnection>>) {

I get this error:

the size for values of type `(dyn r2d2::ManageConnection + 'static)` cannot be known at compilation time

doesn't have a size known at compile-time

help: the trait `std::marker::Sized` is not implemented for `(dyn r2d2::ManageConnection + 'static)`

Body:
r2d2::ManageConnection is a trait. Rather than repeating the trait name you need to pass it a concrete type that implements the trait. Since you're using Postgres you probably want:

fn upload(data: Data, state: rocket::State<ConnectionPool<PostgresConnectionManager>>)

Alternatively, if you want to keep your code database agnostic you can make the method generic over the connection type and let the caller decide:

fn upload<M: r2d2::ManageConnection>(data: Data, state: rocket::State<ConnectionPool<M>>)


答:
This might be a solution but only if number of positive and negative numbers is same.

```<code>select a.column as negative, b.column as non_negative from table a, table b where a.column<0 and b.column>=0;
</code>```

Where of course, column is your column name and table is your table name.

Title: want to display positive and negative values in different columns thru a single query

Body:
This might be a solution but only if number of positive and negative numbers is same.

select a.column as negative, b.column as non_negative from table a, table b where a.column<0 and b.column>=0;

Where of course, column is your column name and table is your table name.


问:
Not able to open more than 2 tabs using webdrivderio
I am trying to three tabs using webdriverIO v5. Here is the sample code.

```<code>browser.newWindow("https://www.google.com");
browser.newWindow("https://www.amazon.com");
browser.newWindow("https://www.paypal.com");
</code>```

The test runs successfully but instead of opening third tab for paypal, it reloads second tab with paypal. Is there a way to avoid that?

答:
You can try to sort this out via window.open() using JavaScript insertion in WebdriverIO.

```<code>browser.execute((url) => {
      window.open(url);
    }, "http://twitter.com");
</code>```

See this example I've put together... It will open four different tabs (I am using Chrome) and switch to them.

```<code>describe("tabs", () => {
  it("multiple browser tabs / windows", () => {
    // open url
    browser.url("https://google.com");
    browser.pause(2000);
browser.newWindow("https://webdriver.io");
    browser.pause(2000);
browser.execute((url) => {
      window.open(url);
    }, "http://yahoo.com");
    browser.pause(2000);
browser.execute((url) => {
      window.open(url);
    }, "http://twitter.com");
    browser.pause(2000);
browser.switchWindow("google.com");
    browser.pause(2000);
browser.switchWindow("webdriver.io");
    browser.pause(2000);
browser.switchWindow("yahoo.com");
    browser.pause(2000);
browser.switchWindow("twitter.com");
    browser.pause(2000);
  });
});
</code>```

I've also wrote a short article in case other guys face the same challenge, here.

Hope it helps!

Body:
I am trying to three tabs using webdriverIO v5. Here is the sample code.

browser.newWindow("https://www.google.com");
browser.newWindow("https://www.amazon.com");
browser.newWindow("https://www.paypal.com");

The test runs successfully but instead of opening third tab for paypal, it reloads second tab with paypal. Is there a way to avoid that?

Body:
You can try to sort this out via window.open() using JavaScript insertion in WebdriverIO.

browser.execute((url) => {
      window.open(url);
    }, "http://twitter.com");

See this example I've put together... It will open four different tabs (I am using Chrome) and switch to them.

describe("tabs", () => {
  it("multiple browser tabs / windows", () => {
    // open url
    browser.url("https://google.com");
    browser.pause(2000);
browser.newWindow("https://webdriver.io");
    browser.pause(2000);
browser.execute((url) => {
      window.open(url);
    }, "http://yahoo.com");
    browser.pause(2000);
browser.execute((url) => {
      window.open(url);
    }, "http://twitter.com");
    browser.pause(2000);
browser.switchWindow("google.com");
    browser.pause(2000);
browser.switchWindow("webdriver.io");
    browser.pause(2000);
browser.switchWindow("yahoo.com");
    browser.pause(2000);
browser.switchWindow("twitter.com");
    browser.pause(2000);
  });
});

I've also wrote a short article in case other guys face the same challenge, here.

Hope it helps!


问:
Razor Host Factory error
I get a MvcWebRazorHostFactory error trying to run my app, but it's not an MVC app at all.  I have the following web packages installed via nuget:

```<code>Microsoft ASP.NET Razor
Microsoft ASP.NET Web API 2.1
Microsoft ASP.NET Web Pages
</code>```

My app is angularjs front end using razor views (.cshtml).  I don't understand why I keep getting this error.

```<code>An exception of type 'System.InvalidOperationException' occurred in System.Web.WebPages.Razor.dll but was not handled in user code

Additional information: Could not locate Razor Host Factory type: System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35
</code>```

And here is the razor section in my web.config:

```<code><system.web.webPages.razor>
<host factoryType="System.Web.WebPages.Razor.WebRazorHostFactory, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.WebPages.WebPage">
  <namespaces>
    <add namespace="System.Web.Configuration" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>
</code>```

答: For MacBook users having the Visual Studio 2019, you simply go to the Web.config file and update version of the System.Web.Mvc to that which is in your Nuget packages folder.</p>

Title: Razor Host Factory error

Body:
I get a MvcWebRazorHostFactory error trying to run my app, but it's not an MVC app at all.  I have the following web packages installed via nuget:

Microsoft ASP.NET Razor
Microsoft ASP.NET Web API 2.1
Microsoft ASP.NET Web Pages

My app is angularjs front end using razor views (.cshtml).  I don't understand why I keep getting this error.

An exception of type 'System.InvalidOperationException' occurred in System.Web.WebPages.Razor.dll but was not handled in user code

Additional information: Could not locate Razor Host Factory type: System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35

And here is the razor section in my web.config:

<system.web.webPages.razor>
<host factoryType="System.Web.WebPages.Razor.WebRazorHostFactory, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.WebPages.WebPage">
  <namespaces>
    <add namespace="System.Web.Configuration" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>


问:
Information retrieval data collection
I am looking for datasets designated for information retrieval. I found some datasets that are used for other NLP tasks like text categorization or sentiment analysis, but I haven't had any luck finding something specifically for information retrieval yet. Are there any places to look?

Thank you for any help.

答:
Specifically for basic Information Retreival, check out the Glasgow IR Collection.

http://ir.dcs.gla.ac.uk/resources/test_collections/

Even though these datasets are very basic and old. They have Relevance Judgements which is beneficial in tasks to evaluate and rank.

TREC Collection is mainly for advanced IR tasks https://trec.nist.gov/

Title: Information retrieval data collection


问:
Reduce nested list of object by parameter
I need to reduce one collection of nested lists to another. I need to keep only objects which have parameter IsOk == true.

```<code>public class Item {
public string Id { get; set; }
public Item[] Items { get; set; }
public bool IsOk { get; set; }
</code>```

This is enter json:

```<code>                {
                'id': '1',
                'isOk': false,
                'items': [
                    {
                        'id': '21',
                        'isOk': false,
                        'items': [
                            {
                                'id': '31',
                                'isOk': true,
                                'items': [
                                    {
                                        'id': '41',
                                        'isOk': true,
                                        'items': null
                                    },
                                    {
                                        'id': '42',
                                        'isOk': true,
                                        'items': null
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        'id': '22',
                        'isOk': true,
                        'items': [
                            {
                                'id': '32',
                                'isOk': true,
                                'items': [
                                    {
                                        'id': '43',
                                        'isOk': true,
                                        'items': null
                                    },
                                    {
                                        'id': '44',
                                        'isOk': true,
                                        'items': null
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
</code>```

This is correct modified json.

```<code>        [
            {
                'id': '31',
                'isOk': true,
                'items': [
                    {
                        'id': '41',
                        'isOk': true,
                        'items': null
                    },
                    {
                        'id': '42',
                        'isOk': true,
                        'items': null
                    }
                ]
            },
                {
                    'id': '22',
                    'isOk': true,
                    'items': [
                        {
                            'id': '32',
                            'isOk': true,
                            'items': [
                                {
                                    'id': '43',
                                    'isOk': true,
                                    'items': null
                                },
                                {
                                    'id': '44',
                                    'isOk': true,
                                    'items': null
                                }
                            ]
                        }
                    ]
                }
            ]
</code>```

As you see new json have modified hierarchy and keep only objects with property IsOk == true.
The biggest problem for me is how to change the hierarchy of the objects.
Currently I try to use recursive function but maybe better is to use while loop?

答:
You can try this. As I stated in the comment to the question it's not a trivial task. The below 5 methods are explained with comments and at the bottom there's an example on how to use them. I tested it on different configurations of the json and seems to work.

```<code>        /// <summary>
        /// Flattens the actual result of the json deserialization (a List<Item>).
        /// </summary>
        /// <param name="deserializedObject">The actual result of the json deserialization (a List<Item>).</param>
        /// <param name="flattenedObject">The resulting flattened object.</param>
        private void FlattenDeserializedObject(List<Item> deserializedObject, List<Item> flattenedObject)
        {
            // Null-check on the flattened list.
            if (flattenedObject is null)
                flattenedObject = new List<Item>();
            // Iterate on every Item of the structure.
            for (var i = 0; i < deserializedObject.Count; i++)
            {
                if (deserializedObject[i] is null) continue;
                // Add the item to the flattened structure.
                flattenedObject.Add(deserializedObject[i]);
                // Check if there are descendants, if no the step to the next Item.
                if (deserializedObject[i].Items is null || deserializedObject[i].Items.Count() == 0)
                    continue;
                // There are descendants, recurse on them and update flattenedStructure.
                FlattenDeserializedObject(deserializedObject[i].Items.ToList(), flattenedObject);
            }
        }
        /// <summary>
        /// Creates a dictionary of descendants of an Item having IsOk=true.
        /// Dictionary KEY=[ItemID, VALUE=List of descendants with IsOk=true].
        /// </summary>
        /// <param name="flattenedObject">The flattened list of Items.</param>
        /// <param name="descIds">Dictionary KEY=[ItemID, VALUE=List of descendants with IsOk=true]</param>
        private void GetValidDescendantsIdDictionary(List<Item> flattenedObject, out Dictionary<string, List<string>> descendantsDictionary)
        {
            // Create an instance of the dictionary.
            descendantsDictionary = new Dictionary<string, List<string>>();
            // Get the descendants for every Item.
            foreach (var node in flattenedObject)
            {
                // Create a new list of ids for this Item id.
                descendantsDictionary.Add(node.Id, new List<string>());
                // Get all the isOk=true descendants for a specific node.
                GetValidNodeDescendantsIds(node, descendantsDictionary[node.Id]);
            }
        }
        /// <summary>
        /// Gets all the isOk=true descendants of a specific Item node.
        /// </summary>
        /// <param name="node">Item node.</param>
        /// <param name="descendantIds">List of isOK=true descendant IDs for the node.</param>
        private void GetValidNodeDescendantsIds(Item node, List<string> descendantIds)
        {
            // Null-empty check on the nodes and the direct descendants.
            if (node is null || node.Items is null || node.Items.Length == 0)
                return;
            descendantIds.AddRange(node.Items.Where(x => x.IsOk).Select(x => x.Id));
            // Recurse on the children of the node.
            node.Items.ToList().ForEach(n => GetValidNodeDescendantsIds(n, descendantIds));
        }
        /// <summary>
        /// Removes all the isOk=false items from the flattened structure.
        /// </summary>
        private void RemoveInvalidItemsFromFlattenedObject(List<Item> flattenedObject)
        {
            // Null-empty check on the flattened list.
            if (flattenedObject is null || flattenedObject.Count == 0) return;
            flattenedObject.RemoveAll(x => !x.IsOk);
        }
        /// <summary>
        /// Rebuilds the original structure node by node from the flattened one (without the invalid elements).
        /// Uses the descendants ID dictionary to get the correct position for the new nodes.
        /// Result will be in flattenedStructure.
        /// </summary>
        private void RebuildOriginalStructureFromFlattened(Item node, List<Item> flattenedStructure, Dictionary<string, List<string>> descendantsDictionary)
        {
            if (node is null || node.Items is null || node.Items.Length == 0)
                return;
            // Get the list of descendants from the support dictionary.
            var nodeDescendants = descendantsDictionary[node.Id];

            if (nodeDescendants.Count > 0)
            {
                // If there are isOk descendants, check their level and fix the hierarchy.
                var nodeLevel = int.Parse(node.Id.Substring(0, 1));
                var nextLevelWithNodes = nodeDescendants.Select(x => int.Parse(x.Substring(0, 1))).Min();
                var nextLevelNodeIds = nodeDescendants.Where(x => int.Parse(x.Substring(0, 1)) == nextLevelWithNodes);
                node.Items = flattenedStructure.Where(x => nextLevelNodeIds.Contains(x.Id)).ToArray();
                flattenedStructure.RemoveAll(x => nextLevelNodeIds.Contains(x.Id));
                // Recurse on every children.
                foreach (var n in node.Items)
                    RebuildOriginalStructureFromFlattened(n, flattenedStructure, descendantsDictionary);
            }
            else
            {
                // There are no isOk descendants, reset the Items array to null.
                node.Items = null;
            }
        }
</code>```

USAGE:

```<code>            // json is the path to the json file.
            var items = JsonConvert.DeserializeObject<List<Item>>(json);
            // Create a list for the flattened structure.
            var flattenedObject = new List<Item>();
            // 1) Fill the flattenedObject list by passing the original structure (items).
            FlattenDeserializedObject(items, flattenedObject);
            // 2) Creates a dictionary of valid (isOk=true) descendants for each node.
            GetValidDescendantsIdDictionary(flattenedObject, out Dictionary<string, List<string>> descIds);
            // 3) Remove all the isOk=false nodes from the flattened structure.
            RemoveInvalidItemsFromFlattenedObject(flattenedObject);
            // 4) Rebuild the original structure from the flattened one.
            for (var i=0; i< flattenedObject.Count; i++)
                RebuildOriginalStructureFromFlattened(flattenedObject[i], flattenedObject, descIds);
            // 5) Get the json without the isOk=false nodes, but keeping the initial structure.
            var okJson = JsonConvert.SerializeObject(flattenedObject);
</code>```

Body:
I need to reduce one collection of nested lists to another. I need to keep only objects which have parameter IsOk == true.

public class Item {
public string Id { get; set; }
public Item[] Items { get; set; }
public bool IsOk { get; set; }

This is enter json:

                {
                'id': '1',
                'isOk': false,
                'items': [
                    {
                        'id': '21',
                        'isOk': false,
                        'items': [
                            {
                                'id': '31',
                                'isOk': true,
                                'items': [
                                    {
                                        'id': '41',
                                        'isOk': true,
                                        'items': null
                                    },
                                    {
                                        'id': '42',
                                        'isOk': true,
                                        'items': null
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        'id': '22',
                        'isOk': true,
                        'items': [
                            {
                                'id': '32',
                                'isOk': true,
                                'items': [
                                    {
                                        'id': '43',
                                        'isOk': true,
                                        'items': null
                                    },
                                    {
                                        'id': '44',
                                        'isOk': true,
                                        'items': null
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }

This is correct modified json.

        [
            {
                'id': '31',
                'isOk': true,
                'items': [
                    {
                        'id': '41',
                        'isOk': true,
                        'items': null
                    },
                    {
                        'id': '42',
                        'isOk': true,
                        'items': null
                    }
                ]
            },
                {
                    'id': '22',
                    'isOk': true,
                    'items': [
                        {
                            'id': '32',
                            'isOk': true,
                            'items': [
                                {
                                    'id': '43',
                                    'isOk': true,
                                    'items': null
                                },
                                {
                                    'id': '44',
                                    'isOk': true,
                                    'items': null
                                }
                            ]
                        }
                    ]
                }
            ]

As you see new json have modified hierarchy and keep only objects with property IsOk == true.
The biggest problem for me is how to change the hierarchy of the objects.
Currently I try to use recursive function but maybe better is to use while loop?

Body:
You can try this. As I stated in the comment to the question it's not a trivial task. The below 5 methods are explained with comments and at the bottom there's an example on how to use them. I tested it on different configurations of the json and seems to work.

        /// <summary>
        /// Flattens the actual result of the json deserialization (a List<Item>).
        /// </summary>
        /// <param name="deserializedObject">The actual result of the json deserialization (a List<Item>).</param>
        /// <param name="flattenedObject">The resulting flattened object.</param>
        private void FlattenDeserializedObject(List<Item> deserializedObject, List<Item> flattenedObject)
        {
            // Null-check on the flattened list.
            if (flattenedObject is null)
                flattenedObject = new List<Item>();
            // Iterate on every Item of the structure.
            for (var i = 0; i < deserializedObject.Count; i++)
            {
                if (deserializedObject[i] is null) continue;
                // Add the item to the flattened structure.
                flattenedObject.Add(deserializedObject[i]);
                // Check if there are descendants, if no the step to the next Item.
                if (deserializedObject[i].Items is null || deserializedObject[i].Items.Count() == 0)
                    continue;
                // There are descendants, recurse on them and update flattenedStructure.
                FlattenDeserializedObject(deserializedObject[i].Items.ToList(), flattenedObject);
            }
        }
        /// <summary>
        /// Creates a dictionary of descendants of an Item having IsOk=true.
        /// Dictionary KEY=[ItemID, VALUE=List of descendants with IsOk=true].
        /// </summary>
        /// <param name="flattenedObject">The flattened list of Items.</param>
        /// <param name="descIds">Dictionary KEY=[ItemID, VALUE=List of descendants with IsOk=true]</param>
        private void GetValidDescendantsIdDictionary(List<Item> flattenedObject, out Dictionary<string, List<string>> descendantsDictionary)
        {
            // Create an instance of the dictionary.
            descendantsDictionary = new Dictionary<string, List<string>>();
            // Get the descendants for every Item.
            foreach (var node in flattenedObject)
            {
                // Create a new list of ids for this Item id.
                descendantsDictionary.Add(node.Id, new List<string>());
                // Get all the isOk=true descendants for a specific node.
                GetValidNodeDescendantsIds(node, descendantsDictionary[node.Id]);
            }
        }
        /// <summary>
        /// Gets all the isOk=true descendants of a specific Item node.
        /// </summary>
        /// <param name="node">Item node.</param>
        /// <param name="descendantIds">List of isOK=true descendant IDs for the node.</param>
        private void GetValidNodeDescendantsIds(Item node, List<string> descendantIds)
        {
            // Null-empty check on the nodes and the direct descendants.
            if (node is null || node.Items is null || node.Items.Length == 0)
                return;
            descendantIds.AddRange(node.Items.Where(x => x.IsOk).Select(x => x.Id));
            // Recurse on the children of the node.
            node.Items.ToList().ForEach(n => GetValidNodeDescendantsIds(n, descendantIds));
        }
        /// <summary>
        /// Removes all the isOk=false items from the flattened structure.
        /// </summary>
        private void RemoveInvalidItemsFromFlattenedObject(List<Item> flattenedObject)
        {
            // Null-empty check on the flattened list.
            if (flattenedObject is null || flattenedObject.Count == 0) return;
            flattenedObject.RemoveAll(x => !x.IsOk);
        }
        /// <summary>
        /// Rebuilds the original structure node by node from the flattened one (without the invalid elements).
        /// Uses the descendants ID dictionary to get the correct position for the new nodes.
        /// Result will be in flattenedStructure.
        /// </summary>
        private void RebuildOriginalStructureFromFlattened(Item node, List<Item> flattenedStructure, Dictionary<string, List<string>> descendantsDictionary)
        {
            if (node is null || node.Items is null || node.Items.Length == 0)
                return;
            // Get the list of descendants from the support dictionary.
            var nodeDescendants = descendantsDictionary[node.Id];

            if (nodeDescendants.Count > 0)
            {
                // If there are isOk descendants, check their level and fix the hierarchy.
                var nodeLevel = int.Parse(node.Id.Substring(0, 1));
                var nextLevelWithNodes = nodeDescendants.Select(x => int.Parse(x.Substring(0, 1))).Min();
                var nextLevelNodeIds = nodeDescendants.Where(x => int.Parse(x.Substring(0, 1)) == nextLevelWithNodes);
                node.Items = flattenedStructure.Where(x => nextLevelNodeIds.Contains(x.Id)).ToArray();
                flattenedStructure.RemoveAll(x => nextLevelNodeIds.Contains(x.Id));
                // Recurse on every children.
                foreach (var n in node.Items)
                    RebuildOriginalStructureFromFlattened(n, flattenedStructure, descendantsDictionary);
            }
            else
            {
                // There are no isOk descendants, reset the Items array to null.
                node.Items = null;
            }
        }

USAGE:

            // json is the path to the json file.
            var items = JsonConvert.DeserializeObject<List<Item>>(json);
            // Create a list for the flattened structure.
            var flattenedObject = new List<Item>();
            // 1) Fill the flattenedObject list by passing the original structure (items).
            FlattenDeserializedObject(items, flattenedObject);
            // 2) Creates a dictionary of valid (isOk=true) descendants for each node.
            GetValidDescendantsIdDictionary(flattenedObject, out Dictionary<string, List<string>> descIds);
            // 3) Remove all the isOk=false nodes from the flattened structure.
            RemoveInvalidItemsFromFlattenedObject(flattenedObject);
            // 4) Rebuild the original structure from the flattened one.
            for (var i=0; i< flattenedObject.Count; i++)
                RebuildOriginalStructureFromFlattened(flattenedObject[i], flattenedObject, descIds);
            // 5) Get the json without the isOk=false nodes, but keeping the initial structure.
            var okJson = JsonConvert.SerializeObject(flattenedObject);


问:
Javascript Class: getter value when instantiating the class
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

```<code>class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2
</code>```

Just curious to know how we can implement this?

答:
First, it looks like you should alter the final line to fix a bug:

```<code>console.log(Array.from(new HeyNumber()).join(',')) // ''
console.log(Array.from(new HeyNumber().numbers).join(',')) // 2,1,2,3
</code>```

Then, try the following on Line 3:

```<code>return [2, 1, 2, 3].reverse();
</code>```

Body:
I have a quick question - it was challenge in Hacker Rank - trying  to find an answer.

Question goes like this.

Console log should print the reverse order of numbers in the class.
Restrictions:
1. Class constructor should not be modified.
2. Console log statement should not be modified.

You can do anything else to make it working.

class HeyNumber {
  get numbers() {
    return [2, 1, 2, 3];
  }

  // You should not change the constructor
  constructor() {
    return this;
  }
}

// You should not alter the following line
console.log(Array.from(new HeyNumber()).join(',')) // 3,2,1,2

Just curious to know how we can implement this?

Body:
First, it looks like you should alter the final line to fix a bug:

console.log(Array.from(new HeyNumber()).join(',')) // ''
console.log(Array.from(new HeyNumber().numbers).join(',')) // 2,1,2,3

Then, try the following on Line 3:

return [2, 1, 2, 3].reverse();


问:
Wait for Redux props and then do some operations on the props in componentDidMount
I have a ChatBox component for my website, which displays the chat history of a user. The chat history is not ordered in my firestore, so I want to (1) sort it from the most to the least recent in componentDidMount once I get the data via Redux props (this.props.profile.chats_history) and (2) set the field "chatlist" in the state of ChatBox to the sorted array. The problem is that it takes time for props to be received and when the array.sort() method was called the console reported that the array was undefined. I tried to get around it by using async and await keywords but my solution did not work.

My solution

```<code>    async componentDidMount() {
        let chatlist;
        await this.props.profile.chats_history;
        chatlist = this.props.profile.chats_history.sort(function(a, b) {return a.time - b.time});
        this.setState({
            chatlist: chatlist
        })
    }
</code>```

答:
You can use getDerivedStateFromProps instead.

```<code>static getDerivedStateFromProps(props, state) {
    const sortedChat = props.profile.chats_history?[...props.profile.chats_history].sort((a,b)=>{/*logic*/}):[]
    return { sortedChat };
}
</code>```

You can optimize your renders by comparing the current data in state and received data in props. That depends on your data again. Personally, I'd keep a timestamp in profile.chats and only update the state when timestamp changes. Also, sort changes the original array order. So, clone before you sort like I did above.

Body:
I have a ChatBox component for my website, which displays the chat history of a user. The chat history is not ordered in my firestore, so I want to (1) sort it from the most to the least recent in componentDidMount once I get the data via Redux props (this.props.profile.chats_history) and (2) set the field "chatlist" in the state of ChatBox to the sorted array. The problem is that it takes time for props to be received and when the array.sort() method was called the console reported that the array was undefined. I tried to get around it by using async and await keywords but my solution did not work.

My solution

    async componentDidMount() {
        let chatlist;
        await this.props.profile.chats_history;
        chatlist = this.props.profile.chats_history.sort(function(a, b) {return a.time - b.time});
        this.setState({
            chatlist: chatlist
        })
    }

Body:
You can use getDerivedStateFromProps instead.

static getDerivedStateFromProps(props, state) {
    const sortedChat = props.profile.chats_history?[...props.profile.chats_history].sort((a,b)=>{/*logic*/}):[]
    return { sortedChat };
}

You can optimize your renders by comparing the current data in state and received data in props. That depends on your data again. Personally, I'd keep a timestamp in profile.chats and only update the state when timestamp changes. Also, sort changes the original array order. So, clone before you sort like I did above.


问:
How do I find the source code for a method in Pandas?
The following is the GitHub link for Python's Pandas package.

https://github.com/pandas-dev/pandas

I would like to find the source code for a specific method (for instance, iterrows). What would be the file path for this?

答: This site and this one have a button with a link (source). I usually just google the method I need and add the word source


问:
Stata and global variables
I am working with Stata.
I have a variable called graduate_secondary.
I generate a global variable called outcome, because eventually I will use another outcome.
Now I want to replace  the variable graduate if a condition relative to global is met, but I get an error:

My code is:

```<code>global outcome "graduate_secondary"

gen graduate=.

replace graduate=1 if graduate_primary==1 & `outcome'==1
</code>```

But i receive the symbol ==1 invalid name.
Does anyone know why?

答:
Something along those lines might work (using a reproducible example):

```<code>sysuse auto, clear
global outcome "rep78"

gen graduate=.

replace graduate=1 if mpg==22 & $outcome==3
(2 real changes made)
</code>```

In your example, just use

```<code>replace graduate=1 if graduate_primary==1 & $outcome==1
</code>```

would work.

Title: Stata and global variables

Body:
I am working with Stata.
I have a variable called graduate_secondary.
I generate a global variable called outcome, because eventually I will use another outcome.
Now I want to replace  the variable graduate if a condition relative to global is met, but I get an error:

My code is:

global outcome "graduate_secondary"

gen graduate=.

replace graduate=1 if graduate_primary==1 & `outcome'==1

But i receive the symbol ==1 invalid name.
Does anyone know why?

Body:
Something along those lines might work (using a reproducible example):

sysuse auto, clear
global outcome "rep78"

gen graduate=.

replace graduate=1 if mpg==22 & $outcome==3
(2 real changes made)

In your example, just use

replace graduate=1 if graduate_primary==1 & $outcome==1

would work.


问:
Deep cloning of inside-out Perl classes - how to use methods from copied objects?
I have 3 classes declared as inside-out Perl classes using Class::Std. In one of these 3, there's a hash reference stored in $basket{ident $self} that looks like so (output of Data::Dumper):

```<code>$VAR1 = {
          'auto' => {
                      'items' => {
                                   'abc' => bless( do{\(my $o = undef)}, 'Item' )
                                 },
                      'obj' => bless( do{\(my $o = undef)}, 'Category' )
                    }
        };
</code>```

I need to take this hash reference and create everything in it again (deep cloning). I tried to use dclone from Storable like so:

```<code>my $new_basket = dclone $basket{ident $self};
</code>```

When I print the hashes, I get different memory addresses:

```<code>print $new_basket, "\n";
print $basket{ident $self}, "\n";
print $new_basket->{auto}->{items}, "\n";
print $basket{ident $self}{auto}->{items}, "\n";
print $new_basket->{auto}->{items}->{abc}, "\n";
print $basket{ident $self}{auto}->{items}->{abc}, "\n";
</code>```

this will output:

```<code>HASH(0x55d325306a20)
HASH(0x55d325245298)
HASH(0x55d323b35ca8)
HASH(0x55d3243dd968)
Item=SCALAR(0x55d323b45190)
Item=SCALAR(0x55d325306588)
</code>```

When I don't use dclone and use my $new_basket = $basket{ident $self} instead, I get the same memory addresses. When I use my $new_basket = { %{ $basket{ident $self} } }, I get different addresses only on the first level, which should be a shallow copy. All this seems fine and expected.

So, to me it seems that dclone actually deep-copied everything because the addresses are different. But when I try to use a method inside Item like so:

```<code>print $new_basket->{auto}->{items}->{abc}->get_added_on();
print $basket{ident $self}{auto}->{items}->{abc}->get_added_on();
</code>```

I get:

```<code>Use of uninitialized value in print at lib/Basket.pm line 231.
2020-05-30
</code>```

clearly that dclone works differently than I naively thought.

How should I deep-copy this whole structure? I'd appreciate some help or reference to some article/doc where I can read what's going on here.

One solution is to create the whole structure again using constructors, but I thought I'd save some space and use dclone. That obviously didn't turn out very well.

EDIT: I've been asked to provide a minimal runnable demonstration, here it is:

```<code>#!/usr/bin/env perl

use strict;
use warnings;

{
    package A;
    use Class::Std;
    use Data::Dumper;
    use Storable qw(dclone);

    my %basket :ATTR;

    sub BUILD {
        my ($self, $ident, $args_ref) = @_;
        $basket{$ident}->{auto} = {};

        my $c = C->new({ date => q{2020-05-30} });

        $basket{$ident}->{auto}->{items}->{abc} = $c;

        return;
    }

    sub deep_clone {
        my $self = shift;

        print Dumper $basket{ident $self};
        # the next line prints "2020-05-30" as expected
        print $basket{ident $self}->{auto}->{items}->{abc}->get_added_on();
        my $new_basket = dclone $basket{ident $self};
        # "Use of uninitialized value in print at ./deep-clone.pl line 35."
        print $new_basket->{auto}->{items}->{abc}->get_added_on();
    }
}

{
    package C;
    use Class::Std;

    my %added_on :ATTR( :get<added_on> );

    sub BUILD {
        my ($self, $ident, $args_ref) = @_;

        $added_on{$ident} = $args_ref->{date};

        return;
    }
}

####

my $a = A->new();
$a->deep_clone();
</code>```

答:
The newly created "C" object was never added to %added_on.

Your classes will have to provide custom handlers for Storable to handle them.

Added to "A":

sub STORABLE_freeze {
    my ($self, $cloning) = @_;
    my $ident = ident($self);
    return "", {
        basket => $basket{$ident},
        # Other attributes...
    };
}

sub STORABLE_thaw {
    my ($self, $cloning, $serialized, $inner) = @_;
    my $ident = ident($self);
    $basket{$ident} = $inner->{basket};
    # Other attributes...
}
```

<p>Added to "C":</p>

<pre class="lang-perl prettyprint-override"><code>sub STORABLE_freeze {
    my ($self, $cloning) = @_;
    my $ident = ident($self);
    return "", {
        added_on => $added_on{$ident},
        # Other attributes...
    };
}

sub STORABLE_thaw {
    my ($self, $cloning, $serialized, $inner) = @_;
    my $ident = ident($self);
    $added_on{$ident} = $inner->{added_on};
    # Other attributes...
}
</code>```

Then you can use freeze/thaw/dclone without problem.

sub deep_clone {
    my $self = shift;

    #print Dumper $basket{ident $self};
    CORE::say $basket{ ident $self  }{auto}{items}{abc}->get_added_on();

    my $clone = dclone($self);

    #print Dumper $basket{ident $self};
    CORE::say $basket{ ident $clone }{auto}{items}{abc}->get_added_on();
}
```

Body:
I have 3 classes declared as inside-out Perl classes using Class::Std. In one of these 3, there's a hash reference stored in $basket{ident $self} that looks like so (output of Data::Dumper):

$VAR1 = {
          'auto' => {
                      'items' => {
                                   'abc' => bless( do{\(my $o = undef)}, 'Item' )
                                 },
                      'obj' => bless( do{\(my $o = undef)}, 'Category' )
                    }
        };

I need to take this hash reference and create everything in it again (deep cloning). I tried to use dclone from Storable like so:

my $new_basket = dclone $basket{ident $self};

When I print the hashes, I get different memory addresses:

print $new_basket, "\n";
print $basket{ident $self}, "\n";
print $new_basket->{auto}->{items}, "\n";
print $basket{ident $self}{auto}->{items}, "\n";
print $new_basket->{auto}->{items}->{abc}, "\n";
print $basket{ident $self}{auto}->{items}->{abc}, "\n";

this will output:

HASH(0x55d325306a20)
HASH(0x55d325245298)
HASH(0x55d323b35ca8)
HASH(0x55d3243dd968)
Item=SCALAR(0x55d323b45190)
Item=SCALAR(0x55d325306588)

When I don't use dclone and use my $new_basket = $basket{ident $self} instead, I get the same memory addresses. When I use my $new_basket = { %{ $basket{ident $self} } }, I get different addresses only on the first level, which should be a shallow copy. All this seems fine and expected.

So, to me it seems that dclone actually deep-copied everything because the addresses are different. But when I try to use a method inside Item like so:

print $new_basket->{auto}->{items}->{abc}->get_added_on();
print $basket{ident $self}{auto}->{items}->{abc}->get_added_on();

I get:

Use of uninitialized value in print at lib/Basket.pm line 231.
2020-05-30

clearly that dclone works differently than I naively thought.

How should I deep-copy this whole structure? I'd appreciate some help or reference to some article/doc where I can read what's going on here.

One solution is to create the whole structure again using constructors, but I thought I'd save some space and use dclone. That obviously didn't turn out very well.

EDIT: I've been asked to provide a minimal runnable demonstration, here it is:

#!/usr/bin/env perl

use strict;
use warnings;

{
    package A;
    use Class::Std;
    use Data::Dumper;
    use Storable qw(dclone);

    my %basket :ATTR;

    sub BUILD {
        my ($self, $ident, $args_ref) = @_;
        $basket{$ident}->{auto} = {};

        my $c = C->new({ date => q{2020-05-30} });

        $basket{$ident}->{auto}->{items}->{abc} = $c;

        return;
    }

    sub deep_clone {
        my $self = shift;

        print Dumper $basket{ident $self};
        # the next line prints "2020-05-30" as expected
        print $basket{ident $self}->{auto}->{items}->{abc}->get_added_on();
        my $new_basket = dclone $basket{ident $self};
        # "Use of uninitialized value in print at ./deep-clone.pl line 35."
        print $new_basket->{auto}->{items}->{abc}->get_added_on();
    }
}

{
    package C;
    use Class::Std;

    my %added_on :ATTR( :get<added_on> );

    sub BUILD {
        my ($self, $ident, $args_ref) = @_;

        $added_on{$ident} = $args_ref->{date};

        return;
    }
}

####

my $a = A->new();
$a->deep_clone();

Body:
The newly created "C" object was never added to %added_on.

Your classes will have to provide custom handlers for Storable to handle them.

Added to "A":

sub STORABLE_freeze {
    my ($self, $cloning) = @_;
    my $ident = ident($self);
    return "", {
        basket => $basket{$ident},
        # Other attributes...
    };
}

sub STORABLE_thaw {
    my ($self, $cloning, $serialized, $inner) = @_;
    my $ident = ident($self);
    $basket{$ident} = $inner->{basket};
    # Other attributes...
}

Added to "C":

sub STORABLE_freeze {
    my ($self, $cloning) = @_;
    my $ident = ident($self);
    return "", {
        added_on => $added_on{$ident},
        # Other attributes...
    };
}

sub STORABLE_thaw {
    my ($self, $cloning, $serialized, $inner) = @_;
    my $ident = ident($self);
    $added_on{$ident} = $inner->{added_on};
    # Other attributes...
}

Then you can use freeze/thaw/dclone without problem.

sub deep_clone {
    my $self = shift;

    #print Dumper $basket{ident $self};
    CORE::say $basket{ ident $self  }{auto}{items}{abc}->get_added_on();

    my $clone = dclone($self);

    #print Dumper $basket{ident $self};
    CORE::say $basket{ ident $clone }{auto}{items}{abc}->get_added_on();
}


问:
Single perceptron keeps outputting values close 0.5
I am trying to create the simplest perception there is with just one neuron (neuron takes 2 input values and * them by weights then + bias and activate the SUM of them with (1 / (1 + Math.exp(-x))) sigmoid function ) and train it via backpropagation (get an error by subtracting expected value from the output I gain, find gradient and weight delta by which we multiply the difference between wight and input value), but after the first iteration, my weights get really close to 0 and start producing a sigmoid(0) which is 0.5 (it always produces values from 0.48 to 0.52 or close.

```<code>class Neuron {constructor(){
    this.inputs = [1,1];
    this.inputWeights = [(Math.random()*2)-1,(Math.random()*2)-1];
    this.bias = 0.1;
    this.activate = () => {
        if(this.inputs.length !== this.inputWeights.length)return "Wrong input length";
        let sum = 0;
        for(var n = 0; n < this.inputs.length;n++){
        sum = sum + (this.inputs[n]*this.inputWeights[n]);
        }
        sum = sum + this.bias;
        //return sigmoid activated value
        let activated_output = (1 / (1 + Math.exp(-sum)));
        return activated_output;
    };
    this.error = (predicted,desired) => {
        let error = predicted - desired;
        let gradient = predicted * (1-predicted);
        let weights_delta = error * gradient;
        return weights_delta;
    };
    this.changeWeights = (weights_delta) => {
        let info = this.inputWeights[0];
        for(var n = 0; n < this.inputWeights.length; n++){
            this.inputWeights[n] = (this.inputWeights[n] - this.inputs[n])  * weights_delta * learning_rate;
        }
        return "first weight changed from " + info + " to " + this.inputWeights[0];
    }
}}
var testNeuron = new Neuron();
var learning_rate = 0.05;
var dataset = [
{ inputs: [1,0], outputs: [1] },
{ inputs: [0,1], outputs: [0] },
{ inputs: [0.5,0.1], outputs: [1] },
{ inputs: [0.1,0.9], outputs: [0] }];
//train
var train = (iterations, data) => {
  for(var i = 0; i < iterations; i++){
    for(var n = 0; n < data.length; n++){
    testNeuron.inputs = data[n].inputs;
    console.log(testNeuron.changeWeights(testNeuron.error(testNeuron.activate() ,
data[n].outputs[0])));
    }
  }
}
train(10,dataset);
</code>```

Here is all the code, I tryed it with and without biases but i feel my math is definitely wrong but I could not figure out where because I'm a noob..halp sirs

答:
The biggest error was that I didn't use any bias input, and did not adjust weights for it. If we don't use bias then a simple input like 0,0 will ALWAYS return 0 and there is no way to adjust weights for output to change.

Second, if we looking at simple Perceptron we should be using a threshold function and not a sigmoid.(although sigmoid is possible but imo slower in this example) Thresh hold function is a simple function that returns 0 if output is negative and 1 if it's positive.
 My redone and working code looks like this, increasing training iteration results in a decrease of error just like it should, Thank you

```<code>class Perceptron{constructor(){
    //bias , input1, input2
    this.inputs = [1,0,0];
    this.inputWeights = [(Math.random()*2)-1,(Math.random()*2)-1,(Math.random()*2)-1];
    this.output = 0;
    this.desiredOutput = 0;
}//perceptron methods
    activate = () => {
        let sum = 0;
        for(var n = 0; n < this.inputs.length; n++){
            sum += this.inputs[n] * this.inputWeights[n];
        };
        this.output = sum < 0 ? 0 : 1;
        this.desiredOutput == this.output ? console.log("Correct answer") : console.log("Incorrect answer");
    };
    propagate = () => {
        let error = this.desiredOutput - this.output;
        for(var m = 0; m < this.inputs.length; m++){
            let delta = error * this.inputs[m];
            this.inputWeights[m] = this.inputWeights[m] + (delta * learningRate);
        }
    };
}
let learningRate = 0.1;
var train = (iterations) => {
    for(var x = 0; x < iterations; x++){
        for(var y = 0; y < dataset.length; y++){
        perception.inputs = [1,dataset[y][0],dataset[y][1]];
        perception.desiredOutput = dataset[y][2];
        perception.activate();
        perception.propagate();
        }
    }
}
var perception = new Perceptron();
//[input1 , input2 , desiredOutput]
var dataset = [
    [0,0,1],
    [1,1,0],
    [0.1,0.3,1],
    [1.5,1.8,0]
];
train(100);
</code>```

Body:
I am trying to create the simplest perception there is with just one neuron (neuron takes 2 input values and * them by weights then + bias and activate the SUM of them with (1 / (1 + Math.exp(-x))) sigmoid function ) and train it via backpropagation (get an error by subtracting expected value from the output I gain, find gradient and weight delta by which we multiply the difference between wight and input value), but after the first iteration, my weights get really close to 0 and start producing a sigmoid(0) which is 0.5 (it always produces values from 0.48 to 0.52 or close.

class Neuron {constructor(){
    this.inputs = [1,1];
    this.inputWeights = [(Math.random()*2)-1,(Math.random()*2)-1];
    this.bias = 0.1;
    this.activate = () => {
        if(this.inputs.length !== this.inputWeights.length)return "Wrong input length";
        let sum = 0;
        for(var n = 0; n < this.inputs.length;n++){
        sum = sum + (this.inputs[n]*this.inputWeights[n]);
        }
        sum = sum + this.bias;
        //return sigmoid activated value
        let activated_output = (1 / (1 + Math.exp(-sum)));
        return activated_output;
    };
    this.error = (predicted,desired) => {
        let error = predicted - desired;
        let gradient = predicted * (1-predicted);
        let weights_delta = error * gradient;
        return weights_delta;
    };
    this.changeWeights = (weights_delta) => {
        let info = this.inputWeights[0];
        for(var n = 0; n < this.inputWeights.length; n++){
            this.inputWeights[n] = (this.inputWeights[n] - this.inputs[n])  * weights_delta * learning_rate;
        }
        return "first weight changed from " + info + " to " + this.inputWeights[0];
    }
}}
var testNeuron = new Neuron();
var learning_rate = 0.05;
var dataset = [
{ inputs: [1,0], outputs: [1] },
{ inputs: [0,1], outputs: [0] },
{ inputs: [0.5,0.1], outputs: [1] },
{ inputs: [0.1,0.9], outputs: [0] }];
//train
var train = (iterations, data) => {
  for(var i = 0; i < iterations; i++){
    for(var n = 0; n < data.length; n++){
    testNeuron.inputs = data[n].inputs;
    console.log(testNeuron.changeWeights(testNeuron.error(testNeuron.activate() ,
data[n].outputs[0])));
    }
  }
}
train(10,dataset);

Here is all the code, I tryed it with and without biases but i feel my math is definitely wrong but I could not figure out where because I'm a noob..halp sirs

Body:
The biggest error was that I didn't use any bias input, and did not adjust weights for it. If we don't use bias then a simple input like 0,0 will ALWAYS return 0 and there is no way to adjust weights for output to change.

Second, if we looking at simple Perceptron we should be using a threshold function and not a sigmoid.(although sigmoid is possible but imo slower in this example) Thresh hold function is a simple function that returns 0 if output is negative and 1 if it's positive.
 My redone and working code looks like this, increasing training iteration results in a decrease of error just like it should, Thank you

class Perceptron{constructor(){
    //bias , input1, input2
    this.inputs = [1,0,0];
    this.inputWeights = [(Math.random()*2)-1,(Math.random()*2)-1,(Math.random()*2)-1];
    this.output = 0;
    this.desiredOutput = 0;
}//perceptron methods
    activate = () => {
        let sum = 0;
        for(var n = 0; n < this.inputs.length; n++){
            sum += this.inputs[n] * this.inputWeights[n];
        };
        this.output = sum < 0 ? 0 : 1;
        this.desiredOutput == this.output ? console.log("Correct answer") : console.log("Incorrect answer");
    };
    propagate = () => {
        let error = this.desiredOutput - this.output;
        for(var m = 0; m < this.inputs.length; m++){
            let delta = error * this.inputs[m];
            this.inputWeights[m] = this.inputWeights[m] + (delta * learningRate);
        }
    };
}
let learningRate = 0.1;
var train = (iterations) => {
    for(var x = 0; x < iterations; x++){
        for(var y = 0; y < dataset.length; y++){
        perception.inputs = [1,dataset[y][0],dataset[y][1]];
        perception.desiredOutput = dataset[y][2];
        perception.activate();
        perception.propagate();
        }
    }
}
var perception = new Perceptron();
//[input1 , input2 , desiredOutput]
var dataset = [
    [0,0,1],
    [1,1,0],
    [0.1,0.3,1],
    [1.5,1.8,0]
];
train(100);


问:
How to make bot print embeds using JSON format
This is the code, I am trying to make it print embeds like the Carl-bot</p>

```<code>const Discord = require('discord.js')

module.exports.run = async (bot, message, args) => {
  if(message.deletable) message.delete();
  let message2 = args.join(" ")
  let embed1 = JSON.parse(message2);

  return message.channel.send({embed: embed1});
}

module.exports.config = {
  name: "say",
  description: "test",
  usage: "-say",
  accessableby: "Members",
  aliases: []
}
</code>```

答:
Not sure what you mean by json format, like initalizing it with json?

If so you can just do

const embed = new MessageEmbed({ author: "fff" })

If you mean making an embed and then filling the details with json you would first make an embed and then you can use the utility functions to set the data

From: https://discord.js.org/#/docs/main/stable/examples/embed

// Extract the required classes from the discord.js module
const { Client, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed()
 .setTitle('A slick little embed')
 .setColor(0xff0000)
 .setDescription('Hello, this is a slick embed!');
 message.channel.send(embed);
```

Complete Docs: https://discord.js.org/#/docs/main/stable/class/MessageEmbed

Body:
This is the code, I am trying to make it print embeds like the Carl-bot

const Discord = require('discord.js')

module.exports.run = async (bot, message, args) => {
  if(message.deletable) message.delete();
  let message2 = args.join(" ")
  let embed1 = JSON.parse(message2);

  return message.channel.send({embed: embed1});
}

module.exports.config = {
  name: "say",
  description: "test",
  usage: "-say",
  accessableby: "Members",
  aliases: []
}

Body:
Not sure what you mean by json format, like initalizing it with json?

If so you can just do

const embed = new MessageEmbed({ author: "fff" })

If you mean making an embed and then filling the details with json you would first make an embed and then you can use the utility functions to set the data

From: https://discord.js.org/#/docs/main/stable/examples/embed

// Extract the required classes from the discord.js module
const { Client, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed()
 .setTitle('A slick little embed')
 .setColor(0xff0000)
 .setDescription('Hello, this is a slick embed!');
 message.channel.send(embed);

Complete Docs: https://discord.js.org/#/docs/main/stable/class/MessageEmbed


问:
how to deploy web.config modifications in a Sharepoint web application?
I have a website in Sharepoint 2007. We use a wsp to deploy our projects. We can deploy dlls, usercontrols, features, but i don't know how to include new lines in the web.config.

Which would be a possible way to make changes in web.config?

Another thing, how can I include resources (resx) in the wsp?

答:
Regarding web.config files...

Web.config is an XML document that contains configuration settings for a web application. It's located in the root directory of a web application, so for SharePoint, it's usually located in the folder C:\Inetpub\wwwroot\wss\VirtualDirectories\SharePoint80, where SharePoint80 is the name of your web application.

Manually making edits to the web.config file is safe as long as you keep the the tags and sections in the right order. Look at this article.

It's also possible to make changes to it programatically, this post should show you how.

Hope this helps.

OwnerDisplayName: netadictos

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dstetsenko


问:
javascript draw image into html from buffer (nodejs/socket.io)
(sorry for my english)
Hi, i have an appplication created with nodejs to push image data into a webpage.

the data from nodejs server is pushed into webpage using socket.io

This data is the complete image, i try to write to disc to see the image and is good.
The data is put into a buffer to encode in base64 then send to the webpage and i try to show using
'data:image/png;base64,'+data
but nothing happend... The data seems to be "complete" including the headers of the PNG image.

The server use thrift to communicate with another client (this in C++), this client create the images and send to the nodejs-thrift server, when a image is receive, the nodejs-socket.io server push into webpage.

some code:
serverside

```<code>var http = require('http'),
url = require('url'),
fs  = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
   case '/':

        fs.readFile(__dirname + '/index.html',function(err,data){
           if(err) return send404(res);
           response.writeHead(200,{'Content-Type':'text/html'});
           response.write(data,'utf8');
           response.end();
        });
    break;
    default: send404(response);
}
   }),
send404 = function(res){
 res.writeHead(404);
 res.write('404');
 res.end();
};

hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
    data: buff.toString('base64'),
    width: image.width,
    height: image.height
});
success(true);
}
</code>```

In the webpage i try to load the image using the on.message callback of socket.io

```<code><script>
var socket = new io.Socket(null,{port:8080});
socket.connect();
socket.on('message',function(obj){
        document.getElementById('imagenes').src='data:image/png;base64,'+obj.data.toString();
});
socket.on('connect',function(){
    document.getElementById('stream').innerHTML = "Conectado!"
});
</script>
</code>```

But i can't see the image..
The obj.data.toString('base64') create a string like this:

```<code> PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
 .............
 /NIlWDHUDmIPdHIEND
</code>```

is the all data of the image..

how can i show the image?? (maybe using img tag or into canvas)

Thanks in advance.

EDIT: Some changes to code, but nothing change.. my guess.. the image don't show because the data (PNGIHDRKIDATxYw......PdHIENDB) isn't the correct data.. i search about this and the png data used to show images inline is diferent (without the header PNGIHDRKIDAT and the tail ENDB), i remove the header and tail and don't show .. maybe the data i receive isn't correct, but if i try to write to filesystem in the server side using nodejs (fs) i get the correct images (with fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ) using binary encode, but with base64 encode theres no image.

答:
Your client side code looks fine (except for the fact that .toString('base64') doesn't do anything to a String object whilst in-browser, only to Buffer objects in node), I'm making a guess that the problem is in receiveImage, which should be:

```<code>var receiveImage = function(image,success) {
    socket.broadcast({
        data: image.data.toString('base64'),
        width: image.width,
        height:image.height
    });
    success(true);
}
</code>```

Body:
(sorry for my english)
Hi, i have an appplication created with nodejs to push image data into a webpage.

the data from nodejs server is pushed into webpage using socket.io

This data is the complete image, i try to write to disc to see the image and is good.
The data is put into a buffer to encode in base64 then send to the webpage and i try to show using
'data:image/png;base64,'+data
but nothing happend... The data seems to be "complete" including the headers of the PNG image.

The server use thrift to communicate with another client (this in C++), this client create the images and send to the nodejs-thrift server, when a image is receive, the nodejs-socket.io server push into webpage.

some code:
serverside

var http = require('http'),
url = require('url'),
fs  = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
   case '/':

        fs.readFile(__dirname + '/index.html',function(err,data){
           if(err) return send404(res);
           response.writeHead(200,{'Content-Type':'text/html'});
           response.write(data,'utf8');
           response.end();
        });
    break;
    default: send404(response);
}
   }),
send404 = function(res){
 res.writeHead(404);
 res.write('404');
 res.end();
};

hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
    data: buff.toString('base64'),
    width: image.width,
    height: image.height
});
success(true);
}

In the webpage i try to load the image using the on.message callback of socket.io

But i can't see the image..
The obj.data.toString('base64') create a string like this:

 PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
 .............
 /NIlWDHUDmIPdHIEND

is the all data of the image..

how can i show the image?? (maybe using img tag or into canvas)

Thanks in advance.

EDIT: Some changes to code, but nothing change.. my guess.. the image don't show because the data (PNGIHDRKIDATxYw......PdHIENDB) isn't the correct data.. i search about this and the png data used to show images inline is diferent (without the header PNGIHDRKIDAT and the tail ENDB), i remove the header and tail and don't show .. maybe the data i receive isn't correct, but if i try to write to filesystem in the server side using nodejs (fs) i get the correct images (with fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ) using binary encode, but with base64 encode theres no image.

Body:
Your client side code looks fine (except for the fact that .toString('base64') doesn't do anything to a String object whilst in-browser, only to Buffer objects in node), I'm making a guess that the problem is in receiveImage, which should be:

var receiveImage = function(image,success) {
    socket.broadcast({
        data: image.data.toString('base64'),
        width: image.width,
        height:image.height
    });
    success(true);
}


问:
regex from scraped data using lookaround not working
I'm trying to figure out why one of my regex commands works but the other doesn't. Here's a sample of two strings it would pull from. There is consistency in the new line garbage which resulted from the scrape so I used that to my advantage as best I could:

```<code>"\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm,
97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"

"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Guard\n\n\n\n  6-9, 225lb (206cm,
102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n
School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"
</code>```

My goal is to pull desired data from this such as position (Forward, Guard respectively) and most importantly, height (6-5, 6-9, respectively). I had success pulling the position with the following:

```<code>test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)"))
</code>```

But when I follow a similar lookaround to add another col for height, it returns NA:

```<code>test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)")) %>%
  mutate(height = str_extract(player, "(?<=\\w+\n\n\n\n  ).*?(?=, \\d{3}lb)"))
</code>```

Here is a sample of the result from above call on the first 3 rows of my df if it's helpful:

```<code>structure(list(player = c("\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm, 97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-9, 225lb (206cm, 102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n  School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tKarl Aaker\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 210lb (196cm, 95kg) \n  \n\n  Hometown: Reno, NV\n\n\n\n  \n\n  \n  \n  \n\n  School: Portland\n\n\n\n\n\n  More player info\n\n\n\n\n\n"
), position = c("Forward", "Forward", "Forward"), height = c(NA_character_,
NA_character_, NA_character_)), row.names = c(NA, 3L), class = "data.frame")
</code>```

答:
You may remove + after \w since ICU regex engine does not support unlimited length string matching patterns inside lookbehinds, and use \s to match any whitespaces:

```<code>test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)")) %>%
  mutate(height = str_extract(player, "(?<=\\w\n{4}\\s{2}).*?(?=,\\s+\\d{3}lb)"))
</code>```

See the regex demo

Details

(?<=\w\n{4}\s{2}) - immediately before the match, there should be a word char, then 4 newline chars and then any 2 whitespace chars

.*? - any 0 or more chars other than line break chars as few as possible

(?=,\s+\d{3}lb) - immediately after the match, there should be a comma, one or more whitespace chars, 3 digits and lb substring.

Body:
I'm trying to figure out why one of my regex commands works but the other doesn't. Here's a sample of two strings it would pull from. There is consistency in the new line garbage which resulted from the scrape so I used that to my advantage as best I could:

"\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm,
97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"

"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Guard\n\n\n\n  6-9, 225lb (206cm,
102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n
School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"

My goal is to pull desired data from this such as position (Forward, Guard respectively) and most importantly, height (6-5, 6-9, respectively). I had success pulling the position with the following:

test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)"))

But when I follow a similar lookaround to add another col for height, it returns NA:

test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)")) %>%
  mutate(height = str_extract(player, "(?<=\\w+\n\n\n\n  ).*?(?=, \\d{3}lb)"))

Here is a sample of the result from above call on the first 3 rows of my df if it's helpful:

structure(list(player = c("\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm, 97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-9, 225lb (206cm, 102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n  School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tKarl Aaker\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 210lb (196cm, 95kg) \n  \n\n  Hometown: Reno, NV\n\n\n\n  \n\n  \n  \n  \n\n  School: Portland\n\n\n\n\n\n  More player info\n\n\n\n\n\n"
), position = c("Forward", "Forward", "Forward"), height = c(NA_character_,
NA_character_, NA_character_)), row.names = c(NA, 3L), class = "data.frame")

Body:
You may remove + after \w since ICU regex engine does not support unlimited length string matching patterns inside lookbehinds, and use \s to match any whitespaces:

test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)")) %>%
  mutate(height = str_extract(player, "(?<=\\w\n{4}\\s{2}).*?(?=,\\s+\\d{3}lb)"))

See the regex demo

Details

(?<=\w\n{4}\s{2}) - immediately before the match, there should be a word char, then 4 newline chars and then any 2 whitespace chars

.*? - any 0 or more chars other than line break chars as few as possible

(?=,\s+\d{3}lb) - immediately after the match, there should be a comma, one or more whitespace chars, 3 digits and lb substring.