问:
How do I get the latest call logs in Android Studio?
I have a code that works below. But I can't limit it. I just want to get the last 20 call logs.
But that's how I see all-time search logs.

It should only be the last call logs and I only need to see 20 pieces. Any help, I'd appreciate it.

My Code;

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

        ContentResolver cr = getBaseContext().getContentResolver();
        Cursor c = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, null);
        int totalCall = 1;
        if (c != null) {
            totalCall = c.getCount();
            if (c.moveToFirst()) {
                for (int j = 0; j < totalCall; j++) {

                    String callDate = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE));
                    String phNumber = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
                    String callDuration = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DURATION));
                    Date dateFormat= new Date(Long.valueOf(callDate));
                    String callDayTimes = String.valueOf(dateFormat);
                    String direction = null;

                    switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(CallLog.Calls.TYPE)))) {
                        case Telephony.Sms.MESSAGE_TYPE_INBOX:
                            direction = "OUTGOING";
                            break;
                        case Telephony.Sms.MESSAGE_TYPE_SENT:
                            direction = "INGOING";
                            break;
                        case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
                            direction = "MISSED";
                            break;
                        default:
                            break;
                    }

                    Toast.makeText(this, phNumber + direction + callDuration + callDayTimes, Toast.LENGTH_SHORT).show();
                }
            }
            c.close();
        }
    }
</code>```

答:
Please add this permission in your manifest file.

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

Add this function in your Activity file and call it in oncreate function.

 public void getCallLogs() {
        int flag=1;
        title.setText(Html.fromHtml("Call Logs"));
        deviceDetails.setText(Html.fromHtml(""));
        StringBuilder callLogs = new StringBuilder();

        ArrayList<String> calllogsBuffer = new ArrayList<String>();
        calllogsBuffer.clear();
        Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI,
                null, null, null, null);
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;
            int dircode = Integer.parseInt(callType);
            switch (dircode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "OUTGOING";
                    break;
                case CallLog.Calls.INCOMING_TYPE:
                    dir = "INCOMING";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    dir = "MISSED";
                    break;
            }
            calllogsBuffer.add("\nPhone Number: " + phNumber + " \nCall Type: "
                    + dir + " \nCall Date: " + callDayTime
                    + " \nCall duration in sec : " + callDuration + "\n");

        }
        managedCursor.close();
}```

To call this function, add this to your oncreate function in your Activity.

getCallLogs();

Body:
I have a code that works below. But I can't limit it. I just want to get the last 20 call logs.
But that's how I see all-time search logs.

It should only be the last call logs and I only need to see 20 pieces. Any help, I'd appreciate it.

My Code;

private void getCallLogs() {

        ContentResolver cr = getBaseContext().getContentResolver();
        Cursor c = cr.query(CallLog.Calls.CONTENT_URI, null, null, null, null);
        int totalCall = 1;
        if (c != null) {
            totalCall = c.getCount();
            if (c.moveToFirst()) {
                for (int j = 0; j < totalCall; j++) {

                    String callDate = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DATE));
                    String phNumber = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
                    String callDuration = c.getString(c.getColumnIndexOrThrow(CallLog.Calls.DURATION));
                    Date dateFormat= new Date(Long.valueOf(callDate));
                    String callDayTimes = String.valueOf(dateFormat);
                    String direction = null;

                    switch (Integer.parseInt(c.getString(c.getColumnIndexOrThrow(CallLog.Calls.TYPE)))) {
                        case Telephony.Sms.MESSAGE_TYPE_INBOX:
                            direction = "OUTGOING";
                            break;
                        case Telephony.Sms.MESSAGE_TYPE_SENT:
                            direction = "INGOING";
                            break;
                        case Telephony.Sms.MESSAGE_TYPE_OUTBOX:
                            direction = "MISSED";
                            break;
                        default:
                            break;
                    }

                    Toast.makeText(this, phNumber + direction + callDuration + callDayTimes, Toast.LENGTH_SHORT).show();
                }
            }
            c.close();
        }
    }

Body:
Please add this permission in your manifest file.

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

Add this function in your Activity file and call it in oncreate function.

 public void getCallLogs() {
        int flag=1;
        title.setText(Html.fromHtml("<b>Call Logs</b>"));
        deviceDetails.setText(Html.fromHtml(""));
        StringBuilder callLogs = new StringBuilder();

        ArrayList<String> calllogsBuffer = new ArrayList<String>();
        calllogsBuffer.clear();
        Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI,
                null, null, null, null);
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;
            int dircode = Integer.parseInt(callType);
            switch (dircode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "OUTGOING";
                    break;
                case CallLog.Calls.INCOMING_TYPE:
                    dir = "INCOMING";
                    break;
                case CallLog.Calls.MISSED_TYPE:
                    dir = "MISSED";
                    break;
            }
            calllogsBuffer.add("\nPhone Number: " + phNumber + " \nCall Type: "
                    + dir + " \nCall Date: " + callDayTime
                    + " \nCall duration in sec : " + callDuration + "\n");

        }
        managedCursor.close();
}

To call this function, add this to your oncreate function in your Activity.

getCallLogs();


来源: stackexchange

问:
Converting .gitignore to .hgignore and vice versa
I’m trying to convert ignore files between these DVCS formats.  I know this question has asked before, but it’s been some time and the reported answer appears to be outdated.  As noted in one of the responses “with git version 1.8.3.4 it does not work for every valid .hgignore”

Mercurial uses syntax to select the type of matching to use:

```<code>syntax: regexp    #Regular expression, Python/Perl
</code>```

or

```<code>syntax: glob      #Shell-style glob.
</code>```

What syntax does git use?  I’ve read it uses glob, but I’m not 100% sure it’s the same thing.  If I specified glob for my mercurial ignore file, will that be 100% compatible with git? (Ignoring the syntax declaration line)

答:
As @VonC states above, it's not possible to convert completely accurately.

However I've written a pretty basic .hgignore to .gitignore converter at https://github.com/devzendo/hgignore-to-gitignore

It tries to convert the elements of regexes that can be converted to glob elements, and passes glob elements as is (since hg seems to have a simpler form of glob than git, I'm assuming git can handle hg's globs).

ContentLicense: CC BY-SA 4.0

Body:
I’m trying to convert ignore files between these DVCS formats.  I know this question has asked before, but it’s been some time and the reported answer appears to be outdated.  As noted in one of the responses “with git version 1.8.3.4 it does not work for every valid .hgignore”

Mercurial uses syntax to select the type of matching to use:

syntax: regexp    #Regular expression, Python/Perl

or

syntax: glob      #Shell-style glob.

What syntax does git use?  I’ve read it uses glob, but I’m not 100% sure it’s the same thing.  If I specified glob for my mercurial ignore file, will that be 100% compatible with git? (Ignoring the syntax declaration line)


问:
Separating Axis Theorem and Python
This is what I am currently doing:

Creating 4 axis that are perpendicular to 4 edges of 2 rectangles. Since they are rectangles I do not need to generate an axis (normal) per edge.

I then loop over my 4 axes.

So for each axis:
I get the projection of every corner of a rectangle on to the axis.
There are 2 lists (arrays) containing those projections. One for each rectangle.
I then get the dot product of each projection and the axis. This returns a scalar value
that can be used to to determine the min and max.

Now the 2 lists contain scalars and not vectors. I sort the lists so I can easily select the min and max values. If the min of box B >= the max of box A  OR the max of box B <= the min of box A then there is no collision on that axis and no collision between the objects.

At this point the function finishes and the loop breaks.

If those conditions are never met for all the axis then we have a collision

I hope this was the correct way of doing it.

The python code itself can be found here http://pastebin.com/vNFP3mAb

Also:
http://www.gamedev.net/page/reference/index.html/_/reference/programming/game-programming/collision-detection/2d-rotated-rectangle-collision-r2604

The problem i was having is that the code above does not work. It always detects a a collision even where there is not a collision. What i typed out is exactly what the code is doing. If I am missing any steps or just not understanding how SAT works please let me know.

答:
I see two things wrong. First, the projection should simply be the dot product of a vertex with the axis. What you're doing is way too complicated. Second, the way you get your axis is incorrect. You write:

```<code>Axis1 = [  -(A_TR[0] - A_TL[0]),
             A_TR[1] - A_TL[1] ]
</code>```

Where it should read:

```<code>Axis1 = [  -(A_TR[1] - A_TL[1]),
             A_TR[0] - A_TL[0] ]
</code>```

The difference is coordinates does give you a vector, but to get the perpendicular you need to exchange the x and y values and negate one of them.

Hope that helps.

EDIT Found another bug

In this code:

```<code>if not ( B_Scalars[0] <= A_Scalars[3] or B_Scalars[3] >= A_Scalars[0] ):
            #no overlap so no collision
            return 0
</code>```

That should read:

```<code>if not ( B_Scalars[3] <= A_Scalars[0] or A_Scalars[3] <= B_Scalars[0] ):
</code>```

Sort gives you a list increasing in value. So [1,2,3,4] and [10,11,12,13] do not overlap because the minimum of the later is greater than the maximum of the former. The second comparison is for when the input sets are swapped.

ContentLicense: CC BY-SA 3.0

Title: Separating Axis Theorem and Python

Body:
I see two things wrong. First, the projection should simply be the dot product of a vertex with the axis. What you're doing is way too complicated. Second, the way you get your axis is incorrect. You write:

Axis1 = [  -(A_TR[0] - A_TL[0]),
             A_TR[1] - A_TL[1] ]

Where it should read:

