问:
I've created a Cloud Function from Pub/Sub topic, shall I expect retry a delivery of message from pub/sub if function fails?
I have a function with a simple test code like:

```<code>    exports.helloPubSub = (event, context) => {
      const message = event.data
         ? Buffer.from(event.data, 'base64').toString()
         : 'Hello, World';
      console.log(context);
      throw new Error("Fail");
    };
</code>```

When I publish a message to Pub/sub the function fails and I expect that it will be called again with the same message after 600 seconds since the pub/sub subscription has Acknowledgement deadline set to 600 Seconds.
But it does not work as expected looks like it acks the message immediately despite the failure in a cloud function.

According to the doc: Cloud Functions acks the message internally upon successful function execution.

答:
You must make sure that you have enabled retries on the function. From the "Retrying Background Functions" documentation (emphasis mine):

Cloud Functions guarantees at-least-once execution of a background
function for each event emitted by an event source. However, by
default, if a function invocation terminates with an error, the
function will not be invoked again, and the event will be dropped.
When you enable retries on a background function, Cloud Functions will
retry a failed function invocation until it completes successfully, or
the retry window (by default, 7 days) expires.

You can enable retries by providing the --retry option when creating the function via the gcloud command-line tool or checking the "Retry on failure" box when creating via the Cloud Console.

When a Cloud Function fails and retry is enabled, it nacks the message, which makes the message a candidate for redelivery. To delay the redelivery of nacked messages, you can set up a RetryPolicy on the subscription. To update the subscription to use a retry policy, find the name of the subscription created by Cloud Functions in the Cloud Console Pub/Sub section. Then, for example, you can issue this gcloud command to set the minimum retry delay to 1 second and the maximum delay to 60 seconds:

```<code>gcloud pubsub subscriptions update <subscription name> --min-retry-delay=1s --max-retry-delay=60s
</code>```

Body:
I have a function with a simple test code like:

    exports.helloPubSub = (event, context) => {
      const message = event.data
         ? Buffer.from(event.data, 'base64').toString()
         : 'Hello, World';
      console.log(context);
      throw new Error("Fail");
    };

When I publish a message to Pub/sub the function fails and I expect that it will be called again with the same message after 600 seconds since the pub/sub subscription has Acknowledgement deadline set to 600 Seconds.
But it does not work as expected looks like it acks the message immediately despite the failure in a cloud function.

According to the doc: Cloud Functions acks the message internally upon successful function execution.

Body:
You must make sure that you have enabled retries on the function. From the "Retrying Background Functions" documentation (emphasis mine):

Cloud Functions guarantees at-least-once execution of a background
function for each event emitted by an event source. However, by
default, if a function invocation terminates with an error, the
function will not be invoked again, and the event will be dropped.
When you enable retries on a background function, Cloud Functions will
retry a failed function invocation until it completes successfully, or
the retry window (by default, 7 days) expires.

You can enable retries by providing the --retry option when creating the function via the gcloud command-line tool or checking the "Retry on failure" box when creating via the Cloud Console.

When a Cloud Function fails and retry is enabled, it nacks the message, which makes the message a candidate for redelivery. To delay the redelivery of nacked messages, you can set up a RetryPolicy on the subscription. To update the subscription to use a retry policy, find the name of the subscription created by Cloud Functions in the Cloud Console Pub/Sub section. Then, for example, you can issue this gcloud command to set the minimum retry delay to 1 second and the maximum delay to 60 seconds:

gcloud pubsub subscriptions update <subscription name> --min-retry-delay=1s --max-retry-delay=60s


来源: stackexchange

问:
Listeners for changes to app config/resources files
I have an app running in tomcat6 which reads a resource file (a simple text file, no xml) at startup to configure/instantiate some classes. Now I want to be able to modify that file and the changes to be reflected in the app without having to restart the server. Is there a way to do that? </p>

<p>Basically if I could define and attach a listener to that resource, that's all I need. </p>

答: Programatically you can trgger a service which will refresh those classes with new files</p>

ContentLicense: CC BY-SA 3.0

Body:
I have an app running in tomcat6 which reads a resource file (a simple text file, no xml) at startup to configure/instantiate some classes. Now I want to be able to modify that file and the changes to be reflected in the app without having to restart the server. Is there a way to do that?

Basically if I could define and attach a listener to that resource, that's all I need.


问:
How to set time with jquery keyup method?
I want to add time with jquery keyup method.
Here is my code:

