问:
How to avoid a destructor being called twice in C++?
I'm testing out a class representing an dynamic array data structure I made for myself as practice with the language, but I ran into a problem where the destructor is called twice over, causing a heap corruption error.

So far, I have attempted to comment out some of the delete words. However, this leads to undefined behavior.

```<code>#include <iostream>
#include "windows.h"
#include <vector>

template<typename T> class Spider {
private:

    T** pointer;

    int maxSize;
    int lengthFilled;
public:
    //default constructor
    Spider()
    {
        pointer = new T * [1];
        maxSize = 1;
        lengthFilled = 0;
    }
    //destructor
    ~Spider()
    {
        for (int i = 0; i < lengthFilled; i++)
        {
            pop();
        }
        delete[] pointer;
    }
    //Pushes an object in
    void push(T thing)
    {
        if (lengthFilled == maxSize)
        {
            increaseSize();
        }

        T* thinggummy = &thing;

        //then save its pointer in the functional array
        pointer[lengthFilled] = thinggummy;
        lengthFilled++;
    }

    //pops the array
    void pop()
    {
        delete pointer[lengthFilled-1];
        setSize(lengthFilled - 1);
        lengthFilled--;
    }
}

int main()
{

    Spider<Spider<int>> test((long long)1);

    for (int i = 0; i < 2; i++)
    {
        test.push(Spider<int>());
        test.get(i).push(2);//this is implemented in the actual code, just omitted here
        std::cout << test.get(i).get(0);
        std::cout << "push complete\n";
    }

    system("pause");

    return 0;
}
</code>```

The expected results for this program should be:

```<code>2
push complete
2
push complete
</code>```

Press any key to continue...

Instead, I get an critical error code in the debug log of "Critical error detected c0000374".

答:
There are two issues here:

Like WhiteSword already mentioned, you are taking the address of a local variable when you do T *thinggummy = &thing. That is going to cause trouble since that address will be invalid as soon as you leave scope (unless maybe T resolves to a reference type).

You call delete on the things in the pointer array. However, these were not allocated via new. Instead they are just addresses of something. So you are trying to free something that was never allocted.

Body:
I'm testing out a class representing an dynamic array data structure I made for myself as practice with the language, but I ran into a problem where the destructor is called twice over, causing a heap corruption error.

So far, I have attempted to comment out some of the delete words. However, this leads to undefined behavior.

#include <iostream>
#include "windows.h"
#include <vector>

template<typename T> class Spider {
private:

    T** pointer;

    int maxSize;
    int lengthFilled;
public:
    //default constructor
    Spider()
    {
        pointer = new T * [1];
        maxSize = 1;
        lengthFilled = 0;
    }
    //destructor
    ~Spider()
    {
        for (int i = 0; i < lengthFilled; i++)
        {
            pop();
        }
        delete[] pointer;
    }
    //Pushes an object in
    void push(T thing)
    {
        if (lengthFilled == maxSize)
        {
            increaseSize();
        }

        T* thinggummy = &thing;

        //then save its pointer in the functional array
        pointer[lengthFilled] = thinggummy;
        lengthFilled++;
    }

    //pops the array
    void pop()
    {
        delete pointer[lengthFilled-1];
        setSize(lengthFilled - 1);
        lengthFilled--;
    }
}

int main()
{

    Spider<Spider<int>> test((long long)1);

    for (int i = 0; i < 2; i++)
    {
        test.push(Spider<int>());
        test.get(i).push(2);//this is implemented in the actual code, just omitted here
        std::cout << test.get(i).get(0);
        std::cout << "push complete\n";
    }

    system("pause");

    return 0;
}

The expected results for this program should be:

2
push complete
2
push complete

Press any key to continue...

Instead, I get an critical error code in the debug log of "Critical error detected c0000374".


来源: stackexchange

问:
Activate camera inside a tab (android)
I am trying to develop an application with 3 tabs, so that the 1st tab enables the camera and captures an image. So far I have 2 issues with the camera:

I want the camera to lock either in portrait or landscape mode. If I lock the camera in portrait then the image seems rotated and I have tried almost everything with camera.parameters but can't fix it. If I lock the camera in landscape mode then the problem is that the tabs menu also change orientation to landscape. Is there a way to change the orientation only inside that tab and leave the tabs menu in portrait mode?

The image is somehow stretched. I guess the problem is that the camera uses height and width of the full screen, but my app tries to fit the camera preview inside a framelayout that is smaller than the screen because of the tabs menu, so that way the image is stretched. Is there any way to fix this and show the actual camera preview with the tabs menu on it?

I use 1 activity that creates the 3 tabs and uses this layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/tabhost"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_weight="1"/>
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"/>
  </LinearLayout>
</TabHost>
</code>```

I use 1 activity for each tab. Specifically for the 1st tab (camera) I use the preview.class in the following layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content">
<FrameLayout android:layout_weight="1" android:id="@+id/preview" android:layout_gravity="fill_vertical" android:fitsSystemWindows="true" android:layout_height="wrap_content" android:layout_width="wrap_content">
</FrameLayout>
<Button android:text="Click" android:id="@+id/buttonClick" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center"></Button>
</LinearLayout>
</code>```

答:
I did it with 3 tabs where the first tab has to be the camera preview in portrait mode without distortion.
Well that's possible with 3 tricks :)

First set your sub preview activity with portrait mode to force the tab to be in portrait.
Either use in onCreate()

```<code>this.getParent().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
</code>```

or in manifest

```<code>android:screenOrientation="portrait"
</code>```

Then to rotate the screen you should not use parameter since it doesn't work but (only since 2.2)

```<code>if (Build.VERSION.SDK_INT >= 8 ) camera.setDisplayOrientation(90);
</code>```

Finally to avoid strectch you can but the FameLayout in fullscreen and make it go under the tabs (tabs is like an overlay but camera underneath is fullscreen without distortion)

```<code><TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@android:id/tabs"/>
</code>```

Et voila!

ContentLicense: CC BY-SA 2.5

Title: Activate camera inside a tab (android)

Body:
I am trying to develop an application with 3 tabs, so that the 1st tab enables the camera and captures an image. So far I have 2 issues with the camera:

I want the camera to lock either in portrait or landscape mode. If I lock the camera in portrait then the image seems rotated and I have tried almost everything with camera.parameters but can't fix it. If I lock the camera in landscape mode then the problem is that the tabs menu also change orientation to landscape. Is there a way to change the orientation only inside that tab and leave the tabs menu in portrait mode?

The image is somehow stretched. I guess the problem is that the camera uses height and width of the full screen, but my app tries to fit the camera preview inside a framelayout that is smaller than the screen because of the tabs menu, so that way the image is stretched. Is there any way to fix this and show the actual camera preview with the tabs menu on it?

I use 1 activity that creates the 3 tabs and uses this layout:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/tabhost"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dp">
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:layout_weight="1"/>
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"/>
  </LinearLayout>
</TabHost>

I use 1 activity for each tab. Specifically for the 1st tab (camera) I use the preview.class in the following layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content">
<FrameLayout android:layout_weight="1" android:id="@+id/preview" android:layout_gravity="fill_vertical" android:fitsSystemWindows="true" android:layout_height="wrap_content" android:layout_width="wrap_content">
</FrameLayout>
<Button android:text="Click" android:id="@+id/buttonClick" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center"></Button>
</LinearLayout>

Body:
I did it with 3 tabs where the first tab has to be the camera preview in portrait mode without distortion.
Well that's possible with 3 tricks :)

First set your sub preview activity with portrait mode to force the tab to be in portrait.
Either use in onCreate()

this.getParent().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

or in manifest

android:screenOrientation="portrait"

Then to rotate the screen you should not use parameter since it doesn't work but (only since 2.2)

if (Build.VERSION.SDK_INT >= 8 ) camera.setDisplayOrientation(90);

Finally to avoid strectch you can but the FameLayout in fullscreen and make it go under the tabs (tabs is like an overlay but camera underneath is fullscreen without distortion)

<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@android:id/tabs"/>

Et voila!

ContentLicense: CC BY-SA 3.0


问:
Store DateTime Value in AsyncStorage while the AppState Changes
I am trying to store DateTime Value when the state of App changes.For suppose the app is in Background and I want to store the value of DateTime in AsyncStorage and when the app is in active state I want to calculate the time difference. But the promise which i get as a return value is null. My RN Version is 56.0 can anyone help me out?

```<code>StoreDate = async () => {
        await AsyncStorage.setItem('date', new Date());
      };

      retrieveDate = async () =>
      {
        try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return JSON.parse(value);

    }
          catch(error){
            Alert.alert(error);
          }
      };

     if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then((filter) => {
            console.log("filter",filter);
            console.log("getDateTime",getDateTime);
          });
    }
</code>```

** Null promise returned when trying to retrieve the values using getItem **

答:
you should store date as string, and change it to Date when retrieving,like</p>

