问:
Doctesting functions that receive and display user input - Python (tearing my hair out)
I am currently writing a small application with Python (3.1), and like a good little boy, I am doctesting as I go. However, I've come across a method that I can't seem to doctest. It contains an input(), an because of that, I'm not entirely sure what to place in the "expecting" portion of the doctest.

Example code to illustrate my problem follows:

```<code>"""
>>> getFiveNums()
Howdy. Please enter five numbers, hit <enter> after each one
Please type in a number:
Please type in a number:
Please type in a number:
Please type in a number:
Please type in a number:
"""

import doctest

numbers = list()

# stores 5 user-entered numbers (strings, for now) in a list
def getFiveNums():
    print("Howdy. Please enter five numbers, hit <enter> after each one")
    for i in range(5):
        newNum = input("Please type in a number:")
        numbers.append(newNum)
    print("Here are your numbers: ", numbers)

if __name__ == "__main__":
    doctest.testmod(verbose=True)
</code>```

When running the doctests, the program stops executing immediately after printing the "Expecting" section, waits for me to enter five numbers one after another (without prompts), and then continues. As shown below:

I don't know what, if anything, I can place in the Expecting section of my doctest to be able to test a method that receives and then displays user input. So my question (finally) is, is this function doctestable?

答:
Here's a work-around I came up with.  It's a bit kludgy, but it works when only one line of input is needed:

```<code>def capitalize_name():
    """
    >>> import io, sys ; sys.stdin = io.StringIO("Bob")  # input
    >>> capitalize_name()
    What is your name?  Your name is BOB!
    """
    name = input('What is your name?  ')
    print('Your name is ' + name.upper() + '!')
</code>```

Unfortunately, it complains when the input contains a newline (for example, "Bob\nAlice").  I suspect that this is due to the doctest parser being overwhelmed (but I can't say for sure).

You can get around the "\n" issue by using chr(10) instead, like this:

```<code># stores 5 user-entered numbers (strings, for now) in a list
def getFiveNums():
    """
    >>> import io, sys ; sys.stdin = io.StringIO(chr(10).join(['1','2','3','4','5']))  # input
    >>> getFiveNums()
    Howdy. Please enter five numbers, hit <enter> after each one
    Please type in a number:Please type in a number:Please type in a number:Please type in a number:Please type in a number:Here are your numbers:  ['1', '2', '3', '4', '5']
    """
    print("Howdy. Please enter five numbers, hit <enter> after each one")
    numbers = []
    for _ in range(5):
        newNum = input("Please type in a number:")
        numbers.append(newNum)
    print("Here are your numbers: ", numbers)
</code>```

This is even more kludgy, but it does work.  You need to remember that all the prompting text (via the input() function) is displayed as output without the accompanying user input.  (That's why "Please type in a number:" appears five times in a row with no spaces or newlines between its instances.)

And while this solution does work, keep in mind that it's harder to read and maintain than some of the other given solutions.  That's something to consider when making your decision on which approach to use.

Body:
I am currently writing a small application with Python (3.1), and like a good little boy, I am doctesting as I go. However, I've come across a method that I can't seem to doctest. It contains an input(), an because of that, I'm not entirely sure what to place in the "expecting" portion of the doctest.

Example code to illustrate my problem follows:

"""
>>> getFiveNums()
Howdy. Please enter five numbers, hit <enter> after each one
Please type in a number:
Please type in a number:
Please type in a number:
Please type in a number:
Please type in a number:
"""

import doctest

numbers = list()

# stores 5 user-entered numbers (strings, for now) in a list
def getFiveNums():
    print("Howdy. Please enter five numbers, hit <enter> after each one")
    for i in range(5):
        newNum = input("Please type in a number:")
        numbers.append(newNum)
    print("Here are your numbers: ", numbers)

if __name__ == "__main__":
    doctest.testmod(verbose=True)

When running the doctests, the program stops executing immediately after printing the "Expecting" section, waits for me to enter five numbers one after another (without prompts), and then continues. As shown below:

I don't know what, if anything, I can place in the Expecting section of my doctest to be able to test a method that receives and then displays user input. So my question (finally) is, is this function doctestable?

Body:
Here's a work-around I came up with.  It's a bit kludgy, but it works when only one line of input is needed:

def capitalize_name():
    """
    >>> import io, sys ; sys.stdin = io.StringIO("Bob")  # input
    >>> capitalize_name()
    What is your name?  Your name is BOB!
    """
    name = input('What is your name?  ')
    print('Your name is ' + name.upper() + '!')

Unfortunately, it complains when the input contains a newline (for example, "Bob\nAlice").  I suspect that this is due to the doctest parser being overwhelmed (but I can't say for sure).

You can get around the "\n" issue by using chr(10) instead, like this:

# stores 5 user-entered numbers (strings, for now) in a list
def getFiveNums():
    """
    >>> import io, sys ; sys.stdin = io.StringIO(chr(10).join(['1','2','3','4','5']))  # input
    >>> getFiveNums()
    Howdy. Please enter five numbers, hit <enter> after each one
    Please type in a number:Please type in a number:Please type in a number:Please type in a number:Please type in a number:Here are your numbers:  ['1', '2', '3', '4', '5']
    """
    print("Howdy. Please enter five numbers, hit <enter> after each one")
    numbers = []
    for _ in range(5):
        newNum = input("Please type in a number:")
        numbers.append(newNum)
    print("Here are your numbers: ", numbers)

This is even more kludgy, but it does work.  You need to remember that all the prompting text (via the input() function) is displayed as output without the accompanying user input.  (That's why "Please type in a number:" appears five times in a row with no spaces or newlines between its instances.)

And while this solution does work, keep in mind that it's harder to read and maintain than some of the other given solutions.  That's something to consider when making your decision on which approach to use.


来源: stackexchange

问:
Creating derived class instance using base class instance
I have a base class instance, there is a derived class that inherits from the base class, I want to transform the base instance into derived instance, (if possible without copying anything (maybe sending to the derived class a reference of the base class)) how can I achieve that?

Note: I need this because I'm using factory design pattern which identify the derived class needed to be created using a parameter located in the base instance.

```<code>//class A
//class B: public A (pure virtual)
//class C: public B

B BFactory::makeB(A &a) {
    int n=a.getN();
    if(n==1){
        return new C();
    }
}
</code>```

Thanks.

答:
You might want to define a constructor that takes the base class instance as the argument so you can later use static_cast to convert from the base class to the derived class.

```<code>class Derived : public Base
{
public:
  Derived(const Base& base) : Base{base} {}
};

int main()
{
  Base a;
  Derived b = static_cast<Derived>(a);
}
</code>```

If you want to create a derived class instance using the base class instance then there is some conversion rule between the two, which you can specify explicitly using a derived class constructor.

ContentLicense: CC BY-SA 3.0

Body:
I have a base class instance, there is a derived class that inherits from the base class, I want to transform the base instance into derived instance, (if possible without copying anything (maybe sending to the derived class a reference of the base class)) how can I achieve that?

Note: I need this because I'm using factory design pattern which identify the derived class needed to be created using a parameter located in the base instance.

//class A
//class B: public A (pure virtual)
//class C: public B

B BFactory::makeB(A &a) {
    int n=a.getN();
    if(n==1){
        return new C();
    }
}

Thanks.

Body:
You might want to define a constructor that takes the base class instance as the argument so you can later use static_cast to convert from the base class to the derived class.

class Derived : public Base
{
public:
  Derived(const Base& base) : Base{base} {}
};

int main()
{
  Base a;
  Derived b = static_cast<Derived>(a);
}

If you want to create a derived class instance using the base class instance then there is some conversion rule between the two, which you can specify explicitly using a derived class constructor.

ContentLicense: CC BY-SA 4.0


问:
Vue-CLI 3.0 - how can I change the production links?
By default in dist/index.html created such links:

```<code><link href=/js/app.2e806e0c.js rel=preload as=script>
<link href=/js/chunk-vendors.bc9ee6a2.js rel=preload as=script>
<link href=/css/chunk-vendors.fc712ce5.css rel=stylesheet>
<link href=/css/app.64eef18a.css rel=stylesheet>
<script src=/js/chunk-vendors.bc9ee6a2.js></script>
<script src=/js/app.2e806e0c.js></script>
</code>```

How can I change links to this?

```<code><link href=js/app.2e806e0c.js rel=preload as=script>
<link href=js/chunk-vendors.bc9ee6a2.js rel=preload as=script>
<link href=css/chunk-vendors.fc712ce5.css rel=stylesheet>
<link href=css/app.64eef18a.css rel=stylesheet>
<script src=js/chunk-vendors.bc9ee6a2.js></script>
<script src=js/app.2e806e0c.js></script>
</code>```

答:
Following answer by @yuriy636, baseUrl is now deprecated, you should use publicPath instead:

```<code>module.exports = {
  publicPath: ""
};
</code>```

Body:
By default in dist/index.html created such links:

<link href=/js/app.2e806e0c.js rel=preload as=script>
<link href=/js/chunk-vendors.bc9ee6a2.js rel=preload as=script>
<link href=/css/chunk-vendors.fc712ce5.css rel=stylesheet>
<link href=/css/app.64eef18a.css rel=stylesheet>

How can I change links to this?

<link href=js/app.2e806e0c.js rel=preload as=script>
<link href=js/chunk-vendors.bc9ee6a2.js rel=preload as=script>
<link href=css/chunk-vendors.fc712ce5.css rel=stylesheet>
<link href=css/app.64eef18a.css rel=stylesheet>

Body:
Following answer by @yuriy636, baseUrl is now deprecated, you should use publicPath instead:

module.exports = {
  publicPath: ""
};


问:
How to show notification from broadcast receiver?
I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?

This is Service:

```<code>public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final int NOTIF_ID = 1;

@Override
public void onCreate() {

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
    mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
    registerReceiver(mReceiver, filter);
    super.onCreate();

}
private void startForeground() {
    startForeground(NOTIF_ID, getMyActivityNotification(""));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.startForeground();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {

    if (mReceiver != null) {
        unregisterReceiver(mReceiver);
        mReceiver = null;

        Log.i("onDestroy Reciever", "Called");

    }
    super.onDestroy();

}

public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}

private Notification getMyActivityNotification(String text) {

    CharSequence title = "new";

    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.abc)
                .setContentTitle("Service running")
                .setContentText("new")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();

    }
    return notification;
}
     /*  public void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIF_ID, notification);
      }*/

   }
</code>```

And this is broadcast receiver:

```<code>public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();

private final static String TAG = "LocationProviderChanged";

boolean isGpsEnabled;
boolean isNetworkEnabled;
@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        Log.i(TAG, "Location Providers changed");

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //Start your Activity if location was enabled:
        if (isGpsEnabled || isNetworkEnabled) {

            Log.i(TAG, "Location Providers on");
       }

       else {

              Log.i(TAG, "Location Providers off");
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
                String channelName = "My Background Service";
                NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                chan.setLightColor(Color.BLUE);
                chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(chan);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, notification);

            }
        }
    }
</code>```

I can see logcat messages on changing location status but notification is not created

答:
Changing notification code to this solved the problem       </p>

```<code>          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = "
            com.example.fizatanveerkhan.citycops";
                CharSequence name =  "My Background Service";
                String description =  "My Background Service";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
                channel.setDescription(description);
                // Register the channel with the system; you can't change the importance
                // or other notification behaviors after this
                NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManagerCompat notificationManagerq =
           NotificationManagerCompat.from(context);

        // notificationId is a unique int for each notification that you must define
                notificationManagerq.notify(1, notificationBuilder.build());

                   }
</code>```

Body:
I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?

This is Service:

public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final int NOTIF_ID = 1;

@Override
public void onCreate() {

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
    mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
    registerReceiver(mReceiver, filter);
    super.onCreate();

}
private void startForeground() {
    startForeground(NOTIF_ID, getMyActivityNotification(""));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.startForeground();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {

    if (mReceiver != null) {
        unregisterReceiver(mReceiver);
        mReceiver = null;

        Log.i("onDestroy Reciever", "Called");

    }
    super.onDestroy();

}

public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}

private Notification getMyActivityNotification(String text) {

    CharSequence title = "new";

    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.abc)
                .setContentTitle("Service running")
                .setContentText("new")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();

    }
    return notification;
}
     /*  public void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIF_ID, notification);
      }*/

   }

And this is broadcast receiver:

public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();

private final static String TAG = "LocationProviderChanged";

boolean isGpsEnabled;
boolean isNetworkEnabled;
@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        Log.i(TAG, "Location Providers changed");

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //Start your Activity if location was enabled:
        if (isGpsEnabled || isNetworkEnabled) {

            Log.i(TAG, "Location Providers on");
       }

       else {

              Log.i(TAG, "Location Providers off");
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
                String channelName = "My Background Service";
                NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                chan.setLightColor(Color.BLUE);
                chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(chan);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, notification);

            }
        }
    }