Axis1 = [  -(A_TR[1] - A_TL[1]),
             A_TR[0] - A_TL[0] ]

The difference is coordinates does give you a vector, but to get the perpendicular you need to exchange the x and y values and negate one of them.

Hope that helps.

EDIT Found another bug

In this code:

if not ( B_Scalars[0] <= A_Scalars[3] or B_Scalars[3] >= A_Scalars[0] ):
            #no overlap so no collision
            return 0

That should read:

if not ( B_Scalars[3] <= A_Scalars[0] or A_Scalars[3] <= B_Scalars[0] ):

Sort gives you a list increasing in value. So [1,2,3,4] and [10,11,12,13] do not overlap because the minimum of the later is greater than the maximum of the former. The second comparison is for when the input sets are swapped.


问:
Multi-Agent framework SACI not found error
I am finding java based multi agent framework SACI since the project I am working get errors

```<code>import saci.agent.*;
</code>```

Is there any jar file related with saci?

答:
SACI is not supported by Jason anymore. It is suggested to move to the currently supported infrastructures like centralised, JADE for distributed agents and CArtAgO for distributed artefacts.

Anyway, if you still need it, you can find SACI jar file in old versions like Jason 1.3 (lib/saci.jar). This article about Jason also brings some information on how to use SACI.

Body:
I am finding java based multi agent framework SACI since the project I am working get errors

import saci.agent.*;

Is there any jar file related with saci?


问:
How to design the following grid view in Xamarin form in Xamarin iOS,Android
Needed same design of the form. My coding is this Xamarin form, Xamarin iOS, Android</p>

```<code><Frame Grid.Row="0" Grid.Column="0">
    <Image
        HeightRequest="50"
        Source="Dash01.png"
        WidthRequest="50" />
    <Label Text="Cow Milk"/>
</Frame>
<BoxView
    HeightRequest="3"
    HorizontalOptions="Fill"
    VerticalOptions="Start"
    Color="DimGray" Grid.Row="1" Grid.Column="0" />
</code>```

答:
Try this Code

```<code><StackLayout
            Padding="0,10"
            BackgroundColor="#e8f5e4"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="FillAndExpand">
            <CollectionView
                x:Name="foodList"
                Grid.Row="1"
                Margin="12,0"
                HorizontalOptions="FillAndExpand"
                ItemSizingStrategy="MeasureAllItems"
                SelectionMode="Single"
                VerticalOptions="FillAndExpand">
                <CollectionView.ItemsLayout>
                    <GridItemsLayout
                        HorizontalItemSpacing="5"
                        Orientation="Vertical"
                        Span="2"
                        VerticalItemSpacing="5" />
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Frame
                            Margin="5"
                            Padding="0"
                            BackgroundColor="Pink"
                            CornerRadius="10"
                            HorizontalOptions="FillAndExpand"
                            VerticalOptions="Fill">
                            <StackLayout
                                Margin="0,0,0,10"
                                Padding="10"
                                BackgroundColor="White"
                                HorizontalOptions="FillAndExpand"
                                VerticalOptions="Fill">
                                <Image
                                    Aspect="AspectFit"
                                    HeightRequest="50"
                                    HorizontalOptions="Center"
                                    Source="star.png" />
                                <Label
                                    FontSize="18"
                                    HorizontalOptions="Center"
                                    HorizontalTextAlignment="Center"
                                    Text="{Binding}" />
                            </StackLayout>
                        </Frame>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>
</code>```

Body:
Needed same design of the form. My coding is this Xamarin form, Xamarin iOS, Android

<Frame Grid.Row="0" Grid.Column="0">
    <Image
        HeightRequest="50"
        Source="Dash01.png"
        WidthRequest="50" />

</Frame>
<BoxView
    HeightRequest="3"
    HorizontalOptions="Fill"
    VerticalOptions="Start"
    Color="DimGray" Grid.Row="1" Grid.Column="0" />

Body:
Try this Code

<StackLayout
            Padding="0,10"
            BackgroundColor="#e8f5e4"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="FillAndExpand">
            <CollectionView
                x:Name="foodList"
                Grid.Row="1"
                Margin="12,0"
                HorizontalOptions="FillAndExpand"
                ItemSizingStrategy="MeasureAllItems"
                SelectionMode="Single"
                VerticalOptions="FillAndExpand">
                <CollectionView.ItemsLayout>
                    <GridItemsLayout
                        HorizontalItemSpacing="5"
                        Orientation="Vertical"
                        Span="2"
                        VerticalItemSpacing="5" />
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Frame
                            Margin="5"
                            Padding="0"
                            BackgroundColor="Pink"
                            CornerRadius="10"
                            HorizontalOptions="FillAndExpand"
                            VerticalOptions="Fill">
                            <StackLayout
                                Margin="0,0,0,10"
                                Padding="10"
                                BackgroundColor="White"
                                HorizontalOptions="FillAndExpand"
                                VerticalOptions="Fill">
                                <Image
                                    Aspect="AspectFit"
                                    HeightRequest="50"
                                    HorizontalOptions="Center"
                                    Source="star.png" />
                                <Label
                                    FontSize="18"
                                    HorizontalOptions="Center"
                                    HorizontalTextAlignment="Center"
                                    Text="{Binding}" />
                            </StackLayout>
                        </Frame>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>


问:
How to return bool value with navigator.pop?
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.</p>

```<code>final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}
</code>```

答:
check out this full woking code. you have to pass value which you want to return.</p>

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

class Delete extends StatefulWidget {
  Delete({Key key}) : super(key: key);

  @override
  _DeleteState createState() => _DeleteState();
}

class _DeleteState extends State<Delete> with SingleTickerProviderStateMixin {
  int index = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            _showDialog().then((value) {
              print(value.toString());
            });
          },
          child: Text("press ME!"),
        ),
      ),
    );
  }

  _showDialog() {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Delete Appointment'),
            content: Text(
              'Are you sure? \nThis action cannot undo.',
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
            actions: <Widget>[
              FlatButton(
                color: Colors.blue,
                child: Text(
                  'CANCEL',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
                onPressed: () {
                  Navigator.pop(context, false);
                },
              ),
              SizedBox(
                width: 50,
              ),
              FlatButton(
                color: Colors.red,
                child: Text(
                  'CONFIRM',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
                onPressed: () {
                  Navigator.pop(context, true);
                },
              )
            ],
          );
        });
  }
}
</code>```

Body:
I'm trying to return a bool value from the dialogbox but I do not understand why the value does not return as need. I have tried returning as a future value and returning the values together with context after popping the dialogbox.

final bool delete = await _showDialog();
print(delete);

Future<bool> _showDialog() {
bool result;

showDialog(
  context: context,
  builder: (BuildContext context) {
    return AlertDialog(
      title: Text('Delete Appointment'),
      content: Text(
        'Are you sure? \nThis action cannot undo.',
        style: TextStyle(
          color: Colors.red,
          fontSize: 20
        ),
      ),
      actions: <Widget>[
        FlatButton(
          color: Colors.blue,
          child: Text(
            'CANCEL',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = false);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        ),
        SizedBox(
          width: 50,
        ),
        FlatButton(
          color: Colors.red,
          child: Text(
            'CONFIRM',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20
            ),
          ),
          onPressed: () {
            setState(() => result = true);
            //print(result);
            Navigator.pop(context, result);
            return Future.value(result);
          },
        )
      ],
    );
  }
);
}

Body:
check out this full woking code. you have to pass value which you want to return.

import 'package:flutter/material.dart';

class Delete extends StatefulWidget {
  Delete({Key key}) : super(key: key);

  @override
  _DeleteState createState() => _DeleteState();
}

class _DeleteState extends State<Delete> with SingleTickerProviderStateMixin {
  int index = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            _showDialog().then((value) {
              print(value.toString());
            });
          },
          child: Text("press ME!"),
        ),
      ),
    );
  }

  _showDialog() {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Delete Appointment'),
            content: Text(
              'Are you sure? \nThis action cannot undo.',
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
            actions: <Widget>[
              FlatButton(
                color: Colors.blue,
                child: Text(
                  'CANCEL',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
                onPressed: () {
                  Navigator.pop(context, false);
                },
              ),
              SizedBox(
                width: 50,
              ),
              FlatButton(
                color: Colors.red,
                child: Text(
                  'CONFIRM',
                  style: TextStyle(color: Colors.white, fontSize: 20),
                ),
                onPressed: () {
                  Navigator.pop(context, true);
                },
              )
            ],
          );
        });
  }
}


问:
Array defined in parent component cannot be sliced
Must be a rookie mistake but here it is:

I have a parent component where i defined an array:

```<code>...
<object-list-grid
   v-bind:objects="objectsList"
