问:
Updating state within setTimeout (React & React-Native)
What I've been trying to achieve are to update state and to update the same state again, based on Javascript's timer.

The reason why I can't achieve this seems to be the nature of state in React.js.

Here is a snippet of my experimentation...

```<code>render() {
    if (this.props.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
    return (
      <View>
        <Blah warning={this.state.showWarning} />
      </View>
    );
}
</code>```

So, the objective is to change state for only just a few seconds if there is a specific props provided.

This approach seems to hit the limit of updating states, if this.props.hasError gets updated too frequently.

Apologies if this question is too basic.
Any suggestion will be appreciated.

答:
You shouldn't update your state in render() function. If you do so, you will end up in an infinite loop, that's why you got that error. You need to use: </p>

```<code>componentWillReceiveProps(nextProps){
    if (this.nextProps.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
}
</code>```

<p>This should resolve your issue. </p>

Body:
What I've been trying to achieve are to update state and to update the same state again, based on Javascript's timer.

The reason why I can't achieve this seems to be the nature of state in React.js.

Here is a snippet of my experimentation...

render() {
    if (this.props.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
    return (
      <View>
        <Blah warning={this.state.showWarning} />
      </View>
    );
}

So, the objective is to change state for only just a few seconds if there is a specific props provided.

This approach seems to hit the limit of updating states, if this.props.hasError gets updated too frequently.

Apologies if this question is too basic.
Any suggestion will be appreciated.

Body:
You shouldn't update your state in render() function. If you do so, you will end up in an infinite loop, that's why you got that error. You need to use:

componentWillReceiveProps(nextProps){
    if (this.nextProps.hasError) {
        setTimeout(function(){this.setState({showWarning: true}); }.bind(this), 3000);
    }
}

This should resolve your issue.


来源: stackexchange

问:
How to find object value from property path in Javascript object
I explain the problem with sample.

For example i have javascript object. It looks like:

```<code>var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }
</code>```

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

```<code>path = ["points",0,"x"]
or
path= ["obj","name"]
</code>```

So my question is that how to generate json object from these path.

For example i have to generate that

```<code>trial.points[0].x        or    trial.obj.name
</code>```

How to do that ?  thank you for your answer.

答:
You can do like this:

var trial= { points:[{x:1,y:2}, {x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"}};
var path = ["points", 0, "x"];

var object = trial;
path.map(field => object = object[field]);

console.log(object);

path = ["obj", "name"];

var object = trial;
path.map(field => object = object[field]);
console.log(object);```

ContentLicense: CC BY-SA 3.0

Body:
I explain the problem with sample.

For example i have javascript object. It looks like:

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

path = ["points",0,"x"]
or
path= ["obj","name"]

So my question is that how to generate json object from these path.

For example i have to generate that

trial.points[0].x        or    trial.obj.name

How to do that ?  thank you for your answer.


问:
How to stop creating files at a specific number?
I want to create 900 files with 3 letter names.

Example: xyz.txt, where x, y, and z are different letters from a to z.

I'm trying to do something like this:

```<code>for ((i=1; i < 900; i++))
      do touch {a..z}{a..z}{a..z}$i.txt
done
</code>```

I expect it to stop at 900.

But in the end I'm creating over 10K of files. Can someone please help me accomplish this?

答:
The following generates 910 names, and discards the last 10 before passing them to touch.

```<code>printf '%s.txt\n' {a..m}{p..v}{0..9} | head -n 900 | xargs touch
</code>```

You might be able to find a combination which generates exactly 900 alternatives so you can just touch <pattern> and have the shell expand it to the required number of unique names.

Body:
I want to create 900 files with 3 letter names.

Example: xyz.txt, where x, y, and z are different letters from a to z.

I'm trying to do something like this:

for ((i=1; i < 900; i++))
      do touch {a..z}{a..z}{a..z}$i.txt
done

I expect it to stop at 900.

But in the end I'm creating over 10K of files. Can someone please help me accomplish this?

Body:
The following generates 910 names, and discards the last 10 before passing them to touch.

printf '%s.txt\n' {a..m}{p..v}{0..9} | head -n 900 | xargs touch

You might be able to find a combination which generates exactly 900 alternatives so you can just touch <pattern> and have the shell expand it to the required number of unique names.


问:
Ruby Selenium - find_elements if nil => Net::ReadTimeout
Hi I got Net::ReadTimeout every time I use find_elements when there are no elements like this. A short example my Feature-file: (cucamber)

```<code>Feature: Retest Faild Testcases
Scenario: Simpel test find_elements
    Given open website humblebundle.com
    And search for civilization
</code>```

my ruby step-file:

```<code>Given /^open website (.*)$/ do |url|
  $driver.navigate.to "http://www."+url
  $wait = Selenium::WebDriver::Wait.new(:timeout => 180)
  $wait.until {
    $driver.find_element(:css => "div[class='navbar-content']").displayed?
  }
end

And /^search for (.*)$/ do |name|
  element=$driver.find_element(:css => "input[placeholder='Search']")
  element.send_keys name
  sleep(1)
  element.send_keys :enter
  sleep(10)
#line199  items=$driver.find_elements(:id => "Games")
  puts items.count
end
</code>```

and the error I get:

Net::ReadTimeout: Net::ReadTimeout
  ./features/step_definitions/basic_steps.rb:199:in /^search for (.*)$/'
  ./features/a_test.feature:4:inAnd search for civilization'

I would be very thankful for any help with this.

答:
Thanks, that was it.
I change the implicit wait 2 secends lesser than my ReadTimeout.</p>

Body:
Hi I got Net::ReadTimeout every time I use find_elements when there are no elements like this. A short example my Feature-file: (cucamber)

Feature: Retest Faild Testcases
Scenario: Simpel test find_elements
    Given open website humblebundle.com
    And search for civilization

my ruby step-file:

Given /^open website (.*)$/ do |url|
  $driver.navigate.to "http://www."+url
  $wait = Selenium::WebDriver::Wait.new(:timeout => 180)
  $wait.until {
    $driver.find_element(:css => "div[class='navbar-content']").displayed?
  }
end

And /^search for (.*)$/ do |name|
  element=$driver.find_element(:css => "input[placeholder='Search']")
  element.send_keys name
  sleep(1)
  element.send_keys :enter
  sleep(10)
#line199  items=$driver.find_elements(:id => "Games")
  puts items.count
end

and the error I get:

Net::ReadTimeout: Net::ReadTimeout
  ./features/step_definitions/basic_steps.rb:199:in /^search for (.*)$/'
  ./features/a_test.feature:4:inAnd search for civilization'

I would be very thankful for any help with this.


问:
App installation data (from google play and apple store)
As part of a project in my workplace -
I'm searching the web for a way to get the daily installations per device
(note that the data from google analytics is irrelevant for us as they give back the
amount of installations and not installations per device -
in case a user installs, removes and installs the app again they regard it as 2 installations while google play developer console display this as 1 installation).

So far I found out that the google play developer console contains the data we need,
but the only way I could get that data is by manually downloading a csv file and parsing it.

This is not good enough for us as we MUST automate the download process and get that data without any human.

I'll note that we are using .net technology and from what I've red we can't get that data with the
beta API library which google supplies for the google play developer console.

P.S. we have to do the same with the apple app store

P.S. 2 we can't use a 3rd party code/service

Any help would be greatly appreciated.

答:
I think it's too late now, but maybe it can help someone else.

Google Play Store:

First of all, you need GCP account
"Reports are available from Google Cloud Storage. Reports are generated daily and accumulated in monthly CSV files. They are stored in a private Google Cloud Storage bucket for your Google Play Developer account."

Second point, you need bucket ID
"Find your reporting bucket ID on one of your Download reports pages, near the bottom of the page.
Your bucket ID begins with: pubsite_prod_rev (Example: pubsite_prod_rev_01234567890987654321)."

and you can follow the steps below

Step 1: Create a service account
Sign in to the Google Developers Console (console.developers.google.com).
If you already have a project, use the drop-down to select a project. If you don't have a project listed or want to create a new one, click Create project.
Select the Menu icon Menu icon > Permissions > Service accounts > Create service account.
Follow the on-screen instructions and select Create.
Copy the email address listed.
Example: accountName@project.iam.gserviceaccount.com

Step 2: Add the service account on your Play Console
Sign in to your Play Console.
Select Settings Settings > User accounts & rights > Invite new user.
Paste or type the email address associated with your service account.
Based on the types of reports needed, select permissions.
For example, if you need access to financial reports, select “View financial reports.”
Click Add user. Your service account will be added to your account.

Step 3: Fetch reports using an API call
Install the API client library for your preferred code language.
Configure the code performing the API call to use OAuth2 server-to-server authentication and to request permission to the OAuth2 scope (https://www.googleapis.com/auth/devstorage.read_only).
Issue authenticated API calls to fetch reports.

To learn more, follow link: https://developers.google.com/api-client-library/

More information here: https://support.google.com/googleplay/android-developer/answer/6135870


问:
pgadmin4 : postgresql application server could not be contacted.
I have installed PostgreSQL 9.6.2 on my Windows 8.1. But the pgadmin4 is not able to contact the local server. I have tried several solutions suggested here in stackoverflow, tried to uninstall and reinstall PostgreSQL 9.6.2 , tried to modify the config.py, config_distro.py, and delete the files in Roaming folder,i tried standalone pgadmin4 installation, but no success.However, in my local machine i am able to access the server using psql.exe and log as as superuser (postgres user). Can you please suggest any possible solutions to starting/running pgadmin4 ? Thank you.</p>

答: I had the same issue on the macosx and I renamed .pgadmin (in /users/costa) to .pgadminx and I was able to start pgAdmin4.


问:
Blend alpha color using bitwise operations
I have code below to blend alpha color in ARGB format:

a, b, o are integers, but should always fall in [0x00ffffff,0xffffffff]

o = ( ( ( a >> 24 ) * ( b >> 24 ) ) >> 8 ) << 24;

Is there anyway to optimize it?

Thanks!

答:
That doesn't perform the alpha blending.  That just combines the alpha component of two pixels.  It's also probably about as efficient as you're going to get without going directly to assembly.  If you can use pointers, you might get a little faster, though:

byte* pa = (byte*)&a;
byte* pb = (byte*)&b;
byte* po = (byte*)&o;

po[3] = pa[3] * pb[3] >> 8;
```

<p>This saves most of the shifting.  Note that this assumes a little-endian machine.  If you're running on a big-endian processor, it becomes even better with:</p>

<pre class="lang-cs prettyprint-override"><code>*po = *pa * *pb >> 8;
</code>```

In either case, you can turn this into a one-liner by doing all the pointer casting inline, but it gets a bit hard to read.

((byte*)&o)[3] = ((byte*)&a)[3] * ((byte*)&b)[3] >> 8;
```

<p>or</p>

<pre class="lang-cs prettyprint-override"><code>*((byte*)&o) = *((byte*)&a) * *((byte*)&b) >> 8;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
That doesn't perform the alpha blending.  That just combines the alpha component of two pixels.  It's also probably about as efficient as you're going to get without going directly to assembly.  If you can use pointers, you might get a little faster, though:

byte* pa = (byte*)&a;
byte* pb = (byte*)&b;
byte* po = (byte*)&o;

po[3] = pa[3] * pb[3] >> 8;

This saves most of the shifting.  Note that this assumes a little-endian machine.  If you're running on a big-endian processor, it becomes even better with:

*po = *pa * *pb >> 8;

In either case, you can turn this into a one-liner by doing all the pointer casting inline, but it gets a bit hard to read.

((byte*)&o)[3] = ((byte*)&a)[3] * ((byte*)&b)[3] >> 8;

or

*((byte*)&o) = *((byte*)&a) * *((byte*)&b) >> 8;


问:
How to check whether a value exists among a set of values in a record in mysql
I am using MySQL in such a way that the user enters a date and flights appear on that day.I was too lazy to put many dates so what I did was made certain flights run on certain days.

The table planes contains many columns out of which dtd(column containing many days of type varchar(50)) .

One record(in dtd) is Monday, Tuesday
The user enters the date 2018-12-03 which is a Monday.

My problem is how do I extract only the record which has Monday?(like the monday,Tuesday one)??

I tried select.....where instr(day(2018-12-03),dtd)<>0 but I realised that instr gives 0 in 2 cases
1. the character(s) is not present in the record or
2.occurence is at the beginning.

Like instr(h,hello) and instr(a,hello) gives 0.

Please help

答:
I suggest that you use the LIKE operator.

For more info about it please check this link: SQL Like Operator

To solve your problem, you can try the following:

```<code>SELECT ...
  WHERE dtd LIKE CONCAT('%', day(2018-12-03), '%');
</code>```

In this case, you will get all the rows of the table, where the value of the field dtd contains the value of day(2018-12-03).

Hope this helps!

Body:
I suggest that you use the LIKE operator.

For more info about it please check this link: SQL Like Operator

To solve your problem, you can try the following:

SELECT ...
  WHERE dtd LIKE CONCAT('%', day(2018-12-03), '%');

In this case, you will get all the rows of the table, where the value of the field dtd contains the value of day(2018-12-03).

Hope this helps!


问:
Why is PtrToStringUni returning some incorrect characters
I'm trying to use advapi32.dll via pinvoke in my C# application to get the path to an executable used by a service. I'm specifying Unicode and getting parts of what appear to be a path, but some of the characters are clearly getting garbaled in the translation.

```<code>private static string GetServicePath(IntPtr service)
{
    SERVICE_CONFIG status = new SERVICE_CONFIG();

    uint bytesNeeded = 1;
    var queryResult = QueryServiceConfig(service, status, 0, out bytesNeeded);
    if (queryResult == 0 && bytesNeeded == 0)
    {
        throw new ApplicationException("Failed to query service config.");
    }
    else
    {
        QueryServiceConfig(service, status, bytesNeeded, out bytesNeeded);
    }

    var servicePath = Marshal.PtrToStringUni(status.lpBinaryPathName);
    return servicePath;
}
</code>```

^ Method being called to get Service name using a handle to the service

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private class SERVICE_CONFIG
{
    public int dwServiceType;
    public ServiceStartType dwStartType;
    public int dwErrorControl;
    public IntPtr lpBinaryPathName;
    public IntPtr lpLoadOrderGroup;
    public int dwTagID;
    public IntPtr lpDependencies;
    public IntPtr lpServiceStartName;
    public IntPtr lpDisplayName;
};

[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
private static extern int QueryServiceConfig(IntPtr hService, SERVICE_CONFIG queryConfig, UInt32 cbBufSize, out UInt32 pcbBytesNeeded);
</code>```

^ Relevant PInvoke Method and Structure

So for example, I would expect asking the for "Bonjour Service" path to return

"C:\Program Files\Bonjour\mDNSResponder.exe"

instead I get this on Windows 10

"C:\??? , m Files\Bonjour\mDNSResponder.exe"

and this on Windows 8

"C:\??? , "C:\??? , "C:\??? , "C:\??? , "C:\

and just this on XP

"C??

If I try to convert any of the other properties like Display Name or Start Name then I get a legitimate string. Why isn't the executable path resolving the way the other strings do?

答:
This happens because you're supposed to allocate a buffer, not pass a fixed buffer size. All the strings pointer in QUERY_SERVICE_CONFIG will be contained in that buffer.

QueryServiceConfig will tell you how big the buffer must be. A native example is available here: Querying a Service's Configuration

So, I have modified your code accordingly:

```<code>    private static string GetServicePath(IntPtr service)
    {
        QueryServiceConfig(service, IntPtr.Zero, 0, out int size);
        if (size == 0)
            throw new Win32Exception(Marshal.GetLastWin32Error());

        var ptr = Marshal.AllocHGlobal(size);
        try
        {
            if (!QueryServiceConfig(service, ptr, size, out size))
                throw new Win32Exception(Marshal.GetLastWin32Error());

            var config = Marshal.PtrToStructure<QUERY_SERVICE_CONFIG>(ptr);
            return config.lpBinaryPathName;
        }
        finally
        {
            Marshal.FreeHGlobal(ptr);
        }
    }

    // note that I use a struct, not a class, so I can call Marshal.PtrToStructure.
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct QUERY_SERVICE_CONFIG
    {
        public int dwServiceType;
        public int dwStartType;
        public int dwErrorControl;
        public string lpBinaryPathName;
        public string lpLoadOrderGroup;
        public int dwTagID;
        public string lpDependencies;
        public string lpServiceStartName;
        public string lpDisplayName;
    };

    // return type is a bool, no need for an int here
    // user SetLastError when the doc says so
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool QueryServiceConfig(IntPtr hService, IntPtr lpServiceConfig, int cbBufSize, out int pcbBytesNeeded);
</code>```

Body:
I'm trying to use advapi32.dll via pinvoke in my C# application to get the path to an executable used by a service. I'm specifying Unicode and getting parts of what appear to be a path, but some of the characters are clearly getting garbaled in the translation.

private static string GetServicePath(IntPtr service)
{
    SERVICE_CONFIG status = new SERVICE_CONFIG();

    uint bytesNeeded = 1;
    var queryResult = QueryServiceConfig(service, status, 0, out bytesNeeded);
    if (queryResult == 0 && bytesNeeded == 0)
    {
        throw new ApplicationException("Failed to query service config.");
    }
    else
    {
        QueryServiceConfig(service, status, bytesNeeded, out bytesNeeded);
    }

    var servicePath = Marshal.PtrToStringUni(status.lpBinaryPathName);
    return servicePath;
}

^ Method being called to get Service name using a handle to the service

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private class SERVICE_CONFIG
{
    public int dwServiceType;
    public ServiceStartType dwStartType;
    public int dwErrorControl;
    public IntPtr lpBinaryPathName;
    public IntPtr lpLoadOrderGroup;
    public int dwTagID;
    public IntPtr lpDependencies;
    public IntPtr lpServiceStartName;
    public IntPtr lpDisplayName;
};

[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
private static extern int QueryServiceConfig(IntPtr hService, SERVICE_CONFIG queryConfig, UInt32 cbBufSize, out UInt32 pcbBytesNeeded);

^ Relevant PInvoke Method and Structure

So for example, I would expect asking the for "Bonjour Service" path to return

"C:\Program Files\Bonjour\mDNSResponder.exe"

instead I get this on Windows 10

"C:\??? , m Files\Bonjour\mDNSResponder.exe"

and this on Windows 8

"C:\??? , "C:\??? , "C:\??? , "C:\??? , "C:\

and just this on XP

"C??

If I try to convert any of the other properties like Display Name or Start Name then I get a legitimate string. Why isn't the executable path resolving the way the other strings do?

Body:
This happens because you're supposed to allocate a buffer, not pass a fixed buffer size. All the strings pointer in QUERY_SERVICE_CONFIG will be contained in that buffer.

QueryServiceConfig will tell you how big the buffer must be. A native example is available here: Querying a Service's Configuration

So, I have modified your code accordingly:

    private static string GetServicePath(IntPtr service)
    {
        QueryServiceConfig(service, IntPtr.Zero, 0, out int size);
        if (size == 0)
            throw new Win32Exception(Marshal.GetLastWin32Error());

        var ptr = Marshal.AllocHGlobal(size);
        try
        {
            if (!QueryServiceConfig(service, ptr, size, out size))
                throw new Win32Exception(Marshal.GetLastWin32Error());

            var config = Marshal.PtrToStructure<QUERY_SERVICE_CONFIG>(ptr);
            return config.lpBinaryPathName;
        }
        finally
        {
            Marshal.FreeHGlobal(ptr);
        }
    }

    // note that I use a struct, not a class, so I can call Marshal.PtrToStructure.
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct QUERY_SERVICE_CONFIG
    {
        public int dwServiceType;
        public int dwStartType;
        public int dwErrorControl;
        public string lpBinaryPathName;
        public string lpLoadOrderGroup;
        public int dwTagID;
        public string lpDependencies;
        public string lpServiceStartName;
        public string lpDisplayName;
    };

    // return type is a bool, no need for an int here
    // user SetLastError when the doc says so
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern bool QueryServiceConfig(IntPtr hService, IntPtr lpServiceConfig, int cbBufSize, out int pcbBytesNeeded);


问:
How to insert a dataframe into a SQL Server table?
I'm trying to upload a dataframe to a SQL Server table, I tried breaking it down to a simple SQL query string..

```<code>library(RODBC)
con <- odbcDriverConnect("driver=SQL Server; server=database")

df <- data.frame(a=1:10, b=10:1, c=11:20)

values <- paste("(",df$a,",", df$b,",",df$c,")", sep="", collapse=",")

cmd <- paste("insert into MyTable values ", values)

result <- sqlQuery(con, cmd, as.is=TRUE)
</code>```

..which seems to work but does not scale very well. Is there an easier way?

答:
This worked for me and I found it to be simpler. </p>

```<code>library(sqldf)
library(odbc)
con <- dbConnect(odbc(),
                 Driver = "SQL Server",
                 Server = "ServerName",
                 Database = "DBName",
                 UID = "UserName",
                 PWD = "Password")
dbWriteTable(conn = con,
             name = "TableName",
             value = x)  ## x is any data frame
</code>```

Body:
I'm trying to upload a dataframe to a SQL Server table, I tried breaking it down to a simple SQL query string..

library(RODBC)
con <- odbcDriverConnect("driver=SQL Server; server=database")

df <- data.frame(a=1:10, b=10:1, c=11:20)

values <- paste("(",df$a,",", df$b,",",df$c,")", sep="", collapse=",")

cmd <- paste("insert into MyTable values ", values)

result <- sqlQuery(con, cmd, as.is=TRUE)

..which seems to work but does not scale very well. Is there an easier way?

Body:
This worked for me and I found it to be simpler.

library(sqldf)
library(odbc)
con <- dbConnect(odbc(),
                 Driver = "SQL Server",
                 Server = "ServerName",
                 Database = "DBName",
                 UID = "UserName",
                 PWD = "Password")
dbWriteTable(conn = con,
             name = "TableName",
             value = x)  ## x is any data frame


问:
Explicit constructors and nested initializer lists
The following code successfully compiles with most modern C++11 compatible compilers (GCC >= 5.x, Clang, ICC, MSVC).

```<code>#include <string>

struct A
{
        explicit A(const char *) {}
        A(std::string) {}
};

struct B
{
        B(A) {}
        B(B &) = delete;
};

int main( void )
{
        B b1({{{"test"}}});
}
</code>```

But why does it compile in the first place, and how are the listed compilers interpreting that code?

Why is MSVC able to compile this without B(B &) = delete;, but the other 3 compilers all need it?

And why does it fail in all compilers except MSVC when I delete a different signature of the copy constructor, e.g. B(const B &) = delete;?

Are the compilers even all choosing the same constructors?

Why does Clang emit the following warning?

```<code>17 : <source>:17:16: warning: braces around scalar initializer [-Wbraced-scalar-init]
        B b1({{{"test"}}});
</code>```

答:
Instead of explaining the behavior of compilers, I'll try to explain what the standard says.

Primary Example

To direct-initialize b1 from {{{"test"}}}, overload resolution applies to choose the best constructor of B. Because there is no implicit conversion from {{{"test"}}} to B& (list initializer is not a lvalue), the constructor B(B&) is not viable. We then focus on the constructor B(A), and check whether it is viable.

To determine the implicit conversion sequence from {{{"test"}}} to A (I will use the notation {{{"test"}}} -> A for simplicity), overload resolution applies to choose the best constructor of A, so we need to compare {{"test"}} -> const char* and {{"test"}} -> std::string (note the outermost layer of braces is elided) according to [over.match.list]/1:

When objects of non-aggregate class type T are list-initialized such that [dcl.init.list] specifies that overload resolution is performed according to the rules in this subclause, overload resolution selects the constructor in two phases:

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T...

If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all the constructors of the class T and the argument list consists of the elements of the initializer list.

... In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed.

Note all constructors are considered here regardless of the specifier explicit.

{{"test"}} -> const char* does not exist according to [over.ics.list]/10 and [over.ics.list]/11:

Otherwise, if the parameter type is not a class:

if the initializer list has one element that is not itself an initializer list...

if the initializer list has no elements...

In all cases other than those enumerated above, no conversion is possible.

To determine {{"test"}} -> std::string, the same process is taken, and overload resolution chooses the constructor of std::string that takes a parameter of type const char*.

As a result, {{{"test"}}} -> A is done by choosing the constructor A(std::string).

Variations

What if explicit is removed?

The process does not change. GCC will choose the constructor A(const char*) while Clang will choose the constructor A(std::string). I think it is a bug for GCC.

What if there are only two layers of braces in the initializer of b1?

Note {{"test"}} -> const char* does not exist but {"test"} -> const char* exists. So if there are only two layers of braces in the initializer of b1, the constructor A(const char*) is chosen because {"test"} -> const char* is better than {"test"} -> std::string. As a result, an explicit constructor is chosen in copy-list-initialization (initialization of the parameter A in the constructor B(A) from {"test"}), then the program is ill-formed.

What if the constructor B(const B&) is declared?

Note this also happens if the declaration of B(B&) is removed. This time we need to compare {{{"test"}}} -> A and {{{"test"}}} -> const B&, or {{{"test"}}} -> const B equivalently.

To determine {{{"test"}}} -> const B, the process described above is taken. We need to compare {{"test"}} -> A and {{"test"}} -> const B&. Note {{"test"}} -> const B& does not exist according to [over.best.ics]/4:

However, if the target is

— the first parameter of a constructor or

— the implicit object parameter of a user-defined conversion function

and the constructor or user-defined conversion function is a candidate by

— [over.match.ctor], when the argument is the temporary in the second step of a class copy-initialization,

—  [over.match.copy], [over.match.conv], or  [over.match.ref] (in all cases), or

— the second phase of [over.match.list] when the initializer list has exactly one element that is itself an initializer list, and the target is the first parameter of a constructor of class X, and the conversion is to X or
  reference to cv X,

user-defined conversion sequences are not considered.

To determine {{"test"}} -> A, the process described above is taken again. This is almost the same as the case we talked in the previous subsection. As a result, the constructor A(const char*) is chosen. Note the constructor is chosen here to determine {{{"test"}}} -> const B, and does not apply actually. This is permitted though the constructor is explicit.

As a result, {{{"test"}}} -> const B is done by choosing the constructor B(A), then the constructor A(const char*). Now both {{{"test"}}} -> A and {{{"test"}}} -> const B are user-defined conversion sequences and neither is better than the other, so the initialization of b1 is ambiguous.

What if the parentheses is replaced by braces?

According to [over.best.ics]/4, which is block-quoted in the previous subsection, the user defined conversion {{{"test"}}} -> const B& is not considered. So the result is the same as the primary example even if the constructor B(const B&) is declared.

Body:
The following code successfully compiles with most modern C++11 compatible compilers (GCC >= 5.x, Clang, ICC, MSVC).

#include <string>

struct A
{
        explicit A(const char *) {}
        A(std::string) {}
};

struct B
{
        B(A) {}
        B(B &) = delete;
};

int main( void )
{
        B b1({{{"test"}}});
}

But why does it compile in the first place, and how are the listed compilers interpreting that code?

Why is MSVC able to compile this without B(B &) = delete;, but the other 3 compilers all need it?

And why does it fail in all compilers except MSVC when I delete a different signature of the copy constructor, e.g. B(const B &) = delete;?

Are the compilers even all choosing the same constructors?

Why does Clang emit the following warning?

17 : <source>:17:16: warning: braces around scalar initializer [-Wbraced-scalar-init]
        B b1({{{"test"}}});


问:
Convert Legacy SQL Outer JOIN *=, =* to ANSI
I need to convert a legacy SQL outer Join to ANSI.

The reason for that being, we're upgrading from a legacy DB instance (2000/5 ?) to SQL 2016.

Legacy SQL query :-

SELECT

--My Data to Select--

```<code> FROM counterparty_alias ca1,
  counterparty_alias ca2,
  counterparty cp,
  party p
 WHERE cp.code *= ca1.counterparty_code AND
  ca1.alias = 'Party1' AND
  cp.code *= ca2.counterparty_code AND
  ca2.alias = 'Party2' AND
  cp.code *= p.child_code AND
  cp.category in ('CAT1','CAT2')
</code>```

Here, Party1 and Party2 Are the party type codes and CAT1 and CAT2 are the category codes. They're just data; I have abstracted it, because the values don't really matter.

Now, when I try to replace the *= with a LEFT OUTER JOIN, I get a huge mismatch on the Data, both in terms of the number of rows, as well as the Data itself.

The query I'm using is this  :

What am I doing wrong ?

SELECT

--My Data to Select--

```<code> FROM
  counterparty cp
  LEFT OUTER JOIN counterparty_alias ca1 ON cp.code = ca1.counterparty_code
  LEFT OUTER JOIN counterparty_alias ca2 ON cp.code = ca2.counterparty_code
  LEFT OUTER JOIN party p  ON  cp.code = p.child_code
 WHERE
  ca1.alias = 'Party1' AND
  ca2.alias = 'Party2' AND
  cp.category in ('CAT1','CAT2')
</code>```

Clearly , in all the three legacy joins , the cp (counterparty) table is on the Left hand Side of the *=. So that should translate to a LEFT OUTER JOIN WITH all the three tables. However, my solution doesn't seem to to be working
How can I fix this ? What am I doing wrong here ?

Any help would be much appreciated.  Thanks in advance  :)

EDIT

I also have another query like this :

SELECT

--My Data to Select--

```<code>FROM dbo.deal d,
 dbo.deal_ccy_option dvco,
 dbo.deal_valuation dv,
 dbo.strike_modifier sm
WHERE d.deal_id = dvco.deal_id
AND d.deal_id = dv.deal_id
AND dvco.base + dvco.quoted *= sm.ccy_pair
AND d.maturity_date *= sm.expiry_date
</code>```

In this case, both the dvco and d tables seem to be doing a LEFT OUTER JOIN on the same table sm. How do I proceed about this ?
Maybe join in on the same table and use an alias sm1 and sm2 ?
Or should I use sm as the central table and change the join to RIGHT OUTER JOIN on dvco and d tables ?

答:
I think the problem with your translation is that you are using conditions on the right tables in the where clause instead of in the on clause.

When I tried to translate it, this is the translation I've got:

```<code>FROM counterparty cp
LEFT JOIN counterparty_alias ca1 ON cp.code = ca1.counterparty_code
                                AND ca1.alias = 'Party1'
LEFT JOIN counterparty_alias ca2 ON cp.code *= ca2.counterparty_code
                                AND ca2.alias = 'Party2'
LEFT JOIN party p ON cp.code = p.child_code
WHERE cp.category in ('CAT1','CAT2')
</code>```

However, it's hard to know if I'm correct since you didn't provide sample data, desired results, or even a complete query.

Body:
I need to convert a legacy SQL outer Join to ANSI.

The reason for that being, we're upgrading from a legacy DB instance (2000/5 ?) to SQL 2016.

Legacy SQL query :-

SELECT

--My Data to Select--

 FROM counterparty_alias ca1,
  counterparty_alias ca2,
  counterparty cp,
  party p
 WHERE cp.code *= ca1.counterparty_code AND
  ca1.alias = 'Party1' AND
  cp.code *= ca2.counterparty_code AND
  ca2.alias = 'Party2' AND
  cp.code *= p.child_code AND
  cp.category in ('CAT1','CAT2')

Here, Party1 and Party2 Are the party type codes and CAT1 and CAT2 are the category codes. They're just data; I have abstracted it, because the values don't really matter.

Now, when I try to replace the *= with a LEFT OUTER JOIN, I get a huge mismatch on the Data, both in terms of the number of rows, as well as the Data itself.

The query I'm using is this  :

What am I doing wrong ?

SELECT

--My Data to Select--

 FROM
  counterparty cp
  LEFT OUTER JOIN counterparty_alias ca1 ON cp.code = ca1.counterparty_code
  LEFT OUTER JOIN counterparty_alias ca2 ON cp.code = ca2.counterparty_code
  LEFT OUTER JOIN party p  ON  cp.code = p.child_code
 WHERE
  ca1.alias = 'Party1' AND
  ca2.alias = 'Party2' AND
  cp.category in ('CAT1','CAT2')

Clearly , in all the three legacy joins , the cp (counterparty) table is on the Left hand Side of the *=. So that should translate to a LEFT OUTER JOIN WITH all the three tables. However, my solution doesn't seem to to be working
How can I fix this ? What am I doing wrong here ?

Any help would be much appreciated.  Thanks in advance  :)

EDIT

I also have another query like this :

SELECT

--My Data to Select--

FROM dbo.deal d,
 dbo.deal_ccy_option dvco,
 dbo.deal_valuation dv,
 dbo.strike_modifier sm
WHERE d.deal_id = dvco.deal_id
AND d.deal_id = dv.deal_id
AND dvco.base + dvco.quoted *= sm.ccy_pair
AND d.maturity_date *= sm.expiry_date

In this case, both the dvco and d tables seem to be doing a LEFT OUTER JOIN on the same table sm. How do I proceed about this ?
Maybe join in on the same table and use an alias sm1 and sm2 ?
Or should I use sm as the central table and change the join to RIGHT OUTER JOIN on dvco and d tables ?

Body:
I think the problem with your translation is that you are using conditions on the right tables in the where clause instead of in the on clause.

When I tried to translate it, this is the translation I've got:

FROM counterparty cp
LEFT JOIN counterparty_alias ca1 ON cp.code = ca1.counterparty_code
                                AND ca1.alias = 'Party1'
LEFT JOIN counterparty_alias ca2 ON cp.code *= ca2.counterparty_code
                                AND ca2.alias = 'Party2'
LEFT JOIN party p ON cp.code = p.child_code
WHERE cp.category in ('CAT1','CAT2')

However, it's hard to know if I'm correct since you didn't provide sample data, desired results, or even a complete query.


问:
Evaluation order of function declarations
With the following code, which is neither ES6, nor is it in "strict mode", I had expected an outcome of 'b' because the second declaration of foo should overwrite the first one. But the outcome is 'a'!

```<code>{
  function foo() {
    console.log('a');
  }
}

function foo() {
  console.log('b');
}

foo(); // 'a' ? Why not 'b'?
</code>```

When this code is surrounded with additional curly braces, the outcome is the expected 'b'.

```<code>{ // additional curly braces

  {
    function foo() {
      console.log('a');
    }
  }

  function foo() {
    console.log('b');
  }

  foo(); // 'b' as expected!

} // end additional curly braces
</code>```

For further illustration, please consider the following additional example:

```<code>foo('before declaration'); // outcome:  from outside block :before declaration

{
  function foo(s) {
    console.log('from inside block: ' + s);
  }
}

function foo(s) {
  console.log('from outside block :' + s);
}

foo('after declaration'); // outcome:  from inside block: after declaration
</code>```

In my opinion the correct outcome should be:

```<code>// from outside block :before declaration
// from outside block :after declaration
</code>```

I'm unable to spot my misconception here.

If I again enclose the complete last example inside curly brackets like so:

```<code>{
  foo('before declaration'); // outcome:  from outside block :before declaration

  {
    function foo(s) {
      console.log('from inside block: ' + s);
    }
  }

  function foo(s) {
    console.log('from outside block :' + s);
  }

  foo('after declaration'); // outcome:  from outside block: after declaration
}
</code>```

I get the expected outcome.

答:
In your first declaration, you have enclosed foo() within {} , which changes the scope for the declaration, but the next declaration is the global scope. From w3schools JavaScript Hoisting,

Hoisting is JavaScript's default behavior of moving all declarations
  to the top of the current scope

So your second declaration is actually moved to top, and then the declaration inside the scope {} executes, which overrides the first declaration and prints a.

ContentLicense: CC BY-SA 4.0

Body:
With the following code, which is neither ES6, nor is it in "strict mode", I had expected an outcome of 'b' because the second declaration of foo should overwrite the first one. But the outcome is 'a'!

{
  function foo() {
    console.log('a');
  }
}

function foo() {
  console.log('b');
}

foo(); // 'a' ? Why not 'b'?

When this code is surrounded with additional curly braces, the outcome is the expected 'b'.

{ // additional curly braces

  {
    function foo() {
      console.log('a');
    }
  }

  function foo() {
    console.log('b');
  }

  foo(); // 'b' as expected!

} // end additional curly braces

For further illustration, please consider the following additional example:

foo('before declaration'); // outcome:  from outside block :before declaration

{
  function foo(s) {
    console.log('from inside block: ' + s);
  }
}

function foo(s) {
  console.log('from outside block :' + s);
}

foo('after declaration'); // outcome:  from inside block: after declaration

In my opinion the correct outcome should be:

// from outside block :before declaration
// from outside block :after declaration

I'm unable to spot my misconception here.

If I again enclose the complete last example inside curly brackets like so:

{
  foo('before declaration'); // outcome:  from outside block :before declaration

  {
    function foo(s) {
      console.log('from inside block: ' + s);
    }
  }

  function foo(s) {
    console.log('from outside block :' + s);
  }

  foo('after declaration'); // outcome:  from outside block: after declaration
}

I get the expected outcome.


问:
What happens if I add an unsigned int to a negative int and the arithmetic result is positive?
When I was about to execute the following code I thought the signed int i would be converted to unsigned and the result would be some big positive number but the result was 2  </p>

```<code>int main()
{
    unsigned u = 10; int i = -8;
    std::cout << u + i << std::endl;
    return 0;
}
</code>```

答:
When performing addition, the usual arithmetic conversions are performed on the operands, which state ([expr]/11.5.3):

Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand,
  the operand with signed integer type shall be converted to the type of
  the operand with unsigned integer type.

So -8 is converted to an unsigned number. Which according to [conv.integral]/2 is as follows:

If the destination type is unsigned, the resulting value is the least
  unsigned integer congruent to the source integer (modulo 2n
  where n is the number of bits used to represent the unsigned type).

That translates our number to (MAX_UINT + 1) - 8. Now, since unsigned addition is modular 2n ([basic.fundamental]/4):

Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

The result must be (MAX_UINT + 1) - 8 + 10 modulo MAX_UINT + 1, and that is just 2.

Body:
When I was about to execute the following code I thought the signed int i would be converted to unsigned and the result would be some big positive number but the result was 2

int main()
{
    unsigned u = 10; int i = -8;
    std::cout << u + i << std::endl;
    return 0;
}


问:
Oracle - Understanding the no_index hint
I'm trying to understand how no_index actually speeds up a query and haven't been able to find documentation online to explain it.

For example I have this query that ran extremely slow

```<code>select  *
    from    <tablename>
    where   field1_ like '%someGenericString%' and
            field1_ <> 'someSpecificString' and
            Action_='_someAction_' and
            Timestamp_ >= trunc(sysdate - 2)
</code>```

And one of our DBAs was able to speed it up significantly by doing this

```<code>select  /*+ NO_INDEX(TAB_000000000019) */ *
    from    <tablename>
    where   field1_ like '%someGenericString%' and
            field1_ <> 'someSpecificString' and
            Action_='_someAction_' and
            Timestamp_ >= trunc(sysdate - 2)
</code>```

And I can't figure out why?  I would like to figure out why this works so I can see if I can apply it to another query (this one a join) to speed it up because it's taking even longer to run.

Thanks!

** Update **
Here's what I know about the table in the example.

It's a 'partitioned table'

TAB_000000000019 is the table not a column in it

field1 is indexed

答:
To add to what Rene' and Dave have said, this is what I have actually observed in a production situation:

If the condition(s) on the indexed field returns too many matches, Oracle is better off doing a Full Table Scan.

We had a report program querying a very large indexed table - the index was on a region code and the query specified the exact region code, so Oracle CBO uses the index.

Unfortunately, one specific region code accounted for 90% of the tables entries.

As long as the report was run for one of the other (minor) region codes, it completed in less than 30 minutes, but for the major region code it took many hours.

Adding a hint to the SQL to force a full table scan solved the problem.

Hope this helps.

Body:
I'm trying to understand how no_index actually speeds up a query and haven't been able to find documentation online to explain it.

For example I have this query that ran extremely slow

select  *
    from    <tablename>
    where   field1_ like '%someGenericString%' and
            field1_ <> 'someSpecificString' and
            Action_='_someAction_' and
            Timestamp_ >= trunc(sysdate - 2)

And one of our DBAs was able to speed it up significantly by doing this

select  /*+ NO_INDEX(TAB_000000000019) */ *
    from    <tablename>
    where   field1_ like '%someGenericString%' and
            field1_ <> 'someSpecificString' and
            Action_='_someAction_' and
            Timestamp_ >= trunc(sysdate - 2)

And I can't figure out why?  I would like to figure out why this works so I can see if I can apply it to another query (this one a join) to speed it up because it's taking even longer to run.

Thanks!

** Update **
Here's what I know about the table in the example.

It's a 'partitioned table'

TAB_000000000019 is the table not a column in it

field1 is indexed


问:
Cannot insert explicit value for identity column while updating entity
I am using ASP.NET Boilerplate template.

I want to update Details table, which contains more than one item. If an item exists, it must update, otherwise a new one must be added and all other entries relating to Master primary key in Details table must be deleted. But it is showing an error:

Cannot insert explicit value for identity column in table
  'SemesterDetails' when IDENTITY_INSERT is set to OFF

This is the Master table:

```<code>public class StudentDegreeCore : Entity<int>
{
    [StringLength(150)]
    [Required(ErrorMessage = "Enter Degree College ")]
    public string DegreeCollege { get; set; }

    [Required()]
    public string CollegeID { get; set; }

    [StringLength(7, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 7)]
    [Required(ErrorMessage = "Enter 10th Pass Year")]
    public string CommencementYear { get; set; }

    public List<StudentSemesterCore> SemesterDetails { get; set; }
}
</code>```

This is the Details table, represented by the StudentSemesterCore class:

```<code>public class StudentSemesterCore
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(150)]
    [Required(ErrorMessage = "Enter Year/Semester")]
    public string YearOrSemester { get; set; }

    [Required()]
    public virtual int StudentDegreeID { get; set; }

    [ForeignKey("StudentDegreeID")]
    public virtual StudentDegreeCore StudentDegreeCore { get; set; }

    [StringLength(4, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
    [Required(ErrorMessage = "Enter Semester Status")]
    public string Status { get; set; }

    [DisplayName("% of Marks")]
    [RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Numbers With Two decimal Place Allowed")]
    public decimal MarkPercentage { get; set; }
}
</code>```

This is the Update code:

```<code>_studentdegreeRepository.Update(st);
CurrentUnitOfWork.SaveChanges();
</code>```

It shows an error when SaveChanges is called. Actually, I want to update the details if the same value exists, otherwise add new one and all other data relating to the same StudentDegreeID must be removed.

答:
I tried this </p>

```<code> public override async Task<StudentDegreeDto> Create(StudentDegreeCreateDto input)
            {
                //CheckCreatePermission();
                StudentDegreeCore st = new StudentDegreeCore();
                try
                {

                    StudentDegreeCore core = new StudentDegreeCore()
                    {
                        Id = input.Id,
                        Address1 = input.Address1,
                        Address2 = input.Address2,
                        City = input.City,
                        CollegeID = input.CollegeID,
                        CommencementYear = input.CommencementYear,
                        CompletionYear = input.CompletionYear,
                        CurrentYear = input.CurrentYear,
                        DegreeCollege = input.DegreeCollege,
                        DegreeId = input.DegreeId,
                        OverallPercent = input.OverallPercent,
                        PinCode = input.PinCode,
                        PostBox = input.PostBox,
                        State = input.State,
                        StreamId = input.StreamId,
                        UserId = input.UserId
                    };
                    core.SemesterDetails = new List<StudentSemesterCore>();

                    foreach (var items in input.SemesterDetails)
                    {
                        core.SemesterDetails.Add(new StudentSemesterCore()
                        {
                            GPA = items.GPA,
                            MarkPercentage = items.MarkPercentage,
                            Status = items.Status,
                            UserId = items.UserId ,
                            Id = items.Id,
                            StudentDegreeID = items.StudentDegreeID ,
                            YearOrSemester = items.YearOrSemester,
                            LastModificationTime = DateTime.Now,
                            CreationTime = DateTime.Now
                        });
                    }
                    var student = core; //ObjectMapper.Map<StudentDegreeCore>(input);
                    long uid = (AbpSession.UserId == null) ? 0 : Convert.ToInt64(AbpSession.UserId);
                    st = _studentRepository.Get(student.Id);
                    if (st != null && st.Id > 0)
                    {
                        st.DegreeCollege = student.DegreeCollege;
                        st.CollegeID = student.CollegeID;
                        st.CommencementYear = student.CommencementYear;
                        st.CompletionYear = student.CompletionYear;
                        st.LastModificationId = Convert.ToInt32(AbpSession.UserId);
                        st.LastModificationTime = DateTime.Now;
                        st.StreamId = student.StreamId;
                        st.DegreeId = student.DegreeId;
                        st.CurrentYear = student.CurrentYear;
                        st.OverallPercent = student.OverallPercent;
                        st.PinCode = student.PinCode;
                        st.PostBox = student.PostBox;
                        st.State = student.State;
                        st.Address1 = student.Address1;
                        st.Address2 = student.Address2;
                        st.City = student.City;
                        st.SemesterDetails = new List<StudentSemesterCore>();
                        //st.SemesterDetails = student.SemesterDetails;
                        _studentRepository.Update(st);
                        foreach (var items in student.SemesterDetails)
                        {
                            _studentSemesterRepository.InsertOrUpdate(items);
                        }
                        //_studentRepository.Update(st);
                        CurrentUnitOfWork.SaveChanges();
                    }
                    else
                    {
                        student.UserId = Convert.ToInt32(AbpSession.UserId);
                        student.CreationId = Convert.ToInt32(AbpSession.UserId);
                        _studentRepository.Insert(student);
                        CurrentUnitOfWork.SaveChanges();
                    }
                }
                catch (Exception ex)
                {

                }
                StudentDegreeDto studentDegreeDto = new StudentDegreeDto()
                {
                    Id = input.Id,
                    Address1 = input.Address1,
                    Address2 = input.Address2,
                    City = input.City,
                    CollegeID = input.CollegeID,
                    CommencementYear = input.CommencementYear,
                    CompletionYear = input.CompletionYear,
                    CurrentYear = input.CurrentYear,
                    DegreeCollege = input.DegreeCollege,
                    DegreeId = input.DegreeId,
                    OverallPercent = input.OverallPercent,
                    PinCode = input.PinCode,
                    PostBox = input.PostBox,
                    State = input.State,
                    StreamId = input.StreamId,
                    UserId = input.UserId
                };
                studentDegreeDto.SemesterDetails = new List<StudentSemesterDto>();
                foreach (var items in input.SemesterDetails)
                {
                    studentDegreeDto.SemesterDetails.Add(new StudentSemesterDto()
                    {
                        GPA = items.GPA,
                        MarkPercentage = items.MarkPercentage,
                        Status = items.Status,
                        YearOrSemester = items.YearOrSemester,
                        LastModificationTime = DateTime.Now,
                        CreationTime = DateTime.Now
                    });
                }
                return studentDegreeDto;
            }
</code>```

Body:
I am using ASP.NET Boilerplate template.

I want to update Details table, which contains more than one item. If an item exists, it must update, otherwise a new one must be added and all other entries relating to Master primary key in Details table must be deleted. But it is showing an error:

Cannot insert explicit value for identity column in table
  'SemesterDetails' when IDENTITY_INSERT is set to OFF

This is the Master table:

public class StudentDegreeCore : Entity<int>
{
    [StringLength(150)]
    [Required(ErrorMessage = "Enter Degree College ")]
    public string DegreeCollege { get; set; }

    [Required()]
    public string CollegeID { get; set; }

    [StringLength(7, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 7)]
    [Required(ErrorMessage = "Enter 10th Pass Year")]
    public string CommencementYear { get; set; }

    public List<StudentSemesterCore> SemesterDetails { get; set; }
}

This is the Details table, represented by the StudentSemesterCore class:

public class StudentSemesterCore
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [StringLength(150)]
    [Required(ErrorMessage = "Enter Year/Semester")]
    public string YearOrSemester { get; set; }

    [Required()]
    public virtual int StudentDegreeID { get; set; }

    [ForeignKey("StudentDegreeID")]
    public virtual StudentDegreeCore StudentDegreeCore { get; set; }

    [StringLength(4, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
    [Required(ErrorMessage = "Enter Semester Status")]
    public string Status { get; set; }

    [DisplayName("% of Marks")]
    [RegularExpression(@"\d+(\.\d{1,2})?", ErrorMessage = "Numbers With Two decimal Place Allowed")]
    public decimal MarkPercentage { get; set; }
}

This is the Update code:

_studentdegreeRepository.Update(st);
CurrentUnitOfWork.SaveChanges();

It shows an error when SaveChanges is called. Actually, I want to update the details if the same value exists, otherwise add new one and all other data relating to the same StudentDegreeID must be removed.

Body:
I tried this

 public override async Task<StudentDegreeDto> Create(StudentDegreeCreateDto input)
            {
                //CheckCreatePermission();
                StudentDegreeCore st = new StudentDegreeCore();
                try
                {

                    StudentDegreeCore core = new StudentDegreeCore()
                    {
                        Id = input.Id,
                        Address1 = input.Address1,
                        Address2 = input.Address2,
                        City = input.City,
                        CollegeID = input.CollegeID,
                        CommencementYear = input.CommencementYear,
                        CompletionYear = input.CompletionYear,
                        CurrentYear = input.CurrentYear,
                        DegreeCollege = input.DegreeCollege,
                        DegreeId = input.DegreeId,
                        OverallPercent = input.OverallPercent,
                        PinCode = input.PinCode,
                        PostBox = input.PostBox,
                        State = input.State,
                        StreamId = input.StreamId,
                        UserId = input.UserId
                    };
                    core.SemesterDetails = new List<StudentSemesterCore>();

                    foreach (var items in input.SemesterDetails)
                    {
                        core.SemesterDetails.Add(new StudentSemesterCore()
                        {
                            GPA = items.GPA,
                            MarkPercentage = items.MarkPercentage,
                            Status = items.Status,
                            UserId = items.UserId ,
                            Id = items.Id,
                            StudentDegreeID = items.StudentDegreeID ,
                            YearOrSemester = items.YearOrSemester,
                            LastModificationTime = DateTime.Now,
                            CreationTime = DateTime.Now
                        });
                    }
                    var student = core; //ObjectMapper.Map<StudentDegreeCore>(input);
                    long uid = (AbpSession.UserId == null) ? 0 : Convert.ToInt64(AbpSession.UserId);
                    st = _studentRepository.Get(student.Id);
                    if (st != null && st.Id > 0)
                    {
                        st.DegreeCollege = student.DegreeCollege;
                        st.CollegeID = student.CollegeID;
                        st.CommencementYear = student.CommencementYear;
                        st.CompletionYear = student.CompletionYear;
                        st.LastModificationId = Convert.ToInt32(AbpSession.UserId);
                        st.LastModificationTime = DateTime.Now;
                        st.StreamId = student.StreamId;
                        st.DegreeId = student.DegreeId;
                        st.CurrentYear = student.CurrentYear;
                        st.OverallPercent = student.OverallPercent;
                        st.PinCode = student.PinCode;
                        st.PostBox = student.PostBox;
                        st.State = student.State;
                        st.Address1 = student.Address1;
                        st.Address2 = student.Address2;
                        st.City = student.City;
                        st.SemesterDetails = new List<StudentSemesterCore>();
                        //st.SemesterDetails = student.SemesterDetails;
                        _studentRepository.Update(st);
                        foreach (var items in student.SemesterDetails)
                        {
                            _studentSemesterRepository.InsertOrUpdate(items);
                        }
                        //_studentRepository.Update(st);
                        CurrentUnitOfWork.SaveChanges();
                    }
                    else
                    {
                        student.UserId = Convert.ToInt32(AbpSession.UserId);
                        student.CreationId = Convert.ToInt32(AbpSession.UserId);
                        _studentRepository.Insert(student);
                        CurrentUnitOfWork.SaveChanges();
                    }
                }
                catch (Exception ex)
                {

                }
                StudentDegreeDto studentDegreeDto = new StudentDegreeDto()
                {
                    Id = input.Id,
                    Address1 = input.Address1,
                    Address2 = input.Address2,
                    City = input.City,
                    CollegeID = input.CollegeID,
                    CommencementYear = input.CommencementYear,
                    CompletionYear = input.CompletionYear,
                    CurrentYear = input.CurrentYear,
                    DegreeCollege = input.DegreeCollege,
                    DegreeId = input.DegreeId,
                    OverallPercent = input.OverallPercent,
                    PinCode = input.PinCode,
                    PostBox = input.PostBox,
                    State = input.State,
                    StreamId = input.StreamId,
                    UserId = input.UserId
                };
                studentDegreeDto.SemesterDetails = new List<StudentSemesterDto>();
                foreach (var items in input.SemesterDetails)
                {
                    studentDegreeDto.SemesterDetails.Add(new StudentSemesterDto()
                    {
                        GPA = items.GPA,
                        MarkPercentage = items.MarkPercentage,
                        Status = items.Status,
                        YearOrSemester = items.YearOrSemester,
                        LastModificationTime = DateTime.Now,
                        CreationTime = DateTime.Now
                    });
                }
                return studentDegreeDto;
            }


问:
Symfony 2: Sonata sortable
I have in my entity:

```<code>/**
 * @ORM\ManyToMany(targetEntity="Sancho\UserBundle\Entity\followers", mappedBy="followers")
 */
private $followers;
</code>```

In Sonata i want to get the number of $followers[]. I create in my entity:

```<code>public function getFollow()
{
      return count($this->followers);
}
</code>```

In UserAdmin i have:

```<code>protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('id')
            ->add('follow', null, array('sortable'=>true));
}
</code>```

I have the number of $follow[] but i can't sort the field. When i sort i have the error:

```<code>PHP Catchable fatal error:  Argument 1 passed to Sonata\\DoctrineORMAdminBundle\\Datagrid\\ProxyQuery::entityJoin() must be of the type array, null given, called in /home/sancho/work/Web/vendor/sonata-project/doctrine-orm-admin-bundle/Datagrid/ProxyQuery.php on line 140 and defined in /home/sancho/work/Web/vendor/sonata-project/doctrine-orm-admin-bundle/Datagrid/ProxyQuery.php on line 245
</code>```

答:
I am not sure if this applies to your situation. But I believe the problem may be how you access the field.

```<code>->add('follow', null, array('sortable'=>true));
</code>```

You should use

```<code>->add('followers.follow');
</code>```

I had a relation between a 'store' and 'product' and I used ManyToOnerelations and from the relation table I had ->addIdentifier('store') which apparently uses __toString method and therefore can't be sorted. However when I associate ->addIdentifier('store.name') it is the name field which can be sorted.

Title: Symfony 2: Sonata sortable

Body:
I have in my entity:

/**
 * @ORM\ManyToMany(targetEntity="Sancho\UserBundle\Entity\followers", mappedBy="followers")
 */
private $followers;

In Sonata i want to get the number of $followers[]. I create in my entity:

public function getFollow()
{
      return count($this->followers);
}

In UserAdmin i have:

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->add('id')
            ->add('follow', null, array('sortable'=>true));
}

I have the number of $follow[] but i can't sort the field. When i sort i have the error:

PHP Catchable fatal error:  Argument 1 passed to Sonata\\DoctrineORMAdminBundle\\Datagrid\\ProxyQuery::entityJoin() must be of the type array, null given, called in /home/sancho/work/Web/vendor/sonata-project/doctrine-orm-admin-bundle/Datagrid/ProxyQuery.php on line 140 and defined in /home/sancho/work/Web/vendor/sonata-project/doctrine-orm-admin-bundle/Datagrid/ProxyQuery.php on line 245

Body:
I am not sure if this applies to your situation. But I believe the problem may be how you access the field.

->add('follow', null, array('sortable'=>true));

You should use

->add('followers.follow');

I had a relation between a 'store' and 'product' and I used ManyToOnerelations and from the relation table I had ->addIdentifier('store') which apparently uses __toString method and therefore can't be sorted. However when I associate ->addIdentifier('store.name') it is the name field which can be sorted.


问:
XSS - Ajax call return string assign to java script variable on jsp
I am finding solution for few days, how to fix vulnerable java script variable that return from ajax call. </p>

```<code> public String getDefaultCopyName(HttpServletRequest request, HttpServletResponse response,
     Long serviceGroupId) {
  MeoOptimizationSet set = service.find(serviceGroupId);
  String name = set.getName() + getCopySuffix();
  return name;
´}

  var defaultName = '';
  $.ajax({
     url: "<c:url value='/MeoOptimizationSet-getDefaultCopyName.mvc'/>",
     data: { serviceGroupId: selectedIds[0] },
     success: function(data) {<b> defaultName = data</b>},
     async: false
  });

  APP.confirm({
  msg: "<br>"+label + "<br><br><input type='text' id='newName' size='40'
  value='" + <b> defaultName </br> + "'  />",
  ok: function() {
    //TODO
     });
  }
  }
</code>```

答:
My questing is very simple, Just I want to know ajax call from JSP to java controller, Controller method return some value to JSPajax caller method and I am assigning value into a java script variable

```<code>var defaultName = '';
   $.ajax({
       url: "/abc.mvc",
       data: { id: 1001},
       success: function (data) {
       defaultName = data
     }
  });
</code>```

How could I protect dafalutName assignment from Cross Site Scripting (XSS)?

Body:
I am finding solution for few days, how to fix vulnerable java script variable that return from ajax call.

 public String getDefaultCopyName(HttpServletRequest request, HttpServletResponse response,
     Long serviceGroupId) {
  MeoOptimizationSet set = service.find(serviceGroupId);
  String name = set.getName() + getCopySuffix();
  return name;
´}

  var defaultName = '';
  $.ajax({
     url: "<c:url value='/MeoOptimizationSet-getDefaultCopyName.mvc'/>",
     data: { serviceGroupId: selectedIds[0] },
     success: function(data) { defaultName = data},
     async: false
  });

  APP.confirm({
  msg: "
"+label + "

<input type='text' id='newName' size='40'
  value='" +  defaultName
 + "'  />",
  ok: function() {
    //TODO
     });
  }
  }

Body:
My questing is very simple, Just I want to know ajax call from JSP to java controller, Controller method return some value to JSPajax caller method and I am assigning value into a java script variable

var defaultName = '';
   $.ajax({
       url: "/abc.mvc",
       data: { id: 1001},
       success: function (data) {
       defaultName = data
     }
  });

How could I protect dafalutName assignment from Cross Site Scripting (XSS)?


问:
CORS error when using PHP on IIS on server side and angular 4 on client side
I have 2 web sites that communicate with REST API on my server side.
The main web site has the main domain and the second website has a sub domain.
for example www.example.com and www.admin.example.com

i have a REST API on the www.example.com root directory and when the www.example.com address to the API everything is OK, but when www.admin.example.com is trying to address to the API, i get an error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.example.com' is therefore not allowed access.

I have this PHP code line on my RestController.php file:

```<code>header("Access-Control-Allow-Origin: *");
</code>```

I also tried to add to my web.config  the following code:

```<code><system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
</code>```

but still i get the the  No 'Access-Control-Allow-Origin' header error, or the error "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

i don't know if it's important, but we are using Angular 4 for client side.

Does anyone has an idea what is the problem, is it an IIS issue or PHP issue or even client side issue?

Thank You

答:
First you should set the Access-Control-Allow-Origin just in one place. I would recommend to do that in your php controller. Otherwise you might run into that "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

Second if you are doing a GET request everything is OK but if you are doing a POST request you might run into the "Response to preflight request doesn't pass access control check..". The reason for that is that your browser sends an OPTIONS preflight request. This request you have to handle on the server side (like you do the post) to be allowed and processed.

You can read more here about preflight requests: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

Further you can find some more information in this thread: CORS with php headers

Body:
I have 2 web sites that communicate with REST API on my server side.
The main web site has the main domain and the second website has a sub domain.
for example www.example.com and www.admin.example.com

i have a REST API on the www.example.com root directory and when the www.example.com address to the API everything is OK, but when www.admin.example.com is trying to address to the API, i get an error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://admin.example.com' is therefore not allowed access.

I have this PHP code line on my RestController.php file:

header("Access-Control-Allow-Origin: *");

I also tried to add to my web.config  the following code:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

but still i get the the  No 'Access-Control-Allow-Origin' header error, or the error "The 'Access-Control-Allow-Origin' header contains multiple values '*, *, but only one is allowed."

i don't know if it's important, but we are using Angular 4 for client side.

Does anyone has an idea what is the problem, is it an IIS issue or PHP issue or even client side issue?

Thank You


问:
Get replicationLag in mongo with pyMongo
I am trying, to get replication-delay using db.rs.printSlaveReplicationInfo from python with pymongo, but not getting any proper way to do so.
I tried the following, but no help.

```<code>>>>from pymongo import MongoClient
>>>client = MongoClient()
>>>db = client.test_database
>>>db.rs.printSlaveReplicationInfo
Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs.printSlaveReplicationInfo')
db.rs.printSlaveReplicationInfo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib64/python2.7/site-packages/pymongo/collection.py", line 2413, in __call__
    self.__name.split(".")[-1])
TypeError: 'Collection' object is not callable. If you meant to call the 'printSlaveReplicationInfo' method on a 'Collection' object it is failing because no such method exists.
>>> db.rs
Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs')
</code>```

Can anyone help with this? or how to do it?

Thanks in advance.

答:
I found out the answer.Here is the complete code :

(Note: You need to have admin privileges to run this command.)

```<code>uri = "mongodb://usernamen:password@host:port/admin"
conn = pymongo.MongoClient(uri)
db = conn['admin']
db_stats = db.command({'replSetGetStatus'  :1})

primary_optime = 0
secondary_optime = 0

for key in db_stats['members'] :
    if key['stateStr'] == 'SECONDARY' :
        secondary_optime = key['optimeDate']
    if key['stateStr'] == 'PRIMARY' :
        primary_optime =key['optimeDate']

print 'primary_optime : ' + str(primary_optime)
print 'secondary_optime : ' + str(secondary_optime)

seconds_lag = (primary_optime - secondary_optime ).total_seconds()
#total_seconds() userd to get the lag in seconds rather than datetime object
print 'secondary_lag : ' + str(seconds_lag)
</code>```

optime reperesents the date,till which that mongo-node has data.

You can read more about it here :

https://docs.mongodb.com/manual/reference/command/replSetGetStatus/

Body:
I am trying, to get replication-delay using db.rs.printSlaveReplicationInfo from python with pymongo, but not getting any proper way to do so.
I tried the following, but no help.

>>>from pymongo import MongoClient
>>>client = MongoClient()
>>>db = client.test_database
>>>db.rs.printSlaveReplicationInfo
Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs.printSlaveReplicationInfo')
db.rs.printSlaveReplicationInfo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib64/python2.7/site-packages/pymongo/collection.py", line 2413, in __call__
    self.__name.split(".")[-1])
TypeError: 'Collection' object is not callable. If you meant to call the 'printSlaveReplicationInfo' method on a 'Collection' object it is failing because no such method exists.
>>> db.rs
Collection(Database(MongoClient([u'10.0.0.19:10006', u'10.0.0.68:10002']), u'xyz'), u'rs')

Can anyone help with this? or how to do it?

Thanks in advance.

Body:
I found out the answer.Here is the complete code :

(Note: You need to have admin privileges to run this command.)

uri = "mongodb://usernamen:password@host:port/admin"
conn = pymongo.MongoClient(uri)
db = conn['admin']
db_stats = db.command({'replSetGetStatus'  :1})

primary_optime = 0
secondary_optime = 0

for key in db_stats['members'] :
    if key['stateStr'] == 'SECONDARY' :
        secondary_optime = key['optimeDate']
    if key['stateStr'] == 'PRIMARY' :
        primary_optime =key['optimeDate']

print 'primary_optime : ' + str(primary_optime)
print 'secondary_optime : ' + str(secondary_optime)

seconds_lag = (primary_optime - secondary_optime ).total_seconds()
#total_seconds() userd to get the lag in seconds rather than datetime object
print 'secondary_lag : ' + str(seconds_lag)

optime reperesents the date,till which that mongo-node has data.

You can read more about it here :

https://docs.mongodb.com/manual/reference/command/replSetGetStatus/


问:
Why is difference between sqlContext.read.load and sqlContext.read.text?
I am only trying to read a textfile into a pyspark RDD, and I am noticing huge differences between sqlContext.read.load and sqlContext.read.text.

```<code>s3_single_file_inpath='s3a://bucket-name/file_name'

indata = sqlContext.read.load(s3_single_file_inpath, format='com.databricks.spark.csv', header='true', inferSchema='false',sep=',')
indata = sqlContext.read.text(s3_single_file_inpath)
</code>```

The sqlContext.read.load command above fails with

```<code>Py4JJavaError: An error occurred while calling o227.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.databricks.spark.csv. Please find packages at http://spark-packages.org
</code>```

But the second one succeeds?

Now, I am confused by this because all of the resources I see online say to use sqlContext.read.load including this one: https://spark.apache.org/docs/1.6.1/sql-programming-guide.html.

It is not clear to me when to use which of these to use when.  Is there a clear distinction between these?

答:
Why is difference between sqlContext.read.load and sqlContext.read.text?

sqlContext.read.load assumes parquet as the data source format while sqlContext.read.text assumes text format.

With sqlContext.read.load you can define the data source format using format parameter.

Depending on the version of Spark 1.6 vs 2.x you may or may not load an external Spark package to have support for csv format.

As of Spark 2.0 you no longer have to load spark-csv Spark package since (quoting the official documentation):

NOTE: This functionality has been inlined in Apache Spark 2.x. This package is in maintenance mode and we only accept critical bug fixes.

That would explain why you got confused as you may have been using Spark 1.6.x and have not loaded the Spark package to have csv support.

Now, I am confused by this because all of the resources I see online say to use sqlContext.read.load including this one: https://spark.apache.org/docs/1.6.1/sql-programming-guide.html.

https://spark.apache.org/docs/1.6.1/sql-programming-guide.html is for Spark 1.6.1 when spark-csv Spark package was not part of Spark. It happened in Spark 2.0.

It is not clear to me when to use which of these to use when. Is there a clear distinction between these?

There's none actually iff you use Spark 2.x.

If however you use Spark 1.6.x, spark-csv has to be loaded separately using --packages option (as described in Using with Spark shell):

This package can be added to Spark using the --packages command line option. For example, to include it when starting the spark shell

As a matter of fact, you can still use com.databricks.spark.csv format explicitly in Spark 2.x as it's recognized internally.

Body:
I am only trying to read a textfile into a pyspark RDD, and I am noticing huge differences between sqlContext.read.load and sqlContext.read.text.

s3_single_file_inpath='s3a://bucket-name/file_name'

indata = sqlContext.read.load(s3_single_file_inpath, format='com.databricks.spark.csv', header='true', inferSchema='false',sep=',')
indata = sqlContext.read.text(s3_single_file_inpath)

The sqlContext.read.load command above fails with

Py4JJavaError: An error occurred while calling o227.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.databricks.spark.csv. Please find packages at http://spark-packages.org

But the second one succeeds?

Now, I am confused by this because all of the resources I see online say to use sqlContext.read.load including this one: https://spark.apache.org/docs/1.6.1/sql-programming-guide.html.

It is not clear to me when to use which of these to use when.  Is there a clear distinction between these?


问:
How will closures in Java enable API design to replace language design?
I can see some of the benefits of closures, such as how they can have their place in simplifying existing libraries and making some future design easier and more efficient.

However, one of the key points mentioned in the draft proposal (http://www.javac.info/consensus-closures-jsr.html) is in section 2.5, point e:

(The specification will improve the language by)

e) enabling future API design to replace language design for extending the Java platform.

I'm struggling to see how this is the case, surely language design is just that - the design of the language itself, and can't be replaced by an API unless Java opens up all sorts of weird APIs using closures for modifying the language (which I highly doubt will happen.)

Can anyone shed some light on this and perhaps provide an example of something that required a language change previously but, with the addition of closures, no longer requires one?

答:
API design and language features are definitely interchangeable at some points. Just look at something like the synchronized key word in Java. It's a keyword, but could just as well be implemented as an API if the language was sufficiently non-verbose. Annotations are another example. The other way around an @Stateless annotation that makes all methods in a class transactional, could also have been a language keyword.

Closures in particular make it easy to hand a "block of code" to a method, which could then do something with that.

A crude example, a for each could be made:

```<code>for_each(myFooList, #(Foo foo) {
   String something = foo.getBar() + foo.getKaz();
   System.out.println(something);
});
</code>```

Maybe not 100% as clean as having the for each loop directly supported by the syntax of the language, but it allows everyone to easily experience with language-like enhancements.

Body:
API design and language features are definitely interchangeable at some points. Just look at something like the synchronized key word in Java. It's a keyword, but could just as well be implemented as an API if the language was sufficiently non-verbose. Annotations are another example. The other way around an @Stateless annotation that makes all methods in a class transactional, could also have been a language keyword.

Closures in particular make it easy to hand a "block of code" to a method, which could then do something with that.

A crude example, a for each could be made:

for_each(myFooList, #(Foo foo) {
   String something = foo.getBar() + foo.getKaz();
   System.out.println(something);
});

Maybe not 100% as clean as having the for each loop directly supported by the syntax of the language, but it allows everyone to easily experience with language-like enhancements.


问:
Alter PHP Array
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

```<code>$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];
</code>```

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

```<code>$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];
</code>```

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

```<code>foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}
</code>```

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

答:
If you rsort (descending) it and foreach it you can then use preg_grep to see if it exsists in your new array.

If not add it.

```<code>$directories = [
"Gallery",
"Images",
"Images/Proof",
"Images/Proof/Another",
];