$("#textbox").keyup(function () {
    var text = $('#textbox').val()

    $("#output").val(text);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
   <body>
      <textarea id="textbox" placeholder = "..." rows="5"></textarea>
      <br><br>
      <input type="text" id="output"/>
   </body>
</html></code>```

Actually I want when I'm typing, the keyup function call every 5 seconds.
Like:
I'm typing The quick brown fox jumps over the lazy dog.
Desired output: T f t d like this.
first lettert t. The keyup function is callded after 5 section. And i'm also typing. After 5 sec the secound word is f from 'fox'.
And continue like this....

Have any way?

答:
One way to do this would be to bind a one() event handler every 5 seconds. Note that you would need to use keypress instead of keyup for the case sensitivity of the character which is typed to be respected. Try this:

addKeyup();

function addKeyup() {
  $("#textbox").one('keypress', function(e) {
    $("#output").val((i, v) => `${v} ${String.fromCharCode(e.which)}`);
    setTimeout(addKeyup, 5000);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textbox" placeholder="..." rows="5"></textarea><br /><br />
<input type="text" id="output" /></code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add time with jquery keyup method.
Here is my code:

$("#textbox").keyup(function () {
    var text = $('#textbox').val()

    $("#output").val(text);
});

<!DOCTYPE html>

      <textarea id="textbox" placeholder = "..." rows="5"></textarea>

      <input type="text" id="output"/>

Actually I want when I'm typing, the keyup function call every 5 seconds.
Like:
I'm typing The quick brown fox jumps over the lazy dog.
Desired output: T f t d like this.
first lettert t. The keyup function is callded after 5 section. And i'm also typing. After 5 sec the secound word is f from 'fox'.
And continue like this....

Have any way?

Body:
One way to do this would be to bind a one() event handler every 5 seconds. Note that you would need to use keypress instead of keyup for the case sensitivity of the character which is typed to be respected. Try this:

addKeyup();

function addKeyup() {
  $("#textbox").one('keypress', function(e) {
    $("#output").val((i, v) => `${v} ${String.fromCharCode(e.which)}`);
    setTimeout(addKeyup, 5000);
  });
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textbox" placeholder="..." rows="5"></textarea><br /><br />
<input type="text" id="output" />


问:
Retrive selected value of ng-select - Angular8
I am a novice with Angular 8.

I created the following dropdown menu, in a component, that works very well for me:

```<code><ng-select class="w-25 p-3" placeholder="{{'author' | translate}}" [clearable]="false" [searchable]="false">
        <ng-option>{{'author' | translate}}</ng-option>
        <ng-option>{{'title' | translate}}</ng-option>
        <ng-option>{{'date' | translate}}</ng-option>
</ng-select>
</code>```

Now I would like to know how I can retrive the selected element in the ts file of the same component.

Thanks in advance.

答:
you can add >> [ngModelOptions]="{standalone: true}" to get value

  <ng-select
    [items]="countries.countries"
    bindLabel="country"
    bindValue="country_code"
    [ngModelOptions]="{standalone: true}"
    [(ngModel)]="selectedCountry" (change)="getCountry()">
   </ng-select>

```

Body:
I am a novice with Angular 8.

I created the following dropdown menu, in a component, that works very well for me:

<ng-select class="w-25 p-3" placeholder="{{'author' | translate}}" [clearable]="false" [searchable]="false">
        <ng-option>{{'author' | translate}}</ng-option>
        <ng-option>{{'title' | translate}}</ng-option>
        <ng-option>{{'date' | translate}}</ng-option>
</ng-select>

Now I would like to know how I can retrive the selected element in the ts file of the same component.

Thanks in advance.

Body:
you can add >> [ngModelOptions]="{standalone: true}" to get value

<div class="col-sm-10 text-left">
  <ng-select
    [items]="countries.countries"
    bindLabel="country"
    bindValue="country_code"
    [ngModelOptions]="{standalone: true}"
    [(ngModel)]="selectedCountry" (change)="getCountry()">
   </ng-select>
</div>


问:
Android - How to inject a values/strings.xml in runtime
Consider that I have an Rest API that let me fetch a strings.xml file.
Once downloaded is it posible set as the default values/strings.xml file of the app?

答:
String resources are static defined and can not be changed at runtime.

However, you could use the Restring library to set and load strings at runtime by adding the dependencies:

```<code>// Replace bundled strings dynamically
implementation 'dev.b3nedikt.restring:restring:4.0.3'

// Intercept view inflation
implementation 'io.github.inflationx:viewpump:2.0.3'

// Allows to update the text of views at runtime without recreating the activity
implementation 'dev.b3nedikt.reword:reword:1.1.0'
</code>```

Initialising it in your Application class:

```<code>Restring.init(this,
        new RestringConfig.Builder()
                .stringsLoader(new SampleStringsLoader())
                .loadAsync(false) // If string loader should load strings asynchronously, default true
                .build()
        );

ViewPump.init(ViewPump.builder()
        .addInterceptor(RewordInterceptor.INSTANCE)
        .build());
</code>```

Then it should be injected into context:

```<code>@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(ViewPumpContextWrapper.wrap(Restring.wrapContext(newBase)));
}

@Override
public Resources getResources() {
    return Restring.wrapContext(getBaseContext()).getResources();
}
</code>```

And you can load more strings at any time:

```<code>// e.g. locale=Locale.EN newStrings=map of (key-value)s
Restring.setStrings(locale, newStrings);
</code>```

And apply updated resources without restarting the app:

```<code>// The layout containing the views you want to localise
final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Reword.reword(rootView);
</code>```

More details: https://github.com/B3nedikt/restring

Body:
String resources are static defined and can not be changed at runtime.

However, you could use the Restring library to set and load strings at runtime by adding the dependencies:

// Replace bundled strings dynamically
implementation 'dev.b3nedikt.restring:restring:4.0.3'

// Intercept view inflation
implementation 'io.github.inflationx:viewpump:2.0.3'

// Allows to update the text of views at runtime without recreating the activity
implementation 'dev.b3nedikt.reword:reword:1.1.0'

Initialising it in your Application class:

Restring.init(this,
        new RestringConfig.Builder()
                .stringsLoader(new SampleStringsLoader())
                .loadAsync(false) // If string loader should load strings asynchronously, default true
                .build()
        );

ViewPump.init(ViewPump.builder()
        .addInterceptor(RewordInterceptor.INSTANCE)
        .build());

Then it should be injected into context:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(ViewPumpContextWrapper.wrap(Restring.wrapContext(newBase)));
}

@Override
public Resources getResources() {
    return Restring.wrapContext(getBaseContext()).getResources();
}

And you can load more strings at any time:

// e.g. locale=Locale.EN newStrings=map of (key-value)s
Restring.setStrings(locale, newStrings);

And apply updated resources without restarting the app:

// The layout containing the views you want to localise
final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Reword.reword(rootView);

More details: https://github.com/B3nedikt/restring


问:
Align mutliple textview to both center and similar left alignment for all screens

I am working on a bottom sheet dialog and was wondering how to align all 3 textviews to the center as well as align them with the same left margin. Please note that there is also an imageview left to the textview for all 3 rows(Here 3 rows are rename, share and delete).
gravity center makes them align to center but their left margin won't be same. I want their left margin to also be same

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:id="@+id/btmsheet"
    android:background="@color/white"
    android:layout_marginLeft="@dimen/pad_5dp"
    android:layout_marginRight="@dimen/pad_5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:id="@+id/dragView"
        android:layout_marginTop="@dimen/pad_10dp">

        <View
            android:layout_width="@dimen/pad_50dp"
            android:layout_height="@dimen/pad_5dp"
            android:background="@color/grey_color" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="15dp">

            <TextView
                android:id="@+id/bottom_sheet_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textSize="@dimen/text_20sp"
                android:textColor="@color/black"
                android:text=""
                tools:text="RB000019.JPG"
                android:textStyle="bold"/>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_duplicate"
            android:orientation="horizontal"
            android:padding="15dp"
       >

            <TextView
                android:id="@+id/bottom_sheet_rename"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableStart="@drawable/edit"
                android:drawablePadding="@dimen/pad_15dp"
                android:paddingStart="@dimen/pad_20dp"
                android:text="@string/rename_project_name"
                android:textColor="@color/black"
                android:textSize="@dimen/text_16sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_rename"
            android:orientation="horizontal"
            android:padding="15dp"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/share_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/ic_share"
                android:drawablePadding="@dimen/pad_15dp"/>
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:orientation="horizontal"
            android:padding="15dp"
            android:id="@+id/lyt_move"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/delete_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/delete"
                android:layout_marginStart="@dimen/pad_5dp"
                android:drawablePadding="@dimen/pad_20dp"
               />
        </android.support.constraint.ConstraintLayout>

    </LinearLayout>

</LinearLayout>
</code>```

答:
Here is an idea but it is still not the most optimal solution.

what you could do is to create another linear layout inside a existing Linear layout and make it wrap_content for both height and width. Later the make the inner Linear Layout to align to centre and finally keep a padding of specific number to align the texts to be aligned.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:padding="4dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"/>

</LinearLayout>
</code>```

Body:
I am working on a bottom sheet dialog and was wondering how to align all 3 textviews to the center as well as align them with the same left margin. Please note that there is also an imageview left to the textview for all 3 rows(Here 3 rows are rename, share and delete).
gravity center makes them align to center but their left margin won't be same. I want their left margin to also be same

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:id="@+id/btmsheet"
    android:background="@color/white"
    android:layout_marginLeft="@dimen/pad_5dp"
    android:layout_marginRight="@dimen/pad_5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:id="@+id/dragView"
        android:layout_marginTop="@dimen/pad_10dp">

        <View
            android:layout_width="@dimen/pad_50dp"
            android:layout_height="@dimen/pad_5dp"
            android:background="@color/grey_color" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="15dp">

            <TextView
                android:id="@+id/bottom_sheet_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textSize="@dimen/text_20sp"
                android:textColor="@color/black"
                android:text=""
                tools:text="RB000019.JPG"
                android:textStyle="bold"/>
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_duplicate"
            android:orientation="horizontal"
            android:padding="15dp"
       >

            <TextView
                android:id="@+id/bottom_sheet_rename"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableStart="@drawable/edit"
                android:drawablePadding="@dimen/pad_15dp"
                android:paddingStart="@dimen/pad_20dp"
                android:text="@string/rename_project_name"
                android:textColor="@color/black"
                android:textSize="@dimen/text_16sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:id="@+id/lyt_rename"
            android:orientation="horizontal"
            android:padding="15dp"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/share_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/ic_share"
                android:drawablePadding="@dimen/pad_15dp"/>
        </android.support.constraint.ConstraintLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="#E5E5E5" />

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:focusable="true"
            android:orientation="horizontal"
            android:padding="15dp"
            android:id="@+id/lyt_move"
            android:gravity="center_horizontal|center_vertical">

            <TextView
                android:id="@+id/bottom_sheet_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_16sp"
                android:textColor="@color/black"
                android:text="@string/delete_project"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                android:drawableStart="@drawable/delete"
                android:layout_marginStart="@dimen/pad_5dp"
                android:drawablePadding="@dimen/pad_20dp"
               />
        </android.support.constraint.ConstraintLayout>

    </LinearLayout>

</LinearLayout>

Body:
Here is an idea but it is still not the most optimal solution.

what you could do is to create another linear layout inside a existing Linear layout and make it wrap_content for both height and width. Later the make the inner Linear Layout to align to centre and finally keep a padding of specific number to align the texts to be aligned.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:padding="4dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"/>

</LinearLayout>


问:
Resources for developing a C++ MySQL application for Linux
I'm going to be developing a C++ application that uses a MySQL database.

I've written similar apps in Java using JDBC, as well as the Spring Framework.

Are there equivalent libraries for C++?  What have you had the most success with?

答:
MySQL Connector/C++ is a C++ implementation of JDBC 4.0

The reference customers who use MySQL Connector/C++ are:

 - OpenOffice

 - MySQL Workbench

Learn more

OwnerDisplayName: Clayton

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MySQL Workbench


问:
Algorithms by Sedgewick & Wayne, Exercise 1.2.3
Algorithms by Sedgewick & Wayne, Exercise 1.2.3:

Write an Interval2D client that takes command-line arguments N,
  min, and max and generates N random 2D intervals whose width and
  height are uniformly distributed between min and max in the unit
  square. Draw them on StdDraw and print the number of pairs of
  intervals that intersect and the number of intervals that are
  contained in one another.

Interval2D exposes the following API:

```<code>Interval2D(Interval1D x, Interval1D y)
boolean intersects(Interval2D)
boolean contains(Point2D)
double area()
void draw()
</code>```

Is it possible to check whether one Interval2D is contained in another using only these methods?

答:
My solution is here:  </p>

```<code>package exercise.chapter2.section2;

import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.Interval2D;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;

public class Ex1_2_03 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int N = Integer.parseInt(args[0]);
        double min = Double.parseDouble(args[1]);
        double max = Double.parseDouble(args[2]);
        MyInterval2D[] boxes = new MyInterval2D[N];
        for (int i = 0; i < N; i++) {
            double width = StdRandom.uniform(min, max);
            double height = StdRandom.uniform(min, max);

            double xlo = StdRandom.uniform(width, 1.0 - width);
            double xhi = xlo + width;
            double ylo = StdRandom.uniform(height, 1.0 - height);
            double yhi = ylo + height;

            boxes[i] = new MyInterval2D(new Interval1D(xlo, xhi), new Interval1D(ylo, yhi));
            boxes[i].draw();
        }

        int cintersects = 0;
        int ccontained = 0;
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                if (boxes[i].intersects(boxes[j])) {
                    cintersects++;
                }
            }
        }

        for (int i = 0; i < N; i++) {
            boxes[i].draw();
            for (int j = 0; j < N; j++) {
                if (i != j && boxes[j].contains(boxes[i])) {
                    ccontained++;
                    break;
                }
            }
        }
        StdOut.println(cintersects);
        StdOut.println(ccontained);
    }

}

class MyInterval2D extends Interval2D {
    private Interval1D xint;
    private Interval1D yint;

    public MyInterval2D(Interval1D xint, Interval1D yint) {
        super(xint, yint);
        this.xint = xint;
        this.yint = yint;
    }

    public boolean contains(MyInterval2D box) {
        if (xint.contains(box.xint.min()) && xint.contains(box.xint.max()) && yint.contains(box.yint.min()) && yint.contains(box.yint.max())) {
            return true;
        }
        return false;
    }

}
</code>```

Body:
Algorithms by Sedgewick & Wayne, Exercise 1.2.3:

Write an Interval2D client that takes command-line arguments N,
  min, and max and generates N random 2D intervals whose width and
  height are uniformly distributed between min and max in the unit
  square. Draw them on StdDraw and print the number of pairs of
  intervals that intersect and the number of intervals that are
  contained in one another.

Interval2D exposes the following API:

Interval2D(Interval1D x, Interval1D y)
boolean intersects(Interval2D)
boolean contains(Point2D)
double area()
void draw()

Is it possible to check whether one Interval2D is contained in another using only these methods?

Body:
My solution is here:

package exercise.chapter2.section2;

import edu.princeton.cs.algs4.Interval1D;
import edu.princeton.cs.algs4.Interval2D;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;

public class Ex1_2_03 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int N = Integer.parseInt(args[0]);
        double min = Double.parseDouble(args[1]);
        double max = Double.parseDouble(args[2]);
        MyInterval2D[] boxes = new MyInterval2D[N];
        for (int i = 0; i < N; i++) {
            double width = StdRandom.uniform(min, max);
            double height = StdRandom.uniform(min, max);

            double xlo = StdRandom.uniform(width, 1.0 - width);
            double xhi = xlo + width;
            double ylo = StdRandom.uniform(height, 1.0 - height);
            double yhi = ylo + height;

            boxes[i] = new MyInterval2D(new Interval1D(xlo, xhi), new Interval1D(ylo, yhi));
            boxes[i].draw();
        }

        int cintersects = 0;
        int ccontained = 0;
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                if (boxes[i].intersects(boxes[j])) {
                    cintersects++;
                }
            }
        }

        for (int i = 0; i < N; i++) {
            boxes[i].draw();
            for (int j = 0; j < N; j++) {
                if (i != j && boxes[j].contains(boxes[i])) {
                    ccontained++;
                    break;
                }
            }
        }
        StdOut.println(cintersects);
        StdOut.println(ccontained);
    }

}