></object-list-grid>
...
data() {
        return {
            ...
            objectsList: [],
            ...
        };
</code>```

I pass this down to a child component (through another child component) as objects:

In middle child (object-list-grid):

```<code><object-list
   :objects="objects"
></object-list>
...
props: ["objects"],
</code>```

And finally in the last child:

props: ["objects"],

I want to create a subset of this array, but i fail to do this. I try to do it in created() of this last child; logs produce results i cannot understand:

```<code>console.log(this.objects);
console.log(this.objects.length);
console.log(this.objects.slice());
</code>```

Produces the following result:

I noticed that in the log it shows as an ob object as opposed to an Array but as a read similar issues my impression was that its normal in Vue. Also it seems to me that the array has 17 elements.

Any help or explanation is appreciated.

答: As far as i can tell @skirtle provided the best explanation.</p>

Body:
Must be a rookie mistake but here it is:

I have a parent component where i defined an array:

...
<object-list-grid
   v-bind:objects="objectsList"
></object-list-grid>
...
data() {
        return {
            ...
            objectsList: [],
            ...
        };

I pass this down to a child component (through another child component) as objects:

In middle child (object-list-grid):

<object-list
   :objects="objects"
></object-list>
...
props: ["objects"],

And finally in the last child:

props: ["objects"],

I want to create a subset of this array, but i fail to do this. I try to do it in created() of this last child; logs produce results i cannot understand:

console.log(this.objects);
console.log(this.objects.length);
console.log(this.objects.slice());

Produces the following result:

I noticed that in the log it shows as an ob object as opposed to an Array but as a read similar issues my impression was that its normal in Vue. Also it seems to me that the array has 17 elements.

Any help or explanation is appreciated.


问:
Do large organizations use Amazon web services?
I was impressed with Amazon's new Amazon Simple Notification Service (Amazon SNS).  Amazon has lots of other really impressive web app building blocks.  Are there examples of large organizations using AWS?  They seem impressive but the downside is you outsource your processing to a third party which could be considered pretty risky.</p>

答:
Netflix has a VERY large AWS deployment.

Here's a talk from Adrian Cockcroft, their "Cloud Architect":
http://blip.tv/file/4252897

Also, http://cloudscaling.com/blog/cloud-computing/cloud-innovators-netflix-strategy-reflects-google-philosophy and http://perspectives.mvdirona.com/2010/05/31/NetflixOnAWS.aspx

PBS for content delivery: http://aws.amazon.com/solutions/case-studies/pbs/

Virgin Atlantic's travel site: http://aws.amazon.com/solutions/case-studies/vtravelled/

Ericsson's set-top-box content service: http://aws.amazon.com/solutions/case-studies/ericsson/

Hitachi for a video delivery service: http://aws.amazon.com/solutions/case-studies/hitachi-systems/

Washington Post for document processing: http://aws.amazon.com/solutions/case-studies/washington-post/

Then there's a slew of backup providers that resell S3 storage and organizations that back their own data into S3.

Plus tons of familiar web brands like Yelp, Reddit, SmugMug, AirBnB, UrbanSpoon, PlayFish, and tons of others.

ContentLicense: CC BY-SA 2.5


问:
In django, getting the following usernames in user profile
i'm building a following model. I have created a following model as shown below and it is working fine in the admin. I did not create a view for the following because i'm in primary stage of building i'm testing in templates to bring that usernames in userspostlist, but it's not working.

my models.py for following:

```<code>class UserProfile(models.Model):
user      = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by')

def __str__(self):
    return str(self.following.all().count())

class post(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='post_pics', null=True, blank=True)
video = models.FileField(upload_to='post_videos', null=True, blank=True)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

objects = postManager()
def __str__(self):
    return self.title
</code>```

my views.py for userpostlist:

```<code>class UserPostListView(ListView):
model = post
template_name = 'blog/user_post.html'  #<app>/<model>_<viewtype>.html
context_object_name = 'posts'

def get_queryset(self):
    user = get_object_or_404(User, username=self.kwargs.get('username'))
    return post.objects.filter(author=user).order_by('-date_posted')
</code>```

and my userpostlist.html:

```<code>{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
  <h1 class="mb-3">posts by {{view.kwargs.username}}</h1>
  {% for user in username.owner.following.all %}
  {{ user.username }}
  {% endfor %}

    {% for post in posts %}
    <article class="content-section">
        <div class="article-metadata">
            <div class="img">
               <img class="rounded-circle article-img" data-toggle="modal" data-target="#mymodal" src="{{ post.author.profile.image.url }}">
            </div>

            <div class="profile-info">
              <a class="h2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
              <div class="text-muted">{{ post.date_posted }}</div>
            </div>
       </div>
{% endfor %}
{% endblock content %}
</code>```

Is there any problem with the userpostlist view in views.py? do i need to add some code there?

答:
You have some options here, where one is to pass users into context:

```<code>class UserPostListView(ListView):
    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['author'] = get_object_or_404(User, username=self.kwargs.get('username')
        return context
</code>```

And then instead of this:

```<code>{% for user in username.owner.following.all %}
   {{ user.username }}
{% endfor %}
</code>```

Use this:

```<code>{{ author.username }}
</code>```

Body:
i'm building a following model. I have created a following model as shown below and it is working fine in the admin. I did not create a view for the following because i'm in primary stage of building i'm testing in templates to bring that usernames in userspostlist, but it's not working.

my models.py for following:

class UserProfile(models.Model):
user      = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by')

def __str__(self):
    return str(self.following.all().count())

class post(models.Model):
parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='post_pics', null=True, blank=True)
video = models.FileField(upload_to='post_videos', null=True, blank=True)
content = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

objects = postManager()
def __str__(self):
    return self.title

my views.py for userpostlist:

class UserPostListView(ListView):
model = post
template_name = 'blog/user_post.html'  #<app>/<model>_<viewtype>.html
context_object_name = 'posts'

def get_queryset(self):
    user = get_object_or_404(User, username=self.kwargs.get('username'))
    return post.objects.filter(author=user).order_by('-date_posted')

and my userpostlist.html:

{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

posts by {{view.kwargs.username}}

  {% for user in username.owner.following.all %}
  {{ user.username }}
  {% endfor %}

    {% for post in posts %}

              {{ post.author }}

{{ post.date_posted }}

{% endfor %}
{% endblock content %}

Is there any problem with the userpostlist view in views.py? do i need to add some code there?

Body:
You have some options here, where one is to pass users into context:

class UserPostListView(ListView):
    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['author'] = get_object_or_404(User, username=self.kwargs.get('username')
        return context

And then instead of this:

{% for user in username.owner.following.all %}
   {{ user.username }}
{% endfor %}

Use this:

{{ author.username }}


问:
How do i return data where that contain empty string instead of NULL in laravel
I want to get my data from database where one of my attribute was empty string instead of null....but my code return all data where NULL and empty string combined...here is my code</p>

```<code>public function findAllPersons2(){
        return $this->where('pi_person_type','3')
                     ->where('pi_vendor_id','!=' , '')
                    ->orderBy('pi_name', 'asc')
                    ->get();
    }

</code>```

答:
This code will also work:

```<code>->where('pi_vendor_id', '')
</code>```

For convenience, if you want to verify that a column is equal to a
  given value, you may pass the value directly as the second argument to
  the where method.

https://laravel.com/docs/6.x/queries#where-clauses

Body:
I want to get my data from database where one of my attribute was empty string instead of null....but my code return all data where NULL and empty string combined...here is my code

public function findAllPersons2(){
        return $this->where('pi_person_type','3')
                     ->where('pi_vendor_id','!=' , '')
                    ->orderBy('pi_name', 'asc')
                    ->get();
    }

Body:
This code will also work:

->where('pi_vendor_id', '')

For convenience, if you want to verify that a column is equal to a
  given value, you may pass the value directly as the second argument to
  the where method.

https://laravel.com/docs/6.x/queries#where-clauses


问:
Correctly storing query response with GROUP BY using PHP
I have this big database storing a lot of info about customers and bills and so on. What I want to do is, using the id's of the customers, search for all their bills, SUM() the price contained in every one of them, and store them to print one unique bill.

So I sarted thinking of this:

try {
    $conn = new PDO('mysql:host=myhost;dbname=accounting','user','pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();
}

$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids
                        FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
    $string = $row['ids'];
}

$array = explode(',', $string);
array_pop($array);
array_shift($array);

$destinationId = 0;
foreach ($array as $id) {
    $stmt2 = $conn->prepare('SELECT id, call_type, source_customer_cost
                            FROM cdr
                            WHERE source_external_subscriber_id = :id
                            AND destination_account_id = :destinationId');

    $stmt2->execute(array('id' => $id, 'destinationId' => $destinationId));

    foreach ($stmt2 as $row2) {
        $datos[] = $row2;
    }
}
```

<p>I was not convinced by the result so I decided to check for myself, executing my code first ad then looking for a customer to compare the number of bills to the lenght of the array (hence the lack of SUM() yet)
Then, as I was looking for a more convincing way I stumbled upon this really useful post. So I changed my code to this. But here they only explain how to write the query, not how to store it inside an array. </p>

<pre class="lang-php prettyprint-override"><code>try {
    $conn = new PDO('mysql:host=host;dbname=accounting','user','pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    var_dump($conn);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();
}

$destinationId = 0;
$stmt2 = $conn->prepare('SELECT source_external_subscriber_id, source_customer_cost FROM cdr WHERE destination_account_id = :destinationId GROUP BY source_external_subscriber_id');
$stmt2->execute(array('destinationId' => $destinationId));

foreach ($stmt as $row) {
     $datos[] = $row2;
}
</code>```

Now I was wondering the right way to store the data so it looks something like this:

array = [
    0 => array(
            "id" => source_external_subscriber_id1,
            "total" => SUM(source_customer_cost)
         ),
    1 => array(
            "id" => source_external_subscriber_id2,
            "total" => SUM(source_customer_cost)
         )...
];
```

Thank you all for the help, I hope you have a great day!

答:
So the answer to this one was as tricky as simple: the array returned by the query had duplicated rows, maybe I got wrong the for-each statement since I recently started using them. Anyways, here are both the query and my storage solution: </p>

<pre class="lang-php prettyprint-override"><code>$destinationId = 0;
$stmt2 = $conn->prepare('SELECT source_external_subscriber_id, SUM(source_customer_cost) FROM cdr WHERE destination_account_id = :destinationId GROUP BY source_external_subscriber_id');
$stmt2->execute(array('destinationId' => $destinationId));

foreach ($stmt2 as $row2) {
    $data[] = $row2;
}

for ($i=0; $i < sizeof($data); $i++) {
    $sanitizedData[$i] = array(
        0 => $data[$i][0],
        1 => $data[$i][1]
    );
}
</code>```

Body:
I have this big database storing a lot of info about customers and bills and so on. What I want to do is, using the id's of the customers, search for all their bills, SUM() the price contained in every one of them, and store them to print one unique bill.

So I sarted thinking of this:

try {
    $conn = new PDO('mysql:host=myhost;dbname=accounting','user','pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();
}

$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids
                        FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
    $string = $row['ids'];
}

$array = explode(',', $string);
array_pop($array);
array_shift($array);

$destinationId = 0;
foreach ($array as $id) {
    $stmt2 = $conn->prepare('SELECT id, call_type, source_customer_cost
                            FROM cdr
                            WHERE source_external_subscriber_id = :id
                            AND destination_account_id = :destinationId');

    $stmt2->execute(array('id' => $id, 'destinationId' => $destinationId));

    foreach ($stmt2 as $row2) {
        $datos[] = $row2;
    }
}

I was not convinced by the result so I decided to check for myself, executing my code first ad then looking for a customer to compare the number of bills to the lenght of the array (hence the lack of SUM() yet)
Then, as I was looking for a more convincing way I stumbled upon this really useful post. So I changed my code to this. But here they only explain how to write the query, not how to store it inside an array.

try {
    $conn = new PDO('mysql:host=host;dbname=accounting','user','pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    var_dump($conn);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();
}

$destinationId = 0;
$stmt2 = $conn->prepare('SELECT source_external_subscriber_id, source_customer_cost FROM cdr WHERE destination_account_id = :destinationId GROUP BY source_external_subscriber_id');
$stmt2->execute(array('destinationId' => $destinationId));

foreach ($stmt as $row) {
     $datos[] = $row2;
}

Now I was wondering the right way to store the data so it looks something like this:

array = [
    0 => array(
            "id" => source_external_subscriber_id1,
            "total" => SUM(source_customer_cost)
         ),
    1 => array(
            "id" => source_external_subscriber_id2,
            "total" => SUM(source_customer_cost)
         )...
];

Thank you all for the help, I hope you have a great day!

Body:
So the answer to this one was as tricky as simple: the array returned by the query had duplicated rows, maybe I got wrong the for-each statement since I recently started using them. Anyways, here are both the query and my storage solution:

$destinationId = 0;
$stmt2 = $conn->prepare('SELECT source_external_subscriber_id, SUM(source_customer_cost) FROM cdr WHERE destination_account_id = :destinationId GROUP BY source_external_subscriber_id');
$stmt2->execute(array('destinationId' => $destinationId));

foreach ($stmt2 as $row2) {
    $data[] = $row2;
}

for ($i=0; $i < sizeof($data); $i++) {
    $sanitizedData[$i] = array(
        0 => $data[$i][0],
        1 => $data[$i][1]
    );
}


问:
How to save only the rows with a specific numpy array / matrix shape in Pandas dataframe?
Say I have a dataframe df, and a column 'Array' that contains bunch of numpy arrays. Now I want to save only the rows with the array shape that most commonly existed in this column, and drop the other rows. I want to input these arrays as features to do some machine learning stuff, so I need to ensure they are all in a same shape. Below is my script, but it doesn't work. I hope the answer should also works when the features are matrices.

```<code>import pandas as pd
df = pd.DataFrame(data)
lst = [i.shape for i in df['Array']]
most_common = max(set(lst), key=lst.count)
df = df[df['Array'].shape==most_common]
</code>```

Basically I want to convert atomic structures into numerical features like numpy arrays or matrices. I'm using a method called Coulomb Matrix to achieve this. In case you want to try yourselves, this is my whole script:

```<code>import pandas as pd
from ase.db import connect
from ase import Atoms
from ase.io import read
import numpy as np
import numpy.linalg as linalg

def eig_data(atoms):
    init_R = atoms.positions
    init_Z = atoms.numbers
    x_list = []
    y_list = []
    z_list = []
    M_list = []
    M_tmp = []
    M_matrix = []
    for x,y,z in init_R:
        x_list.append(x)
        y_list.append(y)
        z_list.append(z)
    order=0
    for xl,yl,zl,Z in zip(x_list,y_list,z_list,init_Z):
        M_list.append((order,xl,yl,zl,Z))
        order+=1
    for order,x,y,z,charge in M_list:
        r = np.array((x,y,z))
        M_tmp = []
        for oorder,ox,oy,oz,ocharge in M_list:
            if oorder == order:
                IJ = 0.5*ocharge**2.4
                M_tmp.append(IJ)
            else:
                otr = np.array((ox,oy,oz))
                dist = np.linalg.norm(r-otr)
                InJ = (charge*ocharge)/dist
                M_tmp.append(InJ)
        M_matrix.append(M_tmp)
    M = np.array(M_matrix)
    w,v = np.linalg.eig(M)
    w_sort = np.sort(w)[::-1]
#    print(np.amax(w_sort))
    return w_sort

res = connect('c2db.db')
df = []
for row in res.select():
    atoms = row.toatoms()
    i = row.id
    c = eig_data(atoms)
    f = row.formula
    E = row.energy
    g = row.gap
    w = row.workfunction
    df.append({'id': i, 'c_matrix':c, 'formula':f, 'energy': E, 'band_gap':g, 'work_function':w})
df = pd.DataFrame(df)

lst = [i.shape for i in df['c_matrix']]
most_common = max(set(lst), key=lst.count)
df = df[df['c_matrix'].shape==most_common]
</code>```

The database can be downloaded here: c2db_database

答:
My suggestion would be to create a filter in this way for your dataframe

```<code>filter = [i.shape == most_common for i in df['c_matrix']]
df = df[filter]
</code>```

Or simply

```<code>df = df[[i.shape == most_common for i in df['c_matrix']]]
</code>```

Body:
Say I have a dataframe df, and a column 'Array' that contains bunch of numpy arrays. Now I want to save only the rows with the array shape that most commonly existed in this column, and drop the other rows. I want to input these arrays as features to do some machine learning stuff, so I need to ensure they are all in a same shape. Below is my script, but it doesn't work. I hope the answer should also works when the features are matrices.

import pandas as pd
df = pd.DataFrame(data)
lst = [i.shape for i in df['Array']]
most_common = max(set(lst), key=lst.count)
df = df[df['Array'].shape==most_common]

Basically I want to convert atomic structures into numerical features like numpy arrays or matrices. I'm using a method called Coulomb Matrix to achieve this. In case you want to try yourselves, this is my whole script:

import pandas as pd
from ase.db import connect
from ase import Atoms
from ase.io import read
import numpy as np
import numpy.linalg as linalg

def eig_data(atoms):
    init_R = atoms.positions
    init_Z = atoms.numbers
    x_list = []
    y_list = []
    z_list = []
    M_list = []
    M_tmp = []
    M_matrix = []
    for x,y,z in init_R:
        x_list.append(x)
        y_list.append(y)
        z_list.append(z)
    order=0
    for xl,yl,zl,Z in zip(x_list,y_list,z_list,init_Z):
        M_list.append((order,xl,yl,zl,Z))
        order+=1
    for order,x,y,z,charge in M_list:
        r = np.array((x,y,z))
        M_tmp = []
        for oorder,ox,oy,oz,ocharge in M_list:
            if oorder == order:
                IJ = 0.5*ocharge**2.4
                M_tmp.append(IJ)
            else:
                otr = np.array((ox,oy,oz))
                dist = np.linalg.norm(r-otr)
                InJ = (charge*ocharge)/dist
                M_tmp.append(InJ)
        M_matrix.append(M_tmp)
    M = np.array(M_matrix)
    w,v = np.linalg.eig(M)
    w_sort = np.sort(w)[::-1]
#    print(np.amax(w_sort))
    return w_sort

res = connect('c2db.db')
df = []
for row in res.select():
    atoms = row.toatoms()
    i = row.id
    c = eig_data(atoms)
    f = row.formula
    E = row.energy
    g = row.gap
    w = row.workfunction
    df.append({'id': i, 'c_matrix':c, 'formula':f, 'energy': E, 'band_gap':g, 'work_function':w})
df = pd.DataFrame(df)

lst = [i.shape for i in df['c_matrix']]
most_common = max(set(lst), key=lst.count)
df = df[df['c_matrix'].shape==most_common]

The database can be downloaded here: c2db_database

Body:
My suggestion would be to create a filter in this way for your dataframe

filter = [i.shape == most_common for i in df['c_matrix']]
df = df[filter]

Or simply

df = df[[i.shape == most_common for i in df['c_matrix']]]


问:
FCKEditor doesn't set Value property on postback!
I'm using FCKEditor on my asp.net web page.  It appears beautifully, and the editor looks really good on the front end.  Only problem is, the .Value property is not being set on the postback.  No matter what changes the user makes to the value of the control on the page, when I click "Submit", the .Value property remains blank.

I have Googled for other solutions, and most of them are of the variety where there's some conflict with Ajax, such as this and this.  My problem is not solved by these solutions; it's much more fundamental than that.  I'm not doing anything to do with Ajax; I'm just a simple asp.net newbie with a simple web form, and the value property is not being set on postback, not in IE and not in FF.

It appears that at least one other person has had this problem, but no solution yet.

Any ideas?
Thanks!

New information:
I tried this out on a "hello world" test web site - and the test web site works 100%.  There is obviously a problem on my page, but I have no idea where to begin tracking this down.

Here's the markup of my page, in case anyone can see anything obvious that my newbie eyes can't:

```<code><%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EmailTemplateEditForm.aspx.vb"
  Inherits="EEI_App.EmailTemplateEditForm" %>

<%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>EEI - Email Template</title>
  <link rel="stylesheet" href="EEI.css">

  <script language="javascript" id="jssembleWare" src="sembleWare.js"></script>

  <style type="text/css">
    .style1
    {
      height: 251px;
    }
    .style2
    {
      width: 2%;
      height: 251px;
    }
    .style3
    {
      height: 490px;
    }
  </style>
</head>
<body>
  <form id="form1" runat="server">
  <%@ register src="header.ascx" tagname="header" tagprefix="uc1" %>
  <%@ register src="footer.ascx" tagname="footer" tagprefix="uc1" %>
  <uc1:header ID="header1" runat="server" />
  <!-- main content area -->
  <div class="content">
    <!-- title of the page -->
    <div class="boxheader">
      Email Template
    </div>
    <div class="standardbox">
      <!-- Start Page Main Contents-->
      <!-- error messages -->
      <div class="errorbox">
        <asp:Label ID="lblError" CssClass="ErrorControlStyle" runat="server" EnableViewState="False"
          Width="100%"></asp:Label>
      </div>
      <table class="contenttable">
        <tr>
          <td align="left" valign="top" class="style3">
            <div class="actionbox">
              <div class="navheadertitle">
                Navigation</div>
              <ul>
                <li>
                  <asp:LinkButton ID="btnSubmit" CssClass="LinkButtonStyle" runat="server">Submit</asp:LinkButton>
                </li>
                <li>
                  <asp:LinkButton ID="btnCancel" CssClass="LinkButtonStyle" runat="server" CausesValidation="false">Cancel</asp:LinkButton>
                </li>
              </ul>
            </div>
          </td>
          <td align="left" valign="top" class="style3">
            <p>
            </p>
            <table>
              <tr class="MCRSFieldRow">
                <td class="MCRSFieldLabelCell">
                  <asp:Label ID="lblEmailTemplate_TemplateName" CssClass="LabelStyle" runat="server"
                    Width="175">Template Name</asp:Label>
                </td>
                <td class="MCRSFieldEditCell">
                  <asp:TextBox ID="txtEmailTemplate_TemplateName" CssClass="TextBoxStyle" runat="server"
                    Width="100%"></asp:TextBox>
                </td>
                <td class="MCRSFieldLabelCell">
                  <asp:Label ID="lblEmailTemplate_TemplateType" CssClass="LabelStyle" runat="server"
                    Width="175">Template Type</asp:Label>
                </td>
                <td class="MCRSFieldEditCell">
                  <asp:RadioButtonList ID="rblEmailTemplate_TemplateType" CssClass="RadioButtonListStyle"
                    runat="server" RepeatColumns="1" RepeatDirection="Horizontal" Width="135px">
                    <asp:ListItem Value="1">Cover Letter</asp:ListItem>
                    <asp:ListItem Value="2">Email</asp:ListItem>
                  </asp:RadioButtonList>
                </td>
                <td class="MCRSRowRightCell">

                </td>
              </tr>
              <tr class="MCRSFieldRow">
                <td class="MCRSFieldLabelCell">
                  Composition Date
                </td>
                <td class="MCRSFieldEditCell">
                  <asp:Label ID="lblEmailTemplate_CompositionDate" CssClass="ElementLabelStyle" runat="server"
                    Width="175"></asp:Label>
                </td>
                <td class="MCRSFieldLabelCell">
                  Last Used Date
                </td>
                <td class="MCRSFieldEditCell">
                  <asp:Label ID="lblEmailTemplate_LastUsedDate" CssClass="ElementLabelStyle" runat="server"
                    Width="175"></asp:Label>
                </td>
                <td class="MCRSRowRightCell">

                </td>
              </tr>
              <tr class="MCRSFieldRow">
                <td class="MCRSFieldLabelCell">
                  Composed By
                </td>
                <td class="MCRSFieldEditCell" colspan="3">
                  <asp:Label ID="lblPerson_FirstNames" CssClass="ElementLabelStyle" runat="server"></asp:Label>
                  <asp:Label ID="lblPerson_LastName" CssClass="ElementLabelStyle" runat="server"></asp:Label>
                </td>
                <td class="MCRSRowRightCell">

                </td>
              </tr>
              <tr class="MCRSFieldRow">
                <td class="MCRSFieldLabelCell">
                  <asp:Label ID="lblEmailTemplate_Subject" CssClass="LabelStyle" runat="server" Width="175">Subject</asp:Label>
                </td>
                <td class="MCRSFieldEditCell" colspan="3">
                  <asp:TextBox ID="txtEmailTemplate_Subject" CssClass="TextBoxStyle" runat="server"
                    Width="100%"></asp:TextBox>
                </td>
                <td class="MCRSRowRightCell">

                </td>
              </tr>
              <tr class="MCRSFieldRow">
                <td class="style1">
                  <asp:Label ID="lblEmailTemplate_Body" CssClass="LabelStyle" runat="server" Width="175">Body</asp:Label>
                </td>
                <td class="style1" colspan="3">
                  <FCKeditorV2:FCKeditor ID="FCKeditor1" runat="server" Height="500px">
                  </FCKeditorV2:FCKeditor>
                </td>
                <td class="style2">

                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </div>
    <p>
      <a class="InputButtonStyle" href="#_swTopOfPage">Top of Page</a>
    </p>
  </div>
  <uc1:footer ID="footer1" runat="server" />
  <p>
    <asp:TextBox ID="txtEmailTemplate_Body" CssClass="TextAreaStyle" Rows="4" runat="server"
      Width="100%" Height="16px" Visible="False"></asp:TextBox>
  </p>
  </form>
</body>
</html>
</code>```

答:
The solution above didn't work for me, however i found solution here

Here's code what I used

```<code>protected void Page_Load(object sender, EventArgs e)
{
    ScriptManager.RegisterOnSubmitStatement(
        this,
        this.GetType(),
        "AjaxHack", "for ( var i = 0; i < parent.frames.length; ++i ) if ( parent.frames[i].FCK ) parent.frames[i].FCK.UpdateLinkedField();");
}
</code>```

Hope that saves someones day. I was looking for the solution for 2 months.

Cheers

OwnerDisplayName: Shaul

Body:
I'm using FCKEditor on my asp.net web page.  It appears beautifully, and the editor looks really good on the front end.  Only problem is, the .Value property is not being set on the postback.  No matter what changes the user makes to the value of the control on the page, when I click "Submit", the .Value property remains blank.

I have Googled for other solutions, and most of them are of the variety where there's some conflict with Ajax, such as this and this.  My problem is not solved by these solutions; it's much more fundamental than that.  I'm not doing anything to do with Ajax; I'm just a simple asp.net newbie with a simple web form, and the value property is not being set on postback, not in IE and not in FF.

It appears that at least one other person has had this problem, but no solution yet.

Any ideas?
Thanks!

New information:
I tried this out on a "hello world" test web site - and the test web site works 100%.  There is obviously a problem on my page, but I have no idea where to begin tracking this down.

Here's the markup of my page, in case anyone can see anything obvious that my newbie eyes can't:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EmailTemplateEditForm.aspx.vb"
  Inherits="EEI_App.EmailTemplateEditForm" %>

<%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>EEI - Email Template</title>
  <link rel="stylesheet" href="EEI.css">

  <form id="form1" runat="server">
  <%@ register src="header.ascx" tagname="header" tagprefix="uc1" %>
  <%@ register src="footer.ascx" tagname="footer" tagprefix="uc1" %>
  <uc1:header ID="header1" runat="server" />

      Email Template

        <asp:Label ID="lblError" CssClass="ErrorControlStyle" runat="server" EnableViewState="False"
          Width="100%"></asp:Label>

                Navigation

                  <asp:LinkButton ID="btnSubmit" CssClass="LinkButtonStyle" runat="server">Submit</asp:LinkButton>

                  <asp:LinkButton ID="btnCancel" CssClass="LinkButtonStyle" runat="server" CausesValidation="false">Cancel</asp:LinkButton>

                  <asp:Label ID="lblEmailTemplate_TemplateName" CssClass="LabelStyle" runat="server"
                    Width="175">Template Name</asp:Label>

                  <asp:TextBox ID="txtEmailTemplate_TemplateName" CssClass="TextBoxStyle" runat="server"
                    Width="100%"></asp:TextBox>

                  <asp:Label ID="lblEmailTemplate_TemplateType" CssClass="LabelStyle" runat="server"
                    Width="175">Template Type</asp:Label>

                  <asp:RadioButtonList ID="rblEmailTemplate_TemplateType" CssClass="RadioButtonListStyle"
                    runat="server" RepeatColumns="1" RepeatDirection="Horizontal" Width="135px">
                    <asp:ListItem Value="1">Cover Letter</asp:ListItem>
                    <asp:ListItem Value="2">Email</asp:ListItem>
                  </asp:RadioButtonList>

                  Composition Date

                  <asp:Label ID="lblEmailTemplate_CompositionDate" CssClass="ElementLabelStyle" runat="server"
                    Width="175"></asp:Label>

                  Last Used Date

                  <asp:Label ID="lblEmailTemplate_LastUsedDate" CssClass="ElementLabelStyle" runat="server"
                    Width="175"></asp:Label>

                  Composed By

                  <asp:Label ID="lblPerson_FirstNames" CssClass="ElementLabelStyle" runat="server"></asp:Label>
                  <asp:Label ID="lblPerson_LastName" CssClass="ElementLabelStyle" runat="server"></asp:Label>

                  <asp:Label ID="lblEmailTemplate_Subject" CssClass="LabelStyle" runat="server" Width="175">Subject</asp:Label>

                  <asp:TextBox ID="txtEmailTemplate_Subject" CssClass="TextBoxStyle" runat="server"
                    Width="100%"></asp:TextBox>

                  <asp:Label ID="lblEmailTemplate_Body" CssClass="LabelStyle" runat="server" Width="175">Body</asp:Label>

                  <FCKeditorV2:FCKeditor ID="FCKeditor1" runat="server" Height="500px">
                  </FCKeditorV2:FCKeditor>

      Top of Page

  <uc1:footer ID="footer1" runat="server" />

    <asp:TextBox ID="txtEmailTemplate_Body" CssClass="TextAreaStyle" Rows="4" runat="server"
      Width="100%" Height="16px" Visible="False"></asp:TextBox>

  </form>

LastEditorDisplayName: Shaul

Body:
The solution above didn't work for me, however i found solution here

Here's code what I used

protected void Page_Load(object sender, EventArgs e)
{
    ScriptManager.RegisterOnSubmitStatement(
        this,
        this.GetType(),
        "AjaxHack", "for ( var i = 0; i < parent.frames.length; ++i ) if ( parent.frames[i].FCK ) parent.frames[i].FCK.UpdateLinkedField();");
}

Hope that saves someones day. I was looking for the solution for 2 months.

Cheers


问:
jQuery - on click with * selector trigger too many times
I want to record down the full css path on every element click by user, I follow this answer to create a function that get css path of the clicked element

```<code>$('body').on('click',"*",function(){
    var rightArrowParents = [];
    $(this).parents().addBack().not('html').each(function(e) {
        var entry = this.tagName.toLowerCase();

        if($(this).attr('id')){
            entry += "#" + $(this).attr('id');
        }

        if (this.className) {
        entry += "." + this.className.replace(/ /g, '.');
        }

        rightArrowParents.push(entry);
    });
    console.log(rightArrowParents.join(" > "));
})
</code>```

but I notice that this function is called so many times when I click on an element which is wrap by multiple element,

for example when I click on h1:

```<code>body > div.sample1.sample2 > div.sample3.sample4 > h1.test1.test2.test3

body > div.sample1.sample2 > div.sample3.sample4

body > div.sample1.sample2

</code>```

when I add return false after console.log, it will only output the full css path of h1, which is the expected result, but if I do this, some element will not work properly such as  will not redirect to another website

below is what I have tried:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <h1 class="test1 test2 test3">some example text</h1>
        </div>
    </div>
    <div>
        <h1 class="test1 test2 test3">some sample text</h1>
    </div>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <a class="test1 test2 test3" href="https://www.google.com/">henlo</a>
        </div>
    </div>
    <script>
        jQuery(function($){
            $('body').on('click',"*",function(){
                var rightArrowParents = [];
                $(this).parents().addBack().not('html').each(function(e) {
                    var entry = this.tagName.toLowerCase();

                    if($(this).attr('id')){
                        entry += "#" + $(this).attr('id');
                    }

                    if (this.className) {
                    entry += "." + this.className.replace(/ /g, '.');
                    }

                    rightArrowParents.push(entry);
                });
                console.log(rightArrowParents.join(" > "));
                //can't do this, since it will make some element malfunction
                //return false
            })
        })
    </script>
</body>
</html>
</code>```

what should I do to make the jQuery work properly?

答:
This solution may look a bit hacky, but it gets the job done. along these lines there may also be a more elegant solution (like to compare some property of the event for cancellation.

jQuery(function($){
    $('body').on('click',"*",function(e) {
        // mark the event as seen and cancel it it was seen
        if (e.seen) return;
        e.seen = true;

        var rightArrowParents = [];
        $(this).parents().addBack().not('html').each(function(i, o) {
            var entry = this.tagName.toLowerCase();

            if($(this).attr('id')){
                entry += "#" + $(this).attr('id');
            }

            if (this.className) {
            entry += "." + this.className.replace(/ /g, '.');
            }

            rightArrowParents.push(entry);
        });
        console.log(rightArrowParents.join(" > "));
    })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <h1 class="test1 test2 test3">some example text</h1>
        </div>
    </div>
    <div>
        <h1 class="test1 test2 test3">some sample text</h1>
    </div>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            henlo
        </div>
    </div>
</body>
</html></code>```

Body:
I want to record down the full css path on every element click by user, I follow this answer to create a function that get css path of the clicked element

$('body').on('click',"*",function(){
    var rightArrowParents = [];
    $(this).parents().addBack().not('html').each(function(e) {
        var entry = this.tagName.toLowerCase();

        if($(this).attr('id')){
            entry += "#" + $(this).attr('id');
        }

        if (this.className) {
        entry += "." + this.className.replace(/ /g, '.');
        }

        rightArrowParents.push(entry);
    });
    console.log(rightArrowParents.join(" > "));
})

but I notice that this function is called so many times when I click on an element which is wrap by multiple element,

for example when I click on h1:

body > div.sample1.sample2 > div.sample3.sample4 > h1.test1.test2.test3

body > div.sample1.sample2 > div.sample3.sample4

body > div.sample1.sample2

when I add return false after console.log, it will only output the full css path of h1, which is the expected result, but if I do this, some element will not work properly such as  will not redirect to another website

below is what I have tried:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

some example text

some sample text

            henlo

what should I do to make the jQuery work properly?

Body:
This solution may look a bit hacky, but it gets the job done. along these lines there may also be a more elegant solution (like to compare some property of the event for cancellation.

jQuery(function($){
    $('body').on('click',"*",function(e) {
        // mark the event as seen and cancel it it was seen
        if (e.seen) return;
        e.seen = true;

        var rightArrowParents = [];
        $(this).parents().addBack().not('html').each(function(i, o) {
            var entry = this.tagName.toLowerCase();

            if($(this).attr('id')){
                entry += "#" + $(this).attr('id');
            }

            if (this.className) {
            entry += "." + this.className.replace(/ /g, '.');
            }

            rightArrowParents.push(entry);
        });
        console.log(rightArrowParents.join(" > "));
    })
})

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <h1 class="test1 test2 test3">some example text</h1>
        </div>
    </div>
    <div>
        <h1 class="test1 test2 test3">some sample text</h1>
    </div>
    <div class="sample1 sample2">
        <div class="sample3 sample4">
            <a class="test1 test2 test3" href="https://www.google.com/">henlo</a>
        </div>
    </div>
</body>
</html>


问:
CTS execution using junit categories
CTS execution:

How can we trigger the test suite of Junit by using annotations and categories through command line?

答:
You can run CTS individual test methods or the whole class using android instrumentation command.

For Example: Here in this example CTS test class with a specific method is mentioned to run, you can remove the test method from the below command to run all test methods within the class.

adb shell am instrument -w -e class android.animation.AnimatorSetEventsTest#testCancel
    \com.android.frameworks.coretests android.support.test.runner.AndroidJUnitRunner

For more details on running tests via instrumentation follow this link -
https://source.android.com/compatibility/tests/development/instrumentation

Title: CTS execution using junit categories


问:
How can I load the hub.KerasLayer offline?
I have build a model by tensorflow hub and save it.
But when I load it, I must add custom_objects={'KerasLayer':hub.KerasLayer}.
It will connect the network.

```<code>model = tf.keras.models.load_model('my_model.h5',custom_objects={'KerasLayer':hub.KerasLayer})
</code>```

How can I download the hub.KerasLayer and load it offline?

答:
You can also use TFHUB_CACHE_DIR to do this automatically

```<code>import tensorflow_hub as hub
import os

os.environ["TFHUB_CACHE_DIR"] = "/tmp/model"
hub.KerasLayer("https://tfhub.dev/google/nnlm-id-dim50-with-normalization/2")
</code>```

Model assets will be downloaded to /tmp/model/
Future calls to hub.KerasLayer("https://tfhub.dev/google/nnlm-id-dim50-with-normalization/2") will use the local copy

Body:
I have build a model by tensorflow hub and save it.
But when I load it, I must add custom_objects={'KerasLayer':hub.KerasLayer}.
It will connect the network.

model = tf.keras.models.load_model('my_model.h5',custom_objects={'KerasLayer':hub.KerasLayer})

How can I download the hub.KerasLayer and load it offline?

Body:
You can also use TFHUB_CACHE_DIR to do this automatically

import tensorflow_hub as hub
import os

os.environ["TFHUB_CACHE_DIR"] = "/tmp/model"
hub.KerasLayer("https://tfhub.dev/google/nnlm-id-dim50-with-normalization/2")

Model assets will be downloaded to /tmp/model/
Future calls to hub.KerasLayer("https://tfhub.dev/google/nnlm-id-dim50-with-normalization/2") will use the local copy


问:
Can we use Condition with axes in XPATH?
Can we use Condition with axes in XPATH?

Trying to check both parent and child in XPath. Example:

```<code>//span[text()='Accounts']/parent::a OR child::div
</code>```

I know this is wrong. But is there any way to check the condition?

I know the situation looks vague. But I am trying to find a logic where I can use both parent and child axes to create an XPath.
The main motive is to inspect an element from UI and create XPath using axes. and automate the process.

When I am trying the above XPath, it throws some error.

答:
Maybe if you use | instead of OR</p>

```<code>//span[text()='Accounts']/(parent::a|child::div)
</code>```

Body:
Can we use Condition with axes in XPATH?

Trying to check both parent and child in XPath. Example:

//span[text()='Accounts']/parent::a OR child::div

I know this is wrong. But is there any way to check the condition?

I know the situation looks vague. But I am trying to find a logic where I can use both parent and child axes to create an XPath.
The main motive is to inspect an element from UI and create XPath using axes. and automate the process.

When I am trying the above XPath, it throws some error.

Body:
Maybe if you use | instead of OR

//span[text()='Accounts']/(parent::a|child::div)


问:
How to find same values and mark them in a separate column in a dataframe in Python?
I have a bunch of column that i want to concatenate and then find how many of them are same in the concat column. I written some code but my dataframe is too big and it takes too long to complete this exercise.

This is what i have done.

```<code>import pandas as pd

l = [[1,'a','b','c','d'],[2,'a','c','c','d'],[3,'a','c','c','d'],[4,'a','b','b','d'],[5,'a','c','c','d']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (df.iloc[i,df.shape[1]-2] == df.iloc[j,df.shape[1]-2]):
                df.iloc[i,df.shape[1]-1] = "yes"
</code>```

This works on the smaller dataframe but on a bigger one it takes too long. Is there a more efficient way to produce the same result?

答:
I think this is a faster way to solve this.</p>

```<code>import pandas as pd

l = [[1, 'a', 'b', 'c', 'd'], [2, 'a', 'c', 'c', 'd'], [3, 'a', 'c', 'c', 'd'], [4, 'a', 'b', 'b', 'd'],
     [5, 'a', 'c', 'c', 'd']]
df = pd.DataFrame(l, columns=['Serial No', 'one', 'two', 'three', 'four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

df['Yes/No'] = df.duplicated(["Conc"], keep=False)
df = df.replace({'Yes/No': {True: "Yes", False: "No"}})
</code>```

Body:
I have a bunch of column that i want to concatenate and then find how many of them are same in the concat column. I written some code but my dataframe is too big and it takes too long to complete this exercise.

This is what i have done.

import pandas as pd

l = [[1,'a','b','c','d'],[2,'a','c','c','d'],[3,'a','c','c','d'],[4,'a','b','b','d'],[5,'a','c','c','d']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (df.iloc[i,df.shape[1]-2] == df.iloc[j,df.shape[1]-2]):
                df.iloc[i,df.shape[1]-1] = "yes"

This works on the smaller dataframe but on a bigger one it takes too long. Is there a more efficient way to produce the same result?

Body:
I think this is a faster way to solve this.

import pandas as pd

l = [[1, 'a', 'b', 'c', 'd'], [2, 'a', 'c', 'c', 'd'], [3, 'a', 'c', 'c', 'd'], [4, 'a', 'b', 'b', 'd'],
     [5, 'a', 'c', 'c', 'd']]
df = pd.DataFrame(l, columns=['Serial No', 'one', 'two', 'three', 'four'])

df["Conc"] = df["one"] + "____" + df["three"] + "____" + df["four"]
df['Yes/No'] = ""

df['Yes/No'] = df.duplicated(["Conc"], keep=False)
df = df.replace({'Yes/No': {True: "Yes", False: "No"}})


问:
Passing a dynamic string to an object
Is it possible to somehow pass arguments to an object?

Something like,

```<code>const messages = (str1, str2){
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
}

const validateInput = ({ str1 = '', str2 = '' }) => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b')
</code>```

I'm not looking for something like,

```<code>const message = (str1, str2) => `${str1} is not the same as ${str2}`
</code>```

I'm curious to know if this can be done specifically with an object.

答:
You could take an object for all messages and inside function which return a string with a message, depending on the handed over strings.

const messages = {
    1: (str1, str2) => `${str1} is not the same as ${str2}`,
    2: (str1, str2) => 'message2',
    3: (str1, str2) => 'message3',
    4: (str1, str2) => 'message4',
    5: (str1, str2) => 'message5',
    6: (str1, str2) => 'message6',
};

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b');```
</div>
</div>
</p>

<p>If you switch the order of calling <code>messages</code> with parameters first and then by a number, then only a single function is necessary.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const messages = (str1, str2) => ({
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
});

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages(str1, str2)[1])
    }
}

validateInput('a', 'b');</code>```

Title: Passing a dynamic string to an object

Body:
Is it possible to somehow pass arguments to an object?

Something like,

const messages = (str1, str2){
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
}

const validateInput = ({ str1 = '', str2 = '' }) => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b')

I'm not looking for something like,

const message = (str1, str2) => `${str1} is not the same as ${str2}`

I'm curious to know if this can be done specifically with an object.

Body:
You could take an object for all messages and inside function which return a string with a message, depending on the handed over strings.

const messages = {
    1: (str1, str2) => `${str1} is not the same as ${str2}`,
    2: (str1, str2) => 'message2',
    3: (str1, str2) => 'message3',
    4: (str1, str2) => 'message4',
    5: (str1, str2) => 'message5',
    6: (str1, str2) => 'message6',
};

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages[1](str1, str2))
    }
}

validateInput('a', 'b');

If you switch the order of calling messages with parameters first and then by a number, then only a single function is necessary.

const messages = (str1, str2) => ({
    1: `${str1} is not the same as ${str2}`,
    2: 'message2',
    3: 'message3',
    4: 'message4',
    5: 'message5',
    6: 'message6',
});

const validateInput = (str1 = '', str2 = '') => {
    if (str1 !== str2) {
        console.log(messages(str1, str2)[1])
    }
}

validateInput('a', 'b');


问:
How are these called? literals, captions, labels or properties?
Instead of hardcoding text in the UI we use placeholders with keys which get replaced by the actual text. This also helps localisation of the application.

example Java properties file:

```<code>about=About
contact=Contact Us
</code>```

These could also be found in the database or in XML files etc

How are these called?

literals?

captions?

labels?

properties?

I'm looking for a general and language agnostic term.

Edit: Adding all the suggested terms from answers:

translatable strings

resource strings

Resource Properties

localization

Culture Variant UI Fields

Locales

Locales Strings

messages

message placeholders

I don't know why but it kind of saddens and confuses me that there isn't a single solid term to describe this thing. And in one way or another it exists in all languages and frameworks.

答:
I'd use Web Constants or Message Constants or UI Constants.

Properties file can be named as WebConstants_en.properties or WebConstants_it.properties etc.

Body:
Instead of hardcoding text in the UI we use placeholders with keys which get replaced by the actual text. This also helps localisation of the application.

example Java properties file:

about=About
contact=Contact Us

These could also be found in the database or in XML files etc

How are these called?

literals?

captions?

labels?

properties?

I'm looking for a general and language agnostic term.

Edit: Adding all the suggested terms from answers:

translatable strings

resource strings

Resource Properties

localization

Culture Variant UI Fields

Locales

Locales Strings

messages

message placeholders

I don't know why but it kind of saddens and confuses me that there isn't a single solid term to describe this thing. And in one way or another it exists in all languages and frameworks.


问:
Responsive cards with aligned footers in Bootstrap 4.4
With Bootstrap 4.4, I would like to have a deck of cards with:

equal height (.h-100)

a .card-footer aligned at the bottom

responsive layout with the number of cards per row defined by the viewport width

It seems that I can't have all three of them at the same time, is that true?

To get the card footers to align at the bottom of the cards, one would place them inside a .card-deck div, but that does not agree at all with
 for example. I have also tried to add a .row-cols-x class to the parent .row, but that does not work either.

Is it possible after all?

答:
You can use the card-deck component to archive the first both points on your list. Here is an example:

```<code><div class="card-deck">
  <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
  <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
  <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
</div>
</code>```

To archive the third point you can extend it in your scss files via:

```<code>.card-deck {
  @include media-breakpoint-only(xs) {
    column-count: 1;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
@include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
}
</code>```

This sets the number of columns per breakpoint. That overwrites the default behavior (having always 3 columns, but just on on xs)

Body:
You can use the card-deck component to archive the first both points on your list. Here is an example:

<div class="card-deck">
  <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
  <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
  <div class="card">
    <img src="..." class="card-img-top" alt="...">
    <div class="card-body">
      <h5 class="card-title">Card title</h5>
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
    </div>
    <div class="card-footer">
      <small class="text-muted">Last updated 3 mins ago</small>
    </div>
  </div>
</div>

To archive the third point you can extend it in your scss files via:

.card-deck {
  @include media-breakpoint-only(xs) {
    column-count: 1;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
@include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
}

This sets the number of columns per breakpoint. That overwrites the default behavior (having always 3 columns, but just on on xs)


问:
How to create object in async and await function in Node js?
Hi i am creating a shopify api node js script which runs with async and await.Basically i am using this to fetch data form paginated page and i am getting the data properly in console log for each page. the issue is i am unable to make a array in which i get all the data in the end of function.

Here is the code

```<code>const fetch = require("node-fetch");
const priceRule = "641166639179"
const totalresult = []
async  function  findCodeId(price_rule, url=null){
    //get(priceRuleId, id)
    let urlneww = url ? url : `https://xxxxxxxxxxxx.myshopify.com/admin/api/2020-01/price_rules/${price_rule}/discount_codes.json`;

    await fetch(urlneww, {
        method: 'GET',
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
        }
    })
        //.then(response => response.json())
        .then(result => {
            let rrr = result.json() ;
            rrr.then((data)=>{
                totalresult.push(data)
                console.log(data)
            }).catch(error =>  error);
        if(result.headers.get('link').includes("next")){
        let str = result.headers.get('link');
        let arrStr = str.split('<').pop().split('>')[0]; // returns 'two'
        //console.log(arrStr);
            findCodeId(priceRule,arrStr);
            //console.log(totalresult)
        }else{
        }
        //return totalresult

    })
    .catch(error => console.log('error', error));

}

findCodeId(priceRule)
</code>```

i am trying to push the data in totalresult constant but it is not working. Could you please suggest how can i do this so that on each result it pushes the data in the totalresult  and at end of function i got all result data collected in totalresult.

答:
You are mixing promise/async-await style which is making it complex. Also you are not awaiting while recursively calling function. Try this</p>

```<code>const fetch = require("node-fetch");
const priceRule = "641166639179";
const totalresult = [];
async function findCodeId(price_rule, url = null) {
  try {
    // get(priceRuleId, id)
    const urlneww = url
      ? url
      : `https://xxxxxxxxxxxx.myshopify.com/admin/api/2020-01/price_rules/${price_rule}/discount_codes.json`;

    const result = await fetch(urlneww, {
      "method": "GET",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
      }
    });
    const data = await result.json();
    totalresult.push(data);
    console.log(data);
    if (result.headers.get("link").includes("next")) {
      const str = result.headers.get("link");
      const arrStr = str
        .split("<")
        .pop()
        .split(">")[0]; // returns 'two'
      // console.log(arrStr);
      await findCodeId(priceRule, arrStr);
      // console.log(totalresult)
    } else {
     console.log(totalresult);
   }
  } catch (Err) {
    console.error(Err);
  }

}

findCodeId(priceRule);

</code>```

Body:
Hi i am creating a shopify api node js script which runs with async and await.Basically i am using this to fetch data form paginated page and i am getting the data properly in console log for each page. the issue is i am unable to make a array in which i get all the data in the end of function.

Here is the code

const fetch = require("node-fetch");
const priceRule = "641166639179"
const totalresult = []
async  function  findCodeId(price_rule, url=null){
    //get(priceRuleId, id)
    let urlneww = url ? url : `https://xxxxxxxxxxxx.myshopify.com/admin/api/2020-01/price_rules/${price_rule}/discount_codes.json`;

    await fetch(urlneww, {
        method: 'GET',
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
        }
    })
        //.then(response => response.json())
        .then(result => {
            let rrr = result.json() ;
            rrr.then((data)=>{
                totalresult.push(data)
                console.log(data)
            }).catch(error =>  error);
        if(result.headers.get('link').includes("next")){
        let str = result.headers.get('link');
        let arrStr = str.split('<').pop().split('>')[0]; // returns 'two'
        //console.log(arrStr);
            findCodeId(priceRule,arrStr);
            //console.log(totalresult)
        }else{
        }
        //return totalresult

    })
    .catch(error => console.log('error', error));

}

findCodeId(priceRule)

i am trying to push the data in totalresult constant but it is not working. Could you please suggest how can i do this so that on each result it pushes the data in the totalresult  and at end of function i got all result data collected in totalresult.

Body:
You are mixing promise/async-await style which is making it complex. Also you are not awaiting while recursively calling function. Try this

const fetch = require("node-fetch");
const priceRule = "641166639179";
const totalresult = [];
async function findCodeId(price_rule, url = null) {
  try {
    // get(priceRuleId, id)
    const urlneww = url
      ? url
      : `https://xxxxxxxxxxxx.myshopify.com/admin/api/2020-01/price_rules/${price_rule}/discount_codes.json`;

    const result = await fetch(urlneww, {
      "method": "GET",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx="
      }
    });
    const data = await result.json();
    totalresult.push(data);
    console.log(data);
    if (result.headers.get("link").includes("next")) {
      const str = result.headers.get("link");
      const arrStr = str
        .split("<")
        .pop()
        .split(">")[0]; // returns 'two'
      // console.log(arrStr);
      await findCodeId(priceRule, arrStr);
      // console.log(totalresult)
    } else {
     console.log(totalresult);
   }
  } catch (Err) {
    console.error(Err);
  }

}

findCodeId(priceRule);


问:
How to replace NA with set of values
I have the following data frame:

```<code>library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df
</code>```

It looks like this:

```<code># A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA
</code>```

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

```<code>  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2
</code>```

How can I achieve that?

答:
Another one, quite similar to ThomasIsCoding's solution:</p>

```<code>> df$score[is.na(df$score)]<-max(df$score, na.rm=T)+(1:sum(is.na(df$score)))
> df
# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12
</code>```

Title: How to replace NA with set of values

Body:
I have the following data frame:

library(dplyr)
library(tibble)

df <- tibble(
  source = c("a", "b", "c", "d", "e"),
  score = c(10, 5, NA, 3, NA ) )

df

It looks like this:

# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10 . # current max value
2 b          5
3 c         NA
4 d          3
5 e         NA

What I want to do is to replace NA in score column with values ranging for existing max  + n onwards. Where n range from 1 to total number of rows of the df

Resulting in this (hand-coded) :

  source score
  a         10
  b          5
  c         11 # obtained from 10 + 1
  d          3
  e         12 #  obtained from 10 + 2

How can I achieve that?

Body:
Another one, quite similar to ThomasIsCoding's solution:

> df$score[is.na(df$score)]<-max(df$score, na.rm=T)+(1:sum(is.na(df$score)))
> df
# A tibble: 5 x 2
  source score
  <chr>  <dbl>
1 a         10
2 b          5
3 c         11
4 d          3
5 e         12


问:
Subtracting two datetimes from each other and returning in HH:MM:SS in python 2.7
I have two date-time strings that I wish to subtract from each other and want to return a answer in
the HH:MM:SS format using python 2.7. For Example I have "2019-01-22 10:46:34" and "2019-01-22 10:30:34" and want it to return something like this 00:16:00. I have tried converting the times to integers but can't seem to convert back. I have also tried the datetime module. Below is a rudimentary example of something I tried that I wish to convert into a function.

```<code>from datetime import datetime
a = "2019-01-22 10:46:34"
b = "2019-01-22 10:30:25"
c = a-b
print(datetime.time(c, '%Y-%m-%d %H:%M:%S')
</code>```

I have been working on this problem for a few days so any help would be much appreciated.

答:
Take a look at the timedelta Object.

With that you can get the difference of two datetime Objects in Seconds and then you can calc the Minutes Hours etc.

Example you have two datetime objects a and b, c will be the timedelta object:

```<code>import datetime

# datetime object (year, month, day, hour, minute, second)
a = datetime.datetime.strptime("2019-01-22 10:46:34", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("2019-01-22 10:30:25", "%Y-%m-%d %H:%M:%S")

# returns timedelta object
c = a-b
print('Difference: ', c)

# return (minutes, seconds)
minutes = divmod(c.seconds, 60)
print('Difference in minutes: ', minutes[0], 'minutes',
                                 minutes[1], 'seconds')
</code>```

EDIT: divmod() is used to get batter result in terms of minutes and seconds, but you could also just write

```<code>minutes = c.seconds / 60
print('Difference in minutes: ', minutes)
</code>```

Output: Difference in minutes: 16 minutes 9 seconds

Body:
I have two date-time strings that I wish to subtract from each other and want to return a answer in
the HH:MM:SS format using python 2.7. For Example I have "2019-01-22 10:46:34" and "2019-01-22 10:30:34" and want it to return something like this 00:16:00. I have tried converting the times to integers but can't seem to convert back. I have also tried the datetime module. Below is a rudimentary example of something I tried that I wish to convert into a function.

from datetime import datetime
a = "2019-01-22 10:46:34"
b = "2019-01-22 10:30:25"
c = a-b
print(datetime.time(c, '%Y-%m-%d %H:%M:%S')

I have been working on this problem for a few days so any help would be much appreciated.

Body:
Take a look at the timedelta Object.

With that you can get the difference of two datetime Objects in Seconds and then you can calc the Minutes Hours etc.

Example you have two datetime objects a and b, c will be the timedelta object:

import datetime

# datetime object (year, month, day, hour, minute, second)
a = datetime.datetime.strptime("2019-01-22 10:46:34", "%Y-%m-%d %H:%M:%S")
b = datetime.datetime.strptime("2019-01-22 10:30:25", "%Y-%m-%d %H:%M:%S")

# returns timedelta object
c = a-b
print('Difference: ', c)

# return (minutes, seconds)
minutes = divmod(c.seconds, 60)
print('Difference in minutes: ', minutes[0], 'minutes',
                                 minutes[1], 'seconds')

EDIT: divmod() is used to get batter result in terms of minutes and seconds, but you could also just write

minutes = c.seconds / 60
print('Difference in minutes: ', minutes)

Output: Difference in minutes: 16 minutes 9 seconds


问:
Change bootstrap datepicker date format on select
I'm using bootstrap datepicker on a textbox. The default format of the date when you select a date is mm/dd/yyyy. Now I want to change it to dd/mm/yyyy. How can I accomplish this. Right now I'm just initializing it just like this.

```<code>$('.datepicker').datepicker()
</code>```

What should I add to change its format?

答:
```<code>  $(function () {
    $('.datetimepicker').datetimepicker(
      {
        format: 'Y-m-d h:m:s'
     }
    );
 });`
</code>```

Body:
I'm using bootstrap datepicker on a textbox. The default format of the date when you select a date is mm/dd/yyyy. Now I want to change it to dd/mm/yyyy. How can I accomplish this. Right now I'm just initializing it just like this.

$('.datepicker').datepicker()

What should I add to change its format?