```<code>StoreDate = async () => {
    await AsyncStorage.setItem('date', new Date().getTime());
  };

retrieveDate = async () => {
    try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return new Date(parseInt(value));
    }
    catch(error){
        Alert.alert(error);
    }
};

if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then(() => {
        this.retrieveDate().then(data => {
           console.log('retrieve data ' , data)
        })
      });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to store DateTime Value when the state of App changes.For suppose the app is in Background and I want to store the value of DateTime in AsyncStorage and when the app is in active state I want to calculate the time difference. But the promise which i get as a return value is null. My RN Version is 56.0 can anyone help me out?

StoreDate = async () => {
        await AsyncStorage.setItem('date', new Date());
      };

      retrieveDate = async () =>
      {
        try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return JSON.parse(value);

    }
          catch(error){
            Alert.alert(error);
          }
      };

     if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then((filter) => {
            console.log("filter",filter);
            console.log("getDateTime",getDateTime);
          });
    }

** Null promise returned when trying to retrieve the values using getItem **

Body:
you should store date as string, and change it to Date when retrieving,like

StoreDate = async () => {
    await AsyncStorage.setItem('date', new Date().getTime());
  };

retrieveDate = async () => {
    try{
        let value = await AsyncStorage.getItem('date');
        console.log("value",value);
        Alert.alert(value);
        return new Date(parseInt(value));
    }
    catch(error){
        Alert.alert(error);
    }
};

if (this.state.appState.match(/inactive/) && nextAppState === 'background') {
    let getDateTime = this.StoreDate().then(() => {
        this.retrieveDate().then(data => {
           console.log('retrieve data ' , data)
        })
      });
}


问:
Cassandra unable to query sum of rows from a table
I am using Cassandra database for capturing and saving a simple network sniffer data, but because the number of rows in the table is greater than 20M+ rows, it is unable to run any aggregate function such as sum or count.

Following is my table schema:

```<code>CREATE TABLE db.uinfo (
    id timeuuid,
    created timestamp,
    dst_ip text,
    dst_mac text,
    dst_port int,
    protocol int,
    src_ip text,
    src_mac text,
    src_port int,
    PRIMARY KEY (id, created)
) WITH CLUSTERING ORDER BY (created ASC)
    AND bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';
</code>```

Now when I run the query(with or without limit):

```<code>select src_ip, sum(data) as total from db.uinfo;
</code>```

It throws me the following error:

```<code>OperationTimedOut: errors={'127.0.0.1': 'Client request timeout. See Session.execute[_async](timeout)'}, last_host=127.0.0.1
</code>```

Any chance any of you good people could help me do the same? I have tried changing the timeouts in the cqlshrc and cassandra.yaml respectively. I have even tried starting the cqlsh using:

cqlsh  --connect-timeout=120 --request-timeout=120.

I am using [cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4]

答:
This kind of queries won't work with Cassandra when you have relatively big data in it - such kind of queries requires the scanning of the whole database, and reading all data in it. Cassandra is great when you know the partition that you want to hit, and as such, send query only to individual servers where they could be processed very effectively. So aggregation functions work best only within partition.

If you need this kind of queries done - the common suggestion is to use Spark to read data in parallel, and perform aggregations. You can do this using Spark Cassandra Connector, but it will be slower than usual queries - maybe dozens of seconds, or even minutes, depending on the size of data, hardware for Spark jobs, etc.

If you need this kind of queries performed very often, then you need to look to other technologies, but it's hard to say who will perform well in such situation.

Body:
I am using Cassandra database for capturing and saving a simple network sniffer data, but because the number of rows in the table is greater than 20M+ rows, it is unable to run any aggregate function such as sum or count.

Following is my table schema:

CREATE TABLE db.uinfo (
    id timeuuid,
    created timestamp,
    dst_ip text,
    dst_mac text,
    dst_port int,
    protocol int,
    src_ip text,
    src_mac text,
    src_port int,
    PRIMARY KEY (id, created)
) WITH CLUSTERING ORDER BY (created ASC)
    AND bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

Now when I run the query(with or without limit):

select src_ip, sum(data) as total from db.uinfo;

It throws me the following error:

OperationTimedOut: errors={'127.0.0.1': 'Client request timeout. See Session.execute[_async](timeout)'}, last_host=127.0.0.1

Any chance any of you good people could help me do the same? I have tried changing the timeouts in the cqlshrc and cassandra.yaml respectively. I have even tried starting the cqlsh using:

cqlsh  --connect-timeout=120 --request-timeout=120.

I am using [cqlsh 5.0.1 | Cassandra 3.11.4 | CQL spec 3.4.4 | Native protocol v4]


问:
Type conversion between two struct pointers
I have a struct that consists of a custom time.Time defined for the sake of it having a custom MarshalJSON() interface, following this answer's suggestion:

```<code>type MyTime time.Time
func (s myTime) MarshalJSON() ([]byte, error) {
    t := time.Time(s)
    return []byte(t.Format(`"20060102T150405Z"`)), nil
}
</code>```

I define a MyStruct type with ThisDate and ThatDate fields of type *MyTime:

```<code>type MyStruct struct {
    ThisDate *MyTime `json:"thisdate,omitempty"`
    ThatDate *MyTime `json:"thatdate,omitempty"`
}
</code>```

As far as I understand, I need to use *MyTime and not MyTime so the omitempty tag will have an effect when I'll MarshalJSON a variable of this type, following this answer's suggestion.

I use a library that has a function that returns me a struct with some fields of type *time.Time:

```<code>someVar := Lib.GetVar()
</code>```

I tried to define a variable of type MyStruct like this:

```<code>myVar := &MyStruct{
    ThisDate: someVar.ThisDate
    ThatDate: someVar.ThatDate
}
</code>```

Naturally, it gives me a compilation error:

```<code>cannot use someVar.ThisDate (variable of type *time.Time) as *MyTime value in struct literal ...
</code>```

I tried typecasting someVar.ThisDate with */& and without these without luck. I thought the following would work:

```<code>myVar := &MyStruct{
    ThisDate: *MyTime(*someVar.ThisDate)
    ThatDate: *MyTime(*someVar.ThatDate)
}
</code>```

But it gives me a different compilation error:

```<code>invalid operation: cannot indirect MyTime(*someVar.ThisDate) (value of type MyTime) ...
</code>```

It seems I probably lack basic understanding of pointers and dereferences in Go. Never the less, I would like to avoid finding a specific solution for my issue which comes down to the combination of the need to make omitempty have an effect and a custom MarshalJSON.

答:
The problem is the ambiguous syntax of *T(v) or whatever else you tried there. The Golang's spec gives useful examples for type conversions as this, quoting:

```<code>*Point(p)        // same as *(Point(p))
(*Point)(p)      // p is converted to *Point
</code>```

Therefor, since *Point is needed, *T(v) should be used.

Body:
I have a struct that consists of a custom time.Time defined for the sake of it having a custom MarshalJSON() interface, following this answer's suggestion:

type MyTime time.Time
func (s myTime) MarshalJSON() ([]byte, error) {
    t := time.Time(s)
    return []byte(t.Format(`"20060102T150405Z"`)), nil
}

I define a MyStruct type with ThisDate and ThatDate fields of type *MyTime:

type MyStruct struct {
    ThisDate *MyTime `json:"thisdate,omitempty"`
    ThatDate *MyTime `json:"thatdate,omitempty"`
}

As far as I understand, I need to use *MyTime and not MyTime so the omitempty tag will have an effect when I'll MarshalJSON a variable of this type, following this answer's suggestion.

I use a library that has a function that returns me a struct with some fields of type *time.Time:

someVar := Lib.GetVar()

I tried to define a variable of type MyStruct like this:

myVar := &MyStruct{
    ThisDate: someVar.ThisDate
    ThatDate: someVar.ThatDate
}

Naturally, it gives me a compilation error:

cannot use someVar.ThisDate (variable of type *time.Time) as *MyTime value in struct literal ...

I tried typecasting someVar.ThisDate with */& and without these without luck. I thought the following would work:

myVar := &MyStruct{
    ThisDate: *MyTime(*someVar.ThisDate)
    ThatDate: *MyTime(*someVar.ThatDate)
}

But it gives me a different compilation error:

invalid operation: cannot indirect MyTime(*someVar.ThisDate) (value of type MyTime) ...

It seems I probably lack basic understanding of pointers and dereferences in Go. Never the less, I would like to avoid finding a specific solution for my issue which comes down to the combination of the need to make omitempty have an effect and a custom MarshalJSON.

Body:
The problem is the ambiguous syntax of *T(v) or whatever else you tried there. The Golang's spec gives useful examples for type conversions as this, quoting:

*Point(p)        // same as *(Point(p))
(*Point)(p)      // p is converted to *Point

Therefor, since *Point is needed, *T(v) should be used.


问:
Powerbuilder 10.5: upgrade or migrate away?
We've recently started to support a PowerBuilder 10.5 application and the question has come whether or not we should think about alternatives or keep the app running in PB 10.5. It is a classic PB app; an administrative software, build upon an Oracle DB.

Right now, the app works great, but there are two reasons why we reconsider:

The sole developer of this app is about to retire. He's the only one
who has all the PB-knowledge to support this app.

We might want to improve the offered services of the app. So integrations with other tools are right around the corner.

I'm not very familiar with PB, but I've read it (only the newest versions) is now supported by Appeon. The latest version is now 2017 R3, with a 2019 version coming up.

I'm wondering what the pro's & con's are of trying to update the current 10.5 version to the latest version. Is it worth it to update? Or what are the pro's & con's of sticking to the 10.5 version?

Or should we consider moving to a newer technology, since so few Powerbuilders are to be found nowadays? And if so, what technology would you advise?

Rather than just differences between the older and newer PB-versions, I'm looking for motivations to upgrade/migrate/do nothing at all.

Thanks.

答:
I would recommend migrating.
You will find several companies that offer migration to both java and .net which are the leading platforms.
In terms of UI for me currently the only option is web. Using other technologies does not make a lot of sense.
If your company uses a lot of MS stack, like MS OS, SQL server. Exchange, Sharepoint etc I will recommend migrating to C# otherwise migrating to Java makes more sense</p>


问:
How to update summary state of data changes without subscribing to every input/component change in angular?
I have a rather complex modal to manage some data state. It has a lot of inputs, selections, checkboxes and other custom components.

Now I would like to show the user some summary hints about what data has been updated during the time modal has been opened and what consequences it would lead.
For example, on some actions, I would like to change the color of the "Update" button, on some actions not to show it at all and for all states show some summary (in a tooltip, for example) of what has been changed. Important thing is that it's not just showing that some input fileds were touched and others not, it's again some combination of their state change.

The problem that I don't use <form> tag at all since most of custom components just don't have name attributes to support it. So I can't write a custom form validator, the main side effect of which will be updating state summary variable (since I need something more complex that just form valid-invalid summary flag).

I also consider an approach of attaching valueChange or ngModelChange callbacks to all inputs and components to be rather complex in implementation at the current state of development.

So there is a question how can I continuously update state summary variable based on data change.

I could use setInterval() to update state but its update delay will be something completely arbitrary from the angular update cycle.

Update state result is used in several places so creating just a function calculating it on request and putting it in all needed places is very ineffective.
I've tried a hack to use such function only in one place, put the result in a variable and in all other places use the variable but it leads to angular smth like "variable is updated after it was used" error.

Is there any better approach to the problem?

答:
For starters you should use reactive forms. It makes it easier to track changes and manage controls.

With that in mind, start by creating a default value for your form :

```<code>defaultFormValue = { firstName: '', lastName: '' };
</code>```

Then create a form from it :

```<code>this.myForm = formBuilder.group(this.defaultFormValue);
</code>```

Now you can use all of the reactive forms methods & properties to manage your form

```<code>get isFirstNameChanged() {
  return this.myForm.get('firstName').dirty;
}