class MyInterval2D extends Interval2D {
    private Interval1D xint;
    private Interval1D yint;

    public MyInterval2D(Interval1D xint, Interval1D yint) {
        super(xint, yint);
        this.xint = xint;
        this.yint = yint;
    }

    public boolean contains(MyInterval2D box) {
        if (xint.contains(box.xint.min()) && xint.contains(box.xint.max()) && yint.contains(box.yint.min()) && yint.contains(box.yint.max())) {
            return true;
        }
        return false;
    }

}


问:
In Angular, How can we detect if DOM element has ngModel associated with it?
I have an attribute directive that modifies the checked state of the host element. I'm using following code to do this:

```<code>constructor(private el: ElementRef, private model: NgModel) {}

//OnInit code

if ('ng-reflect-model' in this.el.nativeElement.attributes) { <-- Problem is here, this attribute is available for debug, i want to put some condition here
  this.model.viewToModelUpdate(modelValue);
  this.model.valueAccessor.writeValue(modelValue);
} else {
  this.el.nativeElement.checked = modelValue;
}
</code>```

My problem is when the input has ngModel associated with it, I want to update the model if it is available otherwise update the checked state of native element.

答:
One solution that i'm using presently is relying on this.model.valueAccessor property of NgModel class. If this attribute is absent then we can't access model value so no point in using it for update.

So my updated code is:

```<code>if (this.model.valueAccessor !== undefined && this.model.valueAccessor !== null) {
  this.model.viewToModelUpdate(modelValue);
  this.model.valueAccessor.writeValue(modelValue);
} else {
  this.el.nativeElement.checked = modelValue;
}
</code>```

This is based on https://angular.io/api/forms/NgControl#valueAccessor

Body:
I have an attribute directive that modifies the checked state of the host element. I'm using following code to do this:

constructor(private el: ElementRef, private model: NgModel) {}

//OnInit code

if ('ng-reflect-model' in this.el.nativeElement.attributes) { <-- Problem is here, this attribute is available for debug, i want to put some condition here
  this.model.viewToModelUpdate(modelValue);
  this.model.valueAccessor.writeValue(modelValue);
} else {
  this.el.nativeElement.checked = modelValue;
}

My problem is when the input has ngModel associated with it, I want to update the model if it is available otherwise update the checked state of native element.

Body:
One solution that i'm using presently is relying on this.model.valueAccessor property of NgModel class. If this attribute is absent then we can't access model value so no point in using it for update.

So my updated code is:

if (this.model.valueAccessor !== undefined && this.model.valueAccessor !== null) {
  this.model.viewToModelUpdate(modelValue);
  this.model.valueAccessor.writeValue(modelValue);
} else {
  this.el.nativeElement.checked = modelValue;
}

This is based on https://angular.io/api/forms/NgControl#valueAccessor


问:
Azure powershell script - create multiple resource groups with different owners
I'm trying to create a loop script that will create multiple RG's with different owners. I have problem with adding different owner into resource groups.

```<code>$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "user1@mail.com","User2@mail.com", "User3@mail.com"

foreach($rg in $RGNamesUSE)
{
New-AzResourceGroup -Name $rg -Location westeurope
}
</code>```

I need to add for each RG the owner. It should be like RG-01 will have owner user1, RG-02 will have owner user2 etc... How can i do this?

答:
Jagrati posted a correct answer, and it fulfills your requirements. Instead, I would like to challenge your requirements :)

I have seen codes like yours. If it is part of a solution and not a just-one-time run, then they get very hard to maintain and very easy to make mistakes.

For example, if somebody adds a new RG in the future, they need to remember to add the owner in the proper place or everything will be broken, and the problem can be even worse since you might not even notice the error neither at build time nor run time.

That is why I prefer these type of structures, where all the details are in the same place and related to each other: (try it here)

```<code>$ResourceGroups = @(
 @{
    "Name"="RG-01";
    "Owners"="user1.1@mail.com"
 },
 @{
    "Name"="RG-02";
    "Owners"="user2@mail.com"
 }
)
</code>```

Then the code to deploy is very easy, without any index or any other magic to relate multiple data sources by position