I can see logcat messages on changing location status but notification is not created

Body:
Changing notification code to this solved the problem

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = "
            com.example.fizatanveerkhan.citycops";
                CharSequence name =  "My Background Service";
                String description =  "My Background Service";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance);
                channel.setDescription(description);
                // Register the channel with the system; you can't change the importance
                // or other notification behaviors after this
                NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManagerCompat notificationManagerq =
           NotificationManagerCompat.from(context);

        // notificationId is a unique int for each notification that you must define
                notificationManagerq.notify(1, notificationBuilder.build());

                   }


问:
Is it possible to publish an Add-on for internal use without approval process?
Is it somehow possible to publish add-on without Google approval if it is going to be used for my internal use only?

If not, is there any possibility to make some of the Google Apps Script projects global. So that I would not need to copy same code/functionality to another spreadsheets or docs to get my custom macros to work again.

答:
The upvoted answer is out of date. You can publish an add-on using G Suite Marketplace SDK which has its own "Integrate With Google" button in its configuration tab for local integration. See https://developers.google.com/gsuite/marketplace/sdk.

Google's help on the subject is decent enough, at https://developers.google.com/gsuite/add-ons/how-tos/publishing-editor-addons.


问:
Mustache - Check Boolean object property within object array
Actually I'm using mustache-express, and I know that I can use conditionals like: {{^isFalse}} and {{#isTrue}}, this stuff is working fine, but my problem is:

I send an object array to template and list their properties with {{prop1}}{{prop2}}

My object has a Boolean property that is only true for the first object, and I need to grab another property from this object and set as audio element source, which I couldn't do, despite this snippet. Probably I'm missing something... But this is what I tried with no success:

Access the Boolean property directly (as he did):

```<code>{{#myBoolean}}
<audio hidden src="{{myPath}}"></audio>
{{/myBoolean}}
</code>```

Access within the array call, as I'm doing with my list:

```<code>{{#myArray}}
{{#myBoolean}}
<audio hidden src="{{myPath}}"></audio>
{{/myBoolean}}
{{/myArray}}
</code>```

Is there any way I can do this without having to create a separate object?

答:
The answer was:</p>

```<code>{{#myArray.0}}
<audio hidden src="{{myPath}}"></audio>
{{/myArray.0}}
</code>```

Body:
Actually I'm using mustache-express, and I know that I can use conditionals like: {{^isFalse}} and {{#isTrue}}, this stuff is working fine, but my problem is:

I send an object array to template and list their properties with {{prop1}}{{prop2}}

My object has a Boolean property that is only true for the first object, and I need to grab another property from this object and set as audio element source, which I couldn't do, despite this snippet. Probably I'm missing something... But this is what I tried with no success:

Access the Boolean property directly (as he did):