Rsort($directories);
$new=[];
Foreach($directories as $val){
    If(!preg_grep("~" . $val. ".*~",$new)){
        $new[] = $val;
    }
}

Var_dump($new);
</code>```

https://3v4l.org/0EnZ3

Preg_grep will look for the pattern and see if it exsists in the array.

Since I loop descending it will first look at Images/Proof/Another then add it to the list because it's not there.

Next iteration will look at Images/Proof/ and since preg_grep has pattern Images/Proof/.* it will be true thus not add it in the list.

Then the same with images.

Title: Alter PHP Array

Body:
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

Body:
If you rsort (descending) it and foreach it you can then use preg_grep to see if it exsists in your new array.

If not add it.

$directories = [
"Gallery",
"Images",
"Images/Proof",
"Images/Proof/Another",
];

Rsort($directories);
$new=[];
Foreach($directories as $val){
    If(!preg_grep("~" . $val. ".*~",$new)){
        $new[] = $val;
    }
}

Var_dump($new);

https://3v4l.org/0EnZ3

Preg_grep will look for the pattern and see if it exsists in the array.

Since I loop descending it will first look at Images/Proof/Another then add it to the list because it's not there.

Next iteration will look at Images/Proof/ and since preg_grep has pattern Images/Proof/.* it will be true thus not add it in the list.

Then the same with images.


问:
How to concatenate columns on top of each other in an array
Say I have the following array:

```<code>a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);
</code>```

How can I stack the columns on top of each other to form a single column vector to produce the following?

```<code>b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);
</code>```

答:
You can flatten the transposed array, create a new axis, and transpose again.</p>

```<code>>>> np.ravel(a.T)[None].T
array([[1],
       [3],
       [1],
       [3],
       [2],
       [7],
       [5],
       [5],
       [3],
       [2],
       [6],
       [6],
       [3],
       [7],
       [5]])