```<code>foreach($rg in $ResourceGroups)
{
    Write-Host "Creating resource group Name: $($rg.Name) with Owners: $($rg.Owners)"

    # Create the Resource group
    New-AzResourceGroup -Name $rg.Name -Location westeurope

    # Assign roles.
    New-AzRoleAssignment -SignInName $rg.Owners -RoleDefinitionName "Owner" -ResourceGroupName $rg.Name
}
</code>```

This will also work much better in cases where you need to add more role assignments per groups, or other properties like each resource group in a different region

Body:
I'm trying to create a loop script that will create multiple RG's with different owners. I have problem with adding different owner into resource groups.

$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "user1@mail.com","User2@mail.com", "User3@mail.com"

foreach($rg in $RGNamesUSE)
{
New-AzResourceGroup -Name $rg -Location westeurope
}

I need to add for each RG the owner. It should be like RG-01 will have owner user1, RG-02 will have owner user2 etc... How can i do this?

Body:
Jagrati posted a correct answer, and it fulfills your requirements. Instead, I would like to challenge your requirements :)

I have seen codes like yours. If it is part of a solution and not a just-one-time run, then they get very hard to maintain and very easy to make mistakes.

For example, if somebody adds a new RG in the future, they need to remember to add the owner in the proper place or everything will be broken, and the problem can be even worse since you might not even notice the error neither at build time nor run time.

That is why I prefer these type of structures, where all the details are in the same place and related to each other: (try it here)

$ResourceGroups = @(
 @{
    "Name"="RG-01";
    "Owners"="user1.1@mail.com"
 },
 @{
    "Name"="RG-02";
    "Owners"="user2@mail.com"
 }
)

Then the code to deploy is very easy, without any index or any other magic to relate multiple data sources by position

foreach($rg in $ResourceGroups)
{
    Write-Host "Creating resource group Name: $($rg.Name) with Owners: $($rg.Owners)"

    # Create the Resource group
    New-AzResourceGroup -Name $rg.Name -Location westeurope

    # Assign roles.
    New-AzRoleAssignment -SignInName $rg.Owners -RoleDefinitionName "Owner" -ResourceGroupName $rg.Name
}

This will also work much better in cases where you need to add more role assignments per groups, or other properties like each resource group in a different region


问:
Add files to a ZIP archive?
What component or method can be used to specify a list of filenames and then zip them into a single archive?

I dont need advanced features or anything really, but if I could add some filenames to a stringlist for example then put those files into a ZIP that would be good.

Ive tried searching a few components but not sure which ones to use.

Thanks

答: VCLZip is good, fairly popular.  http://vclzip.bizland.com/  IIRC, it has good documentation and examples that will get you off to a quick start.</p>

Title: Add files to a ZIP archive?


问:
What type should i pass in ExpressionAttributeValues for a sort key of type integer to query in dynamodb?
According to dynamodb documentation, we need to add type of a number as string. Refer image-

but this throws an error of 'ValidationException: One or more parameter values were invalid: Condition parameter type does not match schema type' if we pass integer then it works which contradicts the documentation.
If someone could suggest to me if there is error in documentation or am I misinterpreting?

答:
You are misinterpreting the documentation. A number should have the "N" type. The value following this "N" is indeed a string representation of the number, e.g., "1234.5" - and that is the string that the documentation is referring to. But you still need to use "N" to say it's a number, not "S".

If you're curious why they didn't just use JSON's number type, well, the problem is that the numbers in DynamoDB have different range and precision from what JSON's number type supports.


问:
How can I rotate an AR object in place?
I'm try the rotate the AR object in place use quaternion.axisAngle, but it's not working.

I just want to make a object rotate in place, like this.

This is my code.

```<code>//Right Rotation
ImageButton.OnTouchListener controll_BtnRigntRoation = new ImageButton.OnTouchListener() {
    @Override
    public boolean onTouch(View controllRightDown, MotionEvent event) {
        if (controllRightDown == mRightRoation) {
            ma.initModel();
            for (int i=0; i<ma.infoArray.size(); i++) {
                if (ma.infoArray.get(i).getNode().isSelected()) {
                    int finalI = i;
                    ma.arFragment.getArSceneView().getScene().addOnUpdateListener(frameTime -> {
                        Quaternion r1 = Quaternion.axisAngle(new Vector3(0, 0, 1), frameTime.getStartSeconds()* 180); //y 방향으로는 안됨..
                        ma.infoArray.get(finalI).getNode().setLocalRotation(r1);
                    });
                }
            }
        }
        return false;
    }
};
</code>```

Please help me.

答:
You most likely want to use a transformable node - this will allow you do the type of rotation I think you are looking for:

https://developers.google.com/sceneform/reference/com/google/ar/sceneform/ux/TransformableNode

Example of use:

           var newAnchorNode:AnchorNode = AnchorNode(newAnchor)
           anchorNode.setParent(arFragment.getArSceneView().getScene());
           var transNode = TransformableNode(arFragment.transformationSystem)

           //Rotate the node - i.e set the direction it is 'looking'
           transNode.setLookDirection(Vector3(0f, xPoint, yPoint), topDirection)

           //Set it's parent to the anchor you created and set
           //the renderable
           transNode.setParent(anchorNode);
           transNode.setRenderable(renderable);
```

Title: How can I rotate an AR object in place?

Body:
I'm try the rotate the AR object in place use quaternion.axisAngle, but it's not working.

I just want to make a object rotate in place, like this.

This is my code.

//Right Rotation
ImageButton.OnTouchListener controll_BtnRigntRoation = new ImageButton.OnTouchListener() {
    @Override
    public boolean onTouch(View controllRightDown, MotionEvent event) {
        if (controllRightDown == mRightRoation) {
            ma.initModel();
            for (int i=0; i<ma.infoArray.size(); i++) {
                if (ma.infoArray.get(i).getNode().isSelected()) {
                    int finalI = i;
                    ma.arFragment.getArSceneView().getScene().addOnUpdateListener(frameTime -> {
                        Quaternion r1 = Quaternion.axisAngle(new Vector3(0, 0, 1), frameTime.getStartSeconds()* 180); //y 방향으로는 안됨..
                        ma.infoArray.get(finalI).getNode().setLocalRotation(r1);
                    });
                }
            }
        }
        return false;
    }
};

Please help me.


问:
cakephp select list showing ids instead of text
i am using cakephp 1.3 to generate a form i am creating a select list using hasOne and belongsTo relation

```<code>my models: image, category
</code>```

category hasMany image

image belongsTo Category

category table has two columns id and category_name

i am doing

```<code>$this->set('categories',
           $this->Image->Category->find(
                                        'list',
                                         array( 'order' => 'category_name ASC' )
                                       )
          ); //to generate the select list
</code>```

so far so good, there is only one problem left, the select list generated shows the id of the category instead of the category_name as the option text, i know this is not cakePHP's fault but i need to know the solution

any help please.

P.S if i am unclear about the question please let me know

答:
When in doubt, read the manual:

3.7.3.1.4 find('list')

When calling find('list') the fields passed are used to determine what should be used as the array key, value and optionally what to group the results by. By default the primary key for the model is used for the key, and the display field (which can be configured using the model attribute displayField) is used for the value.

Body:
i am using cakephp 1.3 to generate a form i am creating a select list using hasOne and belongsTo relation

my models: image, category

category hasMany image

image belongsTo Category

category table has two columns id and category_name

i am doing

$this->set('categories',
           $this->Image->Category->find(
                                        'list',
                                         array( 'order' => 'category_name ASC' )
                                       )
          ); //to generate the select list

so far so good, there is only one problem left, the select list generated shows the id of the category instead of the category_name as the option text, i know this is not cakePHP's fault but i need to know the solution

any help please.

P.S if i am unclear about the question please let me know


问:
Concise way to write the same line in multiple files - Python
I have several opened files. Now, I need to write the same line in all of them. My current code is the following, but it is unelegant and very repetitive. Is there a way of doing it in less lines?

```<code>with open("a.txt", "a+") as fa,\
     open("b.txt", "a+") as fb,\
     open("c.txt", "a+") as fc,\
     open("d.txt",  "a+") as fd,\
     open("e.txt", "a+") as fe,\
     open("f.txt", "a+") as ff,\
     open("g.txt", "a+") as fg:

    fa.write("header")
    fb.write("header")
    fc.write("header")
    fd.write("header")
    fe.write("header")
    ff.write("header")
    fg.write("header")