get isFirstNameDifferentThanDefault() {
  return this.myForm.get('firstName').value !== this.defaultFormValue.firstName;
}

resetForm() {
  this.myForm.reset(this.defaultFormValue);
}

// etc.
</code>```

Body:
For starters you should use reactive forms. It makes it easier to track changes and manage controls.

With that in mind, start by creating a default value for your form :

defaultFormValue = { firstName: '', lastName: '' };

Then create a form from it :

this.myForm = formBuilder.group(this.defaultFormValue);

Now you can use all of the reactive forms methods & properties to manage your form

get isFirstNameChanged() {
  return this.myForm.get('firstName').dirty;
}

get isFirstNameDifferentThanDefault() {
  return this.myForm.get('firstName').value !== this.defaultFormValue.firstName;
}

resetForm() {
  this.myForm.reset(this.defaultFormValue);
}

// etc.


问:
C# Generic Copy Constructor
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

```<code>interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}
</code>```

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

```<code>public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}
</code>```

Calling the method requires the type:

```<code>someFoo.Clone<T> ...
</code>```

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

```<code>IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;
</code>```

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

答:
When you need complete control over your deep copy clone, this pattern is very good:

```<code>public class FooBase
{
    private int x;

    public FooBase() { /* standard contructor */ }

    protected FooBase(FooBase clone)
    {
        this.x = clone.x;
    }

    public FooBase Clone() { return new FooBase(this); }
}

public class Foo : FooBase
{
    private int y;

    public Foo() { /* standard contructor */ }

    protected Foo(Foo clone) : base(clone)
    {
        this.y = clone.y;
    }

    public Foo Clone() { return new Foo(this); }
}
</code>```

Define protected contructor for cloning - so derived classes can clone values in base class.
This pattern must be written by hand (or generated with a help of good T4 template) but is very good for deep cloning.

Update: I think I have misunderstood the question and already have cloning implemented. Freddy is right - compiler must knew which type it should infer for  and it cannot do it from IFoo type. It can do it in (this Foo< T > foo) though.

OwnerDisplayName: blu

Title: C# Generic Copy Constructor

Body:
I have an interface, and two classes that implements the interface.  The classes have generic types.  I would like to clone from an instance of one class to the other.

interface IFoo
{
    // stuff
}

class Foo<T> : IFoo
{
    // foo stuff
    // ifoo implementation
}

class Bar<T> : IFoo
{
    // bar stuff
    // ifoo implementation
}

I have a Foo and would like a Bar.  Bar has a copy constructor taking a parameter of IFoo.
I created an extension method to implement the clone:

public static Bar<T> Clone<T>(this IFoo foo)
{
    return new Bar<T>(foo);
}

Calling the method requires the type:

someFoo.Clone<T> ...

Is there a way to omit declaring the type when calling the method by modifying the extension method, or any other way, to allow the the instance to just be passed in without caring about its underlying type?

Update
Here is how this is being used to better illustrate the situation.

In a method I iterate a collection and return an enumeration of IFoo.  In the method I look at an attribute of the source collection and determine the type of the Foo.

IFoo foo = null;

string type = element.Attribute("Type").Value;
switch (type)
{
    case "int":
        foo = new Foo<int>();
        break;

    case "string":
        foo = new Foo<string>();
        break;

    // etc
}
// other stuff

yield return foo;

The calling method has a List.  Later I select individual items from this list for use, at which point I would like a Bar instead of a Foo.  When selecting from the list the instances are of type IFoo, as in they only see the extension methods for "this IFoo foo".  I do not want to cast the IFoo to a Foo, that would require re-declaring the type of T.  I would just like to have Foo tell Bar what it is.  Is this possible?

LastEditorDisplayName: blu

Body:
When you need complete control over your deep copy clone, this pattern is very good:

public class FooBase
{
    private int x;

    public FooBase() { /* standard contructor */ }

    protected FooBase(FooBase clone)
    {
        this.x = clone.x;
    }

    public FooBase Clone() { return new FooBase(this); }
}

public class Foo : FooBase
{
    private int y;

    public Foo() { /* standard contructor */ }

    protected Foo(Foo clone) : base(clone)
    {
        this.y = clone.y;
    }

    public Foo Clone() { return new Foo(this); }
}

Define protected contructor for cloning - so derived classes can clone values in base class.
This pattern must be written by hand (or generated with a help of good T4 template) but is very good for deep cloning.

Update: I think I have misunderstood the question and already have cloning implemented. Freddy is right - compiler must knew which type it should infer for  and it cannot do it from IFoo type. It can do it in (this Foo< T > foo) though.

OwnerDisplayName: Jozef Izso

LastEditorDisplayName: Jozef Izso


问:
How to execute 2 consecutive commands in a thread without a context switch occurring?
I have a C# program, which has an "Agent" class. The program creates several Agents, and each Agent has a "run()" method, which executes a Task (i.e.: Task.Factory.StartNew()...).

Each Agent performs some calculations, and then needs to wait for all the other Agents to finish their calculations, before proceeding to the next stage (his actions will be based according to the calculations of the others).

In order to make an Agent wait, I have created a CancellationTokenSource (named "tokenSource"), and in order to alert the program that this Agent is going to sleep, I threw an event. Thus, the 2 consecutive commands are:

```<code>(1) OnWaitingForAgents(new EventArgs());
(2) tokenSource.Token.WaitHandle.WaitOne();
</code>```

(The event is caught by an "AgentManager" class, which is a thread in itself, and the 2nd command makes the Agent Task thread sleep until a signal will be received for the Cancellation Token).

Each time the above event is fired, the AgentManager class catches it, and adds +1 to a counter. If the number of the counter equals the number of Agents used in the program, the AgentManager (which holds a reference to all Agents) wakes each one up as follows:

```<code>agent.TokenSource.Cancel();
</code>```

Now we reach my problem: The 1st command is executed asynchronously by an Agent, then due to a context switch between threads, the AgentManager seems to catch the event, and goes on to wake up all the Agents. BUT - the current Agent has not even reached the 2nd command yet !
Thus, the Agent is receiving a "wake up" signal, and only then does he go to sleep, which means he gets stuck sleeping with no one to wake him up!
Is there a way to "atomize" the 2 consecutive methods together, so no context switch will happen, thus forcing the Agent to go to sleep before the AgentManager has the chance to wake him up?

答:
humm... I don't think it's good idea (or even possible) develop software in .NET worrying about context switches, since neither Windows or .NET are real time. Probably you have another kind of problem in that code.

I've understood that you simply run all your agents in parallel, and you want to wait till all of them have finished to go to the next stage. You can use several techniques to accomplish that, the easiest one would be using Monitor.Wait(Object monitor) and Monitor.PulseAll(Object monitor).

In the task library there are several things to do it as well. As @jishi has pointed out, you can use the Parallel flavours, or spawn a lot of Tasks and then wait for all with the Task.WaitAll(Task[] tasks) method.

Each time the above event is fired,
  the AgentManager class catches it, and
  adds +1 to a counter.

How are you adding 1 to that counter and how are you reading it? You should use Interloked.Increment to ensure an atomic operation, and read it in a volatile operation with Thread.VolatileRead for example, or simply put it in a lock statement.

Body:
I have a C# program, which has an "Agent" class. The program creates several Agents, and each Agent has a "run()" method, which executes a Task (i.e.: Task.Factory.StartNew()...).

Each Agent performs some calculations, and then needs to wait for all the other Agents to finish their calculations, before proceeding to the next stage (his actions will be based according to the calculations of the others).

In order to make an Agent wait, I have created a CancellationTokenSource (named "tokenSource"), and in order to alert the program that this Agent is going to sleep, I threw an event. Thus, the 2 consecutive commands are:

(1) OnWaitingForAgents(new EventArgs());
(2) tokenSource.Token.WaitHandle.WaitOne();

(The event is caught by an "AgentManager" class, which is a thread in itself, and the 2nd command makes the Agent Task thread sleep until a signal will be received for the Cancellation Token).

Each time the above event is fired, the AgentManager class catches it, and adds +1 to a counter. If the number of the counter equals the number of Agents used in the program, the AgentManager (which holds a reference to all Agents) wakes each one up as follows:

agent.TokenSource.Cancel();

Now we reach my problem: The 1st command is executed asynchronously by an Agent, then due to a context switch between threads, the AgentManager seems to catch the event, and goes on to wake up all the Agents. BUT - the current Agent has not even reached the 2nd command yet !
Thus, the Agent is receiving a "wake up" signal, and only then does he go to sleep, which means he gets stuck sleeping with no one to wake him up!
Is there a way to "atomize" the 2 consecutive methods together, so no context switch will happen, thus forcing the Agent to go to sleep before the AgentManager has the chance to wake him up?


问:
Regex pattern in JavaScript to test for dots/hyphens in names
Required regex pettern like

allow only letters with  min 1 dot and maximum 3 dots.

allow optional as '-' special character.

Ex: raj.gopal-reddy  or raj.reddy.gopal

答:
Your current regex is on the right track, and I would use a negative lookahead to assert that more than three dots do not occur.  Consider this pattern:</p>

```<code>^(?!.*\..*\..*\..*\.)[A-Za-z-]*\.[A-Za-z-]*$
</code>```

Body:
Your current regex is on the right track, and I would use a negative lookahead to assert that more than three dots do not occur.  Consider this pattern:

^(?!.*\..*\..*\..*\.)[A-Za-z-]*\.[A-Za-z-]*$


问:
Fetching JSON response from web not working
I am trying to fetch a json. While the code used to work I changed it a little and now it doesn't work. The code is supposed to exchange money.

```<code>            sendjsonrequest();
            assert tv != null;

            //Request a string response from the URL resource
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://free.currencyconverterapi.com/api/v6/convert?q=EUR_ILS&compact=ultra&apiKey=6f4b50fae0c5c91a84bd",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the response string.
                            tv.setText("Response is: " + Float.parseFloat(response) * Float.parseFloat(et1.getText().toString()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tv.setText("Oops! That didn't work!");
                }
            });

            //Instantiate the RequestQueue and add the request to the queue
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            queue.add(stringRequest);
            String str1 = et1.getText().toString();
            str = Float.parseFloat(str1);
            float e = f * str;
            String ef = Float.toString(e);
            tv.setText(ef);
        }
    });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