{{#myBoolean}}
<audio hidden src="{{myPath}}"></audio>
{{/myBoolean}}

Access within the array call, as I'm doing with my list:

{{#myArray}}
{{#myBoolean}}
<audio hidden src="{{myPath}}"></audio>
{{/myBoolean}}
{{/myArray}}

Is there any way I can do this without having to create a separate object?

Body:
The answer was:

{{#myArray.0}}
<audio hidden src="{{myPath}}"></audio>
{{/myArray.0}}


问:
Can I integrate my app onto instagram and publish in the app store?
I'm currently working on an app that allows some feature to be displayed when a user clicks on another instagram user's pictures, ie, when the picture and the provision to comment on the comment section displays. This is a simple feature that in a way overlays over this page. M question is, does instagram or any other photo sharing app allow this?

Once the user downloads my app, he/she will be allowed to integrate my app with instagram and have this feature enabled.

答:
Not sure I understand your question right or not. But there is no way to overlay your view to other application. There is a way to display part of your application in other application, which called extension but Instagram needs to design their application to add that feature which likely impossible.

Other way you can think of is checking if Instagram has API to see if a photo is liked/commented then you can response to that action.


问:
Add to cart resulting in 404 error - PrestaShop
I'm working on a Prestashop 1.7 shop and I have an issue. When I clicked on the "Add to cart" button, I'm getting an Error 404 (Not Found) in the JS Console.

This shop is installed on a Apache server:

I have tried to reload the .htaccess, I checked if AllowOverride all is set up in the virtual host config.

I have tried to clear cache and force re-compile the theme in the Back Office.

I have tried to change the theme of the website.

I have tried to enable mod rewrite.

However, when I disable friendly URLs, the "Add to card" button works perfectly !

How I can solve this issue ?

答:
As seen with you through via chat, we:

Regenerated your .htaccess file

Made sure SSL was turned on sitewide

Disabled some 3rd party modules that were causing redirects

Upgraded to PrestaShop v1.7.5.2

And your issue was resolved!


问:
Getting error "The capture file appears to be damaged or corrupt. (pcap: File has 1847605831-byte packet, bigger than maximum of 65535)"
I am getting error when i am trying to dump a packet in pcap file.

```<code> {
    unsigned char *ofilename = "packet.pcap";

    pcap_t *fp;
    pcap_dumper_t *dumpfile;

    const struct pcap_pkthdr *header;

    fp = pcap_open_dead(DLT_RAW,256);

    if(fp != NULL)
    {
        dumpfile = pcap_dump_open(fp, ofilename);

        if(dumpfile == NULL)
        {
            printf("\nError opening output file\n");
            return;
        }

        pcap_dump((u_char *)dumpfile,header,data);

        pcap_close(fp);
        pcap_dump_close(dumpfile);
    }
}
</code>```

HERE data is a u8 data[256].. its 256 byte data.. which has the packet bytes like this

FF FF FF FF FF FF 00 50 56 A8 11 39 81 00 0F FC 81 00 1F FC 08 06 00 01 08 00 06 04 00 01 00 50  56 A8 11 39 65 2B 01 0A 00 00 00 00 00 00 65 2B

But when i open packet.pcap i am getting "The capture file appears to be damaged or corrupt. (pcap: File has 1847605831-byte packet, bigger than maximum of 65535)"

Could someone pls help me on this whats going wrong

答:
Kindly install "pcapfix" on Linux and run it on the corrupt file as follows

$ pcapfix -d 'file / file path here'

This will fix it.

Body:
I am getting error when i am trying to dump a packet in pcap file.

 {
    unsigned char *ofilename = "packet.pcap";

    pcap_t *fp;
    pcap_dumper_t *dumpfile;

    const struct pcap_pkthdr *header;

    fp = pcap_open_dead(DLT_RAW,256);

    if(fp != NULL)
    {
        dumpfile = pcap_dump_open(fp, ofilename);

        if(dumpfile == NULL)
        {
            printf("\nError opening output file\n");
            return;
        }

        pcap_dump((u_char *)dumpfile,header,data);

        pcap_close(fp);
        pcap_dump_close(dumpfile);
    }
}

HERE data is a u8 data[256].. its 256 byte data.. which has the packet bytes like this

FF FF FF FF FF FF 00 50 56 A8 11 39 81 00 0F FC 81 00 1F FC 08 06 00 01 08 00 06 04 00 01 00 50  56 A8 11 39 65 2B 01 0A 00 00 00 00 00 00 65 2B

But when i open packet.pcap i am getting "The capture file appears to be damaged or corrupt. (pcap: File has 1847605831-byte packet, bigger than maximum of 65535)"

Could someone pls help me on this whats going wrong


问:
What's wrong with this bubble-sort function?
I have my array defined but at the moment i go into implement my bubble sorting function it doesn't enter the first for loop. It does run the function however

```<code>function bubbleSort (){

    for (var j=0; j++; j < valores.length){
        for (var i=j+1; i++; i < valores.length){
            if (valores[j]>valores[i]){
                var temp=0
                temp=valores[j]
                valores[i]=valores[j]
                valores[j]=temp
            }
        }
    }
    console.log(valores)
}
</code>```

so if valores input [2,1] I expect the output in console log to be [1,2].

I obtain my array by this function if that is of any help:

```<code>let valores =[];
let papelero=10;
function agregarValor (){

    if (valores.length < papelero){

        let val = Number(valor.value)

        valores.push(val)

        console.log(valores)
    }
}
</code>```

答:
like @ug_ said my swap was incorrect, and he previously said j and i were incremented in the wrong places. </p>

```<code>function bubbleSort() {
    for (var j=0; j<valores.length; j++) {
        for (var i=j+1; i<valores.length; i++) {
            if (valores[j]>valores[i]) {
                var temp=0
                temp=valores[i]
                valores[i]=valores[j]
                valores[j]=temp
             }
        }
    }
    console.log(valores)
}
</code>```

Body:
I have my array defined but at the moment i go into implement my bubble sorting function it doesn't enter the first for loop. It does run the function however

function bubbleSort (){

    for (var j=0; j++; j < valores.length){
        for (var i=j+1; i++; i < valores.length){
            if (valores[j]>valores[i]){
                var temp=0
                temp=valores[j]
                valores[i]=valores[j]
                valores[j]=temp
            }
        }
    }
    console.log(valores)
}

so if valores input [2,1] I expect the output in console log to be [1,2].

I obtain my array by this function if that is of any help:

let valores =[];
let papelero=10;
function agregarValor (){

    if (valores.length < papelero){

        let val = Number(valor.value)

        valores.push(val)

        console.log(valores)
    }
}

Body:
like @ug_ said my swap was incorrect, and he previously said j and i were incremented in the wrong places.

function bubbleSort() {
    for (var j=0; j<valores.length; j++) {
        for (var i=j+1; i<valores.length; i++) {
            if (valores[j]>valores[i]) {
                var temp=0
                temp=valores[i]
                valores[i]=valores[j]
                valores[j]=temp
             }
        }
    }
    console.log(valores)
}


问:
Writing a script to auto-create new google sheet upon data entry
I currently have a google sheet that receives data via a form submission from a third party. I'm trying to write a script that creates a new sheet every time a unique UserID is submitted.

For example, If I have 5 submissions where the UserIDs are A,B,B,C,C, I am trying to have the script create a unique sheet for A, B, and C and group duplicate UserID submissions in that sheet. I figure a pivot table filtered for UserID may accomplish the latter half of that but I haven't been able to figure out the sheet creation yet to test it.

So far, this is the code I've been working with:

```<code>function formSheet(e) {
  var sheetName = e.namedValues['user-id'][0];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName);
if (!sheet) {
  sheet = ss.insertSheet(sheetName);
  var formSheet = e.range.getSheet();
  var headers = formSheet.getRange(1, 1, 1, formSheet.getLastColumn());
  headers.copyTo(sheet.getRange(1, 1));
}
sheet.appendRow(e.values);
}`
</code>```

For reference, the sheet with the data is titled "submissions", and the data I want is under the header "User-Id" in column 2

答:
Try this:

You used 'user-id' in your script and 'User-Id' in your question so which is it?

```<code>function formsheet(e) {
  Logger.log(JSON.stringify(e));
  var ss=SpreadsheetApp.openById('ssid');
  var name=e.namedValues['user-Id'][0];
  var shts=ss.getSheets();
  if(shts.indexOf(name)==-1) {
    var sh=ss.insertSheet(name);
    var hdrs=e.range.getSheet().getRange(1,1,1,e.range.getSheet().getLastColumn()).getValues()[0];
    sh.appendRow(hdrs);
  }else{
      var sh=ss.getSheetByName(name);
  }
  sh.appendRow(e.values)
}
</code>```

Body:
I currently have a google sheet that receives data via a form submission from a third party. I'm trying to write a script that creates a new sheet every time a unique UserID is submitted.

For example, If I have 5 submissions where the UserIDs are A,B,B,C,C, I am trying to have the script create a unique sheet for A, B, and C and group duplicate UserID submissions in that sheet. I figure a pivot table filtered for UserID may accomplish the latter half of that but I haven't been able to figure out the sheet creation yet to test it.

So far, this is the code I've been working with:

function formSheet(e) {
  var sheetName = e.namedValues['user-id'][0];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName);
if (!sheet) {
  sheet = ss.insertSheet(sheetName);
  var formSheet = e.range.getSheet();
  var headers = formSheet.getRange(1, 1, 1, formSheet.getLastColumn());
  headers.copyTo(sheet.getRange(1, 1));
}
sheet.appendRow(e.values);
}`

For reference, the sheet with the data is titled "submissions", and the data I want is under the header "User-Id" in column 2

Body:
Try this:

You used 'user-id' in your script and 'User-Id' in your question so which is it?

function formsheet(e) {
  Logger.log(JSON.stringify(e));
  var ss=SpreadsheetApp.openById('ssid');
  var name=e.namedValues['user-Id'][0];
  var shts=ss.getSheets();
  if(shts.indexOf(name)==-1) {
    var sh=ss.insertSheet(name);
    var hdrs=e.range.getSheet().getRange(1,1,1,e.range.getSheet().getLastColumn()).getValues()[0];
    sh.appendRow(hdrs);
  }else{
      var sh=ss.getSheetByName(name);
  }
  sh.appendRow(e.values)
}


问:
How to fix TypeError in vue.js created hook?
error:

```<code>vue.js:597 [Vue warn]: Error in created hook: "TypeError: handlers[i].call is not a function"

found in

---> <StageExecs>
</code>```

vue.js

```<code><div id="vue-job">
    <div class="row">
        <h3>test</h3>
        <stage-execs></stage-execs>
    </div>
</div>

<script>
    Vue.component('jobs', {
        delimiters: [ '[[', ']]' ],
        props: ['job'],
        data: function() {
                return {
                    showExecs: false,
                    build_ids: []
                }
            },
        created: {
            stageExecs() {
                url = "api/v2/exec?" + this.job.api_url + "&limit=10"
                fetch(url)
                    .then(response => response.json())
                    .then(body => {
                        for(i=0; i<body.length; i++){
                            this.build_ids.push({
                                'id': JSON.stringify(body[i].build_id),
                            })
                        }
                    })
                    .catch( err => {
                        console.log('Error Fetching:', url, err);
                        return { 'failure': url, 'reason': err };
                    });
                }
        },
        template: `
        <ul id="example-1">
          <li v-for="item in build_ids">
            [[ item.url ]]
          </li>
        </ul>
        `,
    });

var v_root = new Vue({
    delimiters: [ '[[', ']]' ],
    el: '#vue-job',
    data: {
        job_exec: {{ job_exec|safe }},

    }
});
</code>```

I assume something is being called in the incorrect order here, but new to vue.js so not sure what I did wrong.

答:
your data component should be an object, not a function, you replace it like below :

please check the doc as well : Declarative-Rendering

```<code> data: {
     return {
         showExecs: false,
         build_ids: []
      }
</code>```

Body:
error:

vue.js:597 [Vue warn]: Error in created hook: "TypeError: handlers[i].call is not a function"

found in

---> <StageExecs>

vue.js

test

        <stage-execs></stage-execs>

Body:
your data component should be an object, not a function, you replace it like below :

please check the doc as well : Declarative-Rendering

 data: {
     return {
         showExecs: false,
         build_ids: []
      }


问:
R data.table values depending on previous row
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}
```

<p>and here's the output:</p>

```     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10
```

Can someone help me improve the code?

Body:
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}

and here's the output:

     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10

Can someone help me improve the code?

Body:
Another option:

cols <- c('a','b','c')
A <- 1; B <- 2; C <- 3
DT[iter==1, (cols) := .(A, B, C)]
DT[iter>1,
    (cols) := {
        A = A + B
        B = B - A
        C = A / B + C
        .(A, B, C)
    },
    by=iter]


问:
Undefined function conn/0 in View
I am working through the Programming Phoenix 1.4 book, and while creating my view for Users, I ran into an issue. I continually get a compile error saying

```<code>== Compilation error in file lib/rumbl_web/views/user_view.ex ==
** (CompileError) lib/rumbl_web/views/user_view.ex:3: undefined function conn/0
    (elixir) src/elixir_locals.erl:107: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
    (elixir) src/elixir_locals.erl:107: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:208: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6`
</code>```

when attempting to compile and run the project.
Here is the view in question:

```<code>defmodule RumblWeb.UserView do
  use RumblWeb, :view
  alias Rumbl.Accounts

  def first_name(%Accounts.User{name: name}) do
    name
    |> String.split(" ")
    |> Enum.at(0)
  end

  def username(%Accounts.User{username: username}) do
    username
  end

end
</code>```

If I comment out the line use RumblWeb, :view, the project compiles (although it cannot render the view for obvious reasons). I am rather new to phoenix and elixir, so this has been pretty perplexing.

答:
If I add conn to the third line of views/user_view.ex:

```<code>defmodule RumWeb.UserView do
  use RumWeb, :view
  conn  #====== *** HERE ***
  alias Rum.Accounts.User

  def first_name(%User{name: name} ) do
    name
    |> IO.inspect
    |> String.split(" ")
    |> Enum.at(0)
  end

end
</code>```

I get almost the same error as you:

```<code>$ mix phx.server
Compiling 9 files (.ex)
warning: variable "conn" does not exist and is being expanded to "conn()", please use parentheses to remove the ambiguity or change the variable name
  lib/rum_web/views/user_view.ex:3

== Compilation error in file lib/rum_web/views/user_view.ex ==
** (CompileError) lib/rum_web/views/user_view.ex:3: undefined function conn/0
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:198: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6
</code>```

I don't have the following in the middle of my error:

```<code>ensure_no_undefined_local/3-
</code>```

but maybe that's due to differences in elixir versions.

If I put conn anywhere in rumbl_web.ex, then the error points to  rumbl_web.ex--not user_view.ex.  Are you posting all the output after you do $ mix phx.server?

Are you sure you don't have two windows open with two different versions of the file user_view.ex?  I would close all your editor's windows, then reopen your project and look at  user_view.ex again.

I had a weird error one time, and the solution was:

```<code>../rumbl$ rm -rf _build
</code>```

then do:

```<code>../rumbl$ mix phx.server
</code>```

and mix will rebuild your project, recreating the _build directory in the process.

Title: Undefined function conn/0 in View

Body:
I am working through the Programming Phoenix 1.4 book, and while creating my view for Users, I ran into an issue. I continually get a compile error saying

== Compilation error in file lib/rumbl_web/views/user_view.ex ==
** (CompileError) lib/rumbl_web/views/user_view.ex:3: undefined function conn/0
    (elixir) src/elixir_locals.erl:107: :elixir_locals."-ensure_no_undefined_local/3-lc$^0/1-0-"/2
    (elixir) src/elixir_locals.erl:107: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:208: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6`

when attempting to compile and run the project.
Here is the view in question:

defmodule RumblWeb.UserView do
  use RumblWeb, :view
  alias Rumbl.Accounts

  def first_name(%Accounts.User{name: name}) do
    name
    |> String.split(" ")
    |> Enum.at(0)
  end

  def username(%Accounts.User{username: username}) do
    username
  end

end

If I comment out the line use RumblWeb, :view, the project compiles (although it cannot render the view for obvious reasons). I am rather new to phoenix and elixir, so this has been pretty perplexing.

Body:
If I add conn to the third line of views/user_view.ex:

defmodule RumWeb.UserView do
  use RumWeb, :view
  conn  #====== *** HERE ***
  alias Rum.Accounts.User

  def first_name(%User{name: name} ) do
    name
    |> IO.inspect
    |> String.split(" ")
    |> Enum.at(0)
  end

end

I get almost the same error as you:

$ mix phx.server
Compiling 9 files (.ex)
warning: variable "conn" does not exist and is being expanded to "conn()", please use parentheses to remove the ambiguity or change the variable name
  lib/rum_web/views/user_view.ex:3

== Compilation error in file lib/rum_web/views/user_view.ex ==
** (CompileError) lib/rum_web/views/user_view.ex:3: undefined function conn/0
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:198: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

I don't have the following in the middle of my error:

ensure_no_undefined_local/3-

but maybe that's due to differences in elixir versions.

If I put conn anywhere in rumbl_web.ex, then the error points to  rumbl_web.ex--not user_view.ex.  Are you posting all the output after you do $ mix phx.server?

Are you sure you don't have two windows open with two different versions of the file user_view.ex?  I would close all your editor's windows, then reopen your project and look at  user_view.ex again.

I had a weird error one time, and the solution was:

../rumbl$ rm -rf _build

then do:

../rumbl$ mix phx.server

and mix will rebuild your project, recreating the _build directory in the process.


问:
Something akin to "Sparse Fieldsets" in .NET
I'm trying to find the vocabulary to describe what I want and if it exists.

I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?

I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.

Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.

Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:

```<code>_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
        .Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
        .Include(f => f.Recipe)
</code>```

答:
Maybe you are looking for Anonymous Types?

For example, if you had a typed object with three properties, but you only wanted to operate on two:

```<code>var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };

var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };
</code>```

Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.

Typically, when passing data around in c#, you want to have it typed.

Body:
I'm trying to find the vocabulary to describe what I want and if it exists.

I have a table that shows a few data points from large objects. Loading the entire objects just for the table is very slow. Is there a way to only pass to the front the few properties I want without having to define a new object?

I found something called Sparse Fieldsets in JSON API, and I'm wondering if something like this exists for .NET under another name.

Update:
Talking to another coder, I realize it probably makes more sense to implement something like this between the backend and the database and make a specific call for this table. I still need to work out if I need to create a new object to support this. I think it'd still be faster if I just kept the same object but nulled out all of the connecting objects that I don't need for the table. But maybe that's considered bad practice? Also we're using Entity Framework for what it's worth.

Update 2:
I just created a new query without all of the .Include() and works well enough for what I need:

_dataContext.ApplePie
.Include(f => f.Apples).ThenInclude(f => f.Apple)
        .Include(f => f.Sugars).ThenInclude(f => f.MolecularStructure)
        .Include(f => f.Recipe)

Body:
Maybe you are looking for Anonymous Types?

For example, if you had a typed object with three properties, but you only wanted to operate on two:

var threePropThing = new ThreePropertyThing { Id = 1, Message = "test", ExtraProperty = "ex" };

var myAnonThing = new { Id = threePropThing.Id, Message = threePropThing.Message };

Best practice would be to not pass this anonymous object around. But, if you really needed to, you could return it as type object.

Typically, when passing data around in c#, you want to have it typed.


问:
Why isn't the function parameter showing in the dialog?
The function parameter that is a string isn't showing in the dialog content block. I need to know why and how to make this work. The parameter I am trying to show is string with php code.

I have used MessageToast.show() in my function to view the output string. The output string shows up. I have also tried adding "hello world" string the content block and that works.

Here is my code logic is a string.

```<code>logicDialog: function (logic) {
            MessageToast.show(logic);
            var dialog = new Dialog({
                title: 'Boolean Logic',
                type: 'Message',
                content: new TextArea({
                    value: logic,
                    editable: false,
                    growing: true,
                    growingMaxLines: 20

                }),
                beginButton: new Button({
                    text: 'Close',
                    press: function () {
                        dialog.close();
                    }
                }),
                afterClose: function () {
                    dialog.destroy();
                }
            });
            dialog.open();
        }
</code>```

The expected result is dialog that shows the string logic.

答:
Since the example of @TiiJ7 works fine I will just try to throw some possible issues:

-is your Dialog a sap.m.Dialog()?;

-is there any error before the dialog is triggered? (that could somehow stop the functionality of the dialog);

-put a break point in the line of "dialog.close();" to check the content of the string on the scope of the dialog opened;

-is it possible that the string is being manipulated somewhere else and it could a be an issue with concurrency? 1 thread could be changing the value of the string (note that a string is a pointer).

I hope these points could bring you light, since you are the only one with access to the entire code.

Body:
The function parameter that is a string isn't showing in the dialog content block. I need to know why and how to make this work. The parameter I am trying to show is string with php code.

I have used MessageToast.show() in my function to view the output string. The output string shows up. I have also tried adding "hello world" string the content block and that works.

Here is my code logic is a string.

logicDialog: function (logic) {
            MessageToast.show(logic);
            var dialog = new Dialog({
                title: 'Boolean Logic',
                type: 'Message',
                content: new TextArea({
                    value: logic,
                    editable: false,
                    growing: true,
                    growingMaxLines: 20

                }),
                beginButton: new Button({
                    text: 'Close',
                    press: function () {
                        dialog.close();
                    }
                }),
                afterClose: function () {
                    dialog.destroy();
                }
            });
            dialog.open();
        }

The expected result is dialog that shows the string logic.


问:
Clearing the Cache on OS Versions above Marshmallow
I want to make an Android App which will clean the cache of other apps. I have figured out how to do that for Android Version below Marshmallow.

This is what I am using for Android Honeycom and above:

```<code>    if (isExternalStorageWritable()) {
        final File externalDataDirectory = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath(), "/Android/data");

        final String externalCachePath = externalDataDirectory.getAbsolutePath() +
                "/%s/cache";

        if (externalDataDirectory.isDirectory()) {
            final File[] files = externalDataDirectory.listFiles();

            for (File file : files) {
                if (!deleteDirectory(new File(String.format(externalCachePath,
                        file.getName())), true)) {
                    Log.e(TAG, "External storage suddenly becomes unavailable");

                    return false;
                }
            }
        } else {
            Log.e(TAG, "External data directory is not a directory!");
        }
    } else {
        Log.d(TAG, "External storage is unavailable");
    }
</code>```

But I am having an issue to figure out how to do it for Android Version Marshmallow and above.

Other cache cleaners present in the market are able to perform this by taking accessibility permission or any other way?

答:
Starting from Android 6.0 (Marshmallow) any normal app is not permitted to clear the cache of other apps. You can clear the cache of other apps only if your app is a system app or is signed by the same certificate the system is signed. But there is a hack on how you can.

You can perform this by using accessibility service(which is correctly pointed by you).

AFAIK you can show the cache value and then ask the user for the accessibility permission and after the permission is granted open the settings screen-->go to storage-->click the Cache button and then press ok.

Keep in mind that this is only a hack and may produce errors based on various OEM's and Android version.

Coming to how you can achieve, this is a very good example to explore how accessibility service can be used.

ALSO, KEEP IN MIND THAT YOU NEED TO TAKE PRE APPROVAL FROM GOOGLE PLAY TO USE ACCESSIBILITY OR ELSE THE MIGHT REMOVE THE APP FROM THE PLAY STORE. DO TAKE PERMISSION BEFORE GIVING AN UPDATE OR ELSE THEY MIGHT SUSPEND OR TERMINATE YOUR APP. BE VERY CAREFUL ABOUT THIS.

Body:
I want to make an Android App which will clean the cache of other apps. I have figured out how to do that for Android Version below Marshmallow.

This is what I am using for Android Honeycom and above:

    if (isExternalStorageWritable()) {
        final File externalDataDirectory = new File(Environment
                .getExternalStorageDirectory().getAbsolutePath(), "/Android/data");

        final String externalCachePath = externalDataDirectory.getAbsolutePath() +
                "/%s/cache";

        if (externalDataDirectory.isDirectory()) {
            final File[] files = externalDataDirectory.listFiles();

            for (File file : files) {
                if (!deleteDirectory(new File(String.format(externalCachePath,
                        file.getName())), true)) {
                    Log.e(TAG, "External storage suddenly becomes unavailable");

                    return false;
                }
            }
        } else {
            Log.e(TAG, "External data directory is not a directory!");
        }
    } else {
        Log.d(TAG, "External storage is unavailable");
    }

But I am having an issue to figure out how to do it for Android Version Marshmallow and above.

Other cache cleaners present in the market are able to perform this by taking accessibility permission or any other way?


问:
How to compress multiple files into one zip with PowerShell?
I want to compress multiple files into one zip.

I am stuck with this at the moment:

```<code>Get-ChildItem -path C:\logs -Recurse | Where {$_.Extension -eq ".csv" -and $_.LastWriteTime -lt (Get-Date).AddDays(-7)} | write-zip -level 9 -append ($_.LastWriteTime).zip | move-item -Force -Destination {
    $dir = "C:\backup\archive"
    $null = mkdir $dir -Force
    "$dir\"
}
</code>```

I get this exception

Write-Zip : Cannot bind argument to parameter 'Path' because it is null.

This part is the problem:

```<code>write-zip -level 9 -append ($_.LastWriteTime).zip
</code>```

I have never used powershell before but i have to provide a script, I can't provide a c# solution.

答:
The problem is that Get-ChildItem returns instances of the System.IO.FileInfo class, which doesn't have a property named Path. Therefore the value cannot be automatically mapped to the Path parameter of the Write-Zip cmdlet through piping.

You'll have to use the ForEach-Object cmdlet to zip the files using the System.IO.FileInfo.FullName property, which contains the full path:

```<code>Get-ChildItem -Path C:\Logs | Where-Object { $_.Extension -eq ".txt" } | ForEach-Object { Write-Zip -Path $_.FullName -OutputPath "$_.zip" }
</code>```

Here's a shorter version of the command using aliases and positional parameters:

```<code>dir C:\Logs | where { $_.Extension -eq ".txt" } | foreach { Write-Zip $_.FullName "$_.zip" }
</code>```

Related resources:

Cool Pipeline Tricks, Redux (TechNet Magazine)

Body:
I want to compress multiple files into one zip.

I am stuck with this at the moment:

Get-ChildItem -path C:\logs -Recurse | Where {$_.Extension -eq ".csv" -and $_.LastWriteTime -lt (Get-Date).AddDays(-7)} | write-zip -level 9 -append ($_.LastWriteTime).zip | move-item -Force -Destination {
    $dir = "C:\backup\archive"
    $null = mkdir $dir -Force
    "$dir\"
}

I get this exception

Write-Zip : Cannot bind argument to parameter 'Path' because it is null.

This part is the problem:

write-zip -level 9 -append ($_.LastWriteTime).zip

I have never used powershell before but i have to provide a script, I can't provide a c# solution.

Body:
The problem is that Get-ChildItem returns instances of the System.IO.FileInfo class, which doesn't have a property named Path. Therefore the value cannot be automatically mapped to the Path parameter of the Write-Zip cmdlet through piping.

You'll have to use the ForEach-Object cmdlet to zip the files using the System.IO.FileInfo.FullName property, which contains the full path:

Get-ChildItem -Path C:\Logs | Where-Object { $_.Extension -eq ".txt" } | ForEach-Object { Write-Zip -Path $_.FullName -OutputPath "$_.zip" }

Here's a shorter version of the command using aliases and positional parameters:

dir C:\Logs | where { $_.Extension -eq ".txt" } | foreach { Write-Zip $_.FullName "$_.zip" }

Related resources:

Cool Pipeline Tricks, Redux (TechNet Magazine)


问:
How to make optional parameter value in ActionResult method in Asp.Net MVC?
When user click the button, it will redirect to another controller action method with or without parameter value

```<code><button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details'" >Go to Details</button>

<button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details?name=xxx'" >View Details</button>
</code>```

CustomerController

```<code>    public ActionResult Details()   // i don't know how to pass optional parameter value
    {
        // some code ...
        return View();
    }
</code>```

答:
If you are using c# 4.0 or higher, you can use this:  </p>

```<code>public ActionResult Details(string name = "xxx")
  {
    // some code ...
    return View();
  }
</code>```

Body:
When user click the button, it will redirect to another controller action method with or without parameter value

<button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details'" >Go to Details</button>

<button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details?name=xxx'" >View Details</button>

CustomerController

    public ActionResult Details()   // i don't know how to pass optional parameter value
    {
        // some code ...
        return View();
    }

Body:
If you are using c# 4.0 or higher, you can use this:

public ActionResult Details(string name = "xxx")
  {
    // some code ...
    return View();
  }


问:
What tools do you use to develop C++ applications on Linux?
I develop C++ applications in a Linux environment.  The tools I use every day include Eclipse with the CDT plugin, gdb and valgrind.

What tools do other people use?  Is there anything out there for Linux that rivals the slickness of Microsoft Visual Studio?

答:
Bash

Vim

Make

G++

GDB

Valgrind

Gprof

svn

Never a GUI to be seen except a good terminal with tab support; keep code, debugger, output, etc all in separate windows and tab back and forwards really quickly.

OwnerDisplayName: Clayton

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Adam Hawes


问:
Implementing cache control using .htaccess on Apache server
okay, I'm still trying to get my head around some of the caching stuff and I have gone through a couple of examples I could find on Google. I have added the following code to my .htaccess file:

```<code>### activate mod_expires
ExpiresActive On
### Expire .gif's 1 month from when they're accessed
ExpiresByType image/gif "access plus 3 months"
ExpiresByType image/png "access plus 3 months"
ExpiresByType image/jpg "access plus 3 months"
ExpiresByType text/javascript "access plus 3 months"
</code>```

Using the Chrome audit tools and the YSlow Firebug tool, it looks like this is caching some of my images/files, but not by far all of them. I still have a list of files (.jpg, .js and .css - I know I've not set the css files to cache here) that aren't caching. The message in the Chrome audit simply states The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:

some of the images that aren't caching are background images, others are part of a js gallery and they're being called via the JS - could that be affecting why they aren't caching?

Sorry I can't give a link to the code - the sites still under wraps and limited to client view only.

Thanks in advance!

答:
It looks like you've written the MIME-types wrong:</p>

```<code># enable expirations
ExpiresActive On
ExpiresDefault "access plus 1 week"
ExpiresByType image/gif "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType image/pjpeg "access plus 1 week"
ExpiresByType text/javascript "modification plus 1 week"
ExpiresByType application/javascript "modification plus 1 week"
ExpiresByType text/css "modification plus 1 week"
</code>```

Body:
okay, I'm still trying to get my head around some of the caching stuff and I have gone through a couple of examples I could find on Google. I have added the following code to my .htaccess file:

### activate mod_expires
ExpiresActive On
### Expire .gif's 1 month from when they're accessed
ExpiresByType image/gif "access plus 3 months"
ExpiresByType image/png "access plus 3 months"
ExpiresByType image/jpg "access plus 3 months"
ExpiresByType text/javascript "access plus 3 months"

Using the Chrome audit tools and the YSlow Firebug tool, it looks like this is caching some of my images/files, but not by far all of them. I still have a list of files (.jpg, .js and .css - I know I've not set the css files to cache here) that aren't caching. The message in the Chrome audit simply states The following resources are missing a cache expiration. Resources that do not specify an expiration may not be cached by browsers:

some of the images that aren't caching are background images, others are part of a js gallery and they're being called via the JS - could that be affecting why they aren't caching?

Sorry I can't give a link to the code - the sites still under wraps and limited to client view only.

Thanks in advance!

Body:
It looks like you've written the MIME-types wrong:

# enable expirations
ExpiresActive On
ExpiresDefault "access plus 1 week"
ExpiresByType image/gif "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType image/pjpeg "access plus 1 week"
ExpiresByType text/javascript "modification plus 1 week"
ExpiresByType application/javascript "modification plus 1 week"
ExpiresByType text/css "modification plus 1 week"


问:
How to Convert EST to Local Time with Dataframe
I'm trying to convert timestamps in EST to various localized timestamps in a pandas dataframe. I have a dataframe with timestamps in EST and a timezone into which they need to be converted.

I know that there are several threads already on topics like this. However, they either start in UTC or I can't replicate with my data.

Before writing, I consulted: How to convert GMT time to EST time using python

I imported the data:

```<code>import pandas
import datetime as dt
import pytz

transaction_timestamp_est         local_timezone

2013-05-28 05:18:00+00:00         America/Chicago
2013-06-12 05:23:20+00:00         America/Los_Angeles
2014-06-21 05:26:26+00:00         America/New_York
</code>```

I converted to datetime and created the following function:

```<code>df.transaction_timestamp_est =
pd.to_datetime(df.transaction_timestamp_est)

def db_time_to_local(row):

    db_tz = pytz.timezone('America/New_York')
    local_tz = pytz.timezone(row['local_timezone'])

    db_date = db_tz.localize(row['transaction_timestamp_est'])
    local_date = db_date.astimezone(local_tz)

    return local_date
</code>```

I run it here:

```<code>df['local_timestamp'] = df.apply(db_time_to_local, axis=1)
</code>```

And get this error:

ValueError: ('Not naive datetime (tzinfo is already set)', 'occurred at index 0')

I expect a new column in the dataframe called 'local_timestamp' that has the timestamp adjusted according to the data in the local_timezone column.

Any help is appreciated!

答:
The error you see looks like its because you are trying to localize a tz-aware timestamp. The '+00:00' in your timestamps indicates these are tz-aware, in UTC (or something like it).

Some terminology: a naive date/time has no concept of timezone, a tz-aware (or localised) one is associated with a particular timezone. Localizing refers to converting a tz-naive date/time to a tz-aware one. By definition you can't localize a tz-aware date/time: you either either convert it to naive and then localize, or convert directly to the target timezone.

To get that column into EST, convert to naive and then localize to EST:

```<code>In [98]: df['transaction_timestamp_est'] = df['transaction_timestamp_est'].dt.tz_localize(None).dt.tz_localize('EST')
In [99]: df
Out [99]:

0   2013-05-28 05:18:00-05:00
1   2013-06-12 05:23:20-05:00
2   2014-06-21 05:26:26-05:00
Name: transaction_timestamp_est, dtype: datetime64[ns, EST]
</code>```

Note the 'EST' in the dtype.
Then, you can convert each timestamp to its target timezone:

```<code>In [100]: df['local_ts'] = df.apply(lambda x: x[0].tz_convert(x[1]), axis=1)

In [101]: df
Out[101]:
  transaction_timestamp_est       local_timezone                   local_ts
0 2013-05-28 05:18:00-05:00      America/Chicago  2013-05-28 05:18:00-05:00
1 2013-06-12 05:23:20-05:00  America/Los_Angeles  2013-06-12 03:23:20-07:00
2 2014-06-21 05:26:26-05:00     America/New_York  2014-06-21 06:26:26-04:00
</code>```

To explain: each element in the first column is of type pd.Timestamp. Its tz_convert() method changes its timezone, converting the date/time to the new zone.

This produces a column of pd.Timestamps with a mixture of timezones, which is a pain to handle in pandas. Most (perhaps all) pandas functions that operate on columns of date/times require the whole column to have the same timezone.

If you prefer, convert to tz-naive:

```<code>In [102]: df['local_ts'] = df.apply(lambda x: x[0].tz_convert(x[1]).tz_convert(None), axis=1)

In [103]: df
Out[103]:
  transaction_timestamp_est       local_timezone            local_ts
0 2013-05-28 05:18:00-05:00      America/Chicago 2013-05-28 10:18:00
1 2013-06-12 05:23:20-05:00  America/Los_Angeles 2013-06-12 10:23:20
2 2014-06-21 05:26:26-05:00     America/New_York 2014-06-21 10:26:26
</code>```

If your data allows, its better to try to keep columns of timestamps (or indices) in a single timezone. UTC is usually best as it doesnt have DST transitions or other issues that can result in missing / ambiguous times, as most other timezones do.

Body:
I'm trying to convert timestamps in EST to various localized timestamps in a pandas dataframe. I have a dataframe with timestamps in EST and a timezone into which they need to be converted.

I know that there are several threads already on topics like this. However, they either start in UTC or I can't replicate with my data.

Before writing, I consulted: How to convert GMT time to EST time using python

I imported the data:

import pandas
import datetime as dt
import pytz

transaction_timestamp_est         local_timezone

2013-05-28 05:18:00+00:00         America/Chicago
2013-06-12 05:23:20+00:00         America/Los_Angeles
2014-06-21 05:26:26+00:00         America/New_York

I converted to datetime and created the following function:

df.transaction_timestamp_est =
pd.to_datetime(df.transaction_timestamp_est)

def db_time_to_local(row):

    db_tz = pytz.timezone('America/New_York')
    local_tz = pytz.timezone(row['local_timezone'])

    db_date = db_tz.localize(row['transaction_timestamp_est'])
    local_date = db_date.astimezone(local_tz)

    return local_date

I run it here:

df['local_timestamp'] = df.apply(db_time_to_local, axis=1)

And get this error:

ValueError: ('Not naive datetime (tzinfo is already set)', 'occurred at index 0')

I expect a new column in the dataframe called 'local_timestamp' that has the timestamp adjusted according to the data in the local_timezone column.

Any help is appreciated!

Body:
The error you see looks like its because you are trying to localize a tz-aware timestamp. The '+00:00' in your timestamps indicates these are tz-aware, in UTC (or something like it).

Some terminology: a naive date/time has no concept of timezone, a tz-aware (or localised) one is associated with a particular timezone. Localizing refers to converting a tz-naive date/time to a tz-aware one. By definition you can't localize a tz-aware date/time: you either either convert it to naive and then localize, or convert directly to the target timezone.

To get that column into EST, convert to naive and then localize to EST:

In [98]: df['transaction_timestamp_est'] = df['transaction_timestamp_est'].dt.tz_localize(None).dt.tz_localize('EST')
In [99]: df
Out [99]:

0   2013-05-28 05:18:00-05:00
1   2013-06-12 05:23:20-05:00
2   2014-06-21 05:26:26-05:00
Name: transaction_timestamp_est, dtype: datetime64[ns, EST]

Note the 'EST' in the dtype.
Then, you can convert each timestamp to its target timezone:

In [100]: df['local_ts'] = df.apply(lambda x: x[0].tz_convert(x[1]), axis=1)

In [101]: df
Out[101]:
  transaction_timestamp_est       local_timezone                   local_ts
0 2013-05-28 05:18:00-05:00      America/Chicago  2013-05-28 05:18:00-05:00
1 2013-06-12 05:23:20-05:00  America/Los_Angeles  2013-06-12 03:23:20-07:00
2 2014-06-21 05:26:26-05:00     America/New_York  2014-06-21 06:26:26-04:00

To explain: each element in the first column is of type pd.Timestamp. Its tz_convert() method changes its timezone, converting the date/time to the new zone.

This produces a column of pd.Timestamps with a mixture of timezones, which is a pain to handle in pandas. Most (perhaps all) pandas functions that operate on columns of date/times require the whole column to have the same timezone.

If you prefer, convert to tz-naive:

In [102]: df['local_ts'] = df.apply(lambda x: x[0].tz_convert(x[1]).tz_convert(None), axis=1)

In [103]: df
Out[103]:
  transaction_timestamp_est       local_timezone            local_ts
0 2013-05-28 05:18:00-05:00      America/Chicago 2013-05-28 10:18:00
1 2013-06-12 05:23:20-05:00  America/Los_Angeles 2013-06-12 10:23:20
2 2014-06-21 05:26:26-05:00     America/New_York 2014-06-21 10:26:26

If your data allows, its better to try to keep columns of timestamps (or indices) in a single timezone. UTC is usually best as it doesnt have DST transitions or other issues that can result in missing / ambiguous times, as most other timezones do.


问:
Change HOC wrapper component with its own state to react hooks
I currently have an HOC component that I'd like to port over to use react hooks and basically just start thinking in that idea.

This HOC component basically provides a functionality for a wrapped component to display an alert dialog box. The HOC component manages its own state making this very easy for the wrapped component to display an alert dialog. The wrapped component simply has to call the function passed down to props to display it.

Here's what the HOC looks like now:

function withAlertDialog(WrappedComponent) {
  return class extends Component {
    constructor(props) {
      super(props);

      this.state = {
        alertDialogOpen: false,
        alertMessage: ""
      };
    }

    displayAlert = message => {
      this.setState({alertDialogOpen: true, alertMessage: message});
    }

    closeAlertDialog = () => {
      this.setState({alertDialogOpen: false});
    }

    render() {
      return (
        <React.Fragment>
          <WrappedComponent
            onDisplayAlert={this.displayAlert}
            onCloseAlert={this.closeAlertDialog} />
          <MyAlertDialogComponent
            open={this.state.alertDialogOpen}
            onClose={this.closeAlertDialog} />
        </React.Fragment>
      );
    }
  }
}
```

This is a more simple case, the actual HOC used is a lot more complex, but the idea still follows. The wrapped component can now basically call this.props.onDisplayAlert('some message here'); to display the alert. The wrapped component also doesn't have to render the MyAlertDialogComponent in its own render function. Basically, the wrapped component does not have to worry about how MyAlertDialogComponent is handled, all it knows is that calling this.props.onDisplayAlert will display an alert dialog box somehow. Reusing this HOC saves a lot of lines of code.

How would one go about changing this to a react hooks implementation? I've tried looking around but most articles and the documentation itself use an HOC with a single wrapped component and isn't really managing another component in addition to that. I'd like to understand how to change to the "react hooks" ideology but keep that same level of convenience about not having to render MyAlertDialogComponent in each component that wants to use it.

答:
The only difference between your old HOC and a new HOC utilizing hooks is that you simply have to change the anonymous class you return from your HOC to an anonymous function that uses hooks.

Conversion between a class and a hooked-in function follows normal conversion rules that you might find in numerous tutorials online. In the case of your example, convert your state to useState and convert your class methods to regular functions.

You just pass the state and these regular functions around to whatever component needs them. Calling the setter for your state will re-render the component.

If you review the example below you'll see MyWrappedComponent is wrapped using withAlertDialog which passes the two function props to MyWrappedComponent. Those functions are used inside MyWrappedComponent to set the state that renders MyAlertDialogComponent

const { useState } = React
function withAlertDialog(WrappedComponent) {
  return function(props){
    const [alertState, setAlertState] = useState({
      alertDialogOpen: false,
      alertMessage: ""
    })

    const displayAlert = message => {
      setAlertState({
        alertDialogOpen: true,
        alertMessage: message
      });
    }

    const closeAlertDialog = () => {
      setAlertState({alertDialogOpen: false});
    }

    return (
      <React.Fragment>
        <WrappedComponent
          onDisplayAlert={displayAlert}
          onCloseAlert={closeAlertDialog} />
        <MyAlertDialogComponent
          open={alertState.alertDialogOpen}
          onClose={closeAlertDialog} />
      </React.Fragment>
    );
  }
}

const MyWrappedComponent = withAlertDialog(function (props){
  return (

      Open Alert
      Close Alert

  )
})

function MyAlertDialogComponent(props){
  if(!props.open){
    return null
  }
  return (

Dialogue Open

  )
}

function App(){
  return (
    <MyWrappedComponent />
  )
}

ReactDOM.render(<App />, document.querySelector('#app'))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div > a {
 display : block;
 padding : 10px 0;
}</code>```

```

Body:
I currently have an HOC component that I'd like to port over to use react hooks and basically just start thinking in that idea.

This HOC component basically provides a functionality for a wrapped component to display an alert dialog box. The HOC component manages its own state making this very easy for the wrapped component to display an alert dialog. The wrapped component simply has to call the function passed down to props to display it.

Here's what the HOC looks like now:

function withAlertDialog(WrappedComponent) {
  return class extends Component {
    constructor(props) {
      super(props);

      this.state = {
        alertDialogOpen: false,
        alertMessage: ""
      };
    }

    displayAlert = message => {
      this.setState({alertDialogOpen: true, alertMessage: message});
    }

    closeAlertDialog = () => {
      this.setState({alertDialogOpen: false});
    }

    render() {
      return (
        <React.Fragment>
          <WrappedComponent
            onDisplayAlert={this.displayAlert}
            onCloseAlert={this.closeAlertDialog} />
          <MyAlertDialogComponent
            open={this.state.alertDialogOpen}
            onClose={this.closeAlertDialog} />
        </React.Fragment>
      );
    }
  }
}

This is a more simple case, the actual HOC used is a lot more complex, but the idea still follows. The wrapped component can now basically call this.props.onDisplayAlert('some message here'); to display the alert. The wrapped component also doesn't have to render the MyAlertDialogComponent in its own render function. Basically, the wrapped component does not have to worry about how MyAlertDialogComponent is handled, all it knows is that calling this.props.onDisplayAlert will display an alert dialog box somehow. Reusing this HOC saves a lot of lines of code.

How would one go about changing this to a react hooks implementation? I've tried looking around but most articles and the documentation itself use an HOC with a single wrapped component and isn't really managing another component in addition to that. I'd like to understand how to change to the "react hooks" ideology but keep that same level of convenience about not having to render MyAlertDialogComponent in each component that wants to use it.

Body:
The only difference between your old HOC and a new HOC utilizing hooks is that you simply have to change the anonymous class you return from your HOC to an anonymous function that uses hooks.

Conversion between a class and a hooked-in function follows normal conversion rules that you might find in numerous tutorials online. In the case of your example, convert your state to useState and convert your class methods to regular functions.

You just pass the state and these regular functions around to whatever component needs them. Calling the setter for your state will re-render the component.

If you review the example below you'll see MyWrappedComponent is wrapped using withAlertDialog which passes the two function props to MyWrappedComponent. Those functions are used inside MyWrappedComponent to set the state that renders MyAlertDialogComponent

const { useState } = React
function withAlertDialog(WrappedComponent) {
  return function(props){
    const [alertState, setAlertState] = useState({
      alertDialogOpen: false,
      alertMessage: ""
    })

    const displayAlert = message => {
      setAlertState({
        alertDialogOpen: true,
        alertMessage: message
      });
    }

    const closeAlertDialog = () => {
      setAlertState({alertDialogOpen: false});
    }

    return (
      <React.Fragment>
        <WrappedComponent
          onDisplayAlert={displayAlert}
          onCloseAlert={closeAlertDialog} />
        <MyAlertDialogComponent
          open={alertState.alertDialogOpen}
          onClose={closeAlertDialog} />
      </React.Fragment>
    );
  }
}

const MyWrappedComponent = withAlertDialog(function (props){
  return (
    <div>
      <a onClick={props.onDisplayAlert}>Open Alert</a>
      <a onClick={props.onCloseAlert}>Close Alert</a>
    </div>
  )
})

function MyAlertDialogComponent(props){
  if(!props.open){
    return null
  }
  return (
    <div>Dialogue Open</div>
  )
}

function App(){
  return (
    <MyWrappedComponent />
  )
}

ReactDOM.render(<App />, document.querySelector('#app'))

div > a {
 display : block;
 padding : 10px 0;
}

<div id="app" />

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>


问:
Database fetch exists only in its own function
I am trying to fetch all the user names in my database but the nameArray only contains values while its inside that function, how can I fix this?

```<code>DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
            self.nameArray = returnedNamesArray
}

for userName in nameArray {
            if(userName.lowercased() == name!.lowercased()){

                self.userNameTaken = true
                self.progressView.progress = Float(progress / self.nameArray.count)
                progress += 1/self.nameArray.count
                break
                }
            }
</code>```

nameArray is empty in this loop

```<code>func getAllUserNamesPlease(handler: @escaping (_ userNames: [String]) -> ()){

        REF_USERS.observeSingleEvent(of: .value) { (userNameSnapshot) in
            guard let userNameSnapshot = userNameSnapshot.children.allObjects as? [DataSnapshot] else {return}
            var namesArray = [String]()
            for names in userNameSnapshot {
                let name = names.childSnapshot(forPath: "userName").value as? String ?? "No Name"
                namesArray.append(name)
            }
            handler(namesArray)
        }
    }
</code>```

答:
Any code that needs access to the results of an asynchronous call, should be inside that callback/completion handler. So your loop over nameArray, needs to be inside the {} braces:

```<code>DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
    self.nameArray = returnedNamesArray

    for userName in nameArray {
        if(userName.lowercased() == name!.lowercased()){

            self.userNameTaken = true
            self.progressView.progress = Float(progress / self.nameArray.count)
            progress += 1/self.nameArray.count
            break
            }
        }
    }
}
</code>```

Body:
I am trying to fetch all the user names in my database but the nameArray only contains values while its inside that function, how can I fix this?

DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
            self.nameArray = returnedNamesArray
}

for userName in nameArray {
            if(userName.lowercased() == name!.lowercased()){

                self.userNameTaken = true
                self.progressView.progress = Float(progress / self.nameArray.count)
                progress += 1/self.nameArray.count
                break
                }
            }

nameArray is empty in this loop

func getAllUserNamesPlease(handler: @escaping (_ userNames: [String]) -> ()){

        REF_USERS.observeSingleEvent(of: .value) { (userNameSnapshot) in
            guard let userNameSnapshot = userNameSnapshot.children.allObjects as? [DataSnapshot] else {return}
            var namesArray = [String]()
            for names in userNameSnapshot {
                let name = names.childSnapshot(forPath: "userName").value as? String ?? "No Name"
                namesArray.append(name)
            }
            handler(namesArray)
        }
    }

Body:
Any code that needs access to the results of an asynchronous call, should be inside that callback/completion handler. So your loop over nameArray, needs to be inside the {} braces:

DataService.instance.getAllUserNamesPlease { (returnedNamesArray) in
    self.nameArray = returnedNamesArray

    for userName in nameArray {
        if(userName.lowercased() == name!.lowercased()){

            self.userNameTaken = true
            self.progressView.progress = Float(progress / self.nameArray.count)
            progress += 1/self.nameArray.count
            break
            }
        }
    }
}


问:
Conditionally insert a line in JSON array like file with awk
I want to push items with awk to a myArray.json file like so

```<code>[
 item1,
 item2
]
</code>```

To add item1 I tried

```<code>echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json
</code>```

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

答:
As a possibly simpler alternative, you could just use jq. So, if you had the json file, myArray.json

```<code>[ "item1" ]
</code>```

You can add additional elements simply with

```<code>jq '. + ["item2"]' myArray.json
</code>```

which should result in

```<code>[
  "item1",
  "item2"
]
</code>```

Body:
I want to push items with awk to a myArray.json file like so

[
 item1,
 item2
]

To add item1 I tried

echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

Body:
As a possibly simpler alternative, you could just use jq. So, if you had the json file, myArray.json

[ "item1" ]

You can add additional elements simply with

jq '. + ["item2"]' myArray.json

which should result in

[
  "item1",
  "item2"
]


问:
Sinon error Attempted to wrap function which is already wrapped
Though there is a same question here but I could not find answer to my problem so here goes my question:

I am testing my node js app using mocha and chai. I am using sinion to wrap my function.

```<code>describe('App Functions', function(){

  let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
     //some stuff
  });
  it('get results',function(done) {
     testApp.someFun
  });
}

describe('App Errors', function(){

  let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
     //some stuff
  });
  it('throws errors',function(done) {
     testApp.someFun
  });
}
</code>```

When I try to run this test it gives me error

```<code>Attempted to wrap getObj which is already wrapped
</code>```

I also tried putting

```<code>beforeEach(function () {
  sandbox = sinon.sandbox.create();
});

afterEach(function () {
  sandbox.restore();
});
</code>```

in each describe, but still giving me same error.

答:
I ran into this with spies. This behaviour makes sinon pretty inflexible to work with. I created a helper function that attempts to remove any existing spy before setting a new one. That way I don't have to worry about any before/after state. A similar approach might work for stubs too.

import sinon, { SinonSpy } from 'sinon';

/**
 * When you set a spy on a method that already had one set in a previous test,
 * sinon throws an "Attempted to wrap [function] which is already wrapped" error
 * rather than replacing the existing spy. This helper function does exactly that.
 *
 * @param {object} obj
 * @param {string} method
 */
export const spy = function spy<T>(obj: T, method: keyof T): SinonSpy {
  // try to remove any existing spy in case it exists
  try {
    // @ts-ignore
    obj[method].restore();
  } catch (e) {
    // noop
  }
  return sinon.spy(obj, method);
};```

Body:
Though there is a same question here but I could not find answer to my problem so here goes my question:

I am testing my node js app using mocha and chai. I am using sinion to wrap my function.

describe('App Functions', function(){

  let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
     //some stuff
  });
  it('get results',function(done) {
     testApp.someFun
  });
}

describe('App Errors', function(){

  let mockObj = sinon.stub(testApp, 'getObj', (dbUrl) => {
     //some stuff
  });
  it('throws errors',function(done) {
     testApp.someFun
  });
}

When I try to run this test it gives me error

Attempted to wrap getObj which is already wrapped

I also tried putting

beforeEach(function () {
  sandbox = sinon.sandbox.create();
});

afterEach(function () {
  sandbox.restore();
});

in each describe, but still giving me same error.