</code>```

In the rest of the program (not shown), I deal with each file differently, appending different information to each of them.

If this post is duplicate, I am sorry!

答:
simply use a for loop:

```<code>for file in files_list:
    with open(file, "a+") as fa:
        fa.write("header")
</code>```

put all file names in files_list

Body:
I have several opened files. Now, I need to write the same line in all of them. My current code is the following, but it is unelegant and very repetitive. Is there a way of doing it in less lines?

with open("a.txt", "a+") as fa,\
     open("b.txt", "a+") as fb,\
     open("c.txt", "a+") as fc,\
     open("d.txt",  "a+") as fd,\
     open("e.txt", "a+") as fe,\
     open("f.txt", "a+") as ff,\
     open("g.txt", "a+") as fg:

    fa.write("header")
    fb.write("header")
    fc.write("header")
    fd.write("header")
    fe.write("header")
    ff.write("header")
    fg.write("header")

In the rest of the program (not shown), I deal with each file differently, appending different information to each of them.

If this post is duplicate, I am sorry!

Body:
simply use a for loop:

for file in files_list:
    with open(file, "a+") as fa:
        fa.write("header")

put all file names in files_list


问:
Problem with function that returns the key with most unique values in python
I am trying to implement greedy algorithm where I need to find the alphabet generator with most unique alphabets, process these alphabets and find the next best generator until I have processed all alphabets. However, when I run the function get_next_best_generator the first time it returns the right values but doesn't return anything in the next call with the following error-
0
[]
KeyError: ''
output of first call-generator_2
6
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']

why its not returning anything in the call after the first call?

Here is my code-

```<code># create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','m'], 'generator_4':['p','e','m','g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while len(alphabets_covered) < 13:

    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
</code>```

After making some changes- My function still doesn't return the key with the most unique elements.

Updated code-

```<code># create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :
            if selected_alphabet  in alphabets:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets -= set(best_generator_unique_alphabets)
</code>```

Expected output-
generator_2
8
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
generator_3
3
['x', 'w', 'b']
generator_4
2
['e','g']
generator_1
1
['r']

答:
```<code># create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets_set = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :

            if selected_alphabet in alphabets_set:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets_set:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets_set -= set(best_generator_unique_alphabets)
</code>```

<p>I used a set of alphabets which was subtracted by the unique elements found in the next best generator and looped while there were elements in the alphabet set.   </p>

Body:
I am trying to implement greedy algorithm where I need to find the alphabet generator with most unique alphabets, process these alphabets and find the next best generator until I have processed all alphabets. However, when I run the function get_next_best_generator the first time it returns the right values but doesn't return anything in the next call with the following error-
0
[]
KeyError: ''
output of first call-generator_2
6
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']

why its not returning anything in the call after the first call?

Here is my code-

# create lists to store covered alphabets and processed generators
alphabets_covered=[]
generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','m'], 'generator_4':['p','e','m','g']}

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''
    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        # Loop to store the unique alphabets for a generator
        for selected_alphabet in generator_alphabets:
            if selected_alphabet not in alphabets_covered:
                unique_alphabets_list.append(selected_alphabet)
                alphabets_covered.append(selected_alphabet)
        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = alphabets
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while len(alphabets_covered) < 13:

    most_alphabets_count, best_generator_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)

After making some changes- My function still doesn't return the key with the most unique elements.

Updated code-

# create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :
            if selected_alphabet  in alphabets:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets -= set(best_generator_unique_alphabets)

Expected output-
generator_2
8
['p', 'q', 'k', 'j', 'l', 'm', 'n', 't']
generator_3
3
['x', 'w', 'b']
generator_4
2
['e','g']
generator_1
1
['r']

Body:
# create lists to store covered alphabets and processed generators

generator_covered=[]
# create a dict to store generators and the alphabets that they generate
generator_alphabets_dict={'generator_1':['p','q','r'], 'generator_2':['p', 'q','k','j','l','m','n','t'],
                          'generator_3':['x','w','b'], 'generator_4':['p','e','m','g']}
alphabets_set = set(['p','q','r','k','j','l','m','n','t','x','w','b','e','g'])

def get_next_best_generator():
    '''get the generator that generates the most unique alphabets that have not been covered'''
    most_alphabets_count=0
    best_generator_alphabets=[]
    best_generator=''

    #Loop through the dict to find the generator with most unique alphabets
    for generator ,alphabets in generator_alphabets_dict.items():
        unique_alphabets_list = []
        generator_alphabets = list(alphabets)
        for selected_alphabet in generator_alphabets :

            if selected_alphabet in alphabets_set:
                unique_alphabets_list.append(selected_alphabet)

        # update all values if current generator's unique element list is greater than its predecessor's
        if len(unique_alphabets_list) > most_alphabets_count:
            most_alphabets_count = len(unique_alphabets_list)
            best_generator_alphabets = unique_alphabets_list
            best_generator = generator

    return  most_alphabets_count, best_generator_alphabets , best_generator

# Loop until all alphabets have been covered
while alphabets_set:

    most_alphabets_count, best_generator_unique_alphabets, best_generator = get_next_best_generator()
    print(best_generator)
    print(most_alphabets_count)
    print(best_generator_unique_alphabets)
    generator_alphabets_dict.pop(best_generator)
    generator_covered.append(best_generator)
    alphabets_set -= set(best_generator_unique_alphabets)

I used a set of alphabets which was subtracted by the unique elements found in the next best generator and looped while there were elements in the alphabet set.


问:
Load an image to an InkPicture control
Im trying to load an image to a inkpicture control in ms access so that I can draw/annotate on top of it.

here is my code

```<code>Dim v As Variant
Dim b() As Byte
Set v = Me.InkPicture0
b = Nz(Me.Text1.Value, "")
v.Ink.Load b
Me.InkPicture0.Requery
Set v = Nothing
</code>```

this generates an error on line "v.ink.load b", the error is RTE, "you entered an expression that has an invalid reference to the property |."

The format appears correct, and what is strange, in some instances it will work once, but not if the same code is run again.

Unfortunately, Microsoft appears to have no documentation on this.

Any ideas?

答:
Your Error is caused by using variant type, what leadsvto get aCustomControlthat doesn't know about theInkproperty. Just check that with a watch onv.
If you declare v asMSINKAUTLib.InkDispinstead ofVariantorSet v = Me.InkPicture0.Objectthat error will disapear (but be replaced byinvalid procedure call/argument).

You can't load sth. to anInkPicturecontrolsInkproperty. You have to load to a newInkDispobject and then set the controlsInkproperty to that.

See How to erase or reload strokes to an InkPicture in VBA for Ms Access?, but avoid the self assigned declaration used there.

Also you need to disable the controlsInkproperty to set it to the newInkobject, withInkEnabled = False
See IInkPicture::get_Ink method

To load an image to draw on, use the controlsPictureproperty and load a picture with Application.LoadPicture

Dim b() As Byte
b = Nz(Me.Text1.Value, "") 'Me.Text1.Value contains saved stroke data
Dim newInk As MSINKAUTLib.InkDisp
Set newInk = New MSINKAUTLib.InkDisp 'need new object to load new ink
newInk.Load b 'load in the ink
Me.InkPicture0.InkEnabled = False
Set Me.InkPicture0.Ink = newInk 'set the InkPictures Ink to the new Ink
Me.InkPicture0.InkEnabled = True
Set newInk = Nothing

Me.InkPicture0.Picture = LoadPicture("path/to/image") 'Load Image from path
```

Title: Load an image to an InkPicture control

Body:
Im trying to load an image to a inkpicture control in ms access so that I can draw/annotate on top of it.

here is my code

Dim v As Variant
Dim b() As Byte
Set v = Me.InkPicture0
b = Nz(Me.Text1.Value, "")
v.Ink.Load b
Me.InkPicture0.Requery
Set v = Nothing

this generates an error on line "v.ink.load b", the error is RTE, "you entered an expression that has an invalid reference to the property |."

The format appears correct, and what is strange, in some instances it will work once, but not if the same code is run again.

Unfortunately, Microsoft appears to have no documentation on this.

Any ideas?


问:
Vue.js: draw the table with elements, calling the api for each row
I have a vue component:

```<code><template>
  <div class="tableWrapper">
    <md-table
            class="scheduledListJobList"
            v-model="scheduledList"
    >
      <md-table-row :class="item.status" slot="md-table-row" slot-scope="{item}" @click="open(item)">
        <md-table-cell class="nameColumn" md-label="Название задания" to="/upload" >{{ item.name}}</md-table-cell>
        <md-table-cell md-label="Номер билда">{{ item.jobNumber }}</md-table-cell>

      </md-table-row>
    </md-table>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {permissionList} from "../../permission/permission";
import {Job} from "../../api";

export default {
  name: "gg-jobs-list",

  computed: mapState(["scheduledList"]),

  mounted: function(){
    this.$store.dispatch('GET_SCHEDULED_JOBS');
  },
  data: function () {
    return {
     element: null
    };
  },

  methods: {
    open(selected) {
      this.$router.push({ path: '/jobs/' + selected.routeId});
    },
    refresh(){
      Job.getJobs()
    }
  }
};
</script>
</code>```

It has a scheduleList that has the name and id fields.

I need to output the name field to the table, and then call a method that goes to the backend, with each id field for the sheet elements, gets an object and complements the table.

Here is the method that calls the api:

```<code>  refresh(){
      Job.getJobs()
    }

  getJobs: id => getRequest(`/routes/monitoring/jobs/${id}`, null)

</code>```

From this method, I should return an object with the start and end fields.
With these fields, I must add each scheduledList element to the tables.

How can I do this? thank you so much for your help.

答:
Add another computed property as v-model directive value :

```<code> computed:{
        ...mapState(["scheduledList"]),
    scheduledListRefreshed:{
      get(){
        return this.scheduledList.map(item=>{
                 item.jobs=Job.getJobs(item.id);
                 return item;
        },
      set(val){

      }
    }
</code>```

template :

<template>

    <md-table
            class="scheduledListJobList"
            v-model="scheduledListRefreshed"
    >
      <md-table-row :class="item.status" slot="md-table-row" slot-scope="{item}" @click="open(item)">
        <md-table-cell class="nameColumn" md-label="Название задания" to="/upload" >{{ item.name}}</md-table-cell>
        <md-table-cell md-label="Номер билда">{{ item.jobNumber }}</md-table-cell>

      </md-table-row>
    </md-table>

</template>