public void sendjsonrequest() {//sends the request to the website and retrieves specififc data (exchange rate between EUR to ILS)
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                tv1 = response.getString("EUR_ILS");

                f = Float.parseFloat(tv1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}
}
</code>```

答:
Hope it helps to you have to just perform like this only

```<code>private void loadHeroList() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        //getting the whole json object from the response
                        JSONObject obj = new JSONObject(response);

                        //we have the array named hero inside the object
                        //so here we are getting that json array
                        JSONArray heroArray = obj.getJSONArray("heroes");

                        //now looping through all the elements of the json array
                        for (int i = 0; i < heroArray.length(); i++) {
                            //getting the json object of the particular index inside the array
                            JSONObject heroObject = heroArray.getJSONObject(i);

                            //creating a hero object and giving them the values from json object
                            Heroes hero = new Heroes(heroObject.getString("name"), heroObject.getString("imageurl"));

                            //adding the hero to herolist
                            heroList.add(hero);
                        }

                        //creating custom adapter object
                        ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());

                        //adding the adapter to listview
                        listView.setAdapter(adapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

    //creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //adding the string request to request queue
    requestQueue.add(stringRequest);
}
</code>```

Body:
I am trying to fetch a json. While the code used to work I changed it a little and now it doesn't work. The code is supposed to exchange money.

            sendjsonrequest();
            assert tv != null;

            //Request a string response from the URL resource
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://free.currencyconverterapi.com/api/v6/convert?q=EUR_ILS&compact=ultra&apiKey=6f4b50fae0c5c91a84bd",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the response string.
                            tv.setText("Response is: " + Float.parseFloat(response) * Float.parseFloat(et1.getText().toString()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tv.setText("Oops! That didn't work!");
                }
            });

            //Instantiate the RequestQueue and add the request to the queue
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            queue.add(stringRequest);
            String str1 = et1.getText().toString();
            str = Float.parseFloat(str1);
            float e = f * str;
            String ef = Float.toString(e);
            tv.setText(ef);
        }
    });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

public void sendjsonrequest() {//sends the request to the website and retrieves specififc data (exchange rate between EUR to ILS)
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                tv1 = response.getString("EUR_ILS");

                f = Float.parseFloat(tv1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}
}

Body:
Hope it helps to you have to just perform like this only

private void loadHeroList() {
    StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        //getting the whole json object from the response
                        JSONObject obj = new JSONObject(response);

                        //we have the array named hero inside the object
                        //so here we are getting that json array
                        JSONArray heroArray = obj.getJSONArray("heroes");

                        //now looping through all the elements of the json array
                        for (int i = 0; i < heroArray.length(); i++) {
                            //getting the json object of the particular index inside the array
                            JSONObject heroObject = heroArray.getJSONObject(i);

                            //creating a hero object and giving them the values from json object
                            Heroes hero = new Heroes(heroObject.getString("name"), heroObject.getString("imageurl"));

                            //adding the hero to herolist
                            heroList.add(hero);
                        }

                        //creating custom adapter object
                        ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());

                        //adding the adapter to listview
                        listView.setAdapter(adapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //displaying the error in toast if occurrs
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

    //creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //adding the string request to request queue
    requestQueue.add(stringRequest);
}


问:
RegEx for matching specific numeric patterns
I want to match numbers without signs or operator, So I came up this regex.

```<code>echo "-123 +1234" | grep -Po '(?<=-)123 (?<=\+)1234'
</code>```

but it's not matching the string. Why two lookbehind not working? If I do

```<code>echo "-123 +1234" | grep -Po '(?<=-)123
</code>```

I get the correct result 123 but when I do grep -Po '(?<=-)123 (?<=\+)1234' the second part is not matching.

My desired result:

```<code>123 1234
</code>```

答:
If you really want to extract the numbers that are preceded by a - or a +, then you can use:

```<code>echo '-123 +1234 456' | grep -oP '(?<=-|\+)\d+'
123
1234
</code>```

If you just want to extract any sequence of digits (that is a word by itself), then using grep in perl like regex is not required and you can simply use:

```<code> echo '-123 +1234 456' | grep -Eo '\b[0-9]+\b'
</code>```

Body:
I want to match numbers without signs or operator, So I came up this regex.

echo "-123 +1234" | grep -Po '(?<=-)123 (?<=\+)1234'

but it's not matching the string. Why two lookbehind not working? If I do

echo "-123 +1234" | grep -Po '(?<=-)123

I get the correct result 123 but when I do grep -Po '(?<=-)123 (?<=\+)1234' the second part is not matching.

My desired result:

123 1234

Body:
If you really want to extract the numbers that are preceded by a - or a +, then you can use:

echo '-123 +1234 456' | grep -oP '(?<=-|\+)\d+'
123
1234

If you just want to extract any sequence of digits (that is a word by itself), then using grep in perl like regex is not required and you can simply use:

 echo '-123 +1234 456' | grep -Eo '\b[0-9]+\b'


问:
Azure CDN Standard Akamai CORS failed
i am using hls/dash for video streaming using azure akamai cdn but every time its getting failed due to CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

i config cors into my storage account but i am unable to stream video

```<code><Cors>
      <CorsRule>
            <AllowedOrigins>*</AllowedOrigins>
            <AllowedMethods>GET,HEAD,OPTIONS</AllowedMethods>
            <AllowedHeaders>*</AllowedHeaders>
            <ExposedHeaders>server,range</ExposedHeaders>
            <MaxAgeInSeconds>3000</MaxAgeInSeconds>
    </CorsRule>
<Cors>
</code>```

is their any other way to config cors in cdn

答: Akamai CDN doesn’t have CORS settings and it will pass all headers from the Origin. So, as long as the origin returns CORS headers and CDN Edge Server has not cached the old resource, it will return CORS headers.</p>

Title: Azure CDN Standard Akamai CORS failed

Body:
i am using hls/dash for video streaming using azure akamai cdn but every time its getting failed due to CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

i config cors into my storage account but i am unable to stream video

<Cors>
      <CorsRule>
            <AllowedOrigins>*</AllowedOrigins>
            <AllowedMethods>GET,HEAD,OPTIONS</AllowedMethods>
            <AllowedHeaders>*</AllowedHeaders>
            <ExposedHeaders>server,range</ExposedHeaders>
            <MaxAgeInSeconds>3000</MaxAgeInSeconds>
    </CorsRule>
<Cors>

is their any other way to config cors in cdn


问:
SQL query with join to get nested array of objects
Summary: I'll start with a JSON schema to describe the expectation. Notice the roles with a nested array of objects and I'm looking for a "Smart query" that can fetch it one single query.

```<code>{
    "id": 1,
    "first": "John",
    "roles": [ // Expectation -> array of objects
        {
            "id": 1,
            "name": "admin"
        },
        {
            "id": 2,
            "name": "accounts"
        }
    ]
}
</code>```

user

```<code>+----+-------+
| id | first |
+----+-------+
|  1 | John  |
|  2 | Jane  |
+----+-------+
</code>```

role

```<code>+----+----------+
| id |   name   |
+----+----------+
|  1 | admin    |
|  2 | accounts |
|  3 | sales    |
+----+----------+
</code>```

user_role

```<code>+---------+---------+
| user_id | role_id |
+---------+---------+
|       1 |       1 |
|       1 |       2 |
|       2 |       2 |
|       2 |       3 |
+---------+---------+
</code>```

Attempt 01

In a naive approach I'd run two sql queries in my nodejs code, with the help of multipleStatements:true in connection string. Info.

```<code>User.getUser = function(id) {
    const sql = "SELECT id, first FROM user WHERE id = ?; \
        SELECT role_id AS id, role.name from user_role \
        INNER JOIN role ON user_role.role_id = role.id WHERE user_id = ?";

    db.query(sql, [id, id], function(error, result){
        const data = result[0][0]; // first query result
        data.roles = result[1];  // second query result, join in code.
        console.log(data);
    });
};
</code>```

Problem: Above code produces the expected JSON schema but it takes two queries, I was able to narrow it down in a smallest possible unit of code because of multiple statements but I don't have such luxury in other languages like Java or maybe C# for instance, there I've to create two functions and two sql queries. so I'm looking for a single query solution.

Attempt 02

In an earlier attempt With the help of SO community, I was able to get close to the following using single query but it can only help to produce the array of string (not array of objects).

```<code>User.getUser = function(id) {
    const sql = "SELECT user.id, user.first, GROUP_CONCAT(role.name) AS roles FROM user \
        INNER JOIN user_role ON user.id = user_role.user_id \
        INNER JOIN role ON user_role.role_id = role.id \
        WHERE user.id = ? \
        GROUP BY user.id";
    db.query(sql, id, function (error, result) {
        const data = {
            id: result[0].id, first: result[0].first,
            roles: result[0].roles.split(",") // manual split to create array
        };
        console.log(data);
    });
};
</code>```

Attempt 02 Result

```<code>{
    "id": 1,
    "first": "John",
    "roles": [ // array of string
        "admin",
        "accounts"
    ]
}
</code>```

it's such a common requirement to produce array of objects so wondering there must be something in SQL that I'm not aware of. Is there a way to better achieve this with the help of an optimum query.

Or let me know that there's no such solution, this is it and this is how it's done in production code out there with two queries.

Attempt 03

use role.id instead of role.name in GROUP_CONCAT(role.id), that way you can get hold of some id's and then use another subquery to get associated role names, just thinking...

SQL (doesn't work but just to throw something out there for some thought)

```<code>SELECT
  user.id,  user.first,
  GROUP_CONCAT(role.id) AS role_ids,
  (SELECT id, name FROM role WHERE id IN role_ids) AS roles