</code>```

Body:
Say I have the following array:

a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);

How can I stack the columns on top of each other to form a single column vector to produce the following?

b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);

Body:
You can flatten the transposed array, create a new axis, and transpose again.

>>> np.ravel(a.T)[None].T
array([[1],
       [3],
       [1],
       [3],
       [2],
       [7],
       [5],
       [5],
       [3],
       [2],
       [6],
       [6],
       [3],
       [7],
       [5]])


问:
How to hide dialled number while calling in android
I want to know how to we can hide the dialed number from screen when user make any call from android device. Don't want to allow user to see the dialed number from the app. In my app i am using calling intent and it works fine. But it shows default dialer. How to hide this dialer and delete number from history?

答:
You'll need the following permissions:

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

Whenever you start the call intent, you'll need to start an ongoing service that will register a listener to listen to calls events (to detect exactly when the call start and ends).
When the service detects the outgoing call starts, it should place a full-screen view with LayoutParams.TYPE_SYSTEM_ALERT Window LayoutParam, this will make the view "on top" of everything else on screen, including the call-UI.
See this and this

When the call ends, make sure you remove the view from the Window, also make sure that if there's a bug, crash, or if the service exists unexpectedly, you remove your view, otherwise you may block the user from using the phone!

When the call ends, the service should add an Observer to the CallLog database and when you detect a change check if the last call is your call.
If so, delete it.

P.S
The SYSTEM_ALERT_WINDOW is granted by default when you install an app from Google Play, while developing, you need to manually enable it in your phone Settings > apps > Menu/Gear icon > Permissions > "Draw over other apps" > Enable for your app.
For the other permissions, you may require to use the Runtime Permissions api

Body:
You'll need the following permissions:

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

Whenever you start the call intent, you'll need to start an ongoing service that will register a listener to listen to calls events (to detect exactly when the call start and ends).
When the service detects the outgoing call starts, it should place a full-screen view with LayoutParams.TYPE_SYSTEM_ALERT Window LayoutParam, this will make the view "on top" of everything else on screen, including the call-UI.
See this and this

When the call ends, make sure you remove the view from the Window, also make sure that if there's a bug, crash, or if the service exists unexpectedly, you remove your view, otherwise you may block the user from using the phone!

When the call ends, the service should add an Observer to the CallLog database and when you detect a change check if the last call is your call.
If so, delete it.

P.S
The SYSTEM_ALERT_WINDOW is granted by default when you install an app from Google Play, while developing, you need to manually enable it in your phone Settings > apps > Menu/Gear icon > Permissions > "Draw over other apps" > Enable for your app.
For the other permissions, you may require to use the Runtime Permissions api