```

Body:
I have a vue component:

<template>

    <md-table
            class="scheduledListJobList"
            v-model="scheduledList"
    >
      <md-table-row :class="item.status" slot="md-table-row" slot-scope="{item}" @click="open(item)">
        <md-table-cell class="nameColumn" md-label="Название задания" to="/upload" >{{ item.name}}</md-table-cell>
        <md-table-cell md-label="Номер билда">{{ item.jobNumber }}</md-table-cell>

      </md-table-row>
    </md-table>

</template>

It has a scheduleList that has the name and id fields.

I need to output the name field to the table, and then call a method that goes to the backend, with each id field for the sheet elements, gets an object and complements the table.

Here is the method that calls the api:

  refresh(){
      Job.getJobs()
    }

  getJobs: id => getRequest(`/routes/monitoring/jobs/${id}`, null)

From this method, I should return an object with the start and end fields.
With these fields, I must add each scheduledList element to the tables.

How can I do this? thank you so much for your help.

Body:
Add another computed property as v-model directive value :

 computed:{
        ...mapState(["scheduledList"]),
    scheduledListRefreshed:{
      get(){
        return this.scheduledList.map(item=>{
                 item.jobs=Job.getJobs(item.id);
                 return item;
        },
      set(val){

      }
    }

template :

<template>
  <div class="tableWrapper">
    <md-table
            class="scheduledListJobList"
            v-model="scheduledListRefreshed"
    >
      <md-table-row :class="item.status" slot="md-table-row" slot-scope="{item}" @click="open(item)">
        <md-table-cell class="nameColumn" md-label="Название задания" to="/upload" >{{ item.name}}</md-table-cell>
        <md-table-cell md-label="Номер билда">{{ item.jobNumber }}</md-table-cell>

      </md-table-row>
    </md-table>
  </div>
</template>


问:
Radius of multiple latitude/longitude points
I have a program that takes as input an array of lat/long points.  I need to perform a check on that array to ensure that all of the points are within a certain radius.  So, for example, the maximum radius I will allow is 100 miles.  Given an array of lat/long (coming from a MySQL database, could be 10 points could be 10000) I need to figure out if they will all fit in a circle with radius of 100 miles.

Kinda stumped on how to approach this.  Any help would be greatly appreciated.

答:
The answer below involves pretending that the earth is a perfect sphere, which should give a more accurate answer than treating the earth as a flat plane.

To figure out the radius of a set of lat/lon points, you must first ensure that your set of points is "hemispherical", ie. all the points can fit into some arbitrary half of your perfect sphere.

Check out Section 3 in the paper "Optimal algorithms for some proximity problems on the Gaussian sphere with applications" by Gupta and Saluja. I don't have a specific link, but I believe that you can find a copy online for free. This paper is not sufficient to implement a solution. You'll also need Appendix 1 in "Approximating Centroids for the Maximum Intersection of Spherical Polygons" by Ha and Yoo.

I wouldn't use Megiddo's algorithm for doing the linear programming part of the hemisphericity testing. Instead, use Seidel's algorithm for solving Linear Programming problems, described in "Small-Dimensional Linear Programming and Convex Hulls Made Easy" by Raimund Seidel. Also see "Seidel’s Randomized Linear Programming Algorithm" by Kurt Mehlhorn and Section 9.4 from "Real-Time Collision Detection" by Christer Ericson.

Once you have determined that your points are hemispherical, move on to Section 4 of the paper by Gupta and Saluja. This part shows how to actually get the "smallest enclosing circle" for the points.

To do the required quadratic programming, see the paper "A Randomized Algorithm for Solving Quadratic Programs" by N.D. Botkin. This tutorial is helpful, but the paper uses (1/2)x^T G x - g^T x and the web tutorial uses (1/2)x^T H x + c^T x. One adds the terms and the other subtracts, leading to sign-related problems. Also see this example 2D QP problem. A hint: if you're using C++, the Eigen library is very good.

This method is a little more complicated than some of the 2D methods above, but it should give you more accurate results than just ignoring the curvature of the earth completely. This method also has O(n) time complexity, which is likely asymptotically optimal.

Note: The method described above may not handle duplicate data well, so you may want to check for duplicate lat/lon points before finding the smallest enclosing circle.


问:
accumulation problem after reshaping multiple arrays
I have x_train, which is an array belong to data waveform, with dimension (475,1501) and I want the final output (seg2) to be (1425,500). I tried the following code:

```<code>count=0
sega=[]
seg2=[]
for i in range (0,len(x_train)):

    sega = x_train[i][:(x_train[i].size // 500) * 500].reshape(-1, 500)
    seg2[count:(count+1),500] = sega
    count = count + i
</code>```

But it complains with the following error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-137-72281c805a83> in <module>
     10     sega = x_train[i][:(x_train[i].size // 500) * 500].reshape(-1, 500)
     11     print(sega.shape)
---> 12     seg2[count:(count+1),500] = sega
     13     count = count + i
     14

TypeError: list indices must be integers or slices, not tuple
</code>```

How can I fix this error?

答:
seg2 is a list. it looks like you need to declare it as np.array. Like this:

seg2 = np.zeros((total_count, 500))
```

<p>Where <code>total_count=1425</code>.</p>

<p>You can also use <code>np.concatenate</code> in this way:</p>

<pre class="lang-py prettyprint-override"><code>seg2 = np.concatenate([
    x_train[i][:(x_train[i].size // 500) * 500].reshape(-1, 500)
    for i in range(0,x_train.shape[0])
], axis=0)
</code>```

Body:
I have x_train, which is an array belong to data waveform, with dimension (475,1501) and I want the final output (seg2) to be (1425,500). I tried the following code:

count=0
sega=[]
seg2=[]
for i in range (0,len(x_train)):

    sega = x_train[i][:(x_train[i].size // 500) * 500].reshape(-1, 500)
    seg2[count:(count+1),500] = sega
    count = count + i

But it complains with the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-137-72281c805a83> in <module>
     10     sega = x_train[i][:(x_train[i].size // 500) * 500].reshape(-1, 500)
     11     print(sega.shape)
---> 12     seg2[count:(count+1),500] = sega
     13     count = count + i
     14

TypeError: list indices must be integers or slices, not tuple

How can I fix this error?

Body:
seg2 is a list. it looks like you need to declare it as np.array. Like this:

seg2 = np.zeros((total_count, 500))

Where total_count=1425.

You can also use np.concatenate in this way:

seg2 = np.concatenate([
    x_train[i][:(x_train[i].size // 500) * 500].reshape(-1, 500)
    for i in range(0,x_train.shape[0])
], axis=0)


问:
Why does the class reference constructor overload get called from an rvalue when there's an rvalue constructor available?
This code

```<code>#include <iostream>

struct A
{
    A(int i) {std::cout << "int received\n";}
    A(A& a) {std::cout << "ref received\n";}
};

int main()
{
    int j = 5;
    A a = j;
}
</code>```

unexpectedly throws the following compiler error:

```<code>error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
note:   initializing argument 1 of 'A::A(A&)'
note:   after user-defined conversion: A::A(int)
</code>```

When I remove the second constructor overload A(A& a), everything works as expected. I suppose that the compiler mistakenly calls the second constructor instead of the first one.

Why does this happen?

How can I have a class with both a reference constructor and an rvalue constructor work in harmony?

I use GNU GCC.

Note: I also noticed something weird: Apparently, if I replace the line A a = j; with A a(j);, everything works as expected. This however is not satisfactory because it still doesn't work if I'm trying to initialize the object from a function argument (ex: calling void f(A a) with f(j)).

答:
A a = j; performs copy initialization.

Until C++17,

If T is a class type, and the cv-unqualified version of the type of other is not T or derived from T, or if T is non-class type, but the type of other is a class type, user-defined conversion sequences that can convert from the type of other to T (or to a type derived from T if T is a class type and a conversion function is available) are examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary (until C++17) prvalue expression (since C++17) if a converting constructor was used, is then used to direct-initialize the object. The last step is usually optimized out and the result of the conversion is constructed directly in the memory allocated for the target object, but the appropriate constructor (move or copy) is required to be accessible even though it's not used. (until C++17)

Class A has a copy construtor taking lvalue-reference to non-const, which can't bind to the temporary converted from int. Even the construction from the temporary A might be optimized the copy constructor has to be available.

Making the copy constructor taking lvalue-reference to const (or adding move constructor) would solve the issue.

Since C++17 because of mandatory copy elision, the code would work fine.

The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

LIVE

On the other hand, A a(j); performs direct initialization, a is initialized from j directly, copy constructor doesn't involve in.

Body:
This code

#include <iostream>

struct A
{
    A(int i) {std::cout << "int received\n";}
    A(A& a) {std::cout << "ref received\n";}
};

int main()
{
    int j = 5;
    A a = j;
}

unexpectedly throws the following compiler error:

error: invalid initialization of non-const reference of type 'A&' from an rvalue of type 'A'
note:   initializing argument 1 of 'A::A(A&)'
note:   after user-defined conversion: A::A(int)

When I remove the second constructor overload A(A& a), everything works as expected. I suppose that the compiler mistakenly calls the second constructor instead of the first one.

Why does this happen?

How can I have a class with both a reference constructor and an rvalue constructor work in harmony?

I use GNU GCC.

Note: I also noticed something weird: Apparently, if I replace the line A a = j; with A a(j);, everything works as expected. This however is not satisfactory because it still doesn't work if I'm trying to initialize the object from a function argument (ex: calling void f(A a) with f(j)).


问:
How to populate JSON data into Bootstrap 4 second level drop down menu
The attached image is my expected result. Every menu item has two more items 'Dashboard' and 'Battery Trends'. Every 'Dashboard' and 'Battery Trends' will have different URLs, which is defined as 'navigationurl' in the JSON file.

I have tried and reached here- https://themepack.net/aaa/jsondata But it's displaying 'undefined'.

It's the HTML code:

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="A fully featured admin theme which can be used to build CRM, CMS, etc." />

    <link rel="stylesheet" href="https://dashkit.goodthemes.co/assets/fonts/feather/feather.css" />
    <link rel="stylesheet" href="https://dashkit.goodthemes.co/assets/css/theme.min.css">
</head>

<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12">

                <nav class="navbar navbar-expand-lg navbar-light" id="topnav">
                    <div class="collapse navbar-collapse mr-lg-auto order-lg-first" id="navbar">
                        <ul class="navbar-nav mr-lg-auto">

                            <li class="nav-item dropdown">
                                <a class="nav-link dropdown-toggle " href="#" id="topnavDocumentation" role="button"
                                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Battery Trends</a>

                                <ul class="dropdown-menu" aria-labelledby="topnavDocumentation" id="myDropdown">
                                    <li class="dropright">

                                    </li>
                                </ul>

                            </li>
                        </ul>
                    </div>
                </nav>

            </div>
        </div>
    </div>

    <!-- JAVASCRIPT
    ================================================== -->
    <script src="https://dashkit.goodthemes.co/assets/libs/jquery/dist/jquery.min.js"></script>
    <script src="https://dashkit.goodthemes.co/assets/libs/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://dashkit.goodthemes.co/assets/js/dashkit.min.js"></script>

    <script>
        $(function () {

            $.getJSON('dashtrend.json', function (loadMainItem) {

                $.each(loadMainItem.data, function (i, f) {
                    var makemenu = "<a href='#' class='dropdown-item dropdown-toggle'  id='" + f.id + "' role='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" + f.text + "</a>";

                    $.each(loadMainItem.data, function (j) {
                        makemenu += "<div class='dropdown-menu' aria-labelledby='" + loadMainItem.data[i].items.id + "'><a class='dropdown-item' href='" + loadMainItem.data[i].items.navigationurl + "'>" + loadMainItem.data[j].items.text + "</a></div>";
                    })

                    // <div class="dropdown-menu" aria-labelledby="ups4">
                    //     <a class="dropdown-item" href="/Ups/UpsDashboard?upsid=1">Dashboard</a>
                    //     <a class="dropdown-item" href="/Ups/Trends?id=1">Battery Trends</a>
                    // </div>

                    $(makemenu).appendTo("#myDropdown li");
                });
            });

        });
    </script>
</body>

</html>
</code>```

And it's the JSON code:

```<code>    {
    "data": [
        {
            "id": 1,
            "text": "80KVA Server UPS4\r\n (Out of Warranty)",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 1,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=1",
                    "items": []
                },
                {
                    "id": 1,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=1",
                    "items": []
                }
            ]
        },
        {
            "id": 2,
            "text": "80KVA Server UPS5\r\n (Out of Warranty)",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 2,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=2",
                    "items": []
                },
                {
                    "id": 2,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=2",
                    "items": []
                }
            ]
        },
        {
            "id": 3,
            "text": "80KVA EL\r\n (Out of Warranty)",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 3,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=3",
                    "items": []
                },
                {
                    "id": 3,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=3",
                    "items": []
                }
            ]
        },
        {
            "id": 4,
            "text": "60KVA W/S Hub UPS1\r\n",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 4,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=4",
                    "items": []
                },
                {
                    "id": 4,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=4",
                    "items": []
                }
            ]
        },
        {
            "id": 5,
            "text": "60KVA W/S Hub UPS2",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 5,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=5",
                    "items": []
                },
                {
                    "id": 5,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=5",
                    "items": []
                }
            ]
        }
    ],
    "totalCount": -1,
    "groupCount": -1,
    "summary": null
}
</code>```

How to I can populate the second level dropdown item and get the expected result?

[NB: I'll apply the code into an ASP.NET project. So if you have any dependencies, you can mention it.]

Thanks

答:
I have made some updates to your code and achieve your desire results. Change your code accordingly.

Here is JavaScript code. Note changes

```<code><ul class="dropdown-menu" aria-labelledby="topnavDocumentation" id="myDropdown">
           //Just removed <li></li> from here
</ul>

<script>
    $(function () {

        $.getJSON('dashtrend.json', function (loadMainItem) {

            $.each(loadMainItem.data, function (i, f) {
                var makemenu = "<li class='dropright'><a href='#' class='dropdown-item dropdown-toggle'  id='" + f.id + "' role='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" + f.text + "</a>";
                makemenu += "<div class='dropdown-menu' aria-labelledby='test'>";
                $.each(f.items, function (j) {
                        makemenu += "<a class='dropdown-item' href='" + f.items[j].navigationurl + "'>" + f.items[j].text + "</a>";

                })
                makemenu += "</div></li>";

                // <div class="dropdown-menu" aria-labelledby="ups4">
                //     <a class="dropdown-item" href="/Ups/UpsDashboard?upsid=1">Dashboard</a>
                //     <a class="dropdown-item" href="/Ups/Trends?id=1">Battery Trends</a>
                // </div>

                $(makemenu).appendTo("#myDropdown");
            });
        });

    });