FROM user
INNER JOIN user_role ON user.id = user_role.user_id
INNER JOIN role ON user_role.role_id = role.id
WHERE user.id = 1
GROUP BY user.id;
</code>```

Edit

Based on Amit's answer, I've learned that there's such solution in SQL Server using JSON AUTO. Yes this is something I'm looking for in MySQL.

To articulate precisely.

When you join tables, columns in the first table are generated as
  properties of the root object. Columns in the second table are
  generated as properties of a nested object.

答:
User this Join Query

FOR JSON AUTO will return JSON for your query result

```<code>SELECT U.UserID, U.Name, Roles.RoleID, Roles.RoleName
FROM [dbo].[User] as U
INNER JOIN [dbo].UserRole as UR ON UR.UserID=U.UserID
INNER JOIN [dbo].RoleMaster as Roles ON Roles.RoleID=UR.RoleMasterID
FOR JSON AUTO
</code>```

out put of above query is

```<code>[
  {
    "UserID": 1,
    "Name": "XYZ",
    "Roles": [
      {
        "RoleID": 1,
        "RoleName": "Admin"
      }
    ]
  },
  {
    "UserID": 2,
    "Name": "PQR",
    "Roles": [
      {
        "RoleID": 1,
        "RoleName": "Admin"
      },
      {
        "RoleID": 2,
        "RoleName": "User"
      }
    ]
  },
  {
    "UserID": 3,
    "Name": "ABC",
    "Roles": [
      {
        "RoleID": 1,
        "RoleName": "Admin"
      }
    ]
  }
]
</code>```

Body:
Summary: I'll start with a JSON schema to describe the expectation. Notice the roles with a nested array of objects and I'm looking for a "Smart query" that can fetch it one single query.

{
    "id": 1,
    "first": "John",
    "roles": [ // Expectation -> array of objects
        {
            "id": 1,
            "name": "admin"
        },
        {
            "id": 2,
            "name": "accounts"
        }
    ]
}

user

+----+-------+
| id | first |
+----+-------+
|  1 | John  |
|  2 | Jane  |
+----+-------+

role

+----+----------+
| id |   name   |
+----+----------+
|  1 | admin    |
|  2 | accounts |
|  3 | sales    |
+----+----------+

user_role

+---------+---------+
| user_id | role_id |
+---------+---------+
|       1 |       1 |
|       1 |       2 |
|       2 |       2 |
|       2 |       3 |
+---------+---------+

Attempt 01

In a naive approach I'd run two sql queries in my nodejs code, with the help of multipleStatements:true in connection string. Info.

User.getUser = function(id) {
    const sql = "SELECT id, first FROM user WHERE id = ?; \
        SELECT role_id AS id, role.name from user_role \
        INNER JOIN role ON user_role.role_id = role.id WHERE user_id = ?";

    db.query(sql, [id, id], function(error, result){
        const data = result[0][0]; // first query result
        data.roles = result[1];  // second query result, join in code.
        console.log(data);
    });
};

Problem: Above code produces the expected JSON schema but it takes two queries, I was able to narrow it down in a smallest possible unit of code because of multiple statements but I don't have such luxury in other languages like Java or maybe C# for instance, there I've to create two functions and two sql queries. so I'm looking for a single query solution.

Attempt 02

In an earlier attempt With the help of SO community, I was able to get close to the following using single query but it can only help to produce the array of string (not array of objects).

User.getUser = function(id) {
    const sql = "SELECT user.id, user.first, GROUP_CONCAT(role.name) AS roles FROM user \
        INNER JOIN user_role ON user.id = user_role.user_id \
        INNER JOIN role ON user_role.role_id = role.id \
        WHERE user.id = ? \
        GROUP BY user.id";
    db.query(sql, id, function (error, result) {
        const data = {
            id: result[0].id, first: result[0].first,
            roles: result[0].roles.split(",") // manual split to create array
        };
        console.log(data);
    });
};

Attempt 02 Result

{
    "id": 1,
    "first": "John",
    "roles": [ // array of string
        "admin",
        "accounts"
    ]
}

it's such a common requirement to produce array of objects so wondering there must be something in SQL that I'm not aware of. Is there a way to better achieve this with the help of an optimum query.

Or let me know that there's no such solution, this is it and this is how it's done in production code out there with two queries.

Attempt 03

use role.id instead of role.name in GROUP_CONCAT(role.id), that way you can get hold of some id's and then use another subquery to get associated role names, just thinking...

SQL (doesn't work but just to throw something out there for some thought)

SELECT
  user.id,  user.first,
  GROUP_CONCAT(role.id) AS role_ids,
  (SELECT id, name FROM role WHERE id IN role_ids) AS roles
FROM user
INNER JOIN user_role ON user.id = user_role.user_id
INNER JOIN role ON user_role.role_id = role.id
WHERE user.id = 1
GROUP BY user.id;

Edit

Based on Amit's answer, I've learned that there's such solution in SQL Server using JSON AUTO. Yes this is something I'm looking for in MySQL.

To articulate precisely.

When you join tables, columns in the first table are generated as
  properties of the root object. Columns in the second table are
  generated as properties of a nested object.

Body:
User this Join Query

FOR JSON AUTO will return JSON for your query result

SELECT U.UserID, U.Name, Roles.RoleID, Roles.RoleName
FROM [dbo].[User] as U
INNER JOIN [dbo].UserRole as UR ON UR.UserID=U.UserID
INNER JOIN [dbo].RoleMaster as Roles ON Roles.RoleID=UR.RoleMasterID
FOR JSON AUTO

out put of above query is

[
  {
    "UserID": 1,
    "Name": "XYZ",
    "Roles": [
      {
        "RoleID": 1,
        "RoleName": "Admin"
      }
    ]
  },
  {
    "UserID": 2,
    "Name": "PQR",
    "Roles": [
      {
        "RoleID": 1,
        "RoleName": "Admin"
      },
      {
        "RoleID": 2,
        "RoleName": "User"
      }
    ]
  },
  {
    "UserID": 3,
    "Name": "ABC",
    "Roles": [
      {
        "RoleID": 1,
        "RoleName": "Admin"
      }
    ]
  }
]


问:
Table going out of div
I have a problem in layout in my spring MVC application. In my app, table which is containing in div going out of it even I set a width parameter for this div. I tried many solutions which I googled but without success. Here is my jsp file, CSS file, and screen from my app. As you can see when text in table is long it's not break to new line (as I want).

CSS file:

```<code>    th,td {
    border-style: solid;
    border-width: 5px;
    border-color: #BCBCBC;
}

#all {
    width: 500px;
}

#tablediv {
    width: 400px;
    float: left;
}
</code>```

jsp file:

```<code>    <body>
<h3>All your notes:</h3>
<c:if test="${!empty notes}"/>

<form method="post" action="manage_note">

<div id="all">
<div id="tablediv">

<table>

<tr>
    <th class="widther">Note date</th>
    <th>Description</th>
</tr>

<c:forEach items="${notes}" var="note">

<tr>
    <td class="widther">${note.date} ${note.time}</td>
    <td >${note.description}</td>
    <td><input type="radio" name="chosen_note" value="${note.note_id}"></td>
</tr>

</c:forEach>

</table>
</div>

<div id="addbutton">
    <input name="add_note" type="submit" value="Add note"/>
</div>

</div>

<div id="restbuttons">
    <input name="edit_note" type="submit" value="Edit"/>
    <input name="delete_note" type="submit" value="Delete"/>
</div>

</form>

</body>
</code>```

And here is screen:

http://imageshack.us/photo/my-images/203/tableproblem.png/

答:
I got a simple solution, hope it may help somebody someday.

Any table  which is flowing out of its container, just encapsulate it with a div tag with style="overflow:auto"

```<code><div style="overflow:auto">
<table>
.
.
.
</table>
</div>
</code>```

Title: Table going out of div

Body:
I have a problem in layout in my spring MVC application. In my app, table which is containing in div going out of it even I set a width parameter for this div. I tried many solutions which I googled but without success. Here is my jsp file, CSS file, and screen from my app. As you can see when text in table is long it's not break to new line (as I want).

CSS file:

    th,td {
    border-style: solid;
    border-width: 5px;
    border-color: #BCBCBC;
}

#all {
    width: 500px;
}

#tablediv {
    width: 400px;
    float: left;
}

jsp file:

All your notes:

<c:if test="${!empty notes}"/>

<form method="post" action="manage_note">

    Note date
    Description

<c:forEach items="${notes}" var="note">

    ${note.date} ${note.time}
    ${note.description}
    <input type="radio" name="chosen_note" value="${note.note_id}">

</c:forEach>

    <input name="add_note" type="submit" value="Add note"/>

    <input name="edit_note" type="submit" value="Edit"/>
    <input name="delete_note" type="submit" value="Delete"/>

</form>

And here is screen:

http://imageshack.us/photo/my-images/203/tableproblem.png/

Body:
I got a simple solution, hope it may help somebody someday.

Any table  which is flowing out of its container, just encapsulate it with a div tag with style="overflow:auto"

<div style="overflow:auto">
<table>
.
.
.
</table>
</div>


问:
error: command 'gcc' failed with exit status 1 while installing eventlet
I wanted to install eventlet on my system in order to have "Herd" for software deployment.. but the terminal is showing a gcc error:

```<code>  root@agrover-OptiPlex-780:~# easy_install -U eventlet
  Searching for eventlet
  Reading http://pypi.python.org/simple/eventlet/
  Reading http://wiki.secondlife.com/wiki/Eventlet
  Reading http://eventlet.net
   Best match: eventlet 0.9.16
    Processing eventlet-0.9.16-py2.7.egg
    eventlet 0.9.16 is already the active version in easy-install.pth

   Using /usr/local/lib/python2.7/dist-packages/eventlet-0.9.16-py2.7.egg
 Processing dependencies for eventlet
 Searching for greenlet>=0.3
Reading http://pypi.python.org/simple/greenlet/
Reading https://github.com/python-greenlet/greenlet
Reading http://bitbucket.org/ambroff/greenlet
Best match: greenlet 0.3.4
Downloading http://pypi.python.org/packages/source/g/greenlet/greenlet-   0.3.4.zip#md5=530a69acebbb0d66eb5abd83523d8272
Processing greenlet-0.3.4.zip
Writing /tmp/easy_install-_aeHYm/greenlet-0.3.4/setup.cfg
Running greenlet-0.3.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-_aeHYm/greenlet-0.3.4/egg-dist-tmp-t9_gbW
In file included from greenlet.c:5:0:
greenlet.h:8:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: Setup script exited with error: command 'gcc' failed with exit status 1`
</code>```

Why can't Python.h be found?

答:
This is an old post but I just run to the same problem on AWS EC2 installing regex. This working perfectly for me </p>

```<code>sudo yum -y install gcc
</code>```

<p>and next </p>

```<code>sudo yum -y install gcc-c++
</code>```

Body:
I wanted to install eventlet on my system in order to have "Herd" for software deployment.. but the terminal is showing a gcc error:

  root@agrover-OptiPlex-780:~# easy_install -U eventlet
  Searching for eventlet
  Reading http://pypi.python.org/simple/eventlet/
  Reading http://wiki.secondlife.com/wiki/Eventlet
  Reading http://eventlet.net
   Best match: eventlet 0.9.16
    Processing eventlet-0.9.16-py2.7.egg
    eventlet 0.9.16 is already the active version in easy-install.pth

   Using /usr/local/lib/python2.7/dist-packages/eventlet-0.9.16-py2.7.egg
 Processing dependencies for eventlet
 Searching for greenlet>=0.3
Reading http://pypi.python.org/simple/greenlet/
Reading https://github.com/python-greenlet/greenlet
Reading http://bitbucket.org/ambroff/greenlet
Best match: greenlet 0.3.4
Downloading http://pypi.python.org/packages/source/g/greenlet/greenlet-   0.3.4.zip#md5=530a69acebbb0d66eb5abd83523d8272
Processing greenlet-0.3.4.zip
Writing /tmp/easy_install-_aeHYm/greenlet-0.3.4/setup.cfg
Running greenlet-0.3.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-_aeHYm/greenlet-0.3.4/egg-dist-tmp-t9_gbW
In file included from greenlet.c:5:0:
greenlet.h:8:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: Setup script exited with error: command 'gcc' failed with exit status 1`

Why can't Python.h be found?

Body:
This is an old post but I just run to the same problem on AWS EC2 installing regex. This working perfectly for me

sudo yum -y install gcc

and next

sudo yum -y install gcc-c++


问:
mongoDB: unique index on a repeated value
So i'm pretty new to mongoDb so i figure this could be a misunderstanding on general usage. so bear with me.
I have a document schema I'm working with as such

```<code>  {
    name: "bob",
    email: "bob@gmail.com",
    logins: [
      { u: 'a', p: 'b', public_id: '123' },
      { u: 'x', p: 'y', public_id: 'abc' }
    ]
  }
</code>```

My Problem is that i need to ensure that the public ids are unique within a document and collection,
Furthermore there are some existing records being migrated from a mySQL DB that dont have records, and will therefore all be replaced by null values in mongo.

I figure its either an index

```<code>db.users.ensureIndex({logins.public_id: 1}, {unique: true});
</code>```

which isn't working because of the missing keys and is throwing a E11000 duplicate key error index:

or this is a more fundamental schema problem in that I shouldn't be nesting objects in an array structure like that. In which case, what? a seperate collection for the user_logins??? which seems to go against the idea of an embedded document.

答:
If you expect u and p to have always the same values on each insert (as in your example snippet), you might want to use the $addToSet operator on inserts to ensure the uniqueness of your public_id field. Otherwise I think it's quite difficult to make them unique across a whole collection not working with external maintenance or js functions.

If not, I would possibly store them in their own collection and use the public_id as _id field to ensure their cross-document uniqueness inside a collection. Maybe that would contradict the idea of embedded docs in a doc database, but according to different requirements I think that's negligible.

Body:
So i'm pretty new to mongoDb so i figure this could be a misunderstanding on general usage. so bear with me.
I have a document schema I'm working with as such

  {
    name: "bob",
    email: "bob@gmail.com",
    logins: [
      { u: 'a', p: 'b', public_id: '123' },
      { u: 'x', p: 'y', public_id: 'abc' }
    ]
  }

My Problem is that i need to ensure that the public ids are unique within a document and collection,
Furthermore there are some existing records being migrated from a mySQL DB that dont have records, and will therefore all be replaced by null values in mongo.

I figure its either an index

db.users.ensureIndex({logins.public_id: 1}, {unique: true});

which isn't working because of the missing keys and is throwing a E11000 duplicate key error index:

or this is a more fundamental schema problem in that I shouldn't be nesting objects in an array structure like that. In which case, what? a seperate collection for the user_logins??? which seems to go against the idea of an embedded document.


问:
Geany IDE backup copy path
I just lost an entire script in Geany editor...
Is there a place where Geany saves a backup or cached copy somewhere?

Thank you for your help...

答:
If you have just overwritten the file (Ctrl+S) and haven't yet quit Geany, you can just Ctrl+Z to the desired document state and save that file version.

If you have already quit Geany after that and haven't set up back up in Geany before, I am afraid that by means of Geany you cannot restore the file to the previous state.

Read this article about how to set up back up in Geany. Basically you can go to Edit -> Preferences -> Various (read the manual and the link above before changing these preferences) and:

disable use_atomic_file_saving (disabled by default)

enable use_gio_unsafe_file_saving (enabled by default)

enable gio_unsafe_save_backup (disabled by default)

This will always keep the previous version of the file (as a hidden file with ~ attached to its name) next to original.

Or you can install/enable the Save Actions Geany plugin and enable the Auto Save and Backup Copy options to automatically save files at a certain time interval and to keep a copy of previous file versions.

Title: Geany IDE backup copy path


问:
Playback restricted on iOS for VEVO videos from YouTube API
I have embedded videos (pulled from YouTube API v3) into my iPhone app using a UIWebView as suggested.  The problem is that some videos, such as those from VEVO, produce the following error when attempting to play them on the device.

This video contains content from VEVO.  It is restricted from playback on certain sites.

This should not occur, since apps like Flipboard and Rockpack also seem to be using a UIWebView, and are able to play videos from VEVO and other sources.

What could I be doing wrong?

PS: I am aware that there exist other posts that touch upon this issue in some way, but they fail to address this specific problem.

答:
For Swift 4.2 of @JAL's answer you just need to do the following and it will work like a charm with vevo videos:</p>

```<code>import UIKit
import youtube_ios_player_helper

class MyYoutubePlayerViewController: UIViewController {

  @IBOutlet weak var playerView: YTPlayerView!

   private var playerVars: [String : Any] =  [
                                                "playsinline" : 1,
                                                "showinfo" : 1,
                                                "rel" : 1,
                                                "modestbranding" : 1,
                                                "controls" : 1,
                                                "origin" : "https://www.youtube.com" ]

  override func viewDidLoad() {
     super.viewDidLoad()

     self.playerView.load(withVideoId: "YQHsXMglC9A", playerVars: playerVars)
  }

}
</code>```

Body:
For Swift 4.2 of @JAL's answer you just need to do the following and it will work like a charm with vevo videos:

import UIKit
import youtube_ios_player_helper

class MyYoutubePlayerViewController: UIViewController {

  @IBOutlet weak var playerView: YTPlayerView!

   private var playerVars: [String : Any] =  [
                                                "playsinline" : 1,
                                                "showinfo" : 1,
                                                "rel" : 1,
                                                "modestbranding" : 1,
                                                "controls" : 1,
                                                "origin" : "https://www.youtube.com" ]

  override func viewDidLoad() {
     super.viewDidLoad()

     self.playerView.load(withVideoId: "YQHsXMglC9A", playerVars: playerVars)
  }

}


问:
Mysql2::Error "Access denied for user" using env variable in database.yml
My System is macOX Mojave 10.14

MySQL is MySQL:8.0.16

My database.yml is:

```<code>development:
  adapter: mysql2
  encoding: utf8
  database: dev_database
  reconnect: false
  pool: 5
  username: <%= ENV['RAILS_DEV_DB_USSERNAME'] %>
  password: <%= ENV['RAILS_DEV_DB_PASSWORD'] %>
  socket: /tmp/mysql.sock
</code>```

and I have confirmed if the variable is valid. Using

Command-Line: erb config/database.yml

I can get:

```<code>development:
  adapter: mysql2
  encoding: utf8
  database: dev_database
  reconnect: false
  pool: 5
  username: root
  password: Wle3S#23sv
  socket: /tmp/mysql.sock