</script>
</code>```

1) I have removed the list from ul in HTML

2) I have updated your JavaScript code

Body:
The attached image is my expected result. Every menu item has two more items 'Dashboard' and 'Battery Trends'. Every 'Dashboard' and 'Battery Trends' will have different URLs, which is defined as 'navigationurl' in the JSON file.

I have tried and reached here- https://themepack.net/aaa/jsondata But it's displaying 'undefined'.

It's the HTML code:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="A fully featured admin theme which can be used to build CRM, CMS, etc." />

    <link rel="stylesheet" href="https://dashkit.goodthemes.co/assets/fonts/feather/feather.css" />
    <link rel="stylesheet" href="https://dashkit.goodthemes.co/assets/css/theme.min.css">

                                Battery Trends

And it's the JSON code:

    {
    "data": [
        {
            "id": 1,
            "text": "80KVA Server UPS4\r\n (Out of Warranty)",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 1,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=1",
                    "items": []
                },
                {
                    "id": 1,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=1",
                    "items": []
                }
            ]
        },
        {
            "id": 2,
            "text": "80KVA Server UPS5\r\n (Out of Warranty)",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 2,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=2",
                    "items": []
                },
                {
                    "id": 2,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=2",
                    "items": []
                }
            ]
        },
        {
            "id": 3,
            "text": "80KVA EL\r\n (Out of Warranty)",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 3,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=3",
                    "items": []
                },
                {
                    "id": 3,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=3",
                    "items": []
                }
            ]
        },
        {
            "id": 4,
            "text": "60KVA W/S Hub UPS1\r\n",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 4,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=4",
                    "items": []
                },
                {
                    "id": 4,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=4",
                    "items": []
                }
            ]
        },
        {
            "id": 5,
            "text": "60KVA W/S Hub UPS2",
            "icon": "rowfield",
            "navigationurl": null,
            "items": [
                {
                    "id": 5,
                    "text": "DashBoard",
                    "icon": "refresh",
                    "navigationurl": "/Ups/UpsDashboard?upsid=5",
                    "items": []
                },
                {
                    "id": 5,
                    "text": "Battery Trends",
                    "icon": "tips",
                    "navigationurl": "/Ups/Trends?id=5",
                    "items": []
                }
            ]
        }
    ],
    "totalCount": -1,
    "groupCount": -1,
    "summary": null
}

How to I can populate the second level dropdown item and get the expected result?

[NB: I'll apply the code into an ASP.NET project. So if you have any dependencies, you can mention it.]

Thanks

Body:
I have made some updates to your code and achieve your desire results. Change your code accordingly.

Here is JavaScript code. Note changes

<ul class="dropdown-menu" aria-labelledby="topnavDocumentation" id="myDropdown">
           //Just removed <li></li> from here
</ul>

<script>
    $(function () {

        $.getJSON('dashtrend.json', function (loadMainItem) {

            $.each(loadMainItem.data, function (i, f) {
                var makemenu = "<li class='dropright'><a href='#' class='dropdown-item dropdown-toggle'  id='" + f.id + "' role='button' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" + f.text + "</a>";
                makemenu += "<div class='dropdown-menu' aria-labelledby='test'>";
                $.each(f.items, function (j) {
                        makemenu += "<a class='dropdown-item' href='" + f.items[j].navigationurl + "'>" + f.items[j].text + "</a>";

                })
                makemenu += "</div></li>";

                // <div class="dropdown-menu" aria-labelledby="ups4">
                //     <a class="dropdown-item" href="/Ups/UpsDashboard?upsid=1">Dashboard</a>
                //     <a class="dropdown-item" href="/Ups/Trends?id=1">Battery Trends</a>
                // </div>

                $(makemenu).appendTo("#myDropdown");
            });
        });

    });
</script>

1) I have removed the list from ul in HTML

2) I have updated your JavaScript code


问:
problem with "title" in UINavigationController
I am having a problem with title and UINavigationController. I am using the following code at UIViewControllerCurrent and when I get back from NextViewController, the title of the NavBar is still "Previous" ..Can anyone kindly help me out with this problem ? Thanks.</p>

```<code>[self setTitle:@"Previous"];
NextViewController *controller = [[NextViewController alloc] init];
[[self navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

- (void)viewWillAppear:(BOOL)animated; {
[self setTitle:@"Real Title"];
[super viewWillAppear:animated]; }
</code>```

答:
I would try to exchange the two lines

```<code>[self setTitle:@"Real Title"];
[super viewWillAppear:animated];
</code>```

so that you get

```<code>[super viewDidAppear:animated];
[self setTitle:@"Real Title"];
</code>```

and I would put these into viewDidAppear.

Body:
I am having a problem with title and UINavigationController. I am using the following code at UIViewControllerCurrent and when I get back from NextViewController, the title of the NavBar is still "Previous" ..Can anyone kindly help me out with this problem ? Thanks.

[self setTitle:@"Previous"];
NextViewController *controller = [[NextViewController alloc] init];
[[self navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

- (void)viewWillAppear:(BOOL)animated; {
[self setTitle:@"Real Title"];
[super viewWillAppear:animated]; }

Body:
I would try to exchange the two lines

[self setTitle:@"Real Title"];
[super viewWillAppear:animated];

so that you get

[super viewDidAppear:animated];
[self setTitle:@"Real Title"];

and I would put these into viewDidAppear.


问:
Java 8 optional .map().orElse always returns orElse
I'm trying to get the version from a package and am having trouble implementing it.
This code returns the correct package:

```<code>private String getVersion(){
    Optional<Class<?>> optional = Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst();
    return optional.isPresent() ? optional.get().getPackage().getImplementationVersion() : "";
}

</code>```

But I think it would be neater to do

```<code>private String getVersionWithMap() {
    return Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst()
            .map(cl -> cl.getPackage().getImplementationVersion())
            .orElse("");
}

</code>```

However, getVersionWithMap() always returns the empty string "".

EDIT:
SOLVED. It ended up being the frontend that was wrong. Found this after going back to using getVersion() and having the same issue of no visible version in the frontend.

答: Both functions work, the issue was somewhere else and I didn't test that part, assuming the fix would be here. My bad.</p>

Body:
I'm trying to get the version from a package and am having trouble implementing it.
This code returns the correct package:

private String getVersion(){
    Optional<Class<?>> optional = Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst();
    return optional.isPresent() ? optional.get().getPackage().getImplementationVersion() : "";
}

But I think it would be neater to do

private String getVersionWithMap() {
    return Arrays.stream(getClass().getInterfaces())
            .filter(cl -> isCorrectClass(cl))
            .findFirst()
            .map(cl -> cl.getPackage().getImplementationVersion())
            .orElse("");
}

However, getVersionWithMap() always returns the empty string "".

EDIT:
SOLVED. It ended up being the frontend that was wrong. Found this after going back to using getVersion() and having the same issue of no visible version in the frontend.


问:
Parse string in nodejs to an array
How can I convert following string into an array in nodejs?

```<code>"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"
</code>```

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?

答:
```<code>const str = "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]".substring(8);
</code>```

This is resolve problem "Unexpected token c in JSON at position 2.".
And you dont need JSON.parse already.

Title: Parse string in nodejs to an array

Body:
How can I convert following string into an array in nodejs?

"Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]"

I tried JSON.parse, but there was an error: Unexpected token c in JSON at position 2.

Do you have any ideas?

Body:
const str = "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]".substring(8);

This is resolve problem "Unexpected token c in JSON at position 2.".
And you dont need JSON.parse already.


问:
The Android Studio Project Synchronization Is Slow After the HMS Core Is Connected
I have configured Google and center Maven repositories. But it shows that they are not configured, what should I do?</p>

答:
Having a separate repository section will help speed up the build.</p>

```<code>allprojects {
    repositories {
        google()
        jcenter()
    }
    repositories {
        maven {
            url 'http://developer.huawei.com/repo/'
        }
    }
}
</code>```

Body:
Having a separate repository section will help speed up the build.

allprojects {
    repositories {
        google()
        jcenter()
    }
    repositories {
        maven {
            url 'http://developer.huawei.com/repo/'
        }
    }
}