</code>```

But when I start rails s -e developent, and browse to my page, I can not connect to my database.

What can I do now?

答:
As Author arpiagar suggested rails 3, how use an ENV config vars in a Settings.yml file? check his example (26)

when you introduce a scriptlet tag in .yml file, it is more of erb template. So read it as a erb template first and then load the yml

You can use dotenv or figaro gems (inspired by the Twelve-Factor App methodology) to loads environment variables.

For example if you use dotenv gem

```<code>By default, load will look for a file called .env in the current working directory. Pass in multiple files and they will be loaded in order. The first value set for a variable will win.

require 'dotenv'
Dotenv.load('file1.env', 'file2.env')
HOSTNAME = ENV['HOSTNAME']
</code>```

More info please check below mentioned links

http://railsapps.github.io/rails-environment-variables.html

https://www.honeybadger.io/blog/ruby-guide-environment-variables/

Body:
My System is macOX Mojave 10.14

MySQL is MySQL:8.0.16

My database.yml is:

development:
  adapter: mysql2
  encoding: utf8
  database: dev_database
  reconnect: false
  pool: 5
  username: <%= ENV['RAILS_DEV_DB_USSERNAME'] %>
  password: <%= ENV['RAILS_DEV_DB_PASSWORD'] %>
  socket: /tmp/mysql.sock

and I have confirmed if the variable is valid. Using

Command-Line: erb config/database.yml

I can get:

development:
  adapter: mysql2
  encoding: utf8
  database: dev_database
  reconnect: false
  pool: 5
  username: root
  password: Wle3S#23sv
  socket: /tmp/mysql.sock

But when I start rails s -e developent, and browse to my page, I can not connect to my database.

What can I do now?

Body:
As Author arpiagar suggested rails 3, how use an ENV config vars in a Settings.yml file? check his example (26)

when you introduce a scriptlet tag in .yml file, it is more of erb template. So read it as a erb template first and then load the yml

You can use dotenv or figaro gems (inspired by the Twelve-Factor App methodology) to loads environment variables.

For example if you use dotenv gem

By default, load will look for a file called .env in the current working directory. Pass in multiple files and they will be loaded in order. The first value set for a variable will win.

require 'dotenv'
Dotenv.load('file1.env', 'file2.env')
HOSTNAME = ENV['HOSTNAME']

More info please check below mentioned links

http://railsapps.github.io/rails-environment-variables.html

https://www.honeybadger.io/blog/ruby-guide-environment-variables/


问:
Is There a function to get a *.exe file's Product Name?

How can i get the product name with exe file's string path?

i tried to get a product name with 'VerQueryValue' function in MSDN.

what i get this function is only version

i want to have a product name

And, Qt is not support to get a file information (file Version, file Product Name etc.)

答:
It can be retrieved using GetFileVersionInfoExW followed by VerQueryValueW with appropriate query string like \StringFileInfo\<4_digit_hex_lang_id><4_digit_hex_code_page_id>\ProductName. In this example I'm trying to get info from neutral / fallback resource using hardcoded IDs, but available IDs for different localizations can be retrieved by querying \VarFileInfo\Translation.

```<code>#include <sdkddkver.h>
#include <Windows.h>

#include <memory>
#include <string>
#include <cstddef>

#define SZ_STRING_FILE_INFO_W L"StringFileInfo"
#define SZ_PRODUCT_NAME_W L"ProductName"
#define SZ_HEX_LANG_ID_EN_US_W L"0409"
#define SZ_HEX_CODE_PAGE_ID_UNICODE_W L"04B0"

int wmain()
{
    auto const psz_file_path{L"C:\\Windows\\notepad.exe"};
    [[maybe_unused]] DWORD dummy{};
    auto const required_buffer_size
    {
        ::GetFileVersionInfoSizeExW
        (
            FILE_VER_GET_NEUTRAL, psz_file_path, ::std::addressof(dummy)
        )
    };
    if(0 == required_buffer_size)
    {
        return ::GetLastError();
    }
    auto const p_buffer
    {
        ::std::make_unique<char[]>
        (
            static_cast<::std::size_t>(required_buffer_size)
        )
    };
    auto const get_version_info_result
    {
        ::GetFileVersionInfoExW
        (
            FILE_VER_GET_NEUTRAL
        ,   psz_file_path
        ,   DWORD{}
        ,   required_buffer_size
        ,   static_cast<void *>(p_buffer.get())
        )
    };
    if(FALSE == get_version_info_result)
    {
        return ::GetLastError();
    }
    LPVOID p_value{};
    UINT value_length{};
    auto const query_result
    {
        ::VerQueryValueW
        (
            static_cast<void *>(p_buffer.get())
        ,   L"\\" SZ_STRING_FILE_INFO_W
            L"\\" SZ_HEX_LANG_ID_EN_US_W SZ_HEX_CODE_PAGE_ID_UNICODE_W
            L"\\" SZ_PRODUCT_NAME_W
        ,   ::std::addressof(p_value)
        ,   ::std::addressof(value_length)
        )
    };
    if
    (
        (FALSE == query_result)
        or
        (nullptr == p_value)
        or
        ((required_buffer_size / sizeof(wchar_t)) < value_length)
    )
    {
        return ::GetLastError();
    }
    ::std::wstring const product_name
    {
        static_cast<wchar_t const *>(p_value)
    ,   static_cast<::std::size_t>(value_length)
    };
    // product_name should contain "Microsoft® Windows® Operating System"
    return 0;
}
</code>```

Body:
It can be retrieved using GetFileVersionInfoExW followed by VerQueryValueW with appropriate query string like \StringFileInfo\<4_digit_hex_lang_id><4_digit_hex_code_page_id>\ProductName. In this example I'm trying to get info from neutral / fallback resource using hardcoded IDs, but available IDs for different localizations can be retrieved by querying \VarFileInfo\Translation.

#include <sdkddkver.h>
#include <Windows.h>

#include <memory>
#include <string>
#include <cstddef>

#define SZ_STRING_FILE_INFO_W L"StringFileInfo"
#define SZ_PRODUCT_NAME_W L"ProductName"
#define SZ_HEX_LANG_ID_EN_US_W L"0409"
#define SZ_HEX_CODE_PAGE_ID_UNICODE_W L"04B0"

int wmain()
{
    auto const psz_file_path{L"C:\\Windows\\notepad.exe"};
    [[maybe_unused]] DWORD dummy{};
    auto const required_buffer_size
    {
        ::GetFileVersionInfoSizeExW
        (
            FILE_VER_GET_NEUTRAL, psz_file_path, ::std::addressof(dummy)
        )
    };
    if(0 == required_buffer_size)
    {
        return ::GetLastError();
    }
    auto const p_buffer
    {
        ::std::make_unique<char[]>
        (
            static_cast<::std::size_t>(required_buffer_size)
        )
    };
    auto const get_version_info_result
    {
        ::GetFileVersionInfoExW
        (
            FILE_VER_GET_NEUTRAL
        ,   psz_file_path
        ,   DWORD{}
        ,   required_buffer_size
        ,   static_cast<void *>(p_buffer.get())
        )
    };
    if(FALSE == get_version_info_result)
    {
        return ::GetLastError();
    }
    LPVOID p_value{};
    UINT value_length{};
    auto const query_result
    {
        ::VerQueryValueW
        (
            static_cast<void *>(p_buffer.get())
        ,   L"\\" SZ_STRING_FILE_INFO_W
            L"\\" SZ_HEX_LANG_ID_EN_US_W SZ_HEX_CODE_PAGE_ID_UNICODE_W
            L"\\" SZ_PRODUCT_NAME_W
        ,   ::std::addressof(p_value)
        ,   ::std::addressof(value_length)
        )
    };
    if
    (
        (FALSE == query_result)
        or
        (nullptr == p_value)
        or
        ((required_buffer_size / sizeof(wchar_t)) < value_length)
    )
    {
        return ::GetLastError();
    }
    ::std::wstring const product_name
    {
        static_cast<wchar_t const *>(p_value)
    ,   static_cast<::std::size_t>(value_length)
    };
    // product_name should contain "Microsoft® Windows® Operating System"
    return 0;
}


问:
How to select a selectbox an option value with JS?
This may sound easy but I'm been having a heck of a time to get this to work. Somebody please help. My select box is like below. How do i select the value 3 from the list?

```<code>        if(!empty($listeDoc))
        {
            $iGroups = 0;
            while($iGroups < count($listeDoc))
            {
            ?>
            <tr>
                <td>
                    <input type="checkbox" name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['product_id']" id="productSelectCreation_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" onchange="setValueToOne(this)"  ><?php echo $listeDoc[$iGroups]->DOC_CLIENT_NOM; ?>
                </td>

                <td>
                    <select name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['quantity']" id="productQty_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" class="form-control1" value="<?php echo $qty; ?>" style="width:100%; height:25px; border : #62270c solid 1px;" tabindex="1">
                        <option value=""/></option>
                        <option value="1"<?php if ($qty == 1) echo 'selected="selected"'; ?>>1</option>
                        <option value="2"<?php if ($qty == 2) echo 'selected="selected"'; ?>>2</option>
                        <option value="3"<?php if ($qty == 3) echo 'selected="selected"'; ?>>3</option>
                        <option value="4"<?php if ($qty == 4) echo 'selected="selected"'; ?>>4</option>
                        <option value="5"<?php if ($qty == 5) echo 'selected="selected"'; ?>>5</option>
                    </select>
                <td>
            </tr>

            <?php
            $iGroups++;
            }
        }
</code>```

here's is what i tried:

function setValueToOne(value)
{
    checkbox = document.getElementById('productSelectCreation');

```<code>if (checkbox.checked == true)
{
    document.getElementById("productQtyCreation").value = 1;
}
else
    document.getElementById("productQtyCreation").value = '0';
</code>```

}

答:
It seems you are looking something like this.

function setValueToOne(chkbox)
{
   if (chkbox.checked) {
      alert("checked");
      alert(chkbox.value);
      document.getElementById("productQtyCreation").value = chkbox.value;
    } else {

      alert("Unchecked");
      document.getElementById("productQtyCreation").value = 0
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="productSelect" id="productQtyCreation" class="form-control1">
    <option value=""/></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

<input type="checkbox" name="productSelect" id="productSelectCreation" onClick="setValueToOne(this)" value="3" />Test</code>```

Body:
This may sound easy but I'm been having a heck of a time to get this to work. Somebody please help. My select box is like below. How do i select the value 3 from the list?

        if(!empty($listeDoc))
        {
            $iGroups = 0;
            while($iGroups < count($listeDoc))
            {
            ?>

                    <input type="checkbox" name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['product_id']" id="productSelectCreation_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" onchange="setValueToOne(this)"  ><?php echo $listeDoc[$iGroups]->DOC_CLIENT_NOM; ?>

                    <select name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['quantity']" id="productQty_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" class="form-control1" value="<?php echo $qty; ?>" style="width:100%; height:25px; border : #62270c solid 1px;" tabindex="1">
                        <option value=""/></option>
                        <option value="1"<?php if ($qty == 1) echo 'selected="selected"'; ?>>1</option>
                        <option value="2"<?php if ($qty == 2) echo 'selected="selected"'; ?>>2</option>
                        <option value="3"<?php if ($qty == 3) echo 'selected="selected"'; ?>>3</option>
                        <option value="4"<?php if ($qty == 4) echo 'selected="selected"'; ?>>4</option>
                        <option value="5"<?php if ($qty == 5) echo 'selected="selected"'; ?>>5</option>
                    </select>

            <?php
            $iGroups++;
            }
        }

here's is what i tried:

function setValueToOne(value)
{
    checkbox = document.getElementById('productSelectCreation');

if (checkbox.checked == true)
{
    document.getElementById("productQtyCreation").value = 1;
}
else
    document.getElementById("productQtyCreation").value = '0';

}

Body:
It seems you are looking something like this.

function setValueToOne(chkbox)
{
   if (chkbox.checked) {
      alert("checked");
      alert(chkbox.value);
      document.getElementById("productQtyCreation").value = chkbox.value;
    } else {

      alert("Unchecked");
      document.getElementById("productQtyCreation").value = 0
    }
}

<select name="productSelect" id="productQtyCreation" class="form-control1">
    <option value=""/></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

<input type="checkbox" name="productSelect" id="productSelectCreation" onClick="setValueToOne(this)" value="3" />Test


问:
How to get window (like dialog, popupmenu...)
I'm working on library and it should find out if non-activity window (e.g. dialog, popupmenu....) is on the screen. I tried this...

```<code>((Activity)context).getWindow()
</code>```

but it always return main activity window, not what I want.

Is there any way to get Window on the screen or activated?

答:
You must specify activity you want instead of (Activity).

Like this;

```<code>((Activity)context).getWindow()
</code>```

to

```<code>((YouWantActivity)context).getWindow()
</code>```

maybe 'context' can be change (to: 'this ' or stg.)

Body:
I'm working on library and it should find out if non-activity window (e.g. dialog, popupmenu....) is on the screen. I tried this...

((Activity)context).getWindow()

but it always return main activity window, not what I want.

Is there any way to get Window on the screen or activated?

Body:
You must specify activity you want instead of (Activity).

Like this;

((Activity)context).getWindow()

to

((YouWantActivity)context).getWindow()

maybe 'context' can be change (to: 'this ' or stg.)


问:
Get identical elements and index from 2 Arrays in Perl
I am new in Perl and I am trying to solve the following comparison.

I have two arrays:

@A = ("Red", "Green", "Yellow");

@B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");

In array A, each element occurs only once.

In array B, each element can occur zero, one or many times.

For every element in A, the code should lists the position at which it is present in B and give the output as following:

> Red at index 3.

> Green is missing.

> Yellow at index 0, 2 and 5.

> Elements from B were detected 4 times in A.

I tried the following but I cannot figure out how to list indexes of elements after comparing two arrays

```<code>foreach $x (@A){
    foreach $y (@B){
    if ($y eq $x){
    print "$y\n";
    }
    elsif ($x ne$y){
    print "$x";
    }
  }
}
</code>```

Can someone please, help me? Thank you very much in advance!
Rebi

答:
Here's a somewhat simple way. A count and a switch variable keeps track of whether an item is found or missing: </p>

```<code>my @a = ("Red", "Green", "Yellow");
my @b = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my $count = 0;
for my $ael (0 .. $#a) {
 my $switch = "off";
 for my $bel (00 .. $#b) {
  if ($a[$ael] eq $b[$bel]) {
  $count++;
  $switch = "on";
print "$b[$bel] found at index $bel\n";
                            }
                         }
print "$a[$ael] is missing\n" if $switch eq "off";
                        }
print "Elements from B found $count times in A";
</code>```

<p>Outputs: </p>

```<code>Red found at index 3
Green is missing
Yellow found at index 0
Yellow found at index 2
Yellow found at index 5
Elements from B found 4 times in A
</code>```

Body:
I am new in Perl and I am trying to solve the following comparison.

I have two arrays:

@A = ("Red", "Green", "Yellow");

@B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");

In array A, each element occurs only once.

In array B, each element can occur zero, one or many times.

For every element in A, the code should lists the position at which it is present in B and give the output as following:

> Red at index 3.

> Green is missing.

> Yellow at index 0, 2 and 5.

> Elements from B were detected 4 times in A.

I tried the following but I cannot figure out how to list indexes of elements after comparing two arrays

foreach $x (@A){
    foreach $y (@B){
    if ($y eq $x){
    print "$y\n";
    }
    elsif ($x ne$y){
    print "$x";
    }
  }
}

Can someone please, help me? Thank you very much in advance!
Rebi

Body:
Here's a somewhat simple way. A count and a switch variable keeps track of whether an item is found or missing:

my @a = ("Red", "Green", "Yellow");
my @b = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my $count = 0;
for my $ael (0 .. $#a) {
 my $switch = "off";
 for my $bel (00 .. $#b) {
  if ($a[$ael] eq $b[$bel]) {
  $count++;
  $switch = "on";
print "$b[$bel] found at index $bel\n";
                            }
                         }
print "$a[$ael] is missing\n" if $switch eq "off";
                        }
print "Elements from B found $count times in A";

Outputs:

Red found at index 3
Green is missing
Yellow found at index 0
Yellow found at index 2
Yellow found at index 5
Elements from B found 4 times in A


问:
Add folder to all URLs in an ASP.net MVC 5 site
I have an MVC 5 site with this structure:

```<code>example.com
example.com/area1 (index for whole section)
example.com/area2/item5 (specific item for section)
</code>```

For SEO reasons I'd like to change every URL to this:

```<code>example.com/keyword (redirected from example.com)
example.com/keyword/area1
example.com/keyword/area2/item5
</code>```

The keyword is fixed and always the same, though at some point in the future there may be a site with the same structure but different content with a different keyword in. That is probably at least a few months off though.

What is the quickest / easiest way to implement the above. Being able to get the name of keyword would be an advantage later though isn't essential right now.

I could use attribute routing, though I'd have to update A LOT of ActionMethods to do this - and most currently don't even use attribute routing.

thx.

Update

I've tried adding the below to RouteConfig.cs, but none of the Url's work for some reason:

```<code>routes.MapRoute(
    name: "Default",
    url: "keyword/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

答:
```<code>public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    string  keyword = "keyword";
    // keyword route - it will be used as a route of the first priority
    routes.MapRoute(
        name: "Defaultkeyword",
        url: "{keyword}/{controller}/{action}/{id}",
        defaults: new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional,
            keyword = keyword
        });

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
</code>```

<p>also you need to add this Defaultkeyword route with few changes into your Area1AreaRegistration.cs file </p>

```<code>public override void RegisterArea(AreaRegistrationContext context)
 {
     context.MapRoute(
            "Area1_defaultKeyword",
            "{Keyword}/Area1/{controller}/{action}/{id}",
            new { Keyword = "Keyword", controller = "HomeArea1", action = "Index", id = UrlParameter.Optional }
            );

 context.MapRoute(
            "Area1_default",
            "Area1/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
           );
 }
</code>```

Body:
I have an MVC 5 site with this structure:

example.com
example.com/area1 (index for whole section)
example.com/area2/item5 (specific item for section)

For SEO reasons I'd like to change every URL to this:

example.com/keyword (redirected from example.com)
example.com/keyword/area1
example.com/keyword/area2/item5

The keyword is fixed and always the same, though at some point in the future there may be a site with the same structure but different content with a different keyword in. That is probably at least a few months off though.

What is the quickest / easiest way to implement the above. Being able to get the name of keyword would be an advantage later though isn't essential right now.

I could use attribute routing, though I'd have to update A LOT of ActionMethods to do this - and most currently don't even use attribute routing.

thx.

Update

I've tried adding the below to RouteConfig.cs, but none of the Url's work for some reason:

routes.MapRoute(
    name: "Default",
    url: "keyword/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Body:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    string  keyword = "keyword";
    // keyword route - it will be used as a route of the first priority
    routes.MapRoute(
        name: "Defaultkeyword",
        url: "{keyword}/{controller}/{action}/{id}",
        defaults: new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional,
            keyword = keyword
        });

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

also you need to add this Defaultkeyword route with few changes into your Area1AreaRegistration.cs file

public override void RegisterArea(AreaRegistrationContext context)
 {
     context.MapRoute(
            "Area1_defaultKeyword",
            "{Keyword}/Area1/{controller}/{action}/{id}",
            new { Keyword = "Keyword", controller = "HomeArea1", action = "Index", id = UrlParameter.Optional }
            );

 context.MapRoute(
            "Area1_default",
            "Area1/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
           